diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..a767c6feb --- /dev/null +++ b/.gitattributes @@ -0,0 +1,37 @@ +* text eol=lf + +*.jar binary + +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.tif binary +*.tiff binary +*.ico binary +*.svg text +*.eps binary + +*.kar binary +*.m4a binary +*.mid binary +*.midi binary +*.mp3 binary +*.ogg binary +*.ra binary + +*.7z binary +*.gz binary +*.tar binary +*.tgz binary +*.zip binary + +*.patch -text + +*.bat text eol=crlf +*.cmd text eol=crlf +*.ps1 text eol=crlf + +*autogenerated binary + +*.tcn binary \ No newline at end of file diff --git a/build.gradle b/build.gradle index 5e787403a..997b94dc3 100755 --- a/build.gradle +++ b/build.gradle @@ -1,10 +1,9 @@ -//version: 1650343995 +//version: 1661114848 /* -DO NOT CHANGE THIS FILE! - -Also, you may replace this file at any time if there is an update available. -Please check https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/main/build.gradle for updates. -*/ + DO NOT CHANGE THIS FILE! + Also, you may replace this file at any time if there is an update available. + Please check https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/main/build.gradle for updates. + */ import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation @@ -12,14 +11,26 @@ 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 { + mavenCentral() + maven { name 'forge' url 'https://maven.minecraftforge.net' } + maven { + // GTNH ForgeGradle Fork + name = "GTNH Maven" + url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" + } maven { name 'sonatype' url 'https://oss.sonatype.org/content/repositories/snapshots/' @@ -28,30 +39,37 @@ buildscript { name 'Scala CI dependencies' url 'https://repo1.maven.org/maven2/' } - maven { - name 'jitpack' - url 'https://jitpack.io' - } } dependencies { - classpath 'com.github.GTNewHorizons:ForgeGradle:1.2.7' + classpath 'net.minecraftforge.gradle:ForgeGradle:1.2.9' } } - plugins { id 'java-library' id 'idea' id 'eclipse' id 'scala' id 'maven-publish' - id 'org.jetbrains.kotlin.jvm' version '1.5.30' apply false - id 'org.jetbrains.kotlin.kapt' version '1.5.30' apply false - id 'org.ajoberstar.grgit' version '4.1.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.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' apply false } +boolean settingsupdated = verifySettingsGradle() +settingsupdated = verifyGitAttributes() || settingsupdated +if (settingsupdated) + throw new GradleException("Settings has been updated, please re-run task.") + +dependencies { + implementation 'com.diffplug:blowdryer:1.6.0' +} + +apply plugin: 'com.diffplug.blowdryer' if (project.file('.git/HEAD').isFile()) { apply plugin: 'com.palantir.git-version' @@ -77,7 +95,14 @@ idea { } } -if(JavaVersion.current() != JavaVersion.VERSION_1_8) { +boolean disableSpotless = project.hasProperty("disableSpotless") ? project.disableSpotless.toBoolean() : false + +if (!disableSpotless) { + apply plugin: 'com.diffplug.spotless' + apply from: Blowdryer.file('spotless.gradle') +} + +if (JavaVersion.current() != JavaVersion.VERSION_1_8) { throw new GradleException("This project requires Java 8, but it's running on " + JavaVersion.current()) } @@ -102,9 +127,11 @@ checkPropertyExists("containsMixinsAndOrCoreModOnly") checkPropertyExists("usesShadowedDependencies") checkPropertyExists("developmentEnvironmentUserName") -boolean noPublishedSources = project.findProperty("noPublishedSources") ? project.noPublishedSources.toBoolean() : false -boolean usesMixinDebug = project.findProperty('usesMixinDebug') ?: project.usesMixins.toBoolean() - +boolean noPublishedSources = project.hasProperty("noPublishedSources") ? project.noPublishedSources.toBoolean() : false +boolean usesMixinDebug = project.hasProperty('usesMixinDebug') ?: project.usesMixins.toBoolean() +boolean forceEnableMixins = project.hasProperty('forceEnableMixins') ? project.forceEnableMixins.toBoolean() : false +String channel = project.hasProperty('channel') ? project.channel : 'stable' +String mappingsVersion = project.hasProperty('mappingsVersion') ? project.mappingsVersion : '12' String javaSourceDir = "src/main/java/" String scalaSourceDir = "src/main/scala/" String kotlinSourceDir = "src/main/kotlin/" @@ -112,53 +139,53 @@ String kotlinSourceDir = "src/main/kotlin/" String targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") String targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") String targetPackageKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") -if(!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { +if (!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { throw new GradleException("Could not resolve \"modGroup\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) } -if(apiPackage) { +if (apiPackage) { targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") targetPackageKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") - if(!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { + if (!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { throw new GradleException("Could not resolve \"apiPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) } } -if(accessTransformersFile) { +if (accessTransformersFile) { String targetFile = "src/main/resources/META-INF/" + accessTransformersFile - if(!getFile(targetFile).exists()) { + if (!getFile(targetFile).exists()) { throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile) } } -if(usesMixins.toBoolean()) { - if(mixinsPackage.isEmpty() || mixinPlugin.isEmpty()) { +if (usesMixins.toBoolean()) { + if (mixinsPackage.isEmpty() || mixinPlugin.isEmpty()) { throw new GradleException("\"mixinPlugin\" requires \"mixinsPackage\" and \"mixinPlugin\" to be set!") } targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/") targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/") targetPackageKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/") - if(!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { - throw new GradleException("Could not resolve \"mixinsPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) + if (!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { + throw new GradleException("Could not resolve \"mixinsPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) } String targetFileJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".java" String targetFileScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".scala" String targetFileScalaJava = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".java" String targetFileKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".kt" - if(!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { + if (!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { throw new GradleException("Could not resolve \"mixinPlugin\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava + " or " + targetFileKotlin) } } -if(coreModClass) { +if (coreModClass) { String targetFileJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".java" String targetFileScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".scala" String targetFileScalaJava = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".java" String targetFileKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".kt" - if(!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { + if (!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { throw new GradleException("Could not resolve \"coreModClass\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava + " or " + targetFileKotlin) } } @@ -188,7 +215,7 @@ try { 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' + + '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' @@ -199,22 +226,21 @@ ext { modVersion = identifiedVersion } -if(identifiedVersion == versionOverride) { +if (identifiedVersion == versionOverride) { out.style(Style.Failure).text('Override version to ').style(Style.Identifier).text(modVersion).style(Style.Failure).println('!\7') } group = modGroup -if(project.hasProperty("customArchiveBaseName") && customArchiveBaseName) { +if (project.hasProperty("customArchiveBaseName") && customArchiveBaseName) { archivesBaseName = customArchiveBaseName -} -else { +} else { archivesBaseName = modId } def arguments = [] def jvmArguments = [] -if (usesMixins.toBoolean()) { +if (usesMixins.toBoolean() || forceEnableMixins) { arguments += [ "--tweakClass org.spongepowered.asm.launch.MixinTweaker" ] @@ -233,16 +259,16 @@ minecraft { if (replaceGradleTokenInFile) { replaceIn replaceGradleTokenInFile - if(gradleTokenModId) { + if (gradleTokenModId) { replace gradleTokenModId, modId } - if(gradleTokenModName) { + if (gradleTokenModName) { replace gradleTokenModName, modName } - if(gradleTokenVersion) { + if (gradleTokenVersion) { replace gradleTokenVersion, modVersion } - if(gradleTokenGroupName) { + if (gradleTokenGroupName) { replace gradleTokenGroupName, modGroup } } @@ -251,7 +277,7 @@ minecraft { args(arguments) jvmArgs(jvmArguments) - if(developmentEnvironmentUserName) { + if (developmentEnvironmentUserName) { args("--username", developmentEnvironmentUserName) } } @@ -262,7 +288,7 @@ minecraft { } } -if(file('addon.gradle').exists()) { +if (file('addon.gradle').exists()) { apply from: 'addon.gradle' } @@ -279,7 +305,7 @@ repositories { name 'Overmind forge repo mirror' url 'https://gregtech.overminddl1.com/' } - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean() || forceEnableMixins) { maven { name 'sponge' url 'https://repo.spongepowered.org/repository/maven-public' @@ -291,11 +317,13 @@ repositories { } dependencies { - if(usesMixins.toBoolean()) { + 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') + } + if (usesMixins.toBoolean() || forceEnableMixins) { // using 0.8 to workaround a issue in 0.7 which fails mixin application compile('com.github.GTNewHorizons:SpongePoweredMixin:0.7.12-GTNH') { // Mixin includes a lot of dependencies that are too up-to-date @@ -353,7 +381,10 @@ shadowJar { } minimize() // This will only allow shading for actually used classes - configurations = [project.configurations.shadowImplementation, project.configurations.shadowCompile] + configurations = [ + project.configurations.shadowImplementation, + project.configurations.shadowCompile + ] dependsOn(relocateShadowJar) } @@ -368,38 +399,38 @@ jar { attributes(getManifestAttributes()) } - if(usesShadowedDependencies.toBoolean()) { + if (usesShadowedDependencies.toBoolean()) { dependsOn(shadowJar) enabled = false } } reobf { - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean()) { addExtraSrgFile mixinSrg } } afterEvaluate { - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean()) { tasks.compileJava { options.compilerArgs += [ - "-AreobfSrgFile=${tasks.reobf.srg}", - "-AoutSrgFile=${mixinSrg}", - "-AoutRefMapFile=${refMap}", - // Elan: from what I understand they are just some linter configs so you get some warning on how to properly code - "-XDenableSunApiLintControl", - "-XDignore.symbol.file" + "-AreobfSrgFile=${tasks.reobf.srg}", + "-AoutSrgFile=${mixinSrg}", + "-AoutRefMapFile=${refMap}", + // Elan: from what I understand they are just some linter configs so you get some warning on how to properly code + "-XDenableSunApiLintControl", + "-XDignore.symbol.file" ] } } } runClient { - if(developmentEnvironmentUserName) { + if (developmentEnvironmentUserName) { arguments += [ - "--username", - developmentEnvironmentUserName + "--username", + developmentEnvironmentUserName ] } @@ -414,9 +445,9 @@ runServer { tasks.withType(JavaExec).configureEach { javaLauncher.set( - javaToolchains.launcherFor { - languageVersion = projectJavaVersion - } + javaToolchains.launcherFor { + languageVersion = projectJavaVersion + } ) } @@ -424,6 +455,7 @@ processResources { // this will ensure that this task is redone when the versions change. inputs.property "version", project.version inputs.property "mcversion", project.minecraft.version + exclude("spotless.gradle") // replace stuff in mcmod.info, nothing else from(sourceSets.main.resources.srcDirs) { @@ -436,43 +468,44 @@ processResources { "modName": modName } - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean()) { from refMap } // copy everything else that's not the mcmod.info from(sourceSets.main.resources.srcDirs) { exclude 'mcmod.info' + exclude 'spotless.gradle' } } def getManifestAttributes() { def manifestAttributes = [:] - if(!containsMixinsAndOrCoreModOnly.toBoolean() && (usesMixins.toBoolean() || coreModClass)) { + if (!containsMixinsAndOrCoreModOnly.toBoolean() && (usesMixins.toBoolean() || coreModClass)) { manifestAttributes += ["FMLCorePluginContainsFMLMod": true] } - if(accessTransformersFile) { - manifestAttributes += ["FMLAT" : accessTransformersFile.toString()] + if (accessTransformersFile) { + manifestAttributes += ["FMLAT": accessTransformersFile.toString()] } - if(coreModClass) { + if (coreModClass) { manifestAttributes += ["FMLCorePlugin": modGroup + "." + coreModClass] } - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean()) { manifestAttributes += [ - "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", - "MixinConfigs" : "mixins." + modId + ".json", - "ForceLoadAsMod" : !containsMixinsAndOrCoreModOnly.toBoolean() + "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", + "MixinConfigs" : "mixins." + modId + ".json", + "ForceLoadAsMod": !containsMixinsAndOrCoreModOnly.toBoolean() ] } return manifestAttributes } task sourcesJar(type: Jar) { - from (sourceSets.main.allSource) - from (file("$projectDir/LICENSE")) + from(sourceSets.main.allSource) + from(file("$projectDir/LICENSE")) getArchiveClassifier().set('sources') } @@ -491,7 +524,10 @@ task shadowDevJar(type: ShadowJar) { } minimize() // This will only allow shading for actually used classes - configurations = [project.configurations.shadowImplementation, project.configurations.shadowCompile] + configurations = [ + project.configurations.shadowImplementation, + project.configurations.shadowCompile + ] } task relocateShadowDevJar(type: ConfigureShadowRelocation) { @@ -519,22 +555,22 @@ task devJar(type: Jar) { attributes(getManifestAttributes()) } - if(usesShadowedDependencies.toBoolean()) { + if (usesShadowedDependencies.toBoolean()) { dependsOn(circularResolverJar) enabled = false } } task apiJar(type: Jar) { - from (sourceSets.main.allSource) { + from(sourceSets.main.allSource) { include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") + '/**' } - from (sourceSets.main.output) { + from(sourceSets.main.output) { include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") + '/**' } - from (sourceSets.main.resources.srcDirs) { + from(sourceSets.main.resources.srcDirs) { include("LICENSE") } @@ -542,11 +578,11 @@ task apiJar(type: Jar) { } artifacts { - if(!noPublishedSources) { + if (!noPublishedSources) { archives sourcesJar } archives devJar - if(apiPackage) { + if (apiPackage) { archives apiJar } } @@ -564,10 +600,10 @@ publishing { publications { maven(MavenPublication) { from components.java - if(usesShadowedDependencies.toBoolean()) { + if (usesShadowedDependencies.toBoolean()) { artifact source: shadowJar, classifier: "" } - if(!noPublishedSources) { + if (!noPublishedSources) { artifact source: sourcesJar, classifier: "sources" } artifact source: usesShadowedDependencies.toBoolean() ? shadowDevJar : devJar, classifier: "dev" @@ -582,8 +618,11 @@ publishing { // remove extra garbage from minecraft and minecraftDeps configuration pom.withXml { - def badArtifacts = [:].withDefault {[] as Set} - for (configuration in [projectConfigs.minecraft, projectConfigs.minecraftDeps]) { + 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 } @@ -621,7 +660,7 @@ task updateBuildScript { } } -if (isNewBuildScriptVersionAvailable(projectDir.toString())) { +if (!project.getGradle().startParameter.isOffline() && isNewBuildScriptVersionAvailable(projectDir.toString())) { if (autoUpdateBuildScript.toBoolean()) { performBuildScriptUpdate(projectDir.toString()) } else { @@ -630,7 +669,40 @@ if (isNewBuildScriptVersionAvailable(projectDir.toString())) { } static URL availableBuildScriptUrl() { - new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/main/build.gradle") + new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/master/build.gradle") +} + +static URL exampleSettingsGradleUrl() { + new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/master/settings.gradle.example") +} + +static URL exampleGitAttributesUrl() { + new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/master/.gitattributes") +} + + +boolean verifyGitAttributes() { + def gitattributesFile = getFile(".gitattributes") + if (!gitattributesFile.exists()) { + println("Downloading default .gitattributes") + exampleGitAttributesUrl().withInputStream { i -> gitattributesFile.withOutputStream { it << i } } + exec { + workingDir '.' + commandLine 'git', 'add', '--renormalize', '.' + } + return true + } + return false +} + +boolean verifySettingsGradle() { + def settingsFile = getFile("settings.gradle") + if (!settingsFile.exists()) { + println("Downloading default settings.gradle") + exampleSettingsGradleUrl().withInputStream { i -> settingsFile.withOutputStream { it << i } } + return true + } + return false } boolean performBuildScriptUpdate(String projectDir) { @@ -638,6 +710,10 @@ boolean performBuildScriptUpdate(String projectDir) { def buildscriptFile = getFile("build.gradle") availableBuildScriptUrl().withInputStream { i -> buildscriptFile.withOutputStream { it << i } } out.style(Style.Success).print("Build script updated. Please REIMPORT the project or RESTART your IDE!") + boolean settingsupdated = verifySettingsGradle() + settingsupdated = verifyGitAttributes() || settingsupdated + if (settingsupdated) + throw new GradleException("Settings has been updated, please re-run task.") return true } return false @@ -657,7 +733,7 @@ boolean isNewBuildScriptVersionAvailable(String projectDir) { static String getVersionHash(String buildScriptContent) { String versionLine = buildScriptContent.find("^//version: [a-z0-9]*") - if(versionLine != null) { + if (versionLine != null) { return versionLine.split(": ").last() } return "" @@ -668,7 +744,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 { @@ -677,42 +849,57 @@ def deobf(String sourceURL) { //get rid of directories: int lastSlash = fileName.lastIndexOf("/") - if(lastSlash > 0) { + if (lastSlash > 0) { 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(".")) } String hostName = url.getHost() - if(hostName.startsWith("www.")) { + if (hostName.startsWith("www.")) { hostName = hostName.substring(4) } List parts = Arrays.asList(hostName.split("\\.")) Collections.reverse(parts) hostName = String.join(".", parts) - return deobf(sourceURL, hostName + "/" + fileName) - } catch(Exception e) { - return deobf(sourceURL, "deobf/" + String.valueOf(sourceURL.hashCode())) + return deobf(sourceURL, "$hostName/$fileName") + } catch (Exception e) { + 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()) { + if (file(deobfFile).exists()) { return files(deobfFile) } + String mappingsVer + String remoteMappings = project.hasProperty('remoteMappings') ? project.remoteMappings : 'https://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/conf/' + 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 @@ -726,14 +913,48 @@ 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) { diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..93c852a12 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,10 @@ +plugins { + id 'com.diffplug.blowdryerSetup' version '1.6.0' +} + +apply plugin: 'com.diffplug.blowdryerSetup' + +blowdryerSetup { + github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.1.5') + //devLocal '.' // Use this when testing config updates locally +} diff --git a/src/main/java/forestry/Forestry.java b/src/main/java/forestry/Forestry.java index 7f93631d9..93aedf8ed 100644 --- a/src/main/java/forestry/Forestry.java +++ b/src/main/java/forestry/Forestry.java @@ -10,13 +10,6 @@ ******************************************************************************/ package forestry; -import java.io.File; - -import net.minecraft.block.Block; -import net.minecraft.item.Item; - -import net.minecraftforge.common.MinecraftForge; - import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; @@ -32,7 +25,6 @@ import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.GameRegistry.Type; - import forestry.api.core.ForestryAPI; import forestry.core.ClimateManager; import forestry.core.EventHandlerCore; @@ -49,6 +41,10 @@ import forestry.core.utils.Log; import forestry.core.utils.StringUtil; import forestry.core.worldgen.WorldGenerator; import forestry.plugins.PluginManager; +import java.io.File; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraftforge.common.MinecraftForge; /** * Forestry Minecraft Mod @@ -56,113 +52,115 @@ import forestry.plugins.PluginManager; * @author SirSengir */ @Mod( - modid = Constants.MOD, - name = Constants.MOD, - version = Constants.VERSION, - guiFactory = "forestry.core.config.ForestryGuiConfigFactory", - dependencies = "required-after:Forge@[10.13.4.1566,);" - + "after:Buildcraft|Core@[6.1.7,);" - + "after:ExtrabiomesXL;" - + "after:BiomesOPlenty;" - + "after:IC2@[2.0.140,);" - + "after:Natura@[2.2.0,);" - + "after:HardcoreEnderExpansion;") + modid = Constants.MOD, + name = Constants.MOD, + version = Constants.VERSION, + guiFactory = "forestry.core.config.ForestryGuiConfigFactory", + dependencies = "required-after:Forge@[10.13.4.1566,);" + + "after:Buildcraft|Core@[6.1.7,);" + + "after:ExtrabiomesXL;" + + "after:BiomesOPlenty;" + + "after:IC2@[2.0.140,);" + + "after:Natura@[2.2.0,);" + + "after:HardcoreEnderExpansion;") public class Forestry { - @Mod.Instance(Constants.MOD) - public static Forestry instance; - private File configFolder; + @Mod.Instance(Constants.MOD) + public static Forestry instance; - public Forestry() { - ForestryAPI.instance = this; - ForestryAPI.climateManager = new ClimateManager(); - ForestryAPI.forestryConstants = new Constants(); - ForestryAPI.errorStateRegistry = new ErrorStateRegistry(); - EnumErrorCode.init(); - } + private File configFolder; - public static PacketHandler packetHandler; + public Forestry() { + ForestryAPI.instance = this; + ForestryAPI.climateManager = new ClimateManager(); + ForestryAPI.forestryConstants = new Constants(); + ForestryAPI.errorStateRegistry = new ErrorStateRegistry(); + EnumErrorCode.init(); + } - @EventHandler - public void preInit(FMLPreInitializationEvent event) { - checkForCoFHLib(); - packetHandler = new PacketHandler(); + public static PacketHandler packetHandler; - // Register event handler - EventHandlerCore eventHandlerCore = new EventHandlerCore(); - MinecraftForge.EVENT_BUS.register(eventHandlerCore); - FMLCommonHandler.instance().bus().register(eventHandlerCore); - MinecraftForge.EVENT_BUS.register(new MultiblockEventHandler()); + @EventHandler + public void preInit(FMLPreInitializationEvent event) { + checkForCoFHLib(); + packetHandler = new PacketHandler(); - configFolder = new File(event.getModConfigurationDirectory(), "forestry"); - Config.load(); + // Register event handler + EventHandlerCore eventHandlerCore = new EventHandlerCore(); + MinecraftForge.EVENT_BUS.register(eventHandlerCore); + FMLCommonHandler.instance().bus().register(eventHandlerCore); + MinecraftForge.EVENT_BUS.register(new MultiblockEventHandler()); - PluginManager.runSetup(); + configFolder = new File(event.getModConfigurationDirectory(), "forestry"); + Config.load(); - ForestryAPI.activeMode = new GameMode(Config.gameMode); + PluginManager.runSetup(); - PluginManager.runPreInit(); - } + ForestryAPI.activeMode = new GameMode(Config.gameMode); - @EventHandler - public void init(FMLInitializationEvent event) { - // Register gui handler - NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler()); + PluginManager.runPreInit(); + } - PluginManager.runInit(); - } + @EventHandler + public void init(FMLInitializationEvent event) { + // Register gui handler + NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler()); - @EventHandler - public void postInit(FMLPostInitializationEvent event) { - PluginManager.runPostInit(); + PluginManager.runInit(); + } - // Register world generator - WorldGenerator worldGenerator = new WorldGenerator(); - GameRegistry.registerWorldGenerator(worldGenerator, 0); + @EventHandler + public void postInit(FMLPostInitializationEvent event) { + PluginManager.runPostInit(); - // Register tick handlers - Proxies.common.registerTickHandlers(worldGenerator); + // Register world generator + WorldGenerator worldGenerator = new WorldGenerator(); + GameRegistry.registerWorldGenerator(worldGenerator, 0); - // Handle IMC messages. - PluginManager.processIMCMessages(FMLInterModComms.fetchRuntimeMessages(ForestryAPI.instance)); - } + // Register tick handlers + Proxies.common.registerTickHandlers(worldGenerator); - @EventHandler - public void serverStarting(FMLServerStartingEvent event) { - PluginManager.serverStarting(event.getServer()); - } + // Handle IMC messages. + PluginManager.processIMCMessages(FMLInterModComms.fetchRuntimeMessages(ForestryAPI.instance)); + } - public File getConfigFolder() { - return configFolder; - } + @EventHandler + public void serverStarting(FMLServerStartingEvent event) { + PluginManager.serverStarting(event.getServer()); + } - @EventHandler - public void processIMCMessages(IMCEvent event) { - PluginManager.processIMCMessages(event.getMessages()); - } + public File getConfigFolder() { + return configFolder; + } - @EventHandler - public void missingMapping(FMLMissingMappingsEvent event) { - for (MissingMapping mapping : event.get()) { - if (mapping.type == Type.BLOCK) { - Block block = GameRegistry.findBlock(Constants.MOD, StringUtil.cleanTags(mapping.name)); - if (block != null) { - mapping.remap(block); - Log.warning("Remapping block " + mapping.name + " to " + StringUtil.cleanBlockName(block)); - } - } else { - Item item = GameRegistry.findItem(Constants.MOD, StringUtil.cleanTags(mapping.name)); - if (item != null) { - mapping.remap(item); - Log.warning("Remapping item " + mapping.name + " to " + StringUtil.cleanItemName(item)); - } - } - } - } - - private static void checkForCoFHLib() { - if (!ModAPIManager.INSTANCE.hasAPI("CoFHAPI|energy")) { - throw new RuntimeException("CoFHAPI|energy could not be found! This version of Forestry does not contain the RedstoneFlux API anymore, so you have to install either CoFHLib or CoFHCore."); - } - } + @EventHandler + public void processIMCMessages(IMCEvent event) { + PluginManager.processIMCMessages(event.getMessages()); + } + + @EventHandler + public void missingMapping(FMLMissingMappingsEvent event) { + for (MissingMapping mapping : event.get()) { + if (mapping.type == Type.BLOCK) { + Block block = GameRegistry.findBlock(Constants.MOD, StringUtil.cleanTags(mapping.name)); + if (block != null) { + mapping.remap(block); + Log.warning("Remapping block " + mapping.name + " to " + StringUtil.cleanBlockName(block)); + } + } else { + Item item = GameRegistry.findItem(Constants.MOD, StringUtil.cleanTags(mapping.name)); + if (item != null) { + mapping.remap(item); + Log.warning("Remapping item " + mapping.name + " to " + StringUtil.cleanItemName(item)); + } + } + } + } + + private static void checkForCoFHLib() { + if (!ModAPIManager.INSTANCE.hasAPI("CoFHAPI|energy")) { + throw new RuntimeException( + "CoFHAPI|energy could not be found! This version of Forestry does not contain the RedstoneFlux API anymore, so you have to install either CoFHLib or CoFHCore."); + } + } } diff --git a/src/main/java/forestry/api/apiculture/BeeManager.java b/src/main/java/forestry/api/apiculture/BeeManager.java index 280ee751f..04eb0ea15 100644 --- a/src/main/java/forestry/api/apiculture/BeeManager.java +++ b/src/main/java/forestry/api/apiculture/BeeManager.java @@ -1,54 +1,54 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; import java.util.ArrayList; import java.util.HashMap; - import net.minecraft.item.ItemStack; + /** - * + * * Some miscellaneous lists and settings for bees. - * + * * @author SirSengir */ public class BeeManager { - /** - * 0 - Common Village Bees 1 - Uncommon Village Bees (20 % of spawns) - */ - public static ArrayList[] villageBees; + /** + * 0 - Common Village Bees 1 - Uncommon Village Bees (20 % of spawns) + */ + public static ArrayList[] villageBees; - /** - * List of items that can induce swarming. Integer denotes x in 1000 chance. - */ - public static HashMap inducers = new HashMap(); + /** + * List of items that can induce swarming. Integer denotes x in 1000 chance. + */ + public static HashMap inducers = new HashMap(); - /** - * Convenient access to AlleleManager.alleleRegistry.getSpeciesRoot("rootBees") - */ - public static IBeeRoot beeRoot; + /** + * Convenient access to AlleleManager.alleleRegistry.getSpeciesRoot("rootBees") + */ + public static IBeeRoot beeRoot; - /** - * Used to create new bees. - */ - public static IBeeFactory beeFactory; + /** + * Used to create new bees. + */ + public static IBeeFactory beeFactory; - /** - * Used to create new bee mutations. - */ - public static IBeeMutationFactory beeMutationFactory; + /** + * Used to create new bee mutations. + */ + public static IBeeMutationFactory beeMutationFactory; - /** - * Used to get Forestry's jubilance implementations. - */ - public static IJubilanceFactory jubilanceFactory; + /** + * Used to get Forestry's jubilance implementations. + */ + public static IJubilanceFactory jubilanceFactory; - /** - * Used to check whether a player is wearing Apiarist Armor. - */ - public static IArmorApiaristHelper armorApiaristHelper; + /** + * Used to check whether a player is wearing Apiarist Armor. + */ + public static IArmorApiaristHelper armorApiaristHelper; } diff --git a/src/main/java/forestry/api/apiculture/DefaultBeeListener.java b/src/main/java/forestry/api/apiculture/DefaultBeeListener.java index 8e76cf28d..be7bebc52 100644 --- a/src/main/java/forestry/api/apiculture/DefaultBeeListener.java +++ b/src/main/java/forestry/api/apiculture/DefaultBeeListener.java @@ -13,19 +13,14 @@ import forestry.api.genetics.IIndividual; * BeeListeners should inherit from this class unless they need to listen for everything. */ public class DefaultBeeListener implements IBeeListener { - @Override - public void wearOutEquipment(int amount) { + @Override + public void wearOutEquipment(int amount) {} - } - - @Override - public void onQueenDeath() { - - } - - @Override - public boolean onPollenRetrieved(IIndividual pollen) { - return false; - } + @Override + public void onQueenDeath() {} + @Override + public boolean onPollenRetrieved(IIndividual pollen) { + return false; + } } diff --git a/src/main/java/forestry/api/apiculture/DefaultBeeModifier.java b/src/main/java/forestry/api/apiculture/DefaultBeeModifier.java index 1264ccba4..b6e2bc05c 100644 --- a/src/main/java/forestry/api/apiculture/DefaultBeeModifier.java +++ b/src/main/java/forestry/api/apiculture/DefaultBeeModifier.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; @@ -12,44 +12,43 @@ package forestry.api.apiculture; */ public class DefaultBeeModifier implements IBeeModifier { - public float getTerritoryModifier(IBeeGenome genome, float currentModifier) { - return 1.0f; - } + public float getTerritoryModifier(IBeeGenome genome, float currentModifier) { + return 1.0f; + } - public float getMutationModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { - return 1.0f; - } + public float getMutationModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { + return 1.0f; + } - public float getLifespanModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { - return 1.0f; - } + public float getLifespanModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { + return 1.0f; + } - public float getProductionModifier(IBeeGenome genome, float currentModifier) { - return 1.0f; - } + public float getProductionModifier(IBeeGenome genome, float currentModifier) { + return 1.0f; + } - public float getFloweringModifier(IBeeGenome genome, float currentModifier) { - return 1.0f; - } + public float getFloweringModifier(IBeeGenome genome, float currentModifier) { + return 1.0f; + } - public float getGeneticDecay(IBeeGenome genome, float currentModifier) { - return 1.0f; - } + public float getGeneticDecay(IBeeGenome genome, float currentModifier) { + return 1.0f; + } - public boolean isSealed() { - return false; - } + public boolean isSealed() { + return false; + } - public boolean isSelfLighted() { - return false; - } + public boolean isSelfLighted() { + return false; + } - public boolean isSunlightSimulated() { - return false; - } - - public boolean isHellish() { - return false; - } + public boolean isSunlightSimulated() { + return false; + } + public boolean isHellish() { + return false; + } } diff --git a/src/main/java/forestry/api/apiculture/EnumBeeChromosome.java b/src/main/java/forestry/api/apiculture/EnumBeeChromosome.java index d23b0f5d7..215ff2730 100644 --- a/src/main/java/forestry/api/apiculture/EnumBeeChromosome.java +++ b/src/main/java/forestry/api/apiculture/EnumBeeChromosome.java @@ -1,12 +1,10 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; -import java.util.Locale; - import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleArea; import forestry.api.genetics.IAlleleBoolean; @@ -16,89 +14,90 @@ import forestry.api.genetics.IAlleleInteger; import forestry.api.genetics.IAlleleTolerance; import forestry.api.genetics.IChromosomeType; import forestry.api.genetics.ISpeciesRoot; +import java.util.Locale; /** * Enum representing the order of chromosomes in a bee's genome and what they control. - * + * * @author SirSengir */ public enum EnumBeeChromosome implements IChromosomeType { - /** - * Species of the bee. Alleles here must implement {@link IAlleleBeeSpecies}. - */ - SPECIES(IAlleleBeeSpecies.class), - /** - * (Production) Speed of the bee. - */ - SPEED(IAlleleFloat.class), - /** - * Lifespan of the bee. - */ - LIFESPAN(IAlleleInteger.class), - /** - * Fertility of the bee. Determines number of offspring. - */ - FERTILITY(IAlleleInteger.class), - /** - * Temperature difference to its native supported one the bee can tolerate. - */ - TEMPERATURE_TOLERANCE(IAlleleTolerance.class), - /** - * Slightly incorrectly named. If true, a naturally dirunal bee can work during the night. If true, a naturally nocturnal bee can work during the day. - */ - NOCTURNAL(IAlleleBoolean.class), - /** - * Not used / superseded by fixed values for the species. Probably going to be replaced with a boolean for FIRE_RESIST. - */ - @Deprecated - HUMIDITY(IAllele.class), - /** - * Humidity difference to its native supported one the bee can tolerate. - */ - HUMIDITY_TOLERANCE(IAlleleTolerance.class), - /** - * If true the bee can work during rain. - */ - TOLERANT_FLYER(IAlleleBoolean.class), - /** - * If true, the bee can work without a clear view of the sky. - */ - CAVE_DWELLING(IAlleleBoolean.class), - /** - * Contains the supported flower provider. - */ - FLOWER_PROVIDER(IAlleleFlowers.class), - /** - * Determines pollination speed. - */ - FLOWERING(IAlleleInteger.class), - /** - * Determines the size of the bee's territory. - */ - TERRITORY(IAlleleArea.class), - /** - * Determines the bee's effect. - */ - EFFECT(IAlleleBeeEffect.class); - - Class clss; - - EnumBeeChromosome(Class clss) { - this.clss = clss; - } + /** + * Species of the bee. Alleles here must implement {@link IAlleleBeeSpecies}. + */ + SPECIES(IAlleleBeeSpecies.class), + /** + * (Production) Speed of the bee. + */ + SPEED(IAlleleFloat.class), + /** + * Lifespan of the bee. + */ + LIFESPAN(IAlleleInteger.class), + /** + * Fertility of the bee. Determines number of offspring. + */ + FERTILITY(IAlleleInteger.class), + /** + * Temperature difference to its native supported one the bee can tolerate. + */ + TEMPERATURE_TOLERANCE(IAlleleTolerance.class), + /** + * Slightly incorrectly named. If true, a naturally dirunal bee can work during the night. If true, a naturally nocturnal bee can work during the day. + */ + NOCTURNAL(IAlleleBoolean.class), + /** + * Not used / superseded by fixed values for the species. Probably going to be replaced with a boolean for FIRE_RESIST. + */ + @Deprecated + HUMIDITY(IAllele.class), + /** + * Humidity difference to its native supported one the bee can tolerate. + */ + HUMIDITY_TOLERANCE(IAlleleTolerance.class), + /** + * If true the bee can work during rain. + */ + TOLERANT_FLYER(IAlleleBoolean.class), + /** + * If true, the bee can work without a clear view of the sky. + */ + CAVE_DWELLING(IAlleleBoolean.class), + /** + * Contains the supported flower provider. + */ + FLOWER_PROVIDER(IAlleleFlowers.class), + /** + * Determines pollination speed. + */ + FLOWERING(IAlleleInteger.class), + /** + * Determines the size of the bee's territory. + */ + TERRITORY(IAlleleArea.class), + /** + * Determines the bee's effect. + */ + EFFECT(IAlleleBeeEffect.class); - @Override - public Class getAlleleClass() { - return clss; - } + Class clss; - @Override - public String getName() { - return this.toString().toLowerCase(Locale.ENGLISH); - } + EnumBeeChromosome(Class clss) { + this.clss = clss; + } - @Override - public ISpeciesRoot getSpeciesRoot() { - return BeeManager.beeRoot; - } + @Override + public Class getAlleleClass() { + return clss; + } + + @Override + public String getName() { + return this.toString().toLowerCase(Locale.ENGLISH); + } + + @Override + public ISpeciesRoot getSpeciesRoot() { + return BeeManager.beeRoot; + } } diff --git a/src/main/java/forestry/api/apiculture/EnumBeeType.java b/src/main/java/forestry/api/apiculture/EnumBeeType.java index c1b6244a1..784ee7018 100644 --- a/src/main/java/forestry/api/apiculture/EnumBeeType.java +++ b/src/main/java/forestry/api/apiculture/EnumBeeType.java @@ -1,26 +1,29 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; +import forestry.api.genetics.ISpeciesType; import java.util.Locale; -import forestry.api.genetics.ISpeciesType; - public enum EnumBeeType implements ISpeciesType { - DRONE, PRINCESS, QUEEN, LARVAE, NONE; + DRONE, + PRINCESS, + QUEEN, + LARVAE, + NONE; - public static final EnumBeeType[] VALUES = values(); + public static final EnumBeeType[] VALUES = values(); - String name; + String name; - EnumBeeType() { - this.name = this.toString().toLowerCase(Locale.ENGLISH); - } + EnumBeeType() { + this.name = this.toString().toLowerCase(Locale.ENGLISH); + } - public String getName() { - return name; - } + public String getName() { + return name; + } } diff --git a/src/main/java/forestry/api/apiculture/FlowerManager.java b/src/main/java/forestry/api/apiculture/FlowerManager.java index 67c25bb08..e98a5224a 100644 --- a/src/main/java/forestry/api/apiculture/FlowerManager.java +++ b/src/main/java/forestry/api/apiculture/FlowerManager.java @@ -1,36 +1,34 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; +import forestry.api.genetics.IFlowerRegistry; import java.util.ArrayList; - import net.minecraft.item.ItemStack; -import forestry.api.genetics.IFlowerRegistry; - public class FlowerManager { - /** - *
e.g. FlowerManager.flowerRegister.registerPlantableFlower(new ItemStack(Blocks.red_flower), 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow);
- */ - public static IFlowerRegistry flowerRegistry; + /** + *
e.g. FlowerManager.flowerRegister.registerPlantableFlower(new ItemStack(Blocks.red_flower), 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow);
+ */ + public static IFlowerRegistry flowerRegistry; - public static final String FlowerTypeVanilla = "flowersVanilla"; - public static final String FlowerTypeNether = "flowersNether"; - public static final String FlowerTypeCacti = "flowersCacti"; - public static final String FlowerTypeMushrooms = "flowersMushrooms"; - public static final String FlowerTypeEnd = "flowersEnd"; - public static final String FlowerTypeJungle = "flowersJungle"; - public static final String FlowerTypeSnow = "flowersSnow"; - public static final String FlowerTypeWheat = "flowersWheat"; - public static final String FlowerTypeGourd = "flowersGourd"; + public static final String FlowerTypeVanilla = "flowersVanilla"; + public static final String FlowerTypeNether = "flowersNether"; + public static final String FlowerTypeCacti = "flowersCacti"; + public static final String FlowerTypeMushrooms = "flowersMushrooms"; + public static final String FlowerTypeEnd = "flowersEnd"; + public static final String FlowerTypeJungle = "flowersJungle"; + public static final String FlowerTypeSnow = "flowersSnow"; + public static final String FlowerTypeWheat = "flowersWheat"; + public static final String FlowerTypeGourd = "flowersGourd"; - /** - * @deprecated since Forestry 3.4. Use IFlowerRegistry.registerPlantableFlower instead. - * Completely unused since Forestry 4.0, kept for backward compatibility with older mods. - */ - @Deprecated - public static ArrayList plainFlowers = new ArrayList(); + /** + * @deprecated since Forestry 3.4. Use IFlowerRegistry.registerPlantableFlower instead. + * Completely unused since Forestry 4.0, kept for backward compatibility with older mods. + */ + @Deprecated + public static ArrayList plainFlowers = new ArrayList(); } diff --git a/src/main/java/forestry/api/apiculture/IAlleleBeeEffect.java b/src/main/java/forestry/api/apiculture/IAlleleBeeEffect.java index b2dddb319..cbfa9c5e8 100644 --- a/src/main/java/forestry/api/apiculture/IAlleleBeeEffect.java +++ b/src/main/java/forestry/api/apiculture/IAlleleBeeEffect.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; @@ -9,28 +9,27 @@ import forestry.api.genetics.IAlleleEffect; import forestry.api.genetics.IEffectData; public interface IAlleleBeeEffect extends IAlleleEffect { - - /** - * Called by apiaries to cause an effect in the world. - * - * @param genome - * Genome of the bee queen causing this effect - * @param storedData - * Object containing the stored effect data for the apiary/hive the bee is in. - * @param housing {@link IBeeHousing} the bee currently resides in. - * @return storedData, may have been manipulated. - */ - IEffectData doEffect(IBeeGenome genome, IEffectData storedData, IBeeHousing housing); - /** - * Is called to produce bee effects. - * - * @param genome - * @param storedData - * Object containing the stored effect data for the apiary/hive the bee is in. - * @param housing {@link IBeeHousing} the bee currently resides in. - * @return storedData, may have been manipulated. - */ - IEffectData doFX(IBeeGenome genome, IEffectData storedData, IBeeHousing housing); - + /** + * Called by apiaries to cause an effect in the world. + * + * @param genome + * Genome of the bee queen causing this effect + * @param storedData + * Object containing the stored effect data for the apiary/hive the bee is in. + * @param housing {@link IBeeHousing} the bee currently resides in. + * @return storedData, may have been manipulated. + */ + IEffectData doEffect(IBeeGenome genome, IEffectData storedData, IBeeHousing housing); + + /** + * Is called to produce bee effects. + * + * @param genome + * @param storedData + * Object containing the stored effect data for the apiary/hive the bee is in. + * @param housing {@link IBeeHousing} the bee currently resides in. + * @return storedData, may have been manipulated. + */ + IEffectData doFX(IBeeGenome genome, IEffectData storedData, IBeeHousing housing); } diff --git a/src/main/java/forestry/api/apiculture/IAlleleBeeSpecies.java b/src/main/java/forestry/api/apiculture/IAlleleBeeSpecies.java index 943fff8ad..920d55c8b 100644 --- a/src/main/java/forestry/api/apiculture/IAlleleBeeSpecies.java +++ b/src/main/java/forestry/api/apiculture/IAlleleBeeSpecies.java @@ -5,52 +5,48 @@ ******************************************************************************/ package forestry.api.apiculture; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.genetics.IAlleleSpecies; import java.util.Map; - import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.genetics.IAlleleSpecies; - public interface IAlleleBeeSpecies extends IAlleleSpecies { - /** - * @return the IBeeRoot - */ - IBeeRoot getRoot(); + /** + * @return the IBeeRoot + */ + IBeeRoot getRoot(); - /** - * @return true if this species is only active at night. - */ - boolean isNocturnal(); + /** + * @return true if this species is only active at night. + */ + boolean isNocturnal(); - /** - * @return Map of possible products with the chance for drop each bee cycle. (0 - 1] - */ - Map getProductChances(); + /** + * @return Map of possible products with the chance for drop each bee cycle. (0 - 1] + */ + Map getProductChances(); - /** - * @return Map of possible specialities with the chance for drop each bee cycle. (0 - 1] - */ - Map getSpecialtyChances(); + /** + * @return Map of possible specialities with the chance for drop each bee cycle. (0 - 1] + */ + Map getSpecialtyChances(); - /** - * Only jubilant bees produce specialities. - * @return true if the bee is jubilant, false otherwise. - */ - boolean isJubilant(IBeeGenome genome, IBeeHousing housing); + /** + * Only jubilant bees produce specialities. + * @return true if the bee is jubilant, false otherwise. + */ + boolean isJubilant(IBeeGenome genome, IBeeHousing housing); - @SideOnly(Side.CLIENT) - IIcon getIcon(EnumBeeType type, int renderPass); - - /** - * @deprecated since Forestry 3.6. - * @return Path of the texture to use for entity rendering. - */ - @Deprecated - String getEntityTexture(); + @SideOnly(Side.CLIENT) + IIcon getIcon(EnumBeeType type, int renderPass); + /** + * @deprecated since Forestry 3.6. + * @return Path of the texture to use for entity rendering. + */ + @Deprecated + String getEntityTexture(); } diff --git a/src/main/java/forestry/api/apiculture/IAlleleBeeSpeciesCustom.java b/src/main/java/forestry/api/apiculture/IAlleleBeeSpeciesCustom.java index ef16cb329..bfe70fb81 100644 --- a/src/main/java/forestry/api/apiculture/IAlleleBeeSpeciesCustom.java +++ b/src/main/java/forestry/api/apiculture/IAlleleBeeSpeciesCustom.java @@ -5,39 +5,38 @@ ******************************************************************************/ package forestry.api.apiculture; -import net.minecraft.item.ItemStack; - import forestry.api.genetics.IAlleleSpeciesCustom; +import net.minecraft.item.ItemStack; public interface IAlleleBeeSpeciesCustom extends IAlleleBeeSpecies, IAlleleSpeciesCustom { - /** - * Add a product for this bee species. - * Chance is between 0 and 1. - */ - IAlleleBeeSpeciesCustom addProduct(ItemStack product, Float chance); + /** + * Add a product for this bee species. + * Chance is between 0 and 1. + */ + IAlleleBeeSpeciesCustom addProduct(ItemStack product, Float chance); - /** - * Add a specialty product for this bee species. - * Bees only produce their specialty when they are Jubilant (see IJubilanceProvider) - * Chance is between 0 and 1. - */ - IAlleleBeeSpeciesCustom addSpecialty(ItemStack specialty, Float chance); + /** + * Add a specialty product for this bee species. + * Bees only produce their specialty when they are Jubilant (see IJubilanceProvider) + * Chance is between 0 and 1. + */ + IAlleleBeeSpeciesCustom addSpecialty(ItemStack specialty, Float chance); - /** - * Set the Jubilance Provider for this bee species. - * Bees only produce their specialty when they are Jubilant (see IJubilanceProvider) - */ - IAlleleBeeSpeciesCustom setJubilanceProvider(IJubilanceProvider provider); + /** + * Set the Jubilance Provider for this bee species. + * Bees only produce their specialty when they are Jubilant (see IJubilanceProvider) + */ + IAlleleBeeSpeciesCustom setJubilanceProvider(IJubilanceProvider provider); - /** - * Make this species only active at night. - */ - IAlleleBeeSpeciesCustom setNocturnal(); + /** + * Make this species only active at night. + */ + IAlleleBeeSpeciesCustom setNocturnal(); - /** Use this if you have custom icons for bees. */ - IAlleleBeeSpeciesCustom setCustomBeeIconProvider(IBeeIconProvider beeIconProvider); + /** Use this if you have custom icons for bees. */ + IAlleleBeeSpeciesCustom setCustomBeeIconProvider(IBeeIconProvider beeIconProvider); - /** Use this if you have custom icon colours for bees (other than the default static primary + secondary colours). */ - IAlleleBeeSpeciesCustom setCustomBeeIconColourProvider(IBeeIconColourProvider beeIconColourProvider); + /** Use this if you have custom icon colours for bees (other than the default static primary + secondary colours). */ + IAlleleBeeSpeciesCustom setCustomBeeIconColourProvider(IBeeIconColourProvider beeIconColourProvider); } diff --git a/src/main/java/forestry/api/apiculture/IApiaristTracker.java b/src/main/java/forestry/api/apiculture/IApiaristTracker.java index 0c65f56be..77a76fcc6 100644 --- a/src/main/java/forestry/api/apiculture/IApiaristTracker.java +++ b/src/main/java/forestry/api/apiculture/IApiaristTracker.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; @@ -10,48 +10,47 @@ import forestry.api.genetics.IIndividual; /** * Can be used to garner information on bee breeding. See {@link forestry.api.genetics.ISpeciesRoot} for retrieval functions. - * + * * @author SirSengir */ public interface IApiaristTracker extends IBreedingTracker { - /** - * Register the birth of a queen. Will mark species as discovered. - * - * @param queen - * Created queen. - */ - void registerQueen(IIndividual queen); + /** + * Register the birth of a queen. Will mark species as discovered. + * + * @param queen + * Created queen. + */ + void registerQueen(IIndividual queen); - /** - * @return Amount of queens bred with this tracker. - */ - int getQueenCount(); + /** + * @return Amount of queens bred with this tracker. + */ + int getQueenCount(); - /** - * Register the birth of a princess. Will mark species as discovered. - * - * @param princess - * Created princess. - */ - void registerPrincess(IIndividual princess); + /** + * Register the birth of a princess. Will mark species as discovered. + * + * @param princess + * Created princess. + */ + void registerPrincess(IIndividual princess); - /** - * @return Amount of princesses bred with this tracker. - */ - int getPrincessCount(); + /** + * @return Amount of princesses bred with this tracker. + */ + int getPrincessCount(); - /** - * Register the birth of a drone. Will mark species as discovered. - * - * @param drone - * Created drone. - */ - void registerDrone(IIndividual drone); - - /** - * @return Amount of drones bred with this tracker. - */ - int getDroneCount(); + /** + * Register the birth of a drone. Will mark species as discovered. + * + * @param drone + * Created drone. + */ + void registerDrone(IIndividual drone); + /** + * @return Amount of drones bred with this tracker. + */ + int getDroneCount(); } diff --git a/src/main/java/forestry/api/apiculture/IArmorApiarist.java b/src/main/java/forestry/api/apiculture/IArmorApiarist.java index ef87163ef..1d9b4ef48 100644 --- a/src/main/java/forestry/api/apiculture/IArmorApiarist.java +++ b/src/main/java/forestry/api/apiculture/IArmorApiarist.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; @@ -13,27 +13,27 @@ import net.minecraft.item.ItemStack; * When implemented by armor piece items, allows them to act as apiarist's armor. */ public interface IArmorApiarist { - /** - * Called when the apiarist's armor acts as protection against an attack. - * - * @param entity Entity being attacked - * @param armor Armor item - * @param cause Optional cause of attack, such as a bee effect identifier - * @param doProtect Whether or not to actually do the side effects of protection - * @return Whether or not the armor should protect the player from that attack - */ - boolean protectEntity(EntityLivingBase entity, ItemStack armor, String cause, boolean doProtect); + /** + * Called when the apiarist's armor acts as protection against an attack. + * + * @param entity Entity being attacked + * @param armor Armor item + * @param cause Optional cause of attack, such as a bee effect identifier + * @param doProtect Whether or not to actually do the side effects of protection + * @return Whether or not the armor should protect the player from that attack + */ + boolean protectEntity(EntityLivingBase entity, ItemStack armor, String cause, boolean doProtect); - /** - * Called when the apiarist's armor acts as protection against an attack. - * - * @param player Player being attacked - * @param armor Armor item - * @param cause Optional cause of attack, such as a bee effect identifier - * @param doProtect Whether or not to actually do the side effects of protection - * @return Whether or not the armor should protect the player from that attack - * @deprecated since Forestry 4.2. Use protectEntity - */ - @Deprecated - public boolean protectPlayer(EntityPlayer player, ItemStack armor, String cause, boolean doProtect); + /** + * Called when the apiarist's armor acts as protection against an attack. + * + * @param player Player being attacked + * @param armor Armor item + * @param cause Optional cause of attack, such as a bee effect identifier + * @param doProtect Whether or not to actually do the side effects of protection + * @return Whether or not the armor should protect the player from that attack + * @deprecated since Forestry 4.2. Use protectEntity + */ + @Deprecated + public boolean protectPlayer(EntityPlayer player, ItemStack armor, String cause, boolean doProtect); } diff --git a/src/main/java/forestry/api/apiculture/IArmorApiaristHelper.java b/src/main/java/forestry/api/apiculture/IArmorApiaristHelper.java index b0f652f0d..4238f2b24 100644 --- a/src/main/java/forestry/api/apiculture/IArmorApiaristHelper.java +++ b/src/main/java/forestry/api/apiculture/IArmorApiaristHelper.java @@ -16,47 +16,47 @@ import net.minecraft.item.ItemStack; */ public interface IArmorApiaristHelper { - /** - * Called when the apiarist's armor acts as protection against an attack. - * @param stack ItemStack to check - * @param entity Entity being attacked - * @param cause Optional cause of attack, such as a bee effect identifier - * @param doProtect Whether or not to actually do the side effects of protection - * @return Whether or not the item is valid Apiarist Armor and should protect the player from that attack - * @since Forestry 4.2 - */ - boolean isArmorApiarist(ItemStack stack, EntityLivingBase entity, String cause, boolean doProtect); + /** + * Called when the apiarist's armor acts as protection against an attack. + * @param stack ItemStack to check + * @param entity Entity being attacked + * @param cause Optional cause of attack, such as a bee effect identifier + * @param doProtect Whether or not to actually do the side effects of protection + * @return Whether or not the item is valid Apiarist Armor and should protect the player from that attack + * @since Forestry 4.2 + */ + boolean isArmorApiarist(ItemStack stack, EntityLivingBase entity, String cause, boolean doProtect); - /** - * Called when the apiarist's armor acts as protection against an attack. - * @param entity Entity being attacked - * @param cause Optional cause of attack, such as a bee effect identifier - * @param doProtect Whether or not to actually do the side effects of protection - * @return The number of valid Apiarist Armor pieces the player is wearing that are actually protecting - * @since Forestry 4.2 - */ - int wearsItems(EntityLivingBase entity, String cause, boolean doProtect); + /** + * Called when the apiarist's armor acts as protection against an attack. + * @param entity Entity being attacked + * @param cause Optional cause of attack, such as a bee effect identifier + * @param doProtect Whether or not to actually do the side effects of protection + * @return The number of valid Apiarist Armor pieces the player is wearing that are actually protecting + * @since Forestry 4.2 + */ + int wearsItems(EntityLivingBase entity, String cause, boolean doProtect); - /** - * Called when the apiarist's armor acts as protection against an attack. - * @param stack ItemStack to check - * @param player Player being attacked - * @param cause Optional cause of attack, such as a bee effect identifier - * @param doProtect Whether or not to actually do the side effects of protection - * @return Whether or not the item is valid Apiarist Armor and should protect the player from that attack - * @deprecated since Forestry 4.2. use the EntityLivingBase version - */ - @Deprecated - boolean isArmorApiarist(ItemStack stack, EntityPlayer player, String cause, boolean doProtect); + /** + * Called when the apiarist's armor acts as protection against an attack. + * @param stack ItemStack to check + * @param player Player being attacked + * @param cause Optional cause of attack, such as a bee effect identifier + * @param doProtect Whether or not to actually do the side effects of protection + * @return Whether or not the item is valid Apiarist Armor and should protect the player from that attack + * @deprecated since Forestry 4.2. use the EntityLivingBase version + */ + @Deprecated + boolean isArmorApiarist(ItemStack stack, EntityPlayer player, String cause, boolean doProtect); - /** - * Called when the apiarist's armor acts as protection against an attack. - * @param player Player being attacked - * @param cause Optional cause of attack, such as a bee effect identifier - * @param doProtect Whether or not to actually do the side effects of protection - * @return The number of valid Apiarist Armor pieces the player is wearing that are actually protecting - * @deprecated since Forestry 4.2. use the EntityLivingBase version - */ - @Deprecated - int wearsItems(EntityPlayer player, String cause, boolean doProtect); + /** + * Called when the apiarist's armor acts as protection against an attack. + * @param player Player being attacked + * @param cause Optional cause of attack, such as a bee effect identifier + * @param doProtect Whether or not to actually do the side effects of protection + * @return The number of valid Apiarist Armor pieces the player is wearing that are actually protecting + * @deprecated since Forestry 4.2. use the EntityLivingBase version + */ + @Deprecated + int wearsItems(EntityPlayer player, String cause, boolean doProtect); } diff --git a/src/main/java/forestry/api/apiculture/IBee.java b/src/main/java/forestry/api/apiculture/IBee.java index 19a496a65..7d5fd84cb 100644 --- a/src/main/java/forestry/api/apiculture/IBee.java +++ b/src/main/java/forestry/api/apiculture/IBee.java @@ -1,86 +1,83 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; -import java.util.List; -import java.util.Set; - -import net.minecraft.item.ItemStack; -import net.minecraft.world.biome.BiomeGenBase; - import forestry.api.core.IErrorState; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IIndividual; import forestry.api.genetics.IIndividualLiving; +import java.util.List; +import java.util.Set; +import net.minecraft.item.ItemStack; +import net.minecraft.world.biome.BiomeGenBase; /** * Other implementations than Forestry's default one are not supported. - * + * * @author SirSengir */ public interface IBee extends IIndividualLiving { - /** - * @return Bee's genetic information. - */ - IBeeGenome getGenome(); + /** + * @return Bee's genetic information. + */ + IBeeGenome getGenome(); - /** - * @return Genetic information of the bee's mate, null if unmated. - */ - IBeeGenome getMate(); + /** + * @return Genetic information of the bee's mate, null if unmated. + */ + IBeeGenome getMate(); - /** - * @return true if the individual is originally of natural origin. - */ - boolean isNatural(); + /** + * @return true if the individual is originally of natural origin. + */ + boolean isNatural(); - /** - * @return generation this individual is removed from the original individual. - */ - int getGeneration(); + /** + * @return generation this individual is removed from the original individual. + */ + int getGeneration(); - /** - * Set the natural flag on this bee. - * @param flag - */ - void setIsNatural(boolean flag); + /** + * Set the natural flag on this bee. + * @param flag + */ + void setIsNatural(boolean flag); - IEffectData[] doEffect(IEffectData[] storedData, IBeeHousing housing); + IEffectData[] doEffect(IEffectData[] storedData, IBeeHousing housing); - IEffectData[] doFX(IEffectData[] storedData, IBeeHousing housing); + IEffectData[] doFX(IEffectData[] storedData, IBeeHousing housing); - /** - * @return true if the bee may spawn offspring - */ - boolean canSpawn(); + /** + * @return true if the bee may spawn offspring + */ + boolean canSpawn(); - /** - * Determines whether the queen can work. - * @param housing the {@link IBeeHousing} the bee currently resides in. - * @return an empty set if the queen can work, a set of error states if the queen can not work - */ - Set getCanWork(IBeeHousing housing); + /** + * Determines whether the queen can work. + * @param housing the {@link IBeeHousing} the bee currently resides in. + * @return an empty set if the queen can work, a set of error states if the queen can not work + */ + Set getCanWork(IBeeHousing housing); - List getSuitableBiomes(); + List getSuitableBiomes(); - ItemStack[] getProduceList(); + ItemStack[] getProduceList(); - ItemStack[] getSpecialtyList(); + ItemStack[] getSpecialtyList(); - ItemStack[] produceStacks(IBeeHousing housing); + ItemStack[] produceStacks(IBeeHousing housing); - IBee spawnPrincess(IBeeHousing housing); + IBee spawnPrincess(IBeeHousing housing); - IBee[] spawnDrones(IBeeHousing housing); + IBee[] spawnDrones(IBeeHousing housing); - void plantFlowerRandom(IBeeHousing housing); + void plantFlowerRandom(IBeeHousing housing); - IIndividual retrievePollen(IBeeHousing housing); - - boolean pollinateRandom(IBeeHousing housing, IIndividual pollen); + IIndividual retrievePollen(IBeeHousing housing); + boolean pollinateRandom(IBeeHousing housing, IIndividual pollen); } diff --git a/src/main/java/forestry/api/apiculture/IBeeFactory.java b/src/main/java/forestry/api/apiculture/IBeeFactory.java index c164731ce..515466ea4 100644 --- a/src/main/java/forestry/api/apiculture/IBeeFactory.java +++ b/src/main/java/forestry/api/apiculture/IBeeFactory.java @@ -9,31 +9,40 @@ import forestry.api.genetics.IClassification; public interface IBeeFactory { - /** - * Creates a new bee species. - * Automatically registered with AlleleManager.alleleRegistry.registerAllele() - * See IAlleleBeeSpeciesCustom and IAlleleSpeciesCustom for adding additional properties to the returned species. - * - * @param uid Unique Identifier for this species - * @param dominant Whether this species is genetically dominant (false means it is recessive) - * @param authority Authority for the binomial name, e.g. "Sengir" on species of base Forestry. - * @param unlocalizedName Unlocalized name for this species - * @param unlocalizedDescription Unlocalized description for this species - * @param branch Classification of this species - * @param binomial Binomial name of the species sans genus ("Apis"). "humboldti" will have the bee species flavour name be "Apis humboldti". Feel free to use fun names or null. - * @param primaryColor The outline color of this species - * @param secondaryColor The body color of this species - * @return a new bee species allele. - */ - IAlleleBeeSpeciesCustom createSpecies(String uid, boolean dominant, String authority, String unlocalizedName, String unlocalizedDescription, IClassification branch, String binomial, int primaryColor, int secondaryColor); + /** + * Creates a new bee species. + * Automatically registered with AlleleManager.alleleRegistry.registerAllele() + * See IAlleleBeeSpeciesCustom and IAlleleSpeciesCustom for adding additional properties to the returned species. + * + * @param uid Unique Identifier for this species + * @param dominant Whether this species is genetically dominant (false means it is recessive) + * @param authority Authority for the binomial name, e.g. "Sengir" on species of base Forestry. + * @param unlocalizedName Unlocalized name for this species + * @param unlocalizedDescription Unlocalized description for this species + * @param branch Classification of this species + * @param binomial Binomial name of the species sans genus ("Apis"). "humboldti" will have the bee species flavour name be "Apis humboldti". Feel free to use fun names or null. + * @param primaryColor The outline color of this species + * @param secondaryColor The body color of this species + * @return a new bee species allele. + */ + IAlleleBeeSpeciesCustom createSpecies( + String uid, + boolean dominant, + String authority, + String unlocalizedName, + String unlocalizedDescription, + IClassification branch, + String binomial, + int primaryColor, + int secondaryColor); - /** - * Creates a new bee branch. - * Must be registered with AlleleManager.alleleRegistry.getClassification("family.apidae").addMemberGroup(); - * - * @param uid Unique Identifier for this branch - * @param scientific approximates a "genus" in real life. Real life examples: "Micrapis", "Megapis" - * @return a new bee branch - */ - IClassification createBranch(String uid, String scientific); + /** + * Creates a new bee branch. + * Must be registered with AlleleManager.alleleRegistry.getClassification("family.apidae").addMemberGroup(); + * + * @param uid Unique Identifier for this branch + * @param scientific approximates a "genus" in real life. Real life examples: "Micrapis", "Megapis" + * @return a new bee branch + */ + IClassification createBranch(String uid, String scientific); } diff --git a/src/main/java/forestry/api/apiculture/IBeeGenome.java b/src/main/java/forestry/api/apiculture/IBeeGenome.java index 642eeeb5c..ba63e8242 100644 --- a/src/main/java/forestry/api/apiculture/IBeeGenome.java +++ b/src/main/java/forestry/api/apiculture/IBeeGenome.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; @@ -11,38 +11,37 @@ import forestry.api.genetics.IGenome; /** * Only the default implementation is supported. - * + * * @author SirSengir - * + * */ public interface IBeeGenome extends IGenome { - IAlleleBeeSpecies getPrimary(); - - IAlleleBeeSpecies getSecondary(); + IAlleleBeeSpecies getPrimary(); - float getSpeed(); + IAlleleBeeSpecies getSecondary(); - int getLifespan(); + float getSpeed(); - int getFertility(); + int getLifespan(); - EnumTolerance getToleranceTemp(); + int getFertility(); - EnumTolerance getToleranceHumid(); + EnumTolerance getToleranceTemp(); - boolean getNocturnal(); + EnumTolerance getToleranceHumid(); - boolean getTolerantFlyer(); + boolean getNocturnal(); - boolean getCaveDwelling(); + boolean getTolerantFlyer(); - IFlowerProvider getFlowerProvider(); + boolean getCaveDwelling(); - int getFlowering(); + IFlowerProvider getFlowerProvider(); - int[] getTerritory(); + int getFlowering(); - IAlleleBeeEffect getEffect(); + int[] getTerritory(); + IAlleleBeeEffect getEffect(); } diff --git a/src/main/java/forestry/api/apiculture/IBeeHousing.java b/src/main/java/forestry/api/apiculture/IBeeHousing.java index 99813813f..fb0c182d2 100644 --- a/src/main/java/forestry/api/apiculture/IBeeHousing.java +++ b/src/main/java/forestry/api/apiculture/IBeeHousing.java @@ -1,47 +1,48 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import forestry.api.core.IClimateProvider; import forestry.api.core.IErrorLogicSource; import forestry.api.genetics.IHousing; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; public interface IBeeHousing extends IHousing, IClimateProvider, IErrorLogicSource { - /** - * Used by BeeManager.beeRoot.createBeeHousingModifier(IBeeHousing housing) - * to combine bee modifiers from several sources that can change over time. - * @return IBeeModifiers from the housing, frames, etc. - */ - Iterable getBeeModifiers(); + /** + * Used by BeeManager.beeRoot.createBeeHousingModifier(IBeeHousing housing) + * to combine bee modifiers from several sources that can change over time. + * @return IBeeModifiers from the housing, frames, etc. + */ + Iterable getBeeModifiers(); - /** - * Used by BeeManager.beeRoot.createBeeHousingListener(IBeeHousing housing) - * to combine bee listeners from several sources that can change over time. - * @return IBeeListeners from the housing, multiblock parts, etc. - */ - Iterable getBeeListeners(); + /** + * Used by BeeManager.beeRoot.createBeeHousingListener(IBeeHousing housing) + * to combine bee listeners from several sources that can change over time. + * @return IBeeListeners from the housing, multiblock parts, etc. + */ + Iterable getBeeListeners(); - IBeeHousingInventory getBeeInventory(); - IBeekeepingLogic getBeekeepingLogic(); + IBeeHousingInventory getBeeInventory(); - int getBlockLightValue(); - boolean canBlockSeeTheSky(); + IBeekeepingLogic getBeekeepingLogic(); - World getWorld(); - GameProfile getOwner(); + int getBlockLightValue(); - /** - * @since Forestry 4.2 - * @return exact coordinates where bee FX should spawn from - */ - Vec3 getBeeFXCoordinates(); + boolean canBlockSeeTheSky(); + + World getWorld(); + + GameProfile getOwner(); + + /** + * @since Forestry 4.2 + * @return exact coordinates where bee FX should spawn from + */ + Vec3 getBeeFXCoordinates(); } diff --git a/src/main/java/forestry/api/apiculture/IBeeHousingInventory.java b/src/main/java/forestry/api/apiculture/IBeeHousingInventory.java index c579a19f7..90f9a4102 100644 --- a/src/main/java/forestry/api/apiculture/IBeeHousingInventory.java +++ b/src/main/java/forestry/api/apiculture/IBeeHousingInventory.java @@ -9,18 +9,20 @@ import net.minecraft.item.ItemStack; public interface IBeeHousingInventory { - ItemStack getQueen(); - ItemStack getDrone(); + ItemStack getQueen(); - void setQueen(ItemStack itemstack); - void setDrone(ItemStack itemstack); + ItemStack getDrone(); - /** - * Adds products to the housing's inventory. - * - * @param product ItemStack with the product to add. - * @param all if true, success requires that all products are added - * @return boolean indicating success or failure. - */ - boolean addProduct(ItemStack product, boolean all); + void setQueen(ItemStack itemstack); + + void setDrone(ItemStack itemstack); + + /** + * Adds products to the housing's inventory. + * + * @param product ItemStack with the product to add. + * @param all if true, success requires that all products are added + * @return boolean indicating success or failure. + */ + boolean addProduct(ItemStack product, boolean all); } diff --git a/src/main/java/forestry/api/apiculture/IBeeIconColourProvider.java b/src/main/java/forestry/api/apiculture/IBeeIconColourProvider.java index 5e7e83af4..a663e9c5a 100644 --- a/src/main/java/forestry/api/apiculture/IBeeIconColourProvider.java +++ b/src/main/java/forestry/api/apiculture/IBeeIconColourProvider.java @@ -9,5 +9,5 @@ package forestry.api.apiculture; * Custom colour provider for bees with complicated colors. */ public interface IBeeIconColourProvider { - int getIconColour(int renderPass); + int getIconColour(int renderPass); } diff --git a/src/main/java/forestry/api/apiculture/IBeeIconProvider.java b/src/main/java/forestry/api/apiculture/IBeeIconProvider.java index d29a722b0..1424a0929 100644 --- a/src/main/java/forestry/api/apiculture/IBeeIconProvider.java +++ b/src/main/java/forestry/api/apiculture/IBeeIconProvider.java @@ -9,6 +9,7 @@ import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.util.IIcon; public interface IBeeIconProvider { - void registerIcons(IIconRegister register); - IIcon getIcon(EnumBeeType type, int renderPass); + void registerIcons(IIconRegister register); + + IIcon getIcon(EnumBeeType type, int renderPass); } diff --git a/src/main/java/forestry/api/apiculture/IBeeListener.java b/src/main/java/forestry/api/apiculture/IBeeListener.java index eaab40af2..8e9e9bcfa 100644 --- a/src/main/java/forestry/api/apiculture/IBeeListener.java +++ b/src/main/java/forestry/api/apiculture/IBeeListener.java @@ -9,21 +9,20 @@ import forestry.api.genetics.IIndividual; public interface IBeeListener { - /** - * Called when the bees wear out the housing's equipment. - * @param amount Integer indicating the amount worn out. - */ - void wearOutEquipment(int amount); + /** + * Called when the bees wear out the housing's equipment. + * @param amount Integer indicating the amount worn out. + */ + void wearOutEquipment(int amount); - /** - * Called after the children have been spawned, and before the new princess is spawned. - */ - void onQueenDeath(); - - /** - * Called when the bees have retrieved some pollen. - * @return true if this bee listener handled the pollen. - */ - boolean onPollenRetrieved(IIndividual pollen); + /** + * Called after the children have been spawned, and before the new princess is spawned. + */ + void onQueenDeath(); + /** + * Called when the bees have retrieved some pollen. + * @return true if this bee listener handled the pollen. + */ + boolean onPollenRetrieved(IIndividual pollen); } diff --git a/src/main/java/forestry/api/apiculture/IBeeModifier.java b/src/main/java/forestry/api/apiculture/IBeeModifier.java index 134f441d2..5185848d2 100644 --- a/src/main/java/forestry/api/apiculture/IBeeModifier.java +++ b/src/main/java/forestry/api/apiculture/IBeeModifier.java @@ -6,65 +6,64 @@ package forestry.api.apiculture; public interface IBeeModifier { - /** - * @param genome Genome of the bee this modifier is called for. - * @param currentModifier Current modifier. - * @return Float used to modify the base territory. - */ - float getTerritoryModifier(IBeeGenome genome, float currentModifier); + /** + * @param genome Genome of the bee this modifier is called for. + * @param currentModifier Current modifier. + * @return Float used to modify the base territory. + */ + float getTerritoryModifier(IBeeGenome genome, float currentModifier); - /** - * @param genome Genome of the bee this modifier is called for. - * @param mate Genome of the bee mate this modifier is called for. - * @param currentModifier Current modifier. - * @return Float used to modify the base mutation chance. - */ - float getMutationModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier); + /** + * @param genome Genome of the bee this modifier is called for. + * @param mate Genome of the bee mate this modifier is called for. + * @param currentModifier Current modifier. + * @return Float used to modify the base mutation chance. + */ + float getMutationModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier); - /** - * @param genome Genome of the bee this modifier is called for. - * @param currentModifier Current modifier. - * @return Float used to modify the life span of queens. - */ - float getLifespanModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier); + /** + * @param genome Genome of the bee this modifier is called for. + * @param currentModifier Current modifier. + * @return Float used to modify the life span of queens. + */ + float getLifespanModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier); - /** - * @param genome Genome of the bee this modifier is called for. - * @param currentModifier Current modifier. - * @return Float modifying the production speed of queens. - */ - float getProductionModifier(IBeeGenome genome, float currentModifier); + /** + * @param genome Genome of the bee this modifier is called for. + * @param currentModifier Current modifier. + * @return Float modifying the production speed of queens. + */ + float getProductionModifier(IBeeGenome genome, float currentModifier); - /** - * @param genome Genome of the bee this modifier is called for. - * @return Float modifying the flowering of queens. - */ - float getFloweringModifier(IBeeGenome genome, float currentModifier); + /** + * @param genome Genome of the bee this modifier is called for. + * @return Float modifying the flowering of queens. + */ + float getFloweringModifier(IBeeGenome genome, float currentModifier); - /** - * @param genome Genome of the bee this modifier is called for. - * @return Float modifying the chance for a swarmer queen to die off. - */ - float getGeneticDecay(IBeeGenome genome, float currentModifier); + /** + * @param genome Genome of the bee this modifier is called for. + * @return Float modifying the chance for a swarmer queen to die off. + */ + float getGeneticDecay(IBeeGenome genome, float currentModifier); - /** - * @return Boolean indicating if housing can ignore rain - */ - boolean isSealed(); + /** + * @return Boolean indicating if housing can ignore rain + */ + boolean isSealed(); - /** - * @return Boolean indicating if housing can ignore darkness/night - */ - boolean isSelfLighted(); + /** + * @return Boolean indicating if housing can ignore darkness/night + */ + boolean isSelfLighted(); - /** - * @return Boolean indicating if housing can ignore not seeing the sky - */ - boolean isSunlightSimulated(); - - /** - * @return Boolean indicating whether this housing simulates the nether - */ - boolean isHellish(); + /** + * @return Boolean indicating if housing can ignore not seeing the sky + */ + boolean isSunlightSimulated(); + /** + * @return Boolean indicating whether this housing simulates the nether + */ + boolean isHellish(); } diff --git a/src/main/java/forestry/api/apiculture/IBeeMutation.java b/src/main/java/forestry/api/apiculture/IBeeMutation.java index bdbc710d5..38bfbf81f 100644 --- a/src/main/java/forestry/api/apiculture/IBeeMutation.java +++ b/src/main/java/forestry/api/apiculture/IBeeMutation.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; @@ -8,11 +8,16 @@ package forestry.api.apiculture; import forestry.api.genetics.IMutation; public interface IBeeMutation extends IMutation { - - IBeeRoot getRoot(); - - /** - * @return float representing the chance for mutation to occur. note that this is 0 - 100 based, since it was an integer previously! - */ - float getChance(IBeeHousing housing, IAlleleBeeSpecies allele0, IAlleleBeeSpecies allele1, IBeeGenome genome0, IBeeGenome genome1); + + IBeeRoot getRoot(); + + /** + * @return float representing the chance for mutation to occur. note that this is 0 - 100 based, since it was an integer previously! + */ + float getChance( + IBeeHousing housing, + IAlleleBeeSpecies allele0, + IAlleleBeeSpecies allele1, + IBeeGenome genome0, + IBeeGenome genome1); } diff --git a/src/main/java/forestry/api/apiculture/IBeeMutationCustom.java b/src/main/java/forestry/api/apiculture/IBeeMutationCustom.java index d97a839a1..22b60129d 100644 --- a/src/main/java/forestry/api/apiculture/IBeeMutationCustom.java +++ b/src/main/java/forestry/api/apiculture/IBeeMutationCustom.java @@ -7,6 +7,4 @@ package forestry.api.apiculture; import forestry.api.genetics.IMutationCustom; -public interface IBeeMutationCustom extends IBeeMutation, IMutationCustom { - -} +public interface IBeeMutationCustom extends IBeeMutation, IMutationCustom {} diff --git a/src/main/java/forestry/api/apiculture/IBeeMutationFactory.java b/src/main/java/forestry/api/apiculture/IBeeMutationFactory.java index 315a4c6f1..dd9f1c864 100644 --- a/src/main/java/forestry/api/apiculture/IBeeMutationFactory.java +++ b/src/main/java/forestry/api/apiculture/IBeeMutationFactory.java @@ -8,16 +8,17 @@ package forestry.api.apiculture; import forestry.api.genetics.IAllele; public interface IBeeMutationFactory { - /** - * Creates a new bee mutation. - * Automatically registered with BeeManager.beeRoot.registerMutation() - * See IBeeMutationCustom and IMutationCustom for adding additional properties to the returned mutation. - * - * @param parentBee0 A parent bee for this mutation - * @param parentBee1 A parent bee for this mutation - * @param result The resulting alleles for this mutation - * @param chance The chance that breeding the two parent bees will result in this mutation - * @return a new bee mutation. - */ - IBeeMutationCustom createMutation(IAlleleBeeSpecies parentBee0, IAlleleBeeSpecies parentBee1, IAllele[] result, int chance); + /** + * Creates a new bee mutation. + * Automatically registered with BeeManager.beeRoot.registerMutation() + * See IBeeMutationCustom and IMutationCustom for adding additional properties to the returned mutation. + * + * @param parentBee0 A parent bee for this mutation + * @param parentBee1 A parent bee for this mutation + * @param result The resulting alleles for this mutation + * @param chance The chance that breeding the two parent bees will result in this mutation + * @return a new bee mutation. + */ + IBeeMutationCustom createMutation( + IAlleleBeeSpecies parentBee0, IAlleleBeeSpecies parentBee1, IAllele[] result, int chance); } diff --git a/src/main/java/forestry/api/apiculture/IBeeRoot.java b/src/main/java/forestry/api/apiculture/IBeeRoot.java index fc99f545f..0e1480030 100644 --- a/src/main/java/forestry/api/apiculture/IBeeRoot.java +++ b/src/main/java/forestry/api/apiculture/IBeeRoot.java @@ -1,132 +1,128 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; +import com.mojang.authlib.GameProfile; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.ISpeciesRoot; import java.util.ArrayList; import java.util.Collection; - import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import com.mojang.authlib.GameProfile; - -import forestry.api.genetics.IAllele; -import forestry.api.genetics.ISpeciesRoot; - public interface IBeeRoot extends ISpeciesRoot { - /** - * @return true if passed item is a Forestry bee. Equal to getType(ItemStack stack) != EnumBeeType.NONE - */ - @Override - boolean isMember(ItemStack stack); + /** + * @return true if passed item is a Forestry bee. Equal to getType(ItemStack stack) != EnumBeeType.NONE + */ + @Override + boolean isMember(ItemStack stack); - /** - * @return {@link IBee} pattern parsed from the passed stack's nbt data. - */ - @Override - IBee getMember(ItemStack stack); + /** + * @return {@link IBee} pattern parsed from the passed stack's nbt data. + */ + @Override + IBee getMember(ItemStack stack); - @Override - IBee getMember(NBTTagCompound compound); + @Override + IBee getMember(NBTTagCompound compound); - /* GENOME CONVERSION */ - @Override - IBee templateAsIndividual(IAllele[] template); + /* GENOME CONVERSION */ + @Override + IBee templateAsIndividual(IAllele[] template); - @Override - IBee templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive); + @Override + IBee templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive); - @Override - IBeeGenome templateAsGenome(IAllele[] template); + @Override + IBeeGenome templateAsGenome(IAllele[] template); - @Override - IBeeGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive); + @Override + IBeeGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive); - /* BREEDING TRACKER */ - /** - * @param world - * @return {@link IApiaristTracker} associated with the passed world. - */ - IApiaristTracker getBreedingTracker(World world, GameProfile player); + /* BREEDING TRACKER */ + /** + * @param world + * @return {@link IApiaristTracker} associated with the passed world. + */ + IApiaristTracker getBreedingTracker(World world, GameProfile player); - /* BEE SPECIFIC */ - /** - * @return type of bee encoded on the itemstack. EnumBeeType.NONE if it isn't a bee. - */ - @Override - EnumBeeType getType(ItemStack stack); + /* BEE SPECIFIC */ + /** + * @return type of bee encoded on the itemstack. EnumBeeType.NONE if it isn't a bee. + */ + @Override + EnumBeeType getType(ItemStack stack); - /** - * @return true if passed item is a drone. Equal to getType(ItemStack stack) == EnumBeeType.DRONE - */ - boolean isDrone(ItemStack stack); + /** + * @return true if passed item is a drone. Equal to getType(ItemStack stack) == EnumBeeType.DRONE + */ + boolean isDrone(ItemStack stack); - /** - * @return true if passed item is mated (i.e. a queen) - */ - boolean isMated(ItemStack stack); + /** + * @return true if passed item is mated (i.e. a queen) + */ + boolean isMated(ItemStack stack); - /** - * @param genome - * Valid {@link IBeeGenome} - * @return {@link IBee} from the passed genome - */ - IBee getBee(World world, IBeeGenome genome); + /** + * @param genome + * Valid {@link IBeeGenome} + * @return {@link IBee} from the passed genome + */ + IBee getBee(World world, IBeeGenome genome); - /** - * Creates an IBee suitable for a queen containing the necessary second genome for the mate. - * - * @param genome - * Valid {@link IBeeGenome} - * @param mate - * Valid {@link IBee} representing the mate. - * @return Mated {@link IBee} from the passed genomes. - */ - IBee getBee(World world, IBeeGenome genome, IBee mate); + /** + * Creates an IBee suitable for a queen containing the necessary second genome for the mate. + * + * @param genome + * Valid {@link IBeeGenome} + * @param mate + * Valid {@link IBee} representing the mate. + * @return Mated {@link IBee} from the passed genomes. + */ + IBee getBee(World world, IBeeGenome genome, IBee mate); - /* TEMPLATES */ - @Override - ArrayList getIndividualTemplates(); + /* TEMPLATES */ + @Override + ArrayList getIndividualTemplates(); - /* MUTATIONS */ - @Override - Collection getMutations(boolean shuffle); + /* MUTATIONS */ + @Override + Collection getMutations(boolean shuffle); - /* GAME MODE */ - void resetBeekeepingMode(); + /* GAME MODE */ + void resetBeekeepingMode(); - ArrayList getBeekeepingModes(); + ArrayList getBeekeepingModes(); - IBeekeepingMode getBeekeepingMode(World world); + IBeekeepingMode getBeekeepingMode(World world); - IBeekeepingMode getBeekeepingMode(String name); + IBeekeepingMode getBeekeepingMode(String name); - void registerBeekeepingMode(IBeekeepingMode mode); + void registerBeekeepingMode(IBeekeepingMode mode); - void setBeekeepingMode(World world, String name); + void setBeekeepingMode(World world, String name); - /* MISC */ - /** - * Creates beekeepingLogic for a housing. - * Should be used when the housing is created, see IBeekeepingLogic - */ - IBeekeepingLogic createBeekeepingLogic(IBeeHousing housing); + /* MISC */ + /** + * Creates beekeepingLogic for a housing. + * Should be used when the housing is created, see IBeekeepingLogic + */ + IBeekeepingLogic createBeekeepingLogic(IBeeHousing housing); - /** - * Combines multiple modifiers from an IBeeHousing into one. - * Stays up to date with changes to the housing's modifiers. - */ - IBeeModifier createBeeHousingModifier(IBeeHousing housing); - - /** - * Combines multiple listeners from an IBeeHousing into one. - * Stays up to date with changes to the housing's listeners. - */ - IBeeListener createBeeHousingListener(IBeeHousing housing); + /** + * Combines multiple modifiers from an IBeeHousing into one. + * Stays up to date with changes to the housing's modifiers. + */ + IBeeModifier createBeeHousingModifier(IBeeHousing housing); + /** + * Combines multiple listeners from an IBeeHousing into one. + * Stays up to date with changes to the housing's listeners. + */ + IBeeListener createBeeHousingListener(IBeeHousing housing); } diff --git a/src/main/java/forestry/api/apiculture/IBeekeepingLogic.java b/src/main/java/forestry/api/apiculture/IBeekeepingLogic.java index d591c4b3c..a28972c5c 100644 --- a/src/main/java/forestry/api/apiculture/IBeekeepingLogic.java +++ b/src/main/java/forestry/api/apiculture/IBeekeepingLogic.java @@ -1,13 +1,12 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; -import net.minecraft.entity.player.EntityPlayerMP; - import forestry.api.core.INBTTagable; +import net.minecraft.entity.player.EntityPlayerMP; /** * Stores beekeeping logic for bee housings. @@ -16,46 +15,45 @@ import forestry.api.core.INBTTagable; */ public interface IBeekeepingLogic extends INBTTagable { - /* SERVER */ + /* SERVER */ - /** - * Checks that the bees can work, setting error conditions on the housing where needed - * @return true if no errors are present and doWork should be called - */ - boolean canWork(); + /** + * Checks that the bees can work, setting error conditions on the housing where needed + * @return true if no errors are present and doWork should be called + */ + boolean canWork(); - /** - * Performs actual work, breeding, production, etc. - */ - void doWork(); + /** + * Performs actual work, breeding, production, etc. + */ + void doWork(); + /* CLIENT */ - /* CLIENT */ + /** + * Call this when the housing comes into view of the client. + * (i.e. when tile.getDescriptionPacket() is called) + */ + void syncToClient(); - /** - * Call this when the housing comes into view of the client. - * (i.e. when tile.getDescriptionPacket() is called) - */ - void syncToClient(); - void syncToClient(EntityPlayerMP player); + void syncToClient(EntityPlayerMP player); - /** - * Get the progress bar for breeding and production. - * To avoid network spam, this is only available server-side, - * and must be synced manually to the client when a GUI is open. - */ - int getBeeProgressPercent(); + /** + * Get the progress bar for breeding and production. + * To avoid network spam, this is only available server-side, + * and must be synced manually to the client when a GUI is open. + */ + int getBeeProgressPercent(); - /** - * Whether bee fx should be active. - * Internally, this is automatically synced to the client. - */ - boolean canDoBeeFX(); - - /** - * Display bee fx. Calls IBee.doFX(IEffectData[] storedData, IBeeHousing housing) on the queen. - * Internally, the queen is automatically synced to the client for the fx. - */ - void doBeeFX(); + /** + * Whether bee fx should be active. + * Internally, this is automatically synced to the client. + */ + boolean canDoBeeFX(); + /** + * Display bee fx. Calls IBee.doFX(IEffectData[] storedData, IBeeHousing housing) on the queen. + * Internally, the queen is automatically synced to the client for the fx. + */ + void doBeeFX(); } diff --git a/src/main/java/forestry/api/apiculture/IBeekeepingMode.java b/src/main/java/forestry/api/apiculture/IBeekeepingMode.java index 86b31503b..3eae06269 100644 --- a/src/main/java/forestry/api/apiculture/IBeekeepingMode.java +++ b/src/main/java/forestry/api/apiculture/IBeekeepingMode.java @@ -1,73 +1,72 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; import java.util.ArrayList; - import net.minecraft.world.World; public interface IBeekeepingMode { - /** - * @return Localized name of this beekeeping mode. - */ - String getName(); + /** + * @return Localized name of this beekeeping mode. + */ + String getName(); - /** - * @return Localized list of strings outlining the behaviour of this beekeeping mode. - */ - ArrayList getDescription(); + /** + * @return Localized list of strings outlining the behaviour of this beekeeping mode. + */ + ArrayList getDescription(); - /** - * @return Float used to modify the wear on comb frames. - */ - float getWearModifier(); + /** + * @return Float used to modify the wear on comb frames. + */ + float getWearModifier(); - /** - * @param queen - * @return fertility taking into account the birthing queen and surroundings. - */ - int getFinalFertility(IBee queen, World world, int x, int y, int z); + /** + * @param queen + * @return fertility taking into account the birthing queen and surroundings. + */ + int getFinalFertility(IBee queen, World world, int x, int y, int z); - /** - * @param queen - * @return true if the queen is genetically "fatigued" and should not be reproduced anymore. - */ - boolean isFatigued(IBee queen, IBeeHousing housing); + /** + * @param queen + * @return true if the queen is genetically "fatigued" and should not be reproduced anymore. + */ + boolean isFatigued(IBee queen, IBeeHousing housing); - /** - * @param queen - * @param housing - * @return true if the queen is being overworked in the bee housing (with chance). will trigger a negative effect. - */ - boolean isOverworked(IBee queen, IBeeHousing housing); + /** + * @param queen + * @param housing + * @return true if the queen is being overworked in the bee housing (with chance). will trigger a negative effect. + */ + boolean isOverworked(IBee queen, IBeeHousing housing); - /** - * - * @param queen - * @param offspring - * @param housing - * @return true if the genetic structure of the queen is breaking down during spawning of the offspring (with chance). will trigger a negative effect. - */ - boolean isDegenerating(IBee queen, IBee offspring, IBeeHousing housing); + /** + * + * @param queen + * @param offspring + * @param housing + * @return true if the genetic structure of the queen is breaking down during spawning of the offspring (with chance). will trigger a negative effect. + */ + boolean isDegenerating(IBee queen, IBee offspring, IBeeHousing housing); - /** - * @param queen - * @return true if an offspring of this queen is considered a natural - */ - boolean isNaturalOffspring(IBee queen); + /** + * @param queen + * @return true if an offspring of this queen is considered a natural + */ + boolean isNaturalOffspring(IBee queen); - /** - * @param queen - * @return true if this mode allows the passed queen or princess to be multiplied - */ - boolean mayMultiplyPrincess(IBee queen); + /** + * @param queen + * @return true if this mode allows the passed queen or princess to be multiplied + */ + boolean mayMultiplyPrincess(IBee queen); - /** - * @return the bee modifier for this mode - */ - IBeeModifier getBeeModifier(); + /** + * @return the bee modifier for this mode + */ + IBeeModifier getBeeModifier(); } diff --git a/src/main/java/forestry/api/apiculture/IHiveDrop.java b/src/main/java/forestry/api/apiculture/IHiveDrop.java index ea175f8b3..c1c338448 100644 --- a/src/main/java/forestry/api/apiculture/IHiveDrop.java +++ b/src/main/java/forestry/api/apiculture/IHiveDrop.java @@ -1,38 +1,37 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; import java.util.Collection; - import net.minecraft.item.ItemStack; import net.minecraft.world.World; /** * Bees can be seeded either as hive drops or as mutation results. - * + * * Add IHiveDrops with HiveManager.get___Hive.addDrop - * + * * @author SirSengir */ public interface IHiveDrop { - ItemStack getPrincess(World world, int x, int y, int z, int fortune); + ItemStack getPrincess(World world, int x, int y, int z, int fortune); - Collection getDrones(World world, int x, int y, int z, int fortune); + Collection getDrones(World world, int x, int y, int z, int fortune); - Collection getAdditional(World world, int x, int y, int z, int fortune); + Collection getAdditional(World world, int x, int y, int z, int fortune); - /** - * Chance to drop. Default drops have 80 (= 80 %). - * - * @param world Minecraft world this is called for. - * @param x x-Coordinate of the broken hive. - * @param y y-Coordinate of the broken hive. - * @param z z-Coordinate of the broken hive. - * @return Chance for drop as an integer of 0 - 100. - */ - int getChance(World world, int x, int y, int z); + /** + * Chance to drop. Default drops have 80 (= 80 %). + * + * @param world Minecraft world this is called for. + * @param x x-Coordinate of the broken hive. + * @param y y-Coordinate of the broken hive. + * @param z z-Coordinate of the broken hive. + * @return Chance for drop as an integer of 0 - 100. + */ + int getChance(World world, int x, int y, int z); } diff --git a/src/main/java/forestry/api/apiculture/IHiveFrame.java b/src/main/java/forestry/api/apiculture/IHiveFrame.java index 08259cae7..e0690ba27 100644 --- a/src/main/java/forestry/api/apiculture/IHiveFrame.java +++ b/src/main/java/forestry/api/apiculture/IHiveFrame.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.apiculture; @@ -9,16 +9,16 @@ import net.minecraft.item.ItemStack; public interface IHiveFrame { - /** - * Wears out a frame. - * - * @param housing IBeeHousing the frame is contained in. - * @param frame ItemStack containing the actual frame. - * @param queen Current queen in the caller. - * @param wear Integer denoting the amount worn out. The wear modifier of the current beekeeping mode has already been taken into account. - * @return ItemStack containing the actual frame with adjusted damage, or null if it has been broken. - */ - ItemStack frameUsed(IBeeHousing housing, ItemStack frame, IBee queen, int wear); + /** + * Wears out a frame. + * + * @param housing IBeeHousing the frame is contained in. + * @param frame ItemStack containing the actual frame. + * @param queen Current queen in the caller. + * @param wear Integer denoting the amount worn out. The wear modifier of the current beekeeping mode has already been taken into account. + * @return ItemStack containing the actual frame with adjusted damage, or null if it has been broken. + */ + ItemStack frameUsed(IBeeHousing housing, ItemStack frame, IBee queen, int wear); - IBeeModifier getBeeModifier(); + IBeeModifier getBeeModifier(); } diff --git a/src/main/java/forestry/api/apiculture/IJubilanceFactory.java b/src/main/java/forestry/api/apiculture/IJubilanceFactory.java index 1b81a9d06..fcbfcce54 100644 --- a/src/main/java/forestry/api/apiculture/IJubilanceFactory.java +++ b/src/main/java/forestry/api/apiculture/IJubilanceFactory.java @@ -8,9 +8,9 @@ package forestry.api.apiculture; import net.minecraft.block.Block; public interface IJubilanceFactory { - /** The default Jubilance Provider is satisfied when the humidity and temperature are ideal for the bee. */ - IJubilanceProvider getDefault(); + /** The default Jubilance Provider is satisfied when the humidity and temperature are ideal for the bee. */ + IJubilanceProvider getDefault(); - /** The Requires Resource Jubilance Provider is satisfied when a specific block is under the hive. */ - IJubilanceProvider getRequiresResource(Block block, int meta); + /** The Requires Resource Jubilance Provider is satisfied when a specific block is under the hive. */ + IJubilanceProvider getRequiresResource(Block block, int meta); } diff --git a/src/main/java/forestry/api/apiculture/IJubilanceProvider.java b/src/main/java/forestry/api/apiculture/IJubilanceProvider.java index faf34d05e..903e1e5a8 100644 --- a/src/main/java/forestry/api/apiculture/IJubilanceProvider.java +++ b/src/main/java/forestry/api/apiculture/IJubilanceProvider.java @@ -7,9 +7,9 @@ package forestry.api.apiculture; public interface IJubilanceProvider { - /** - * Returns true when conditions are right to make this species Jubilant. - * Jubilant bees can produce their Specialty products. - */ - boolean isJubilant(IAlleleBeeSpecies species, IBeeGenome genome, IBeeHousing housing); + /** + * Returns true when conditions are right to make this species Jubilant. + * Jubilant bees can produce their Specialty products. + */ + boolean isJubilant(IAlleleBeeSpecies species, IBeeGenome genome, IBeeHousing housing); } diff --git a/src/main/java/forestry/api/apiculture/hives/HiveManager.java b/src/main/java/forestry/api/apiculture/hives/HiveManager.java index 17ca7d20e..16d4d92a1 100644 --- a/src/main/java/forestry/api/apiculture/hives/HiveManager.java +++ b/src/main/java/forestry/api/apiculture/hives/HiveManager.java @@ -7,7 +7,6 @@ package forestry.api.apiculture.hives; public class HiveManager { - public static IHiveRegistry hiveRegistry; - public static IHiveGenHelper genHelper; - + public static IHiveRegistry hiveRegistry; + public static IHiveGenHelper genHelper; } diff --git a/src/main/java/forestry/api/apiculture/hives/IHiveDescription.java b/src/main/java/forestry/api/apiculture/hives/IHiveDescription.java index 82d761dbc..10ca5004f 100644 --- a/src/main/java/forestry/api/apiculture/hives/IHiveDescription.java +++ b/src/main/java/forestry/api/apiculture/hives/IHiveDescription.java @@ -5,44 +5,46 @@ ******************************************************************************/ package forestry.api.apiculture.hives; +import forestry.api.core.EnumHumidity; +import forestry.api.core.EnumTemperature; import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; -import forestry.api.core.EnumHumidity; -import forestry.api.core.EnumTemperature; - public interface IHiveDescription { - /** - * The hive generator for this hive. - */ - IHiveGen getHiveGen(); + /** + * The hive generator for this hive. + */ + IHiveGen getHiveGen(); - /** - * The hive block to be placed in the world. - */ - Block getBlock(); - int getMeta(); + /** + * The hive block to be placed in the world. + */ + Block getBlock(); - /** - * returns true if the hive can be generated in these conditions. - * Used as a fast early-elimination check for hives that have no hope of spawning in the area. - */ - boolean isGoodBiome(BiomeGenBase biome); - boolean isGoodHumidity(EnumHumidity humidity); - boolean isGoodTemperature(EnumTemperature temperature); + int getMeta(); - /** - * float representing the relative chance a hive will generate in a chunk. - * Default is 1.0, higher numbers result in more hives, smaller will result in fewer. - * Tree hives want around 3.0 to 4.0 since there are less locations to generate on. - */ - float getGenChance(); + /** + * returns true if the hive can be generated in these conditions. + * Used as a fast early-elimination check for hives that have no hope of spawning in the area. + */ + boolean isGoodBiome(BiomeGenBase biome); - /** - * Called after successful hive generation. - * world, x, y, z give the location of the new hive. - **/ - void postGen(World world, int x, int y, int z); + boolean isGoodHumidity(EnumHumidity humidity); + + boolean isGoodTemperature(EnumTemperature temperature); + + /** + * float representing the relative chance a hive will generate in a chunk. + * Default is 1.0, higher numbers result in more hives, smaller will result in fewer. + * Tree hives want around 3.0 to 4.0 since there are less locations to generate on. + */ + float getGenChance(); + + /** + * Called after successful hive generation. + * world, x, y, z give the location of the new hive. + **/ + void postGen(World world, int x, int y, int z); } diff --git a/src/main/java/forestry/api/apiculture/hives/IHiveGen.java b/src/main/java/forestry/api/apiculture/hives/IHiveGen.java index 57569d26e..e0be1ddfb 100644 --- a/src/main/java/forestry/api/apiculture/hives/IHiveGen.java +++ b/src/main/java/forestry/api/apiculture/hives/IHiveGen.java @@ -9,21 +9,20 @@ import net.minecraft.world.World; public interface IHiveGen { - /** - * return a Y value that the hive should try to generate at. - * returns negative if the hive can't be placed anywhere. - */ - int getYForHive(World world, int x, int z); + /** + * return a Y value that the hive should try to generate at. + * returns negative if the hive can't be placed anywhere. + */ + int getYForHive(World world, int x, int z); - /** - * returns true if the hive can be generated at this location. - * Used for advanced conditions, like checking that the ground below the hive is a certain type. - */ - boolean isValidLocation(World world, int x, int y, int z); - - /** - * returns true if the hive can safely replace the block at this location. - */ - boolean canReplace(World world, int x, int y, int z); + /** + * returns true if the hive can be generated at this location. + * Used for advanced conditions, like checking that the ground below the hive is a certain type. + */ + boolean isValidLocation(World world, int x, int y, int z); + /** + * returns true if the hive can safely replace the block at this location. + */ + boolean canReplace(World world, int x, int y, int z); } diff --git a/src/main/java/forestry/api/apiculture/hives/IHiveGenHelper.java b/src/main/java/forestry/api/apiculture/hives/IHiveGenHelper.java index 0eb6400cb..04b0ec82c 100644 --- a/src/main/java/forestry/api/apiculture/hives/IHiveGenHelper.java +++ b/src/main/java/forestry/api/apiculture/hives/IHiveGenHelper.java @@ -9,15 +9,14 @@ import net.minecraft.block.Block; public interface IHiveGenHelper { - /** - * Returns a hiveGen for a hive that spawns on the ground. - * validGroundBlocks specifies which block materials it can spawn on. - */ - IHiveGen ground(Block... validGroundBlocks); - - /** - * Returns a hiveGen for a hive that spawns in trees. - */ - IHiveGen tree(); + /** + * Returns a hiveGen for a hive that spawns on the ground. + * validGroundBlocks specifies which block materials it can spawn on. + */ + IHiveGen ground(Block... validGroundBlocks); + /** + * Returns a hiveGen for a hive that spawns in trees. + */ + IHiveGen tree(); } diff --git a/src/main/java/forestry/api/apiculture/hives/IHiveRegistry.java b/src/main/java/forestry/api/apiculture/hives/IHiveRegistry.java index 73f3524cc..20b871a5f 100644 --- a/src/main/java/forestry/api/apiculture/hives/IHiveRegistry.java +++ b/src/main/java/forestry/api/apiculture/hives/IHiveRegistry.java @@ -5,29 +5,29 @@ ******************************************************************************/ package forestry.api.apiculture.hives; -import java.util.List; - import forestry.api.apiculture.IHiveDrop; +import java.util.List; public interface IHiveRegistry { - /* Forestry Hive Names */ - public static final String forest = "Forestry:forest"; - public static final String meadows = "Forestry:meadows"; - public static final String desert = "Forestry:desert"; - public static final String jungle = "Forestry:jungle"; - public static final String end = "Forestry:end"; - public static final String snow = "Forestry:snow"; - public static final String swamp = "Forestry:swamp"; + /* Forestry Hive Names */ + public static final String forest = "Forestry:forest"; + public static final String meadows = "Forestry:meadows"; + public static final String desert = "Forestry:desert"; + public static final String jungle = "Forestry:jungle"; + public static final String end = "Forestry:end"; + public static final String snow = "Forestry:snow"; + public static final String swamp = "Forestry:swamp"; - /** - * Adds a new hive to be generated in the world. - */ - void registerHive(String hiveName, IHiveDescription hiveDescription); + /** + * Adds a new hive to be generated in the world. + */ + void registerHive(String hiveName, IHiveDescription hiveDescription); - /** - * Add drops to a registered hive. - */ - void addDrops(String hiveName, IHiveDrop... drops); - void addDrops(String hiveName, List drop); + /** + * Add drops to a registered hive. + */ + void addDrops(String hiveName, IHiveDrop... drops); + + void addDrops(String hiveName, List drop); } diff --git a/src/main/java/forestry/api/apiculture/hives/package-info.java b/src/main/java/forestry/api/apiculture/hives/package-info.java index a045530c2..c041d4170 100644 --- a/src/main/java/forestry/api/apiculture/hives/package-info.java +++ b/src/main/java/forestry/api/apiculture/hives/package-info.java @@ -3,6 +3,7 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ -@API(apiVersion="4.1.0", owner="ForestryAPI|apiculture", provides="ForestryAPI|hives") +@API(apiVersion = "4.1.0", owner = "ForestryAPI|apiculture", provides = "ForestryAPI|hives") package forestry.api.apiculture.hives; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/api/apiculture/package-info.java b/src/main/java/forestry/api/apiculture/package-info.java index e9c33f6bd..fcd5b2dda 100644 --- a/src/main/java/forestry/api/apiculture/package-info.java +++ b/src/main/java/forestry/api/apiculture/package-info.java @@ -1,8 +1,9 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ -@API(apiVersion="5.0.0", owner="ForestryAPI|core", provides="ForestryAPI|apiculture") +@API(apiVersion = "5.0.0", owner = "ForestryAPI|core", provides = "ForestryAPI|apiculture") package forestry.api.apiculture; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/api/arboriculture/EnumFruitFamily.java b/src/main/java/forestry/api/arboriculture/EnumFruitFamily.java index 85a995d90..dd1234d21 100644 --- a/src/main/java/forestry/api/arboriculture/EnumFruitFamily.java +++ b/src/main/java/forestry/api/arboriculture/EnumFruitFamily.java @@ -5,44 +5,42 @@ ******************************************************************************/ package forestry.api.arboriculture; -import net.minecraft.util.StatCollector; - import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IFruitFamily; +import net.minecraft.util.StatCollector; public enum EnumFruitFamily implements IFruitFamily { - PRUNES("prunes", "Prunus domestica"), - POMES("pomes", "Pomum"), - JUNGLE("jungle", "Tropicus"), - NUX("nuts", "Nux"); + PRUNES("prunes", "Prunus domestica"), + POMES("pomes", "Pomum"), + JUNGLE("jungle", "Tropicus"), + NUX("nuts", "Nux"); - private final String uid; - private final String scientific; + private final String uid; + private final String scientific; - EnumFruitFamily(String uid, String scientific) { - this.uid = uid; - this.scientific = scientific; - AlleleManager.alleleRegistry.registerFruitFamily(this); - } + EnumFruitFamily(String uid, String scientific) { + this.uid = uid; + this.scientific = scientific; + AlleleManager.alleleRegistry.registerFruitFamily(this); + } - @Override - public String getUID() { - return "forestry." + uid; - } + @Override + public String getUID() { + return "forestry." + uid; + } - @Override - public String getScientific() { - return this.scientific; - } + @Override + public String getScientific() { + return this.scientific; + } - @Override - public String getName() { - return StatCollector.translateToLocal("for.family." + uid); - } - - @Override - public String getDescription() { - return StatCollector.translateToLocal("for.family." + uid + ".description"); - } + @Override + public String getName() { + return StatCollector.translateToLocal("for.family." + uid); + } + @Override + public String getDescription() { + return StatCollector.translateToLocal("for.family." + uid + ".description"); + } } diff --git a/src/main/java/forestry/api/arboriculture/EnumGermlingType.java b/src/main/java/forestry/api/arboriculture/EnumGermlingType.java index ead88b1d7..813da063a 100644 --- a/src/main/java/forestry/api/arboriculture/EnumGermlingType.java +++ b/src/main/java/forestry/api/arboriculture/EnumGermlingType.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; @@ -8,18 +8,21 @@ package forestry.api.arboriculture; import forestry.api.genetics.ISpeciesType; public enum EnumGermlingType implements ISpeciesType { - SAPLING("sapling"), BLOSSOM("blossom"), POLLEN("pollen"), GERMLING("germling"), NONE("none"); + SAPLING("sapling"), + BLOSSOM("blossom"), + POLLEN("pollen"), + GERMLING("germling"), + NONE("none"); - public static final EnumGermlingType[] VALUES = values(); - - private final String name; + public static final EnumGermlingType[] VALUES = values(); - EnumGermlingType(String name) { - this.name = name; - } + private final String name; - public String getName() { - return name; - } + EnumGermlingType(String name) { + this.name = name; + } + public String getName() { + return name; + } } diff --git a/src/main/java/forestry/api/arboriculture/EnumGrowthConditions.java b/src/main/java/forestry/api/arboriculture/EnumGrowthConditions.java index 8b28601c1..f409395d4 100644 --- a/src/main/java/forestry/api/arboriculture/EnumGrowthConditions.java +++ b/src/main/java/forestry/api/arboriculture/EnumGrowthConditions.java @@ -1,10 +1,14 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; public enum EnumGrowthConditions { - HOSTILE, PALTRY, NORMAL, GOOD, EXCELLENT + HOSTILE, + PALTRY, + NORMAL, + GOOD, + EXCELLENT } diff --git a/src/main/java/forestry/api/arboriculture/EnumLeafType.java b/src/main/java/forestry/api/arboriculture/EnumLeafType.java index 472b3555a..dfb443ba6 100644 --- a/src/main/java/forestry/api/arboriculture/EnumLeafType.java +++ b/src/main/java/forestry/api/arboriculture/EnumLeafType.java @@ -6,5 +6,10 @@ package forestry.api.arboriculture; public enum EnumLeafType { - DECIDUOUS, CONIFERS, JUNGLE, WILLOW, MAPLE, PALM + DECIDUOUS, + CONIFERS, + JUNGLE, + WILLOW, + MAPLE, + PALM } diff --git a/src/main/java/forestry/api/arboriculture/EnumTreeChromosome.java b/src/main/java/forestry/api/arboriculture/EnumTreeChromosome.java index 29fcebad3..9a30c90ff 100644 --- a/src/main/java/forestry/api/arboriculture/EnumTreeChromosome.java +++ b/src/main/java/forestry/api/arboriculture/EnumTreeChromosome.java @@ -1,14 +1,10 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; -import java.util.Locale; - -import net.minecraftforge.common.EnumPlantType; - import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleArea; import forestry.api.genetics.IAlleleBoolean; @@ -18,81 +14,82 @@ import forestry.api.genetics.IAllelePlantType; import forestry.api.genetics.IChromosomeType; import forestry.api.genetics.IFruitFamily; import forestry.api.genetics.ISpeciesRoot; +import java.util.Locale; +import net.minecraftforge.common.EnumPlantType; public enum EnumTreeChromosome implements IChromosomeType { - /** - * Determines the following: - WorldGen, including the used wood blocks - {@link IFruitFamily}s supported. Limits which {@link IFruitProvider} - * will actually yield fruit with this species. - Native {@link EnumPlantType} for this tree. Combines with the PLANT chromosome. - */ - SPECIES(IAlleleTreeSpecies.class), - /** - * {@link IGrowthProvider}, determines conditions required by the tree to grow. - */ - GROWTH(IAlleleGrowth.class), - /** - * A float modifying the height of the tree. Taken into account at worldgen. - */ - HEIGHT(IAlleleFloat.class), - /** - * Chance for saplings. - */ - FERTILITY(IAlleleFloat.class), - /** - * {@link IFruitProvider}, determines if and what fruits are grown on the tree. Limited by the {@link IFruitFamily}s the species supports. - */ - FRUITS(IAlleleFruit.class), - /** - * Chance for fruit leaves and/or drops. - */ - YIELD(IAlleleFloat.class), - /** - * May add additional tolerances for {@link EnumPlantTypes}. - */ - PLANT(IAllelePlantType.class), - /** - * Determines the speed at which fruit will ripen on this tree. - */ - SAPPINESS(IAlleleFloat.class), - /** - * Territory for leaf effects. Unused. - */ - TERRITORY(IAlleleArea.class), - /** - * Leaf effect. Unused. - */ - EFFECT(IAlleleLeafEffect.class), - /** - * Amount of random ticks which need to elapse before a sapling will grow into a tree. - */ - MATURATION(IAlleleInteger.class), + /** + * Determines the following: - WorldGen, including the used wood blocks - {@link IFruitFamily}s supported. Limits which {@link IFruitProvider} + * will actually yield fruit with this species. - Native {@link EnumPlantType} for this tree. Combines with the PLANT chromosome. + */ + SPECIES(IAlleleTreeSpecies.class), + /** + * {@link IGrowthProvider}, determines conditions required by the tree to grow. + */ + GROWTH(IAlleleGrowth.class), + /** + * A float modifying the height of the tree. Taken into account at worldgen. + */ + HEIGHT(IAlleleFloat.class), + /** + * Chance for saplings. + */ + FERTILITY(IAlleleFloat.class), + /** + * {@link IFruitProvider}, determines if and what fruits are grown on the tree. Limited by the {@link IFruitFamily}s the species supports. + */ + FRUITS(IAlleleFruit.class), + /** + * Chance for fruit leaves and/or drops. + */ + YIELD(IAlleleFloat.class), + /** + * May add additional tolerances for {@link EnumPlantTypes}. + */ + PLANT(IAllelePlantType.class), + /** + * Determines the speed at which fruit will ripen on this tree. + */ + SAPPINESS(IAlleleFloat.class), + /** + * Territory for leaf effects. Unused. + */ + TERRITORY(IAlleleArea.class), + /** + * Leaf effect. Unused. + */ + EFFECT(IAlleleLeafEffect.class), + /** + * Amount of random ticks which need to elapse before a sapling will grow into a tree. + */ + MATURATION(IAlleleInteger.class), - GIRTH(IAlleleInteger.class), - /** - * Determines if the tree can burn. - */ - FIREPROOF(IAlleleBoolean.class), - ; - - Class clss; - - EnumTreeChromosome(Class clss) { - this.clss = clss; - } + GIRTH(IAlleleInteger.class), + /** + * Determines if the tree can burn. + */ + FIREPROOF(IAlleleBoolean.class), + ; - @Override - public Class getAlleleClass() { - return clss; - } + Class clss; - @Override - public String getName() { - return this.toString().toLowerCase(Locale.ENGLISH); - } + EnumTreeChromosome(Class clss) { + this.clss = clss; + } - @Override - public ISpeciesRoot getSpeciesRoot() { - return TreeManager.treeRoot; - } + @Override + public Class getAlleleClass() { + return clss; + } + @Override + public String getName() { + return this.toString().toLowerCase(Locale.ENGLISH); + } + + @Override + public ISpeciesRoot getSpeciesRoot() { + return TreeManager.treeRoot; + } } diff --git a/src/main/java/forestry/api/arboriculture/EnumWoodType.java b/src/main/java/forestry/api/arboriculture/EnumWoodType.java index de22ddfbd..290f05b41 100644 --- a/src/main/java/forestry/api/arboriculture/EnumWoodType.java +++ b/src/main/java/forestry/api/arboriculture/EnumWoodType.java @@ -7,63 +7,85 @@ package forestry.api.arboriculture; import java.util.Locale; import java.util.Random; - import net.minecraft.nbt.NBTTagCompound; public enum EnumWoodType { - LARCH, TEAK, ACACIA, LIME, CHESTNUT, - WENGE, BAOBAB, SEQUOIA(4.0f), KAPOK, EBONY, - MAHOGANY, BALSA(1.0f), WILLOW, WALNUT, GREENHEART(7.5f), - CHERRY, MAHOE, POPLAR, PALM, PAPAYA, - PINE(3.0f), PLUM, MAPLE, CITRUS, GIGANTEUM, - IPE, PADAUK, COCOBOLO, ZEBRAWOOD; + LARCH, + TEAK, + ACACIA, + LIME, + CHESTNUT, + WENGE, + BAOBAB, + SEQUOIA(4.0f), + KAPOK, + EBONY, + MAHOGANY, + BALSA(1.0f), + WILLOW, + WALNUT, + GREENHEART(7.5f), + CHERRY, + MAHOE, + POPLAR, + PALM, + PAPAYA, + PINE(3.0f), + PLUM, + MAPLE, + CITRUS, + GIGANTEUM, + IPE, + PADAUK, + COCOBOLO, + ZEBRAWOOD; - public static final float DEFAULT_HARDNESS = 2.0f; - public static final EnumWoodType[] VALUES = values(); + public static final float DEFAULT_HARDNESS = 2.0f; + public static final EnumWoodType[] VALUES = values(); - private final float hardness; + private final float hardness; - EnumWoodType() { - this.hardness = DEFAULT_HARDNESS; - } + EnumWoodType() { + this.hardness = DEFAULT_HARDNESS; + } - EnumWoodType(float hardness) { - this.hardness = hardness; - } + EnumWoodType(float hardness) { + this.hardness = hardness; + } - public float getHardness() { - return hardness; - } + public float getHardness() { + return hardness; + } - /** - * @deprecated since Forestry 4.2. Woods use itemDamage instead of NBT now - */ - @Deprecated - public void saveToCompound(NBTTagCompound compound) { - compound.setInteger("WoodType", ordinal()); - } + /** + * @deprecated since Forestry 4.2. Woods use itemDamage instead of NBT now + */ + @Deprecated + public void saveToCompound(NBTTagCompound compound) { + compound.setInteger("WoodType", ordinal()); + } - /** - * @deprecated since Forestry 4.2. Woods use itemDamage instead of NBT now - */ - @Deprecated - public static EnumWoodType getFromCompound(NBTTagCompound compound) { - if (compound != null) { - int typeOrdinal = compound.getInteger("WoodType"); - if (typeOrdinal >= 0 && typeOrdinal < VALUES.length) { - return VALUES[typeOrdinal]; - } - } + /** + * @deprecated since Forestry 4.2. Woods use itemDamage instead of NBT now + */ + @Deprecated + public static EnumWoodType getFromCompound(NBTTagCompound compound) { + if (compound != null) { + int typeOrdinal = compound.getInteger("WoodType"); + if (typeOrdinal >= 0 && typeOrdinal < VALUES.length) { + return VALUES[typeOrdinal]; + } + } - return EnumWoodType.LARCH; - } + return EnumWoodType.LARCH; + } - public static EnumWoodType getRandom(Random random) { - return VALUES[random.nextInt(VALUES.length)]; - } + public static EnumWoodType getRandom(Random random) { + return VALUES[random.nextInt(VALUES.length)]; + } - @Override - public String toString() { - return super.toString().toLowerCase(Locale.ENGLISH); - } + @Override + public String toString() { + return super.toString().toLowerCase(Locale.ENGLISH); + } } diff --git a/src/main/java/forestry/api/arboriculture/IAlleleFruit.java b/src/main/java/forestry/api/arboriculture/IAlleleFruit.java index 0f54db510..4bccc02ca 100644 --- a/src/main/java/forestry/api/arboriculture/IAlleleFruit.java +++ b/src/main/java/forestry/api/arboriculture/IAlleleFruit.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; @@ -12,6 +12,5 @@ import forestry.api.genetics.IAllele; */ public interface IAlleleFruit extends IAllele { - IFruitProvider getProvider(); - + IFruitProvider getProvider(); } diff --git a/src/main/java/forestry/api/arboriculture/IAlleleGrowth.java b/src/main/java/forestry/api/arboriculture/IAlleleGrowth.java index 6cb4b4389..747c46ce1 100644 --- a/src/main/java/forestry/api/arboriculture/IAlleleGrowth.java +++ b/src/main/java/forestry/api/arboriculture/IAlleleGrowth.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; @@ -12,6 +12,5 @@ import forestry.api.genetics.IAllele; */ public interface IAlleleGrowth extends IAllele { - IGrowthProvider getProvider(); - + IGrowthProvider getProvider(); } diff --git a/src/main/java/forestry/api/arboriculture/IAlleleLeafEffect.java b/src/main/java/forestry/api/arboriculture/IAlleleLeafEffect.java index d52d963ac..525393824 100644 --- a/src/main/java/forestry/api/arboriculture/IAlleleLeafEffect.java +++ b/src/main/java/forestry/api/arboriculture/IAlleleLeafEffect.java @@ -1,20 +1,18 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; -import net.minecraft.world.World; - import forestry.api.genetics.IAlleleEffect; import forestry.api.genetics.IEffectData; +import net.minecraft.world.World; /** * Simple allele encapsulating a leaf effect. (Not implemented) */ public interface IAlleleLeafEffect extends IAlleleEffect { - IEffectData doEffect(ITreeGenome genome, IEffectData storedData, World world, int x, int y, int z); - + IEffectData doEffect(ITreeGenome genome, IEffectData storedData, World world, int x, int y, int z); } diff --git a/src/main/java/forestry/api/arboriculture/IAlleleTreeSpecies.java b/src/main/java/forestry/api/arboriculture/IAlleleTreeSpecies.java index e5a65a7d7..9412a65f7 100644 --- a/src/main/java/forestry/api/arboriculture/IAlleleTreeSpecies.java +++ b/src/main/java/forestry/api/arboriculture/IAlleleTreeSpecies.java @@ -1,51 +1,46 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; -import java.util.Collection; - -import net.minecraft.util.IIcon; - -import net.minecraftforge.common.EnumPlantType; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IFruitFamily; +import java.util.Collection; +import net.minecraft.util.IIcon; +import net.minecraftforge.common.EnumPlantType; public interface IAlleleTreeSpecies extends IAlleleSpecies { - ITreeRoot getRoot(); - - /** - * @return Native plant type of this species. - */ - EnumPlantType getPlantType(); + ITreeRoot getRoot(); - /** - * @return List of all {@link IFruitFamily}s which can grow on leaves generated by this species. - */ - Collection getSuitableFruit(); + /** + * @return Native plant type of this species. + */ + EnumPlantType getPlantType(); - /** - * @return Tree generator for this species. - */ - ITreeGenerator getGenerator(); + /** + * @return List of all {@link IFruitFamily}s which can grow on leaves generated by this species. + */ + Collection getSuitableFruit(); - /* TEXTURES AND OVERRIDES */ - int getLeafColour(boolean pollinated); + /** + * @return Tree generator for this species. + */ + ITreeGenerator getGenerator(); - @SideOnly(Side.CLIENT) - IIcon getLeafIcon(boolean pollinated, boolean fancy); + /* TEXTURES AND OVERRIDES */ + int getLeafColour(boolean pollinated); - @SideOnly(Side.CLIENT) - IIcon getGermlingIcon(EnumGermlingType type, int renderPass); - - @SideOnly(Side.CLIENT) - int getGermlingColour(EnumGermlingType type, int renderPass); + @SideOnly(Side.CLIENT) + IIcon getLeafIcon(boolean pollinated, boolean fancy); + @SideOnly(Side.CLIENT) + IIcon getGermlingIcon(EnumGermlingType type, int renderPass); + + @SideOnly(Side.CLIENT) + int getGermlingColour(EnumGermlingType type, int renderPass); } diff --git a/src/main/java/forestry/api/arboriculture/IAlleleTreeSpeciesCustom.java b/src/main/java/forestry/api/arboriculture/IAlleleTreeSpeciesCustom.java index d5bf25b7e..088b80670 100644 --- a/src/main/java/forestry/api/arboriculture/IAlleleTreeSpeciesCustom.java +++ b/src/main/java/forestry/api/arboriculture/IAlleleTreeSpeciesCustom.java @@ -5,17 +5,15 @@ ******************************************************************************/ package forestry.api.arboriculture; -import net.minecraftforge.common.EnumPlantType; - import forestry.api.genetics.IAlleleSpeciesCustom; import forestry.api.genetics.IFruitFamily; +import net.minecraftforge.common.EnumPlantType; public interface IAlleleTreeSpeciesCustom extends IAlleleSpeciesCustom, IAlleleTreeSpecies { - /** Add a fruit family for this tree. Trees can have multiple fruit families. */ - IAlleleTreeSpeciesCustom addFruitFamily(IFruitFamily family); - - /** Set the minecraft plant type for this tree. Default is Plains. */ - IAlleleTreeSpeciesCustom setPlantType(EnumPlantType type); + /** Add a fruit family for this tree. Trees can have multiple fruit families. */ + IAlleleTreeSpeciesCustom addFruitFamily(IFruitFamily family); + /** Set the minecraft plant type for this tree. Default is Plains. */ + IAlleleTreeSpeciesCustom setPlantType(EnumPlantType type); } diff --git a/src/main/java/forestry/api/arboriculture/IArboristTracker.java b/src/main/java/forestry/api/arboriculture/IArboristTracker.java index 9777e8763..66329b342 100644 --- a/src/main/java/forestry/api/arboriculture/IArboristTracker.java +++ b/src/main/java/forestry/api/arboriculture/IArboristTracker.java @@ -1,12 +1,10 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; import forestry.api.genetics.IBreedingTracker; -public interface IArboristTracker extends IBreedingTracker { - -} +public interface IArboristTracker extends IBreedingTracker {} diff --git a/src/main/java/forestry/api/arboriculture/IFruitProvider.java b/src/main/java/forestry/api/arboriculture/IFruitProvider.java index ef54fc99f..fd083c542 100644 --- a/src/main/java/forestry/api/arboriculture/IFruitProvider.java +++ b/src/main/java/forestry/api/arboriculture/IFruitProvider.java @@ -1,74 +1,72 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.genetics.IFruitFamily; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.genetics.IFruitFamily; - public interface IFruitProvider { - IFruitFamily getFamily(); + IFruitFamily getFamily(); - int getColour(ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime); + int getColour(ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime); - boolean markAsFruitLeaf(ITreeGenome genome, World world, int x, int y, int z); + boolean markAsFruitLeaf(ITreeGenome genome, World world, int x, int y, int z); - int getRipeningPeriod(); + int getRipeningPeriod(); - // / Products, Chance - ItemStack[] getProducts(); + // / Products, Chance + ItemStack[] getProducts(); - // / Specialty, Chance - ItemStack[] getSpecialty(); + // / Specialty, Chance + ItemStack[] getSpecialty(); - ItemStack[] getFruits(ITreeGenome genome, World world, int x, int y, int z, int ripeningTime); + ItemStack[] getFruits(ITreeGenome genome, World world, int x, int y, int z, int ripeningTime); - /** - * @return Short, human-readable identifier used in the treealyzer. - */ - String getDescription(); + /** + * @return Short, human-readable identifier used in the treealyzer. + */ + String getDescription(); - /* TEXTURE OVERLAY */ - /** - * @param genome - * @param world - * @param x - * @param y - * @param z - * @param ripeningTime - * Elapsed ripening time for the fruit. - * @param fancy - * @return IIcon index of the texture to overlay on the leaf block. - */ - short getIconIndex(ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime, boolean fancy); + /* TEXTURE OVERLAY */ + /** + * @param genome + * @param world + * @param x + * @param y + * @param z + * @param ripeningTime + * Elapsed ripening time for the fruit. + * @param fancy + * @return IIcon index of the texture to overlay on the leaf block. + */ + short getIconIndex(ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime, boolean fancy); - /** - * @return true if this fruit provider requires fruit blocks to spawn, false otherwise. - */ - boolean requiresFruitBlocks(); + /** + * @return true if this fruit provider requires fruit blocks to spawn, false otherwise. + */ + boolean requiresFruitBlocks(); - /** - * Tries to spawn a fruit block at the potential position when the tree generates. - * - * @param genome - * @param world - * @param x - * @param y - * @param z - * @return true if a fruit block was spawned, false otherwise. - */ - boolean trySpawnFruitBlock(ITreeGenome genome, World world, int x, int y, int z); + /** + * Tries to spawn a fruit block at the potential position when the tree generates. + * + * @param genome + * @param world + * @param x + * @param y + * @param z + * @return true if a fruit block was spawned, false otherwise. + */ + boolean trySpawnFruitBlock(ITreeGenome genome, World world, int x, int y, int z); - @SideOnly(Side.CLIENT) - void registerIcons(IIconRegister register); + @SideOnly(Side.CLIENT) + void registerIcons(IIconRegister register); } diff --git a/src/main/java/forestry/api/arboriculture/IGermlingIconProvider.java b/src/main/java/forestry/api/arboriculture/IGermlingIconProvider.java index f93a806a1..c96dea9cc 100644 --- a/src/main/java/forestry/api/arboriculture/IGermlingIconProvider.java +++ b/src/main/java/forestry/api/arboriculture/IGermlingIconProvider.java @@ -14,6 +14,7 @@ import net.minecraft.util.IIcon; * There is no default implementation because every sapling has a unique icon. */ public interface IGermlingIconProvider { - void registerIcons(IIconRegister register); - IIcon getIcon(EnumGermlingType type, int renderPass); + void registerIcons(IIconRegister register); + + IIcon getIcon(EnumGermlingType type, int renderPass); } diff --git a/src/main/java/forestry/api/arboriculture/IGrowthProvider.java b/src/main/java/forestry/api/arboriculture/IGrowthProvider.java index 92e553e0d..c3c872241 100644 --- a/src/main/java/forestry/api/arboriculture/IGrowthProvider.java +++ b/src/main/java/forestry/api/arboriculture/IGrowthProvider.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; @@ -9,30 +9,30 @@ import net.minecraft.world.World; public interface IGrowthProvider { - /** - * Check to see whether a sapling at the given location with the given genome can grow into a tree. - * - * @param genome Genome of the tree this is called for. - * @param world Minecraft world the tree will inhabit. - * @param xPos x-Coordinate to attempt growth at. - * @param yPos y-Coordinate to attempt growth at. - * @param zPos z-Coordinate to attempt growth at. - * @param expectedGirth Trunk size of the tree to generate. - * @param expectedHeight Height of the tree to generate. - * @return true if the tree can grow at the given coordinates, false otherwise. - */ - boolean canGrow(ITreeGenome genome, World world, int xPos, int yPos, int zPos, int expectedGirth, int expectedHeight); + /** + * Check to see whether a sapling at the given location with the given genome can grow into a tree. + * + * @param genome Genome of the tree this is called for. + * @param world Minecraft world the tree will inhabit. + * @param xPos x-Coordinate to attempt growth at. + * @param yPos y-Coordinate to attempt growth at. + * @param zPos z-Coordinate to attempt growth at. + * @param expectedGirth Trunk size of the tree to generate. + * @param expectedHeight Height of the tree to generate. + * @return true if the tree can grow at the given coordinates, false otherwise. + */ + boolean canGrow( + ITreeGenome genome, World world, int xPos, int yPos, int zPos, int expectedGirth, int expectedHeight); - EnumGrowthConditions getGrowthConditions(ITreeGenome genome, World world, int xPos, int yPos, int zPos); + EnumGrowthConditions getGrowthConditions(ITreeGenome genome, World world, int xPos, int yPos, int zPos); - /** - * @return Short, human-readable identifier used in the treealyzer. - */ - String getDescription(); - - /** - * @return Detailed description of growth behaviour used in the treealyzer. - */ - String[] getInfo(); + /** + * @return Short, human-readable identifier used in the treealyzer. + */ + String getDescription(); + /** + * @return Detailed description of growth behaviour used in the treealyzer. + */ + String[] getInfo(); } diff --git a/src/main/java/forestry/api/arboriculture/ILeafIconProvider.java b/src/main/java/forestry/api/arboriculture/ILeafIconProvider.java index d7df51395..43f81159f 100644 --- a/src/main/java/forestry/api/arboriculture/ILeafIconProvider.java +++ b/src/main/java/forestry/api/arboriculture/ILeafIconProvider.java @@ -15,6 +15,7 @@ import net.minecraft.util.IIcon; * Icon registration is not done here because these icons are heavily reused. */ public interface ILeafIconProvider { - IIcon getIcon(boolean pollinated, boolean fancy); - int getColor(boolean pollinated); + IIcon getIcon(boolean pollinated, boolean fancy); + + int getColor(boolean pollinated); } diff --git a/src/main/java/forestry/api/arboriculture/ILeafTickHandler.java b/src/main/java/forestry/api/arboriculture/ILeafTickHandler.java index 1f5d5b9f9..e1d596496 100644 --- a/src/main/java/forestry/api/arboriculture/ILeafTickHandler.java +++ b/src/main/java/forestry/api/arboriculture/ILeafTickHandler.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; @@ -8,5 +8,5 @@ package forestry.api.arboriculture; import net.minecraft.world.World; public interface ILeafTickHandler { - boolean onRandomLeafTick(ITree tree, World world, int x, int y, int z, boolean isDestroyed); + boolean onRandomLeafTick(ITree tree, World world, int x, int y, int z, boolean isDestroyed); } diff --git a/src/main/java/forestry/api/arboriculture/IToolGrafter.java b/src/main/java/forestry/api/arboriculture/IToolGrafter.java index 339725e6b..205e15dde 100644 --- a/src/main/java/forestry/api/arboriculture/IToolGrafter.java +++ b/src/main/java/forestry/api/arboriculture/IToolGrafter.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; @@ -10,15 +10,15 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.World; public interface IToolGrafter { - /** - * Called by leaves to determine the increase in sapling droprate. - * - * @param stack ItemStack containing the grafter. - * @param world Minecraft world the player and the target block inhabit. - * @param x x-Coordinate of the broken leaf block. - * @param y y-Coordinate of the broken leaf block. - * @param z z-Coordinate of the broken leaf block. - * @return Float representing the factor the usual drop chance is to be multiplied by. - */ - float getSaplingModifier(ItemStack stack, World world, EntityPlayer player, int x, int y, int z); + /** + * Called by leaves to determine the increase in sapling droprate. + * + * @param stack ItemStack containing the grafter. + * @param world Minecraft world the player and the target block inhabit. + * @param x x-Coordinate of the broken leaf block. + * @param y y-Coordinate of the broken leaf block. + * @param z z-Coordinate of the broken leaf block. + * @return Float representing the factor the usual drop chance is to be multiplied by. + */ + float getSaplingModifier(ItemStack stack, World world, EntityPlayer player, int x, int y, int z); } diff --git a/src/main/java/forestry/api/arboriculture/ITree.java b/src/main/java/forestry/api/arboriculture/ITree.java index 93ff3f0e1..2279da229 100644 --- a/src/main/java/forestry/api/arboriculture/ITree.java +++ b/src/main/java/forestry/api/arboriculture/ITree.java @@ -1,84 +1,80 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; -import java.util.EnumSet; - -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; -import net.minecraft.world.gen.feature.WorldGenerator; - import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.EnumPlantType; - import forestry.api.genetics.IEffectData; import forestry.api.genetics.IIndividual; import forestry.api.world.ITreeGenData; +import java.util.EnumSet; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraft.world.gen.feature.WorldGenerator; +import net.minecraftforge.common.EnumPlantType; public interface ITree extends IIndividual, ITreeGenData { - void mate(ITree other); + void mate(ITree other); - IEffectData[] doEffect(IEffectData[] storedData, World world, int x, int y, int z); + IEffectData[] doEffect(IEffectData[] storedData, World world, int x, int y, int z); - IEffectData[] doFX(IEffectData[] storedData, World world, int x, int y, int z); + IEffectData[] doFX(IEffectData[] storedData, World world, int x, int y, int z); - ITreeGenome getGenome(); + ITreeGenome getGenome(); - ITreeGenome getMate(); + ITreeGenome getMate(); - EnumSet getPlantTypes(); + EnumSet getPlantTypes(); - /** - * @since Forestry 4.0 - */ - ITree[] getSaplings(World world, GameProfile playerProfile, int x, int y, int z, float modifier); + /** + * @since Forestry 4.0 + */ + ITree[] getSaplings(World world, GameProfile playerProfile, int x, int y, int z, float modifier); - ItemStack[] getProduceList(); + ItemStack[] getProduceList(); - ItemStack[] getSpecialtyList(); + ItemStack[] getSpecialtyList(); - ItemStack[] produceStacks(World world, int x, int y, int z, int ripeningTime); + ItemStack[] produceStacks(World world, int x, int y, int z, int ripeningTime); - /** - * @return Boolean indicating whether a sapling can stay planted at the given position. - */ - boolean canStay(World world, int x, int y, int z); + /** + * @return Boolean indicating whether a sapling can stay planted at the given position. + */ + boolean canStay(World world, int x, int y, int z); - /** - * @return Boolean indicating whether a sapling at the given position can grow into a tree. - */ - boolean canGrow(World world, int x, int y, int z, int expectedGirth, int expectedHeight); + /** + * @return Boolean indicating whether a sapling at the given position can grow into a tree. + */ + boolean canGrow(World world, int x, int y, int z, int expectedGirth, int expectedHeight); - /** - * @return Integer denoting the maturity (block ticks) required for a sapling to attempt to grow into a tree. - */ - int getRequiredMaturity(); + /** + * @return Integer denoting the maturity (block ticks) required for a sapling to attempt to grow into a tree. + */ + int getRequiredMaturity(); - /** - * @return Integer denoting how resilient leaf blocks are against adverse influences (i.e. caterpillars). - */ - int getResilience(); - - /** - * @return Integer denoting the size of the tree trunk. - */ - int getGirth(World world, int x, int y, int z); + /** + * @return Integer denoting how resilient leaf blocks are against adverse influences (i.e. caterpillars). + */ + int getResilience(); - /** - * @return Growth conditions at the given position. - */ - EnumGrowthConditions getGrowthCondition(World world, int x, int y, int z); + /** + * @return Integer denoting the size of the tree trunk. + */ + int getGirth(World world, int x, int y, int z); - WorldGenerator getTreeGenerator(World world, int x, int y, int z, boolean wasBonemealed); + /** + * @return Growth conditions at the given position. + */ + EnumGrowthConditions getGrowthCondition(World world, int x, int y, int z); - ITree copy(); + WorldGenerator getTreeGenerator(World world, int x, int y, int z, boolean wasBonemealed); - boolean isPureBred(EnumTreeChromosome chromosome); + ITree copy(); - boolean canBearFruit(); + boolean isPureBred(EnumTreeChromosome chromosome); + + boolean canBearFruit(); } diff --git a/src/main/java/forestry/api/arboriculture/ITreeFactory.java b/src/main/java/forestry/api/arboriculture/ITreeFactory.java index 246f3edd1..fbcaf2d5c 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeFactory.java +++ b/src/main/java/forestry/api/arboriculture/ITreeFactory.java @@ -5,30 +5,39 @@ ******************************************************************************/ package forestry.api.arboriculture; +import forestry.api.genetics.IClassification; import java.awt.Color; -import forestry.api.genetics.IClassification; - public interface ITreeFactory { - /** - * Creates a new tree species. - * Automatically registered with AlleleManager.alleleRegistry.registerAllele() - * See IAlleleTreeSpeciesCustom and IAlleleSpeciesCustom for adding additional properties to the returned species. - * - * @param uid Unique Identifier for this species - * @param unlocalizedName Unlocalized name for this species - * @param authority Authority for the binomial name, e.g. "Sengir" on species of base Forestry. - * @param unlocalizedDescription Unlocalized description for this species - * @param dominant Whether this species is genetically dominant (false means it is recessive) - * @param branch Classification of this species - * @param binomial Binomial name of the species sans genus. "humboldti" will have the bee species flavour name be "Apis humboldti". Feel free to use fun names or null. - * @param leafIconProvider The leaf icon provider for this species - * @param germlingIconProvider The germling icon provider for this species - * @param generator The tree generator - * @return a new tree species allele. - */ - IAlleleTreeSpeciesCustom createSpecies(String uid, String unlocalizedName, String authority, String unlocalizedDescription, boolean dominant, IClassification branch, String binomial, ILeafIconProvider leafIconProvider, IGermlingIconProvider germlingIconProvider, ITreeGenerator generator); + /** + * Creates a new tree species. + * Automatically registered with AlleleManager.alleleRegistry.registerAllele() + * See IAlleleTreeSpeciesCustom and IAlleleSpeciesCustom for adding additional properties to the returned species. + * + * @param uid Unique Identifier for this species + * @param unlocalizedName Unlocalized name for this species + * @param authority Authority for the binomial name, e.g. "Sengir" on species of base Forestry. + * @param unlocalizedDescription Unlocalized description for this species + * @param dominant Whether this species is genetically dominant (false means it is recessive) + * @param branch Classification of this species + * @param binomial Binomial name of the species sans genus. "humboldti" will have the bee species flavour name be "Apis humboldti". Feel free to use fun names or null. + * @param leafIconProvider The leaf icon provider for this species + * @param germlingIconProvider The germling icon provider for this species + * @param generator The tree generator + * @return a new tree species allele. + */ + IAlleleTreeSpeciesCustom createSpecies( + String uid, + String unlocalizedName, + String authority, + String unlocalizedDescription, + boolean dominant, + IClassification branch, + String binomial, + ILeafIconProvider leafIconProvider, + IGermlingIconProvider germlingIconProvider, + ITreeGenerator generator); - /** Get one of the built-in Forestry leaf types. Default type is deciduous. */ - ILeafIconProvider getLeafIconProvider(EnumLeafType enumLeafType, Color color, Color colorPollinated); + /** Get one of the built-in Forestry leaf types. Default type is deciduous. */ + ILeafIconProvider getLeafIconProvider(EnumLeafType enumLeafType, Color color, Color colorPollinated); } diff --git a/src/main/java/forestry/api/arboriculture/ITreeGenerator.java b/src/main/java/forestry/api/arboriculture/ITreeGenerator.java index 6b62e7ac3..ff94c3323 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeGenerator.java +++ b/src/main/java/forestry/api/arboriculture/ITreeGenerator.java @@ -5,34 +5,31 @@ ******************************************************************************/ package forestry.api.arboriculture; +import com.mojang.authlib.GameProfile; +import forestry.api.world.ITreeGenData; import net.minecraft.world.World; import net.minecraft.world.gen.feature.WorldGenerator; - -import com.mojang.authlib.GameProfile; - import net.minecraftforge.common.util.ForgeDirection; -import forestry.api.world.ITreeGenData; - /** * Implements the tree generation for a tree species. */ public interface ITreeGenerator { - WorldGenerator getWorldGenerator(ITreeGenData tree); + WorldGenerator getWorldGenerator(ITreeGenData tree); - void setLogBlock(ITreeGenome genome, World world, int x, int y, int z, ForgeDirection facing); + void setLogBlock(ITreeGenome genome, World world, int x, int y, int z, ForgeDirection facing); - void setLeaves(ITreeGenome genome, World world, GameProfile owner, int x, int y, int z, boolean decorative); + void setLeaves(ITreeGenome genome, World world, GameProfile owner, int x, int y, int z, boolean decorative); - /** - * @deprecated since Forestry 4.2. use the genome version - */ - @Deprecated - void setLogBlock(World world, int x, int y, int z, ForgeDirection facing); + /** + * @deprecated since Forestry 4.2. use the genome version + */ + @Deprecated + void setLogBlock(World world, int x, int y, int z, ForgeDirection facing); - /** - * @deprecated since Forestry 4.2. use the genome version - */ - @Deprecated - void setLeaves(World world, GameProfile owner, int x, int y, int z, boolean decorative); + /** + * @deprecated since Forestry 4.2. use the genome version + */ + @Deprecated + void setLeaves(World world, GameProfile owner, int x, int y, int z, boolean decorative); } diff --git a/src/main/java/forestry/api/arboriculture/ITreeGenome.java b/src/main/java/forestry/api/arboriculture/ITreeGenome.java index ee5a1f029..02098945f 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeGenome.java +++ b/src/main/java/forestry/api/arboriculture/ITreeGenome.java @@ -1,46 +1,44 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; -import java.util.EnumSet; - -import net.minecraftforge.common.EnumPlantType; - import forestry.api.genetics.IGenome; +import java.util.EnumSet; +import net.minecraftforge.common.EnumPlantType; public interface ITreeGenome extends IGenome { - IAlleleTreeSpecies getPrimary(); + IAlleleTreeSpecies getPrimary(); - IAlleleTreeSpecies getSecondary(); + IAlleleTreeSpecies getSecondary(); - IFruitProvider getFruitProvider(); + IFruitProvider getFruitProvider(); - IGrowthProvider getGrowthProvider(); + IGrowthProvider getGrowthProvider(); - float getHeight(); + float getHeight(); - float getFertility(); + float getFertility(); - /** - * @return Determines either a) how many fruit leaves there are or b) the chance for any fruit leave to drop a sapling. Exact usage determined by the - * IFruitProvider - */ - float getYield(); + /** + * @return Determines either a) how many fruit leaves there are or b) the chance for any fruit leave to drop a sapling. Exact usage determined by the + * IFruitProvider + */ + float getYield(); - float getSappiness(); + float getSappiness(); - EnumSet getPlantTypes(); + EnumSet getPlantTypes(); - /** - * @return Amount of random block ticks required for a sapling to mature into a fully grown tree. - */ - int getMaturationTime(); + /** + * @return Amount of random block ticks required for a sapling to mature into a fully grown tree. + */ + int getMaturationTime(); - int getGirth(); + int getGirth(); - IAlleleLeafEffect getEffect(); + IAlleleLeafEffect getEffect(); } diff --git a/src/main/java/forestry/api/arboriculture/ITreeModifier.java b/src/main/java/forestry/api/arboriculture/ITreeModifier.java index 775f91ebe..69b7a56e3 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeModifier.java +++ b/src/main/java/forestry/api/arboriculture/ITreeModifier.java @@ -1,45 +1,44 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; public interface ITreeModifier { - /** - * - * @param genome - * @return Float used to modify the height. - */ - float getHeightModifier(ITreeGenome genome, float currentModifier); + /** + * + * @param genome + * @return Float used to modify the height. + */ + float getHeightModifier(ITreeGenome genome, float currentModifier); - /** - * - * @param genome - * @return Float used to modify the yield. - */ - float getYieldModifier(ITreeGenome genome, float currentModifier); + /** + * + * @param genome + * @return Float used to modify the yield. + */ + float getYieldModifier(ITreeGenome genome, float currentModifier); - /** - * - * @param genome - * @return Float used to modify the sappiness. - */ - float getSappinessModifier(ITreeGenome genome, float currentModifier); + /** + * + * @param genome + * @return Float used to modify the sappiness. + */ + float getSappinessModifier(ITreeGenome genome, float currentModifier); - /** - * - * @param genome - * @return Float used to modify the maturation. - */ - float getMaturationModifier(ITreeGenome genome, float currentModifier); - - /** - * @param genome0 - * @param genome1 - * @return Float used to modify the base mutation chance. - */ - float getMutationModifier(ITreeGenome genome0, ITreeGenome genome1, float currentModifier); + /** + * + * @param genome + * @return Float used to modify the maturation. + */ + float getMaturationModifier(ITreeGenome genome, float currentModifier); + /** + * @param genome0 + * @param genome1 + * @return Float used to modify the base mutation chance. + */ + float getMutationModifier(ITreeGenome genome0, ITreeGenome genome1, float currentModifier); } diff --git a/src/main/java/forestry/api/arboriculture/ITreeMutation.java b/src/main/java/forestry/api/arboriculture/ITreeMutation.java index 423e61692..ee33b625c 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeMutation.java +++ b/src/main/java/forestry/api/arboriculture/ITreeMutation.java @@ -1,25 +1,32 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; -import net.minecraft.world.World; - import forestry.api.genetics.IMutation; import forestry.api.genetics.ISpeciesRoot; +import net.minecraft.world.World; public interface ITreeMutation extends IMutation { - - /** - * @return {@link ISpeciesRoot} this mutation is associated with. - */ - ITreeRoot getRoot(); - /** - * @return float representing the percent chance for mutation to occur, from 0.0 to 100.0. - * @since Forestry 4.0 - */ - float getChance(World world, int x, int y, int z, IAlleleTreeSpecies allele0, IAlleleTreeSpecies allele1, ITreeGenome genome0, ITreeGenome genome1); + /** + * @return {@link ISpeciesRoot} this mutation is associated with. + */ + ITreeRoot getRoot(); + + /** + * @return float representing the percent chance for mutation to occur, from 0.0 to 100.0. + * @since Forestry 4.0 + */ + float getChance( + World world, + int x, + int y, + int z, + IAlleleTreeSpecies allele0, + IAlleleTreeSpecies allele1, + ITreeGenome genome0, + ITreeGenome genome1); } diff --git a/src/main/java/forestry/api/arboriculture/ITreeMutationCustom.java b/src/main/java/forestry/api/arboriculture/ITreeMutationCustom.java index b4d2075ad..fe0e705c5 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeMutationCustom.java +++ b/src/main/java/forestry/api/arboriculture/ITreeMutationCustom.java @@ -7,6 +7,4 @@ package forestry.api.arboriculture; import forestry.api.genetics.IMutationCustom; -public interface ITreeMutationCustom extends ITreeMutation, IMutationCustom { - -} +public interface ITreeMutationCustom extends ITreeMutation, IMutationCustom {} diff --git a/src/main/java/forestry/api/arboriculture/ITreeMutationFactory.java b/src/main/java/forestry/api/arboriculture/ITreeMutationFactory.java index a6cf802fc..f646ff70b 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeMutationFactory.java +++ b/src/main/java/forestry/api/arboriculture/ITreeMutationFactory.java @@ -8,16 +8,17 @@ package forestry.api.arboriculture; import forestry.api.genetics.IAllele; public interface ITreeMutationFactory { - /** - * Creates a new tree mutation. - * Automatically registered with TreeManager.treeRoot.registerMutation() - * See ITreeMutationCustom and IMutationCustom for adding additional properties to the returned mutation. - * - * @param parentTree0 A parent tree for this mutation - * @param parentTree1 A parent tree for this mutation - * @param result The resulting alleles for this mutation - * @param chance The chance that breeding the two parent trees will result in this mutation - * @return a new tree mutation. - */ - ITreeMutationCustom createMutation(IAlleleTreeSpecies parentTree0, IAlleleTreeSpecies parentTree1, IAllele[] result, int chance); + /** + * Creates a new tree mutation. + * Automatically registered with TreeManager.treeRoot.registerMutation() + * See ITreeMutationCustom and IMutationCustom for adding additional properties to the returned mutation. + * + * @param parentTree0 A parent tree for this mutation + * @param parentTree1 A parent tree for this mutation + * @param result The resulting alleles for this mutation + * @param chance The chance that breeding the two parent trees will result in this mutation + * @return a new tree mutation. + */ + ITreeMutationCustom createMutation( + IAlleleTreeSpecies parentTree0, IAlleleTreeSpecies parentTree1, IAllele[] result, int chance); } diff --git a/src/main/java/forestry/api/arboriculture/ITreeRoot.java b/src/main/java/forestry/api/arboriculture/ITreeRoot.java index d853b2a0a..4b7c7ae54 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeRoot.java +++ b/src/main/java/forestry/api/arboriculture/ITreeRoot.java @@ -1,99 +1,95 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; +import com.mojang.authlib.GameProfile; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IChromosome; +import forestry.api.genetics.ISpeciesRoot; import java.util.ArrayList; import java.util.Collection; - import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import com.mojang.authlib.GameProfile; - -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IChromosome; -import forestry.api.genetics.ISpeciesRoot; - public interface ITreeRoot extends ISpeciesRoot { - @Override - boolean isMember(ItemStack itemstack); + @Override + boolean isMember(ItemStack itemstack); - @Override - ITree getMember(ItemStack itemstack); + @Override + ITree getMember(ItemStack itemstack); - @Override - ITree getMember(NBTTagCompound compound); + @Override + ITree getMember(NBTTagCompound compound); - @Override - ITree templateAsIndividual(IAllele[] template); + @Override + ITree templateAsIndividual(IAllele[] template); - @Override - ITree templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive); + @Override + ITree templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive); - @Override - ITreeGenome templateAsGenome(IAllele[] template); + @Override + ITreeGenome templateAsGenome(IAllele[] template); - @Override - ITreeGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive); + @Override + ITreeGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive); - /** - * @param world - * @return {@link IArboristTracker} associated with the passed world. - */ - @Override - IArboristTracker getBreedingTracker(World world, GameProfile player); + /** + * @param world + * @return {@link IArboristTracker} associated with the passed world. + */ + @Override + IArboristTracker getBreedingTracker(World world, GameProfile player); - /* TREE SPECIFIC */ - /** - * Register a leaf tick handler. - * @param handler the {@link ILeafTickHandler} to register. - */ - void registerLeafTickHandler(ILeafTickHandler handler); + /* TREE SPECIFIC */ + /** + * Register a leaf tick handler. + * @param handler the {@link ILeafTickHandler} to register. + */ + void registerLeafTickHandler(ILeafTickHandler handler); - Collection getLeafTickHandlers(); + Collection getLeafTickHandlers(); - /** - * @return type of tree encoded on the itemstack. EnumGermlingType.NONE if it isn't a tree. - */ - @Override - EnumGermlingType getType(ItemStack stack); + /** + * @return type of tree encoded on the itemstack. EnumGermlingType.NONE if it isn't a tree. + */ + @Override + EnumGermlingType getType(ItemStack stack); - ITree getTree(World world, int x, int y, int z); + ITree getTree(World world, int x, int y, int z); - ITree getTree(World world, ITreeGenome genome); + ITree getTree(World world, ITreeGenome genome); - boolean plantSapling(World world, ITree tree, GameProfile owner, int x, int y, int z); + boolean plantSapling(World world, ITree tree, GameProfile owner, int x, int y, int z); - @Override - IChromosome[] templateAsChromosomes(IAllele[] template); + @Override + IChromosome[] templateAsChromosomes(IAllele[] template); - @Override - IChromosome[] templateAsChromosomes(IAllele[] templateActive, IAllele[] templateInactive); + @Override + IChromosome[] templateAsChromosomes(IAllele[] templateActive, IAllele[] templateInactive); - boolean setFruitBlock(World world, IAlleleFruit allele, float sappiness, short[] indices, int x, int y, int z); + boolean setFruitBlock(World world, IAlleleFruit allele, float sappiness, short[] indices, int x, int y, int z); - /* GAME MODE */ - ArrayList getTreekeepingModes(); + /* GAME MODE */ + ArrayList getTreekeepingModes(); - ITreekeepingMode getTreekeepingMode(World world); + ITreekeepingMode getTreekeepingMode(World world); - ITreekeepingMode getTreekeepingMode(String name); + ITreekeepingMode getTreekeepingMode(String name); - void registerTreekeepingMode(ITreekeepingMode mode); + void registerTreekeepingMode(ITreekeepingMode mode); - void setTreekeepingMode(World world, String name); + void setTreekeepingMode(World world, String name); - /* TEMPLATES */ - @Override - ArrayList getIndividualTemplates(); - - /* MUTATIONS */ - @Override - Collection getMutations(boolean shuffle); + /* TEMPLATES */ + @Override + ArrayList getIndividualTemplates(); + /* MUTATIONS */ + @Override + Collection getMutations(boolean shuffle); } diff --git a/src/main/java/forestry/api/arboriculture/ITreekeepingMode.java b/src/main/java/forestry/api/arboriculture/ITreekeepingMode.java index cc5224d8a..b742e3c74 100644 --- a/src/main/java/forestry/api/arboriculture/ITreekeepingMode.java +++ b/src/main/java/forestry/api/arboriculture/ITreekeepingMode.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; @@ -9,14 +9,13 @@ import java.util.ArrayList; public interface ITreekeepingMode extends ITreeModifier { - /** - * @return Localized name of this treekeeping mode. - */ - String getName(); - - /** - * @return Localized list of strings outlining the behaviour of this treekeeping mode. - */ - ArrayList getDescription(); + /** + * @return Localized name of this treekeeping mode. + */ + String getName(); + /** + * @return Localized list of strings outlining the behaviour of this treekeeping mode. + */ + ArrayList getDescription(); } diff --git a/src/main/java/forestry/api/arboriculture/IWoodItemAccess.java b/src/main/java/forestry/api/arboriculture/IWoodItemAccess.java index 023fdbd23..ad5bce076 100644 --- a/src/main/java/forestry/api/arboriculture/IWoodItemAccess.java +++ b/src/main/java/forestry/api/arboriculture/IWoodItemAccess.java @@ -8,9 +8,13 @@ package forestry.api.arboriculture; import net.minecraft.item.ItemStack; public interface IWoodItemAccess { - ItemStack getLog(EnumWoodType woodType, boolean fireproof); - ItemStack getPlanks(EnumWoodType woodType, boolean fireproof); - ItemStack getSlab(EnumWoodType woodType, boolean fireproof); - ItemStack getFence(EnumWoodType woodType, boolean fireproof); - ItemStack getStairs(EnumWoodType woodType, boolean fireproof); + ItemStack getLog(EnumWoodType woodType, boolean fireproof); + + ItemStack getPlanks(EnumWoodType woodType, boolean fireproof); + + ItemStack getSlab(EnumWoodType woodType, boolean fireproof); + + ItemStack getFence(EnumWoodType woodType, boolean fireproof); + + ItemStack getStairs(EnumWoodType woodType, boolean fireproof); } diff --git a/src/main/java/forestry/api/arboriculture/TreeManager.java b/src/main/java/forestry/api/arboriculture/TreeManager.java index e8e46c72e..f5c819f46 100644 --- a/src/main/java/forestry/api/arboriculture/TreeManager.java +++ b/src/main/java/forestry/api/arboriculture/TreeManager.java @@ -7,23 +7,23 @@ package forestry.api.arboriculture; public class TreeManager { - /** - * Convenient access to AlleleManager.alleleRegistry.getSpeciesRoot("rootTrees") - */ - public static ITreeRoot treeRoot; + /** + * Convenient access to AlleleManager.alleleRegistry.getSpeciesRoot("rootTrees") + */ + public static ITreeRoot treeRoot; - /** - * Convenient access to wood items. - */ - public static IWoodItemAccess woodItemAccess; + /** + * Convenient access to wood items. + */ + public static IWoodItemAccess woodItemAccess; - /** - * Used to create new trees. - */ - public static ITreeFactory treeFactory; + /** + * Used to create new trees. + */ + public static ITreeFactory treeFactory; - /** - * Used to create new tree mutations. - */ - public static ITreeMutationFactory treeMutationFactory; + /** + * Used to create new tree mutations. + */ + public static ITreeMutationFactory treeMutationFactory; } diff --git a/src/main/java/forestry/api/arboriculture/package-info.java b/src/main/java/forestry/api/arboriculture/package-info.java index ecf2105dc..488eb556a 100644 --- a/src/main/java/forestry/api/arboriculture/package-info.java +++ b/src/main/java/forestry/api/arboriculture/package-info.java @@ -1,8 +1,9 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ @API(apiVersion = "4.2.1", owner = "ForestryAPI|core", provides = "ForestryAPI|arboriculture") package forestry.api.arboriculture; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/api/circuits/ChipsetManager.java b/src/main/java/forestry/api/circuits/ChipsetManager.java index c5f0db5c3..b87b48b56 100644 --- a/src/main/java/forestry/api/circuits/ChipsetManager.java +++ b/src/main/java/forestry/api/circuits/ChipsetManager.java @@ -1,13 +1,12 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.circuits; public class ChipsetManager { - public static ISolderManager solderManager; - public static ICircuitRegistry circuitRegistry; - + public static ISolderManager solderManager; + public static ICircuitRegistry circuitRegistry; } diff --git a/src/main/java/forestry/api/circuits/CircuitSocketType.java b/src/main/java/forestry/api/circuits/CircuitSocketType.java index f7f67091a..0fa2ed345 100644 --- a/src/main/java/forestry/api/circuits/CircuitSocketType.java +++ b/src/main/java/forestry/api/circuits/CircuitSocketType.java @@ -6,24 +6,24 @@ package forestry.api.circuits; public enum CircuitSocketType implements ICircuitSocketType { - NONE("none"), - FARM("forestry.farm"), - ELECTRIC_ENGINE("forestry.electric.engine"), - MACHINE("forestry.machine"); + NONE("none"), + FARM("forestry.farm"), + ELECTRIC_ENGINE("forestry.electric.engine"), + MACHINE("forestry.machine"); - private final String uid; + private final String uid; - CircuitSocketType(String uid) { - this.uid = uid; - } + CircuitSocketType(String uid) { + this.uid = uid; + } - @Override - public String getUid() { - return uid; - } + @Override + public String getUid() { + return uid; + } - @Override - public boolean equals(ICircuitSocketType socketType) { - return uid.equals(socketType.getUid()); - } + @Override + public boolean equals(ICircuitSocketType socketType) { + return uid.equals(socketType.getUid()); + } } diff --git a/src/main/java/forestry/api/circuits/ICircuit.java b/src/main/java/forestry/api/circuits/ICircuit.java index 23175c19e..4986dc290 100644 --- a/src/main/java/forestry/api/circuits/ICircuit.java +++ b/src/main/java/forestry/api/circuits/ICircuit.java @@ -1,32 +1,30 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.circuits; import java.util.List; -import net.minecraft.tileentity.TileEntity; - public interface ICircuit { - String getUID(); + String getUID(); - boolean requiresDiscovery(); + boolean requiresDiscovery(); - int getLimit(); + int getLimit(); - String getName(); + String getName(); - boolean isCircuitable(Object tile); + boolean isCircuitable(Object tile); - void onInsertion(int slot, Object tile); + void onInsertion(int slot, Object tile); - void onLoad(int slot, Object tile); + void onLoad(int slot, Object tile); - void onRemoval(int slot, Object tile); + void onRemoval(int slot, Object tile); - void onTick(int slot, Object tile); + void onTick(int slot, Object tile); - void addTooltip(List list); + void addTooltip(List list); } diff --git a/src/main/java/forestry/api/circuits/ICircuitBoard.java b/src/main/java/forestry/api/circuits/ICircuitBoard.java index ef09575c2..605c21fc6 100644 --- a/src/main/java/forestry/api/circuits/ICircuitBoard.java +++ b/src/main/java/forestry/api/circuits/ICircuitBoard.java @@ -1,36 +1,34 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.circuits; -import java.util.List; - import forestry.api.core.INBTTagable; +import java.util.List; public interface ICircuitBoard extends INBTTagable { - int getPrimaryColor(); + int getPrimaryColor(); - int getSecondaryColor(); + int getSecondaryColor(); - void addTooltip(List list); + void addTooltip(List list); - void onInsertion(Object tile); + void onInsertion(Object tile); - void onLoad(Object tile); + void onLoad(Object tile); - void onRemoval(Object tile); + void onRemoval(Object tile); - void onTick(Object tile); - - ICircuit[] getCircuits(); + void onTick(Object tile); - /** - * Specifies where a circuit can be used. - * @since Forestry 4.0 - */ - ICircuitSocketType getSocketType(); + ICircuit[] getCircuits(); + /** + * Specifies where a circuit can be used. + * @since Forestry 4.0 + */ + ICircuitSocketType getSocketType(); } diff --git a/src/main/java/forestry/api/circuits/ICircuitLayout.java b/src/main/java/forestry/api/circuits/ICircuitLayout.java index 8c49ab120..dd25e1c22 100644 --- a/src/main/java/forestry/api/circuits/ICircuitLayout.java +++ b/src/main/java/forestry/api/circuits/ICircuitLayout.java @@ -1,25 +1,24 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.circuits; public interface ICircuitLayout { - /** unique ID for this circuit layout */ - String getUID(); + /** unique ID for this circuit layout */ + String getUID(); - /** localized name for this circuit layout */ - String getName(); + /** localized name for this circuit layout */ + String getName(); - /** localized string for how this circuit layout is used */ - String getUsage(); - - /** - * Specifies where a circuit layout is used. - * @since Forestry 4.0 - */ - ICircuitSocketType getSocketType(); + /** localized string for how this circuit layout is used */ + String getUsage(); + /** + * Specifies where a circuit layout is used. + * @since Forestry 4.0 + */ + ICircuitSocketType getSocketType(); } diff --git a/src/main/java/forestry/api/circuits/ICircuitLibrary.java b/src/main/java/forestry/api/circuits/ICircuitLibrary.java index 0d65ba458..34a1d600f 100644 --- a/src/main/java/forestry/api/circuits/ICircuitLibrary.java +++ b/src/main/java/forestry/api/circuits/ICircuitLibrary.java @@ -1,10 +1,8 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.circuits; -public interface ICircuitLibrary { - -} +public interface ICircuitLibrary {} diff --git a/src/main/java/forestry/api/circuits/ICircuitRegistry.java b/src/main/java/forestry/api/circuits/ICircuitRegistry.java index 9fb2b94d5..003d552e4 100644 --- a/src/main/java/forestry/api/circuits/ICircuitRegistry.java +++ b/src/main/java/forestry/api/circuits/ICircuitRegistry.java @@ -1,37 +1,35 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.circuits; import java.util.Map; - import net.minecraft.item.ItemStack; import net.minecraft.world.World; public interface ICircuitRegistry { - /* CIRCUITS */ - Map getRegisteredCircuits(); + /* CIRCUITS */ + Map getRegisteredCircuits(); - void registerCircuit(ICircuit circuit); + void registerCircuit(ICircuit circuit); - ICircuit getCircuit(String uid); + ICircuit getCircuit(String uid); - ICircuitLibrary getCircuitLibrary(World world, String playername); + ICircuitLibrary getCircuitLibrary(World world, String playername); - /* LAYOUTS */ - Map getRegisteredLayouts(); + /* LAYOUTS */ + Map getRegisteredLayouts(); - void registerLayout(ICircuitLayout layout); + void registerLayout(ICircuitLayout layout); - ICircuitLayout getLayout(String uid); + ICircuitLayout getLayout(String uid); - ICircuitLayout getDefaultLayout(); + ICircuitLayout getDefaultLayout(); - ICircuitBoard getCircuitboard(ItemStack itemstack); - - boolean isChipset(ItemStack itemstack); + ICircuitBoard getCircuitboard(ItemStack itemstack); + boolean isChipset(ItemStack itemstack); } diff --git a/src/main/java/forestry/api/circuits/ICircuitSocketType.java b/src/main/java/forestry/api/circuits/ICircuitSocketType.java index 60250f712..f033058f6 100644 --- a/src/main/java/forestry/api/circuits/ICircuitSocketType.java +++ b/src/main/java/forestry/api/circuits/ICircuitSocketType.java @@ -10,9 +10,9 @@ package forestry.api.circuits; * See CircuitSocketType for Forestry's uses. */ public interface ICircuitSocketType { - /** unique identifier for this socket type */ - String getUid(); + /** unique identifier for this socket type */ + String getUid(); - /** comparison using uid */ - boolean equals(ICircuitSocketType socketType); + /** comparison using uid */ + boolean equals(ICircuitSocketType socketType); } diff --git a/src/main/java/forestry/api/circuits/ISolderManager.java b/src/main/java/forestry/api/circuits/ISolderManager.java index af9b41f1b..b7742d0cb 100644 --- a/src/main/java/forestry/api/circuits/ISolderManager.java +++ b/src/main/java/forestry/api/circuits/ISolderManager.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.circuits; @@ -9,6 +9,5 @@ import net.minecraft.item.ItemStack; public interface ISolderManager { - void addRecipe(ICircuitLayout layout, ItemStack resource, ICircuit circuit); - + void addRecipe(ICircuitLayout layout, ItemStack resource, ICircuit circuit); } diff --git a/src/main/java/forestry/api/circuits/package-info.java b/src/main/java/forestry/api/circuits/package-info.java index 30a63300a..7a962ec83 100644 --- a/src/main/java/forestry/api/circuits/package-info.java +++ b/src/main/java/forestry/api/circuits/package-info.java @@ -5,4 +5,5 @@ ******************************************************************************/ @API(apiVersion = "3.1.0", owner = "ForestryAPI|core", provides = "ForestryAPI|circuits") package forestry.api.circuits; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/api/core/BiomeHelper.java b/src/main/java/forestry/api/core/BiomeHelper.java index bc20cd668..2ef71c8b2 100644 --- a/src/main/java/forestry/api/core/BiomeHelper.java +++ b/src/main/java/forestry/api/core/BiomeHelper.java @@ -2,35 +2,33 @@ package forestry.api.core; import java.util.HashMap; import java.util.Map; - import net.minecraft.world.biome.BiomeGenBase; - import net.minecraftforge.common.BiomeDictionary; public class BiomeHelper { - private static final Map isBiomeHellishCache = new HashMap(); + private static final Map isBiomeHellishCache = new HashMap(); - /** - * Determines if it can rain or snow in the given biome. - */ - public static boolean canRainOrSnow(BiomeGenBase biomeGenBase) { - return biomeGenBase.getEnableSnow() || biomeGenBase.canSpawnLightningBolt(); - } + /** + * Determines if it can rain or snow in the given biome. + */ + public static boolean canRainOrSnow(BiomeGenBase biomeGenBase) { + return biomeGenBase.getEnableSnow() || biomeGenBase.canSpawnLightningBolt(); + } - /** - * Determines if a given BiomeGenBase is of HELLISH temperature, since it is treated separately from actual temperature values. - * Uses the BiomeDictionary. - * @param biomeGen BiomeGenBase of the biome in question - * @return true, if the BiomeGenBase is a Nether-type biome; false otherwise. - */ - public static boolean isBiomeHellish(BiomeGenBase biomeGen) { - if (isBiomeHellishCache.containsKey(biomeGen)) { - return isBiomeHellishCache.get(biomeGen); - } + /** + * Determines if a given BiomeGenBase is of HELLISH temperature, since it is treated separately from actual temperature values. + * Uses the BiomeDictionary. + * @param biomeGen BiomeGenBase of the biome in question + * @return true, if the BiomeGenBase is a Nether-type biome; false otherwise. + */ + public static boolean isBiomeHellish(BiomeGenBase biomeGen) { + if (isBiomeHellishCache.containsKey(biomeGen)) { + return isBiomeHellishCache.get(biomeGen); + } - boolean isBiomeHellish = BiomeDictionary.isBiomeOfType(biomeGen, BiomeDictionary.Type.NETHER); - isBiomeHellishCache.put(biomeGen, isBiomeHellish); - return isBiomeHellish; - } + boolean isBiomeHellish = BiomeDictionary.isBiomeOfType(biomeGen, BiomeDictionary.Type.NETHER); + isBiomeHellishCache.put(biomeGen, isBiomeHellish); + return isBiomeHellish; + } } diff --git a/src/main/java/forestry/api/core/EnumHumidity.java b/src/main/java/forestry/api/core/EnumHumidity.java index a87431691..50594afcf 100644 --- a/src/main/java/forestry/api/core/EnumHumidity.java +++ b/src/main/java/forestry/api/core/EnumHumidity.java @@ -1,43 +1,43 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; /** * Many things Forestry use temperature and humidity of a biome to determine whether they can or how they can work or spawn at a given location. - * - * This enum concerns humidity. + * + * This enum concerns humidity. */ public enum EnumHumidity { - ARID("Arid"), NORMAL("Normal"), DAMP("Damp"); + ARID("Arid"), + NORMAL("Normal"), + DAMP("Damp"); - public final String name; + public final String name; - private EnumHumidity(String name) { - this.name = name; - } + private EnumHumidity(String name) { + this.name = name; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - /** - * Determines the EnumHumidity given a floating point representation of Minecraft Rainfall. - * To check if rainfall is possible in a biome, use BiomeHelper.canRainOrSnow(). - * @param rawHumidity raw rainfall value - * @return EnumHumidity corresponding to rainfall value - */ - public static EnumHumidity getFromValue(float rawHumidity) { - if (rawHumidity > 0.85f) { // matches BiomeGenBase.isHighHumidity() - return DAMP; - } - else if (rawHumidity >= 0.3f) { - return NORMAL; - } - else { - return ARID; - } - } + /** + * Determines the EnumHumidity given a floating point representation of Minecraft Rainfall. + * To check if rainfall is possible in a biome, use BiomeHelper.canRainOrSnow(). + * @param rawHumidity raw rainfall value + * @return EnumHumidity corresponding to rainfall value + */ + public static EnumHumidity getFromValue(float rawHumidity) { + if (rawHumidity > 0.85f) { // matches BiomeGenBase.isHighHumidity() + return DAMP; + } else if (rawHumidity >= 0.3f) { + return NORMAL; + } else { + return ARID; + } + } } diff --git a/src/main/java/forestry/api/core/EnumTemperature.java b/src/main/java/forestry/api/core/EnumTemperature.java index d73b9edd4..b183465ff 100644 --- a/src/main/java/forestry/api/core/EnumTemperature.java +++ b/src/main/java/forestry/api/core/EnumTemperature.java @@ -1,79 +1,79 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.util.IIcon; import net.minecraft.world.biome.BiomeGenBase; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - /** * Many things Forestry use temperature and humidity of a biome to determine whether they can or how they can work or spawn at a given location. - * + * * This enum concerns temperature. */ public enum EnumTemperature { - NONE("None", "habitats/ocean"), ICY("Icy", "habitats/snow"), COLD("Cold", "habitats/taiga"), - NORMAL("Normal", "habitats/plains"), WARM("Warm", "habitats/jungle"), HOT("Hot", "habitats/desert"), HELLISH("Hellish", "habitats/nether"); + NONE("None", "habitats/ocean"), + ICY("Icy", "habitats/snow"), + COLD("Cold", "habitats/taiga"), + NORMAL("Normal", "habitats/plains"), + WARM("Warm", "habitats/jungle"), + HOT("Hot", "habitats/desert"), + HELLISH("Hellish", "habitats/nether"); - public final String name; - public final String iconIndex; + public final String name; + public final String iconIndex; - private EnumTemperature(String name, String iconIndex) { - this.name = name; - this.iconIndex = iconIndex; - } + private EnumTemperature(String name, String iconIndex) { + this.name = name; + this.iconIndex = iconIndex; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return ForestryAPI.textureManager.getDefault(iconIndex); - } + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return ForestryAPI.textureManager.getDefault(iconIndex); + } - /** - * Determines the EnumTemperature given a floating point representation of - * Minecraft temperature. Hellish biomes are handled based on their biome - * type - check BiomeHelper.isBiomeHellish. - * @param rawTemp raw temperature value - * @return EnumTemperature corresponding to value of rawTemp - */ - public static EnumTemperature getFromValue(float rawTemp) { - if (rawTemp > 1.00f) { - return HOT; - } - else if (rawTemp > 0.85f) { - return WARM; - } - else if (rawTemp > 0.35f) { - return NORMAL; - } - else if (rawTemp > 0.0f) { - return COLD; - } - else { - return ICY; - } - } + /** + * Determines the EnumTemperature given a floating point representation of + * Minecraft temperature. Hellish biomes are handled based on their biome + * type - check BiomeHelper.isBiomeHellish. + * @param rawTemp raw temperature value + * @return EnumTemperature corresponding to value of rawTemp + */ + public static EnumTemperature getFromValue(float rawTemp) { + if (rawTemp > 1.00f) { + return HOT; + } else if (rawTemp > 0.85f) { + return WARM; + } else if (rawTemp > 0.35f) { + return NORMAL; + } else if (rawTemp > 0.0f) { + return COLD; + } else { + return ICY; + } + } - public static EnumTemperature getFromBiome(BiomeGenBase biomeGenBase) { - if (BiomeHelper.isBiomeHellish(biomeGenBase)) { - return HELLISH; - } - return getFromValue(biomeGenBase.temperature); - } + public static EnumTemperature getFromBiome(BiomeGenBase biomeGenBase) { + if (BiomeHelper.isBiomeHellish(biomeGenBase)) { + return HELLISH; + } + return getFromValue(biomeGenBase.temperature); + } - public static EnumTemperature getFromBiome(BiomeGenBase biomeGenBase, int x, int y, int z) { - if (BiomeHelper.isBiomeHellish(biomeGenBase)) { - return HELLISH; - } - float temperature = biomeGenBase.getFloatTemperature(x, y, z); - return getFromValue(temperature); - } + public static EnumTemperature getFromBiome(BiomeGenBase biomeGenBase, int x, int y, int z) { + if (BiomeHelper.isBiomeHellish(biomeGenBase)) { + return HELLISH; + } + float temperature = biomeGenBase.getFloatTemperature(x, y, z); + return getFromValue(temperature); + } } diff --git a/src/main/java/forestry/api/core/ForestryAPI.java b/src/main/java/forestry/api/core/ForestryAPI.java index 01011cadc..394bac3a9 100644 --- a/src/main/java/forestry/api/core/ForestryAPI.java +++ b/src/main/java/forestry/api/core/ForestryAPI.java @@ -1,21 +1,20 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; -import java.util.Set; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Set; /** * Forestry's API is divided into several subcategories to make it easier to understand. - * + * * If you need to distribute API files, try to only include the parts you are actually * using to minimize conflicts due to API changes. - * + * * .core - Miscallenous base classes and interfaces as well as some basics for tools, armor, game modes and stuff needed by biome mods. * .fuels - Managers and classes to facilitate adding fuels to various engines and machines. * .recipes - Managers and helpers to facilitate adding new recipes to various machines. @@ -25,44 +24,44 @@ import cpw.mods.fml.relauncher.SideOnly; * \ .apiculture - Bees. * \ .arboriculture - Trees. * \ .lepidopterology - Butterflies. - * + * * Note that if Forestry is not present, all these references will be null. */ public class ForestryAPI { - /** - * The main mod instance for Forestry. - */ - public static Object instance; + /** + * The main mod instance for Forestry. + */ + public static Object instance; - /** - * A {@link ITextureManager} needed for some things in the API. - */ - @SideOnly(Side.CLIENT) - public static ITextureManager textureManager; + /** + * A {@link ITextureManager} needed for some things in the API. + */ + @SideOnly(Side.CLIENT) + public static ITextureManager textureManager; - public static IClimateManager climateManager; + public static IClimateManager climateManager; - /** - * The currently active {@link IGameMode}. - */ - public static IGameMode activeMode; + /** + * The currently active {@link IGameMode}. + */ + public static IGameMode activeMode; - /** - * Provides information on certain Forestry constants (Villager IDs, Chest gen keys, etc) - */ - public static IForestryConstants forestryConstants; + /** + * Provides information on certain Forestry constants (Villager IDs, Chest gen keys, etc) + */ + public static IForestryConstants forestryConstants; - /** - * The currently enabled Forestry plugins. - * Can be used to check if certain features are available, for example: - * ForestryAPI.enabledPlugins.contains("APICULTURE") - */ - public static Set enabledPlugins; + /** + * The currently enabled Forestry plugins. + * Can be used to check if certain features are available, for example: + * ForestryAPI.enabledPlugins.contains("APICULTURE") + */ + public static Set enabledPlugins; - /** - * Instance of the errorStateRegistry for registering errors. - * Also creates new instances of IErrorLogic. - */ - public static IErrorStateRegistry errorStateRegistry; + /** + * Instance of the errorStateRegistry for registering errors. + * Also creates new instances of IErrorLogic. + */ + public static IErrorStateRegistry errorStateRegistry; } diff --git a/src/main/java/forestry/api/core/ForestryEvent.java b/src/main/java/forestry/api/core/ForestryEvent.java index 86aac9bcc..629a694a4 100644 --- a/src/main/java/forestry/api/core/ForestryEvent.java +++ b/src/main/java/forestry/api/core/ForestryEvent.java @@ -1,60 +1,60 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; -import net.minecraft.entity.player.EntityPlayer; - import com.mojang.authlib.GameProfile; - import cpw.mods.fml.common.eventhandler.Event; - import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.IMutation; import forestry.api.genetics.ISpeciesRoot; +import net.minecraft.entity.player.EntityPlayer; public abstract class ForestryEvent extends Event { - private static abstract class BreedingEvent extends ForestryEvent { - public final ISpeciesRoot root; - public final IBreedingTracker tracker; - public final GameProfile username; + private abstract static class BreedingEvent extends ForestryEvent { + public final ISpeciesRoot root; + public final IBreedingTracker tracker; + public final GameProfile username; - private BreedingEvent(ISpeciesRoot root, GameProfile username, IBreedingTracker tracker) { - super(); - this.root = root; - this.username = username; - this.tracker = tracker; - } - } + private BreedingEvent(ISpeciesRoot root, GameProfile username, IBreedingTracker tracker) { + super(); + this.root = root; + this.username = username; + this.tracker = tracker; + } + } - public static class SpeciesDiscovered extends BreedingEvent { - public final IAlleleSpecies species; - public SpeciesDiscovered(ISpeciesRoot root, GameProfile username, IAlleleSpecies species, IBreedingTracker tracker) { - super(root, username, tracker); - this.species = species; - } - } + public static class SpeciesDiscovered extends BreedingEvent { + public final IAlleleSpecies species; - public static class MutationDiscovered extends BreedingEvent { - public final IMutation allele; - public MutationDiscovered(ISpeciesRoot root, GameProfile username, IMutation allele, IBreedingTracker tracker) { - super(root, username, tracker); - this.allele = allele; - } - } + public SpeciesDiscovered( + ISpeciesRoot root, GameProfile username, IAlleleSpecies species, IBreedingTracker tracker) { + super(root, username, tracker); + this.species = species; + } + } - public static class SyncedBreedingTracker extends ForestryEvent { - public final IBreedingTracker tracker; - public final EntityPlayer player; - public SyncedBreedingTracker(IBreedingTracker tracker, EntityPlayer player) { - super(); - this.tracker = tracker; - this.player = player; - } + public static class MutationDiscovered extends BreedingEvent { + public final IMutation allele; - } + public MutationDiscovered(ISpeciesRoot root, GameProfile username, IMutation allele, IBreedingTracker tracker) { + super(root, username, tracker); + this.allele = allele; + } + } + + public static class SyncedBreedingTracker extends ForestryEvent { + public final IBreedingTracker tracker; + public final EntityPlayer player; + + public SyncedBreedingTracker(IBreedingTracker tracker, EntityPlayer player) { + super(); + this.tracker = tracker; + this.player = player; + } + } } diff --git a/src/main/java/forestry/api/core/IArmorNaturalist.java b/src/main/java/forestry/api/core/IArmorNaturalist.java index 87400e271..ab4766f30 100644 --- a/src/main/java/forestry/api/core/IArmorNaturalist.java +++ b/src/main/java/forestry/api/core/IArmorNaturalist.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; @@ -10,16 +10,16 @@ import net.minecraft.item.ItemStack; public interface IArmorNaturalist { - /** - * Called when the naturalist's armor acts as spectacles for seeing pollinated tree leaves/flowers. - * - * @param player - * Player doing the viewing - * @param armor - * Armor item - * @param doSee - * Whether or not to actually do the side effects of viewing - * @return true if the armor actually allows the player to see pollination. - */ - public boolean canSeePollination(EntityPlayer player, ItemStack armor, boolean doSee); + /** + * Called when the naturalist's armor acts as spectacles for seeing pollinated tree leaves/flowers. + * + * @param player + * Player doing the viewing + * @param armor + * Armor item + * @param doSee + * Whether or not to actually do the side effects of viewing + * @return true if the armor actually allows the player to see pollination. + */ + public boolean canSeePollination(EntityPlayer player, ItemStack armor, boolean doSee); } diff --git a/src/main/java/forestry/api/core/IClimateControlled.java b/src/main/java/forestry/api/core/IClimateControlled.java index 01ae27638..94e9de024 100644 --- a/src/main/java/forestry/api/core/IClimateControlled.java +++ b/src/main/java/forestry/api/core/IClimateControlled.java @@ -11,13 +11,13 @@ package forestry.api.core; public interface IClimateControlled { - /** - * Change the temperature, but not lower than boundaryDown or higher than boundaryUp. - */ - void addTemperatureChange(float change, float boundaryDown, float boundaryUp); + /** + * Change the temperature, but not lower than boundaryDown or higher than boundaryUp. + */ + void addTemperatureChange(float change, float boundaryDown, float boundaryUp); - /** - * Change the humidity, but not lower than boundaryDown or higher than boundaryUp. - */ - void addHumidityChange(float change, float boundaryDown, float boundaryUp); + /** + * Change the humidity, but not lower than boundaryDown or higher than boundaryUp. + */ + void addHumidityChange(float change, float boundaryDown, float boundaryUp); } diff --git a/src/main/java/forestry/api/core/IClimateManager.java b/src/main/java/forestry/api/core/IClimateManager.java index d1d822703..b18747f00 100644 --- a/src/main/java/forestry/api/core/IClimateManager.java +++ b/src/main/java/forestry/api/core/IClimateManager.java @@ -14,5 +14,4 @@ public interface IClimateManager { float getHumidity(World world, int x, int y, int z); IClimateProvider getDefaultClimate(World world, int x, int y, int z); - } diff --git a/src/main/java/forestry/api/core/IErrorLogic.java b/src/main/java/forestry/api/core/IErrorLogic.java index 03a9eb54f..0b4bec3e0 100644 --- a/src/main/java/forestry/api/core/IErrorLogic.java +++ b/src/main/java/forestry/api/core/IErrorLogic.java @@ -15,30 +15,31 @@ import java.io.IOException; */ public interface IErrorLogic extends IErrorSource { - /** - * Sets the errorState when condition is true, and unsets it when condition is false. - * @return condition - */ - boolean setCondition(boolean condition, IErrorState errorState); + /** + * Sets the errorState when condition is true, and unsets it when condition is false. + * @return condition + */ + boolean setCondition(boolean condition, IErrorState errorState); - /** - * @return true if the error state is active. - */ - boolean contains(IErrorState state); + /** + * @return true if the error state is active. + */ + boolean contains(IErrorState state); - /** - * @return true if there are any active error states. - */ - boolean hasErrors(); + /** + * @return true if there are any active error states. + */ + boolean hasErrors(); - /** - * Sets all active error states to false - */ - void clearErrors(); + /** + * Sets all active error states to false + */ + void clearErrors(); - /** - * Network serialization for syncing errors to the client from the server. - */ - void writeData(DataOutputStream data) throws IOException; - void readData(DataInputStream data) throws IOException; + /** + * Network serialization for syncing errors to the client from the server. + */ + void writeData(DataOutputStream data) throws IOException; + + void readData(DataInputStream data) throws IOException; } diff --git a/src/main/java/forestry/api/core/IErrorLogicSource.java b/src/main/java/forestry/api/core/IErrorLogicSource.java index 5161ae0ec..d0d69d90d 100644 --- a/src/main/java/forestry/api/core/IErrorLogicSource.java +++ b/src/main/java/forestry/api/core/IErrorLogicSource.java @@ -9,5 +9,5 @@ package forestry.api.core; * An IErrorLogicSource uses an instance of IErrorLogic to deal with its errors. */ public interface IErrorLogicSource { - IErrorLogic getErrorLogic(); + IErrorLogic getErrorLogic(); } diff --git a/src/main/java/forestry/api/core/IErrorSource.java b/src/main/java/forestry/api/core/IErrorSource.java index a594c4b2b..bde502412 100644 --- a/src/main/java/forestry/api/core/IErrorSource.java +++ b/src/main/java/forestry/api/core/IErrorSource.java @@ -8,8 +8,8 @@ package forestry.api.core; import com.google.common.collect.ImmutableSet; public interface IErrorSource { - /** - * @return the active error states. An empty Set indicates no errors. - */ - ImmutableSet getErrorStates(); + /** + * @return the active error states. An empty Set indicates no errors. + */ + ImmutableSet getErrorStates(); } diff --git a/src/main/java/forestry/api/core/IErrorState.java b/src/main/java/forestry/api/core/IErrorState.java index 90e21ebf3..d50ab35a1 100644 --- a/src/main/java/forestry/api/core/IErrorState.java +++ b/src/main/java/forestry/api/core/IErrorState.java @@ -5,30 +5,28 @@ ******************************************************************************/ package forestry.api.core; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.util.IIcon; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.util.IIcon; /** * * @author CovertJaguar */ public interface IErrorState { - - short getID(); - - String getUniqueName(); - String getDescription(); + short getID(); - String getHelp(); + String getUniqueName(); - @SideOnly(Side.CLIENT) - void registerIcons(IIconRegister register); + String getDescription(); - @SideOnly(value = Side.CLIENT) - IIcon getIcon(); + String getHelp(); + @SideOnly(Side.CLIENT) + void registerIcons(IIconRegister register); + + @SideOnly(value = Side.CLIENT) + IIcon getIcon(); } diff --git a/src/main/java/forestry/api/core/IErrorStateRegistry.java b/src/main/java/forestry/api/core/IErrorStateRegistry.java index fc67ae78a..bc033b9ec 100644 --- a/src/main/java/forestry/api/core/IErrorStateRegistry.java +++ b/src/main/java/forestry/api/core/IErrorStateRegistry.java @@ -8,12 +8,15 @@ package forestry.api.core; import java.util.Set; public interface IErrorStateRegistry { - void registerErrorState(IErrorState state); - void addAlias(IErrorState state, String name); + void registerErrorState(IErrorState state); - IErrorState getErrorState(short id); - IErrorState getErrorState(String name); - Set getErrorStates(); + void addAlias(IErrorState state, String name); - IErrorLogic createErrorLogic(); + IErrorState getErrorState(short id); + + IErrorState getErrorState(String name); + + Set getErrorStates(); + + IErrorLogic createErrorLogic(); } diff --git a/src/main/java/forestry/api/core/IForestryConstants.java b/src/main/java/forestry/api/core/IForestryConstants.java index 4cf876f67..a7fbad5ce 100644 --- a/src/main/java/forestry/api/core/IForestryConstants.java +++ b/src/main/java/forestry/api/core/IForestryConstants.java @@ -1,24 +1,24 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; public interface IForestryConstants { - /** - * @return The villager ID for the Apiarist Villager. - */ - public int getApicultureVillagerID(); - - /** - * @return The villager ID for the Arborist Villager. - */ - public int getArboricultureVillagerID(); - - /** - * @return The ChestGenHooks key for adding items to the Forestry Villager chest. - */ - public String getVillagerChestGenKey(); + /** + * @return The villager ID for the Apiarist Villager. + */ + public int getApicultureVillagerID(); + + /** + * @return The villager ID for the Arborist Villager. + */ + public int getArboricultureVillagerID(); + + /** + * @return The ChestGenHooks key for adding items to the Forestry Villager chest. + */ + public String getVillagerChestGenKey(); } diff --git a/src/main/java/forestry/api/core/IGameMode.java b/src/main/java/forestry/api/core/IGameMode.java index 0b2b0c55d..eaa9931ad 100644 --- a/src/main/java/forestry/api/core/IGameMode.java +++ b/src/main/java/forestry/api/core/IGameMode.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; @@ -9,33 +9,32 @@ import net.minecraft.item.ItemStack; public interface IGameMode { - /** - * @return Human-readable identifier for the game mode. (i.e. 'EASY', 'NORMAL', 'HARD') - */ - String getIdentifier(); + /** + * @return Human-readable identifier for the game mode. (i.e. 'EASY', 'NORMAL', 'HARD') + */ + String getIdentifier(); - /** - * @param ident Identifier for the setting. (See the gamemode config.) - * @return Value of the requested setting, false if unknown setting. - */ - boolean getBooleanSetting(String ident); - - /** - * @param ident Identifier for the setting. (See the gamemode config.) - * @return Value of the requested setting, 0 if unknown setting. - */ - int getIntegerSetting(String ident); + /** + * @param ident Identifier for the setting. (See the gamemode config.) + * @return Value of the requested setting, false if unknown setting. + */ + boolean getBooleanSetting(String ident); - /** - * @param ident Identifier for the setting. (See the gamemode config.) - * @return Value of the requested setting, 0 if unknown setting. - */ - float getFloatSetting(String ident); + /** + * @param ident Identifier for the setting. (See the gamemode config.) + * @return Value of the requested setting, 0 if unknown setting. + */ + int getIntegerSetting(String ident); - /** - * @param ident Identifier for the setting. (See the gamemode config.) - * @return Value of the requested setting, an itemstack containing an apple if unknown setting. - */ - ItemStack getStackSetting(String ident); + /** + * @param ident Identifier for the setting. (See the gamemode config.) + * @return Value of the requested setting, 0 if unknown setting. + */ + float getFloatSetting(String ident); + /** + * @param ident Identifier for the setting. (See the gamemode config.) + * @return Value of the requested setting, an itemstack containing an apple if unknown setting. + */ + ItemStack getStackSetting(String ident); } diff --git a/src/main/java/forestry/api/core/IIconProvider.java b/src/main/java/forestry/api/core/IIconProvider.java index 308e3ce5f..ae29102ec 100644 --- a/src/main/java/forestry/api/core/IIconProvider.java +++ b/src/main/java/forestry/api/core/IIconProvider.java @@ -1,25 +1,23 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - /** - * Provides icons, needed in some interfaces, most notably for bees and trees. + * Provides icons, needed in some interfaces, most notably for bees and trees. */ public interface IIconProvider { - - @SideOnly(Side.CLIENT) - IIcon getIcon(short texUID); - - @SideOnly(Side.CLIENT) - void registerIcons(IIconRegister register); + @SideOnly(Side.CLIENT) + IIcon getIcon(short texUID); + + @SideOnly(Side.CLIENT) + void registerIcons(IIconRegister register); } diff --git a/src/main/java/forestry/api/core/INBTTagable.java b/src/main/java/forestry/api/core/INBTTagable.java index 1d3f85808..cd09390ac 100644 --- a/src/main/java/forestry/api/core/INBTTagable.java +++ b/src/main/java/forestry/api/core/INBTTagable.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; @@ -8,7 +8,7 @@ package forestry.api.core; import net.minecraft.nbt.NBTTagCompound; public interface INBTTagable { - void readFromNBT(NBTTagCompound nbttagcompound); + void readFromNBT(NBTTagCompound nbttagcompound); - void writeToNBT(NBTTagCompound nbttagcompound); + void writeToNBT(NBTTagCompound nbttagcompound); } diff --git a/src/main/java/forestry/api/core/ITextureManager.java b/src/main/java/forestry/api/core/ITextureManager.java index a259fcaea..1114ab661 100644 --- a/src/main/java/forestry/api/core/ITextureManager.java +++ b/src/main/java/forestry/api/core/ITextureManager.java @@ -1,21 +1,20 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; -import net.minecraft.util.IIcon; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.util.IIcon; @SideOnly(Side.CLIENT) public interface ITextureManager { - void registerIconProvider(IIconProvider provider); + void registerIconProvider(IIconProvider provider); - IIcon getIcon(short texUID); + IIcon getIcon(short texUID); - IIcon getDefault(String ident); + IIcon getDefault(String ident); } diff --git a/src/main/java/forestry/api/core/IToolPipette.java b/src/main/java/forestry/api/core/IToolPipette.java index f5f1a6338..9ef992fdd 100644 --- a/src/main/java/forestry/api/core/IToolPipette.java +++ b/src/main/java/forestry/api/core/IToolPipette.java @@ -11,7 +11,6 @@ package forestry.api.core; import net.minecraft.item.ItemStack; - import net.minecraftforge.fluids.FluidStack; /** diff --git a/src/main/java/forestry/api/core/IToolScoop.java b/src/main/java/forestry/api/core/IToolScoop.java index 583b6c7ed..1fe6f392b 100644 --- a/src/main/java/forestry/api/core/IToolScoop.java +++ b/src/main/java/forestry/api/core/IToolScoop.java @@ -1,13 +1,11 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; /** - * Marks a tool as a scoop. + * Marks a tool as a scoop. */ -public interface IToolScoop { - -} +public interface IToolScoop {} diff --git a/src/main/java/forestry/api/core/Tabs.java b/src/main/java/forestry/api/core/Tabs.java index 4ce85838d..c11cc250a 100644 --- a/src/main/java/forestry/api/core/Tabs.java +++ b/src/main/java/forestry/api/core/Tabs.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; @@ -8,12 +8,11 @@ package forestry.api.core; import net.minecraft.creativetab.CreativeTabs; /** - * References to the specialised tabs added by Forestry to creative inventory. + * References to the specialised tabs added by Forestry to creative inventory. */ public class Tabs { - public static CreativeTabs tabApiculture; - public static CreativeTabs tabArboriculture; - public static CreativeTabs tabLepidopterology; - + public static CreativeTabs tabApiculture; + public static CreativeTabs tabArboriculture; + public static CreativeTabs tabLepidopterology; } diff --git a/src/main/java/forestry/api/core/package-info.java b/src/main/java/forestry/api/core/package-info.java index 0c4c98885..52e850ac1 100644 --- a/src/main/java/forestry/api/core/package-info.java +++ b/src/main/java/forestry/api/core/package-info.java @@ -5,4 +5,5 @@ ******************************************************************************/ @API(apiVersion = "5.0.0", owner = "Forestry", provides = "ForestryAPI|core") package forestry.api.core; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/api/farming/DefaultFarmListener.java b/src/main/java/forestry/api/farming/DefaultFarmListener.java index 837d51d65..4dcd24937 100644 --- a/src/main/java/forestry/api/farming/DefaultFarmListener.java +++ b/src/main/java/forestry/api/farming/DefaultFarmListener.java @@ -6,45 +6,34 @@ package forestry.api.farming; import java.util.Collection; - import net.minecraft.item.ItemStack; -import net.minecraftforge.common.util.ForgeDirection; - /** * Easily extendable default farmListener. * By itself, this farmListener does nothing. * FarmListeners should inherit from this class unless they need to listen for everything. */ public class DefaultFarmListener implements IFarmListener { - @Override - public boolean beforeCropHarvest(ICrop crop) { - return false; - } + @Override + public boolean beforeCropHarvest(ICrop crop) { + return false; + } - @Override - public void afterCropHarvest(Collection harvested, ICrop crop) { + @Override + public void afterCropHarvest(Collection harvested, ICrop crop) {} - } + @Override + public void hasCollected(Collection collected, IFarmLogic logic) {} - @Override - public void hasCollected(Collection collected, IFarmLogic logic) { + @Override + public void hasCultivated(IFarmLogic logic, int x, int y, int z, FarmDirection direction, int extent) {} - } - - @Override - public void hasCultivated(IFarmLogic logic, int x, int y, int z, FarmDirection direction, int extent) { - - } - - @Override - public void hasScheduledHarvest(Collection harvested, IFarmLogic logic, int x, int y, int z, FarmDirection direction, int extent) { - - } - - @Override - public boolean cancelTask(IFarmLogic logic, FarmDirection direction) { - return false; - } + @Override + public void hasScheduledHarvest( + Collection harvested, IFarmLogic logic, int x, int y, int z, FarmDirection direction, int extent) {} + @Override + public boolean cancelTask(IFarmLogic logic, FarmDirection direction) { + return false; + } } diff --git a/src/main/java/forestry/api/farming/FarmDirection.java b/src/main/java/forestry/api/farming/FarmDirection.java index ea9808062..051170e54 100644 --- a/src/main/java/forestry/api/farming/FarmDirection.java +++ b/src/main/java/forestry/api/farming/FarmDirection.java @@ -8,28 +8,32 @@ package forestry.api.farming; import net.minecraftforge.common.util.ForgeDirection; public enum FarmDirection { - NORTH(ForgeDirection.NORTH), - EAST(ForgeDirection.EAST), - SOUTH(ForgeDirection.SOUTH), - WEST(ForgeDirection.WEST); + NORTH(ForgeDirection.NORTH), + EAST(ForgeDirection.EAST), + SOUTH(ForgeDirection.SOUTH), + WEST(ForgeDirection.WEST); - private final ForgeDirection forgeDirection; + private final ForgeDirection forgeDirection; - FarmDirection(ForgeDirection forgeDirection) { - this.forgeDirection = forgeDirection; - } + FarmDirection(ForgeDirection forgeDirection) { + this.forgeDirection = forgeDirection; + } - public ForgeDirection getForgeDirection() { - return forgeDirection; - } + public ForgeDirection getForgeDirection() { + return forgeDirection; + } - public static FarmDirection getFarmDirection(ForgeDirection forgeDirection) { - switch (forgeDirection) { - case NORTH: return NORTH; - case EAST: return EAST; - case SOUTH: return SOUTH; - case WEST: return WEST; - } - return null; - } + public static FarmDirection getFarmDirection(ForgeDirection forgeDirection) { + switch (forgeDirection) { + case NORTH: + return NORTH; + case EAST: + return EAST; + case SOUTH: + return SOUTH; + case WEST: + return WEST; + } + return null; + } } diff --git a/src/main/java/forestry/api/farming/Farmables.java b/src/main/java/forestry/api/farming/Farmables.java index 9816e64ee..3a864b7b4 100644 --- a/src/main/java/forestry/api/farming/Farmables.java +++ b/src/main/java/forestry/api/farming/Farmables.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.farming; @@ -9,11 +9,10 @@ import java.util.Collection; import java.util.HashMap; public class Farmables { - /** - * Can be used to add IFarmables to some of the vanilla farm logics. - * - * Identifiers: farmArboreal farmWheat farmGourd farmInfernal farmPoales farmSucculentes farmVegetables farmShroom - */ - public static HashMap> farmables = new HashMap>(); - + /** + * Can be used to add IFarmables to some of the vanilla farm logics. + * + * Identifiers: farmArboreal farmWheat farmGourd farmInfernal farmPoales farmSucculentes farmVegetables farmShroom + */ + public static HashMap> farmables = new HashMap>(); } diff --git a/src/main/java/forestry/api/farming/ICrop.java b/src/main/java/forestry/api/farming/ICrop.java index 22575477d..c766d57bf 100644 --- a/src/main/java/forestry/api/farming/ICrop.java +++ b/src/main/java/forestry/api/farming/ICrop.java @@ -1,21 +1,19 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.farming; import java.util.Collection; - import net.minecraft.item.ItemStack; public interface ICrop { - /** - * Harvests this crop. Performs the necessary manipulations to set the crop into a "harvested" state. - * - * @return Products harvested. - */ - Collection harvest(); - + /** + * Harvests this crop. Performs the necessary manipulations to set the crop into a "harvested" state. + * + * @return Products harvested. + */ + Collection harvest(); } diff --git a/src/main/java/forestry/api/farming/IFarmHousing.java b/src/main/java/forestry/api/farming/IFarmHousing.java index 934c636e9..0fdb0caf0 100644 --- a/src/main/java/forestry/api/farming/IFarmHousing.java +++ b/src/main/java/forestry/api/farming/IFarmHousing.java @@ -1,48 +1,52 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.farming; -import net.minecraft.world.World; - -import net.minecraftforge.fluids.FluidStack; - import forestry.api.core.IErrorLogicSource; +import net.minecraft.world.World; +import net.minecraftforge.fluids.FluidStack; public interface IFarmHousing extends IErrorLogicSource { - int[] getCoords(); - int[] getArea(); - int[] getOffset(); - World getWorld(); + int[] getCoords(); - /** - * @return true if any work was done, false otherwise. - */ - boolean doWork(); + int[] getArea(); - boolean hasLiquid(FluidStack liquid); - void removeLiquid(FluidStack liquid); + int[] getOffset(); - /** - * Callback for {@link IFarmLogic}s to plant a sapling, seed, germling, stem. - * Will remove the appropriate germling from the farm's inventory. - * It's up to the logic to only call this on a valid location. - * - * @return true if planting was successful, false otherwise. - */ - boolean plantGermling(IFarmable farmable, World world, int x, int y, int z); + World getWorld(); - /* INTERACTION WITH HATCHES */ - IFarmInventory getFarmInventory(); + /** + * @return true if any work was done, false otherwise. + */ + boolean doWork(); - /* LOGIC */ - void setFarmLogic(FarmDirection direction, IFarmLogic logic); - void resetFarmLogic(FarmDirection direction); - IFarmLogic getFarmLogic(FarmDirection direction); + boolean hasLiquid(FluidStack liquid); - /* GUI */ - int getStoredFertilizerScaled(int scale); + void removeLiquid(FluidStack liquid); + + /** + * Callback for {@link IFarmLogic}s to plant a sapling, seed, germling, stem. + * Will remove the appropriate germling from the farm's inventory. + * It's up to the logic to only call this on a valid location. + * + * @return true if planting was successful, false otherwise. + */ + boolean plantGermling(IFarmable farmable, World world, int x, int y, int z); + + /* INTERACTION WITH HATCHES */ + IFarmInventory getFarmInventory(); + + /* LOGIC */ + void setFarmLogic(FarmDirection direction, IFarmLogic logic); + + void resetFarmLogic(FarmDirection direction); + + IFarmLogic getFarmLogic(FarmDirection direction); + + /* GUI */ + int getStoredFertilizerScaled(int scale); } diff --git a/src/main/java/forestry/api/farming/IFarmInventory.java b/src/main/java/forestry/api/farming/IFarmInventory.java index 36f45ea39..10d3f74f5 100644 --- a/src/main/java/forestry/api/farming/IFarmInventory.java +++ b/src/main/java/forestry/api/farming/IFarmInventory.java @@ -9,15 +9,21 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; public interface IFarmInventory { - boolean hasResources(ItemStack[] resources); - void removeResources(ItemStack[] resources); + boolean hasResources(ItemStack[] resources); - boolean acceptsAsGermling(ItemStack itemstack); - boolean acceptsAsResource(ItemStack itemstack); - boolean acceptsAsFertilizer(ItemStack itemstack); + void removeResources(ItemStack[] resources); - IInventory getProductInventory(); - IInventory getGermlingsInventory(); - IInventory getResourcesInventory(); - IInventory getFertilizerInventory(); + boolean acceptsAsGermling(ItemStack itemstack); + + boolean acceptsAsResource(ItemStack itemstack); + + boolean acceptsAsFertilizer(ItemStack itemstack); + + IInventory getProductInventory(); + + IInventory getGermlingsInventory(); + + IInventory getResourcesInventory(); + + IInventory getFertilizerInventory(); } diff --git a/src/main/java/forestry/api/farming/IFarmListener.java b/src/main/java/forestry/api/farming/IFarmListener.java index e1875c605..9b25f1bb9 100644 --- a/src/main/java/forestry/api/farming/IFarmListener.java +++ b/src/main/java/forestry/api/farming/IFarmListener.java @@ -6,50 +6,48 @@ package forestry.api.farming; import java.util.Collection; - import net.minecraft.item.ItemStack; -import net.minecraftforge.common.util.ForgeDirection; - public interface IFarmListener { - /** - * Called before a crop is harvested. - * - * @param crop ICrop about to be harvested. - * @return true to cancel further processing of this crop. - */ - boolean beforeCropHarvest(ICrop crop); + /** + * Called before a crop is harvested. + * + * @param crop ICrop about to be harvested. + * @return true to cancel further processing of this crop. + */ + boolean beforeCropHarvest(ICrop crop); - /** - * Called after a crop has been harvested, but before harvested items are stowed in the farms inventory. - * - * @param harvested Collection of harvested stacks. May be manipulated. Ensure removal of stacks with 0 or less items! - * @param crop Harvested {@link ICrop} - */ - void afterCropHarvest(Collection harvested, ICrop crop); + /** + * Called after a crop has been harvested, but before harvested items are stowed in the farms inventory. + * + * @param harvested Collection of harvested stacks. May be manipulated. Ensure removal of stacks with 0 or less items! + * @param crop Harvested {@link ICrop} + */ + void afterCropHarvest(Collection harvested, ICrop crop); - /** - * Called after the stack of collected items has been returned by the farm logic, but before it is added to the farm's pending queue. - * - * @param collected Collection of collected stacks. May be manipulated. Ensure removal of stacks with 0 or less items! - */ - void hasCollected(Collection collected, IFarmLogic logic); + /** + * Called after the stack of collected items has been returned by the farm logic, but before it is added to the farm's pending queue. + * + * @param collected Collection of collected stacks. May be manipulated. Ensure removal of stacks with 0 or less items! + */ + void hasCollected(Collection collected, IFarmLogic logic); - /** - * Called after farmland has successfully been cultivated by a farm logic. - */ - void hasCultivated(IFarmLogic logic, int x, int y, int z, FarmDirection direction, int extent); + /** + * Called after farmland has successfully been cultivated by a farm logic. + */ + void hasCultivated(IFarmLogic logic, int x, int y, int z, FarmDirection direction, int extent); - /** - * Called after the stack of harvested crops has been returned by the farm logic, but before it is added to the farm's pending queue. - */ - void hasScheduledHarvest(Collection harvested, IFarmLogic logic, int x, int y, int z, FarmDirection direction, int extent); + /** + * Called after the stack of harvested crops has been returned by the farm logic, but before it is added to the farm's pending queue. + */ + void hasScheduledHarvest( + Collection harvested, IFarmLogic logic, int x, int y, int z, FarmDirection direction, int extent); - /** - * Can be used to cancel farm task on a per side/{@link IFarmLogic} basis. - * - * @return true to skip any work action on the given logic and direction for this work cycle. - */ - boolean cancelTask(IFarmLogic logic, FarmDirection direction); + /** + * Can be used to cancel farm task on a per side/{@link IFarmLogic} basis. + * + * @return true to skip any work action on the given logic and direction for this work cycle. + */ + boolean cancelTask(IFarmLogic logic, FarmDirection direction); } diff --git a/src/main/java/forestry/api/farming/IFarmLogic.java b/src/main/java/forestry/api/farming/IFarmLogic.java index f38a0a8e8..b0ad53afd 100644 --- a/src/main/java/forestry/api/farming/IFarmLogic.java +++ b/src/main/java/forestry/api/farming/IFarmLogic.java @@ -1,41 +1,39 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.farming; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import java.util.Collection; - import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - public interface IFarmLogic { - int getFertilizerConsumption(); + int getFertilizerConsumption(); - int getWaterConsumption(float hydrationModifier); + int getWaterConsumption(float hydrationModifier); - boolean isAcceptedResource(ItemStack itemstack); + boolean isAcceptedResource(ItemStack itemstack); - boolean isAcceptedGermling(ItemStack itemstack); + boolean isAcceptedGermling(ItemStack itemstack); - Collection collect(); + Collection collect(); - boolean cultivate(int x, int y, int z, FarmDirection direction, int extent); + boolean cultivate(int x, int y, int z, FarmDirection direction, int extent); - Collection harvest(int x, int y, int z, FarmDirection direction, int extent); + Collection harvest(int x, int y, int z, FarmDirection direction, int extent); - IFarmLogic setManual(boolean manual); + IFarmLogic setManual(boolean manual); - @SideOnly(Side.CLIENT) - IIcon getIcon(); + @SideOnly(Side.CLIENT) + IIcon getIcon(); - ResourceLocation getSpriteSheet(); - - String getName(); + ResourceLocation getSpriteSheet(); + + String getName(); } diff --git a/src/main/java/forestry/api/farming/IFarmable.java b/src/main/java/forestry/api/farming/IFarmable.java index 77bc93549..c2fb1c7bc 100644 --- a/src/main/java/forestry/api/farming/IFarmable.java +++ b/src/main/java/forestry/api/farming/IFarmable.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.farming; @@ -14,32 +14,31 @@ import net.minecraft.world.World; */ public interface IFarmable { - /** - * @return true if the block at the given location is a "sapling" for this type, i.e. a non-harvestable immature version of the crop. - */ - boolean isSaplingAt(World world, int x, int y, int z); + /** + * @return true if the block at the given location is a "sapling" for this type, i.e. a non-harvestable immature version of the crop. + */ + boolean isSaplingAt(World world, int x, int y, int z); - /** - * @return {@link ICrop} if the block at the given location is a harvestable and mature crop, null otherwise. - */ - ICrop getCropAt(World world, int x, int y, int z); + /** + * @return {@link ICrop} if the block at the given location is a harvestable and mature crop, null otherwise. + */ + ICrop getCropAt(World world, int x, int y, int z); - /** - * @return true if the item is a valid germling (plantable sapling, seed, etc.) for this type. - */ - boolean isGermling(ItemStack itemstack); + /** + * @return true if the item is a valid germling (plantable sapling, seed, etc.) for this type. + */ + boolean isGermling(ItemStack itemstack); - /** - * @return true if the item is something that can drop from this type without actually being harvested as a crop. (Apples or sapling from decaying leaves.) - */ - boolean isWindfall(ItemStack itemstack); - - /** - * Plants a sapling by manipulating the world. The {@link IFarmLogic} should have verified the given location as valid. Called by the {@link IFarmHousing} - * which handles resources. - * - * @return true on success, false otherwise. - */ - boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z); + /** + * @return true if the item is something that can drop from this type without actually being harvested as a crop. (Apples or sapling from decaying leaves.) + */ + boolean isWindfall(ItemStack itemstack); + /** + * Plants a sapling by manipulating the world. The {@link IFarmLogic} should have verified the given location as valid. Called by the {@link IFarmHousing} + * which handles resources. + * + * @return true on success, false otherwise. + */ + boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z); } diff --git a/src/main/java/forestry/api/farming/IFarmableBasic.java b/src/main/java/forestry/api/farming/IFarmableBasic.java index 84f3cfcc1..e6a20f49d 100644 --- a/src/main/java/forestry/api/farming/IFarmableBasic.java +++ b/src/main/java/forestry/api/farming/IFarmableBasic.java @@ -13,20 +13,20 @@ import net.minecraft.world.World; */ public interface IFarmableBasic extends IFarmable { - /** - * @return true if the block at the given location is a "sapling" for this type, i.e. a non-harvestable immature version of the crop. - */ - default boolean isSaplingAt(World world, int x, int y, int z) { - return world.blockExists(x, y, z) && isSapling(world.getBlock(x, y, z), isMetadataAware() ? world.getBlockMetadata(x, y, z) : 0); - } + /** + * @return true if the block at the given location is a "sapling" for this type, i.e. a non-harvestable immature version of the crop. + */ + default boolean isSaplingAt(World world, int x, int y, int z) { + return world.blockExists(x, y, z) + && isSapling(world.getBlock(x, y, z), isMetadataAware() ? world.getBlockMetadata(x, y, z) : 0); + } + /** + * @return true if given block at the given location is a "sapling" for this type, i.e. a non-harvestable immature version of the crop. + */ + boolean isSapling(Block block, int meta); - /** - * @return true if given block at the given location is a "sapling" for this type, i.e. a non-harvestable immature version of the crop. - */ - boolean isSapling(Block block, int meta); - - default boolean isMetadataAware() { - return false; - } + default boolean isMetadataAware() { + return false; + } } diff --git a/src/main/java/forestry/api/farming/package-info.java b/src/main/java/forestry/api/farming/package-info.java index ad99e6533..dfa739708 100644 --- a/src/main/java/forestry/api/farming/package-info.java +++ b/src/main/java/forestry/api/farming/package-info.java @@ -1,8 +1,9 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ -@API(apiVersion="2.1.0", owner="ForestryAPI|core", provides="ForestryAPI|farming") +@API(apiVersion = "2.1.0", owner = "ForestryAPI|core", provides = "ForestryAPI|farming") package forestry.api.farming; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/api/food/BeverageManager.java b/src/main/java/forestry/api/food/BeverageManager.java index 2b0143ab1..576a3d7c0 100644 --- a/src/main/java/forestry/api/food/BeverageManager.java +++ b/src/main/java/forestry/api/food/BeverageManager.java @@ -1,13 +1,13 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.food; public class BeverageManager { - public static IBeverageEffect[] effectList = new IBeverageEffect[128]; + public static IBeverageEffect[] effectList = new IBeverageEffect[128]; - public static IInfuserManager infuserManager; - public static IIngredientManager ingredientManager; + public static IInfuserManager infuserManager; + public static IIngredientManager ingredientManager; } diff --git a/src/main/java/forestry/api/food/IBeverageEffect.java b/src/main/java/forestry/api/food/IBeverageEffect.java index 6a787411d..b452db31d 100644 --- a/src/main/java/forestry/api/food/IBeverageEffect.java +++ b/src/main/java/forestry/api/food/IBeverageEffect.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.food; @@ -9,9 +9,9 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; public interface IBeverageEffect { - int getId(); + int getId(); - void doEffect(World world, EntityPlayer player); + void doEffect(World world, EntityPlayer player); - String getDescription(); + String getDescription(); } diff --git a/src/main/java/forestry/api/food/IInfuserManager.java b/src/main/java/forestry/api/food/IInfuserManager.java index d778ffa41..38b8203af 100644 --- a/src/main/java/forestry/api/food/IInfuserManager.java +++ b/src/main/java/forestry/api/food/IInfuserManager.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.food; @@ -9,16 +9,15 @@ import net.minecraft.item.ItemStack; public interface IInfuserManager { - void addMixture(int meta, ItemStack ingredient, IBeverageEffect effect); + void addMixture(int meta, ItemStack ingredient, IBeverageEffect effect); - void addMixture(int meta, ItemStack[] ingredients, IBeverageEffect effect); + void addMixture(int meta, ItemStack[] ingredients, IBeverageEffect effect); - ItemStack getSeasoned(ItemStack base, ItemStack[] ingredients); + ItemStack getSeasoned(ItemStack base, ItemStack[] ingredients); - boolean hasMixtures(ItemStack[] ingredients); + boolean hasMixtures(ItemStack[] ingredients); - boolean isIngredient(ItemStack itemstack); - - ItemStack[] getRequired(ItemStack[] ingredients); + boolean isIngredient(ItemStack itemstack); + ItemStack[] getRequired(ItemStack[] ingredients); } diff --git a/src/main/java/forestry/api/food/IIngredientManager.java b/src/main/java/forestry/api/food/IIngredientManager.java index fab0e0129..8cb70abc7 100644 --- a/src/main/java/forestry/api/food/IIngredientManager.java +++ b/src/main/java/forestry/api/food/IIngredientManager.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.food; @@ -9,8 +9,7 @@ import net.minecraft.item.ItemStack; public interface IIngredientManager { - String getDescription(ItemStack itemstack); - - void addIngredient(ItemStack ingredient, String description); + String getDescription(ItemStack itemstack); + void addIngredient(ItemStack ingredient, String description); } diff --git a/src/main/java/forestry/api/food/package-info.java b/src/main/java/forestry/api/food/package-info.java index 372c30160..9b3d77c2d 100644 --- a/src/main/java/forestry/api/food/package-info.java +++ b/src/main/java/forestry/api/food/package-info.java @@ -1,8 +1,9 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ -@API(apiVersion="1.1.0", owner="ForestryAPI|core", provides="ForestryAPI|food") +@API(apiVersion = "1.1.0", owner = "ForestryAPI|core", provides = "ForestryAPI|food") package forestry.api.food; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/api/fuels/EngineBronzeFuel.java b/src/main/java/forestry/api/fuels/EngineBronzeFuel.java index cbab0cafc..5c427b1c9 100644 --- a/src/main/java/forestry/api/fuels/EngineBronzeFuel.java +++ b/src/main/java/forestry/api/fuels/EngineBronzeFuel.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.fuels; @@ -8,27 +8,27 @@ package forestry.api.fuels; import net.minecraftforge.fluids.Fluid; public class EngineBronzeFuel { - /** - * Item that is valid fuel for a biogas engine. - */ - public final Fluid liquid; - /** - * Power produced by this fuel per work cycle of the engine. - */ - public final int powerPerCycle; - /** - * How many work cycles a single "stack" of this type lasts. - */ - public final int burnDuration; - /** - * By how much the normal heat dissipation rate of 1 is multiplied when using this fuel type. - */ - public final int dissipationMultiplier; + /** + * Item that is valid fuel for a biogas engine. + */ + public final Fluid liquid; + /** + * Power produced by this fuel per work cycle of the engine. + */ + public final int powerPerCycle; + /** + * How many work cycles a single "stack" of this type lasts. + */ + public final int burnDuration; + /** + * By how much the normal heat dissipation rate of 1 is multiplied when using this fuel type. + */ + public final int dissipationMultiplier; - public EngineBronzeFuel(Fluid liquid, int powerPerCycle, int burnDuration, int dissipationMultiplier) { - this.liquid = liquid; - this.powerPerCycle = powerPerCycle; - this.burnDuration = burnDuration; - this.dissipationMultiplier = dissipationMultiplier; - } + public EngineBronzeFuel(Fluid liquid, int powerPerCycle, int burnDuration, int dissipationMultiplier) { + this.liquid = liquid; + this.powerPerCycle = powerPerCycle; + this.burnDuration = burnDuration; + this.dissipationMultiplier = dissipationMultiplier; + } } diff --git a/src/main/java/forestry/api/fuels/EngineCopperFuel.java b/src/main/java/forestry/api/fuels/EngineCopperFuel.java index af568dd41..3f617baa0 100644 --- a/src/main/java/forestry/api/fuels/EngineCopperFuel.java +++ b/src/main/java/forestry/api/fuels/EngineCopperFuel.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.fuels; @@ -9,23 +9,22 @@ import net.minecraft.item.ItemStack; public class EngineCopperFuel { - /** - * Item that is valid fuel for a peat-fired engine. - */ - public final ItemStack fuel; - /** - * Power produced by this fuel per work cycle. - */ - public final int powerPerCycle; - /** - * Amount of work cycles this item lasts before being consumed. - */ - public final int burnDuration; - - public EngineCopperFuel(ItemStack fuel, int powerPerCycle, int burnDuration) { - this.fuel = fuel; - this.powerPerCycle = powerPerCycle; - this.burnDuration = burnDuration; - } + /** + * Item that is valid fuel for a peat-fired engine. + */ + public final ItemStack fuel; + /** + * Power produced by this fuel per work cycle. + */ + public final int powerPerCycle; + /** + * Amount of work cycles this item lasts before being consumed. + */ + public final int burnDuration; + public EngineCopperFuel(ItemStack fuel, int powerPerCycle, int burnDuration) { + this.fuel = fuel; + this.powerPerCycle = powerPerCycle; + this.burnDuration = burnDuration; + } } diff --git a/src/main/java/forestry/api/fuels/FermenterFuel.java b/src/main/java/forestry/api/fuels/FermenterFuel.java index 32989a803..ad2ddfd11 100644 --- a/src/main/java/forestry/api/fuels/FermenterFuel.java +++ b/src/main/java/forestry/api/fuels/FermenterFuel.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.fuels; @@ -8,22 +8,22 @@ package forestry.api.fuels; import net.minecraft.item.ItemStack; public class FermenterFuel { - /** - * Item that is a valid fuel for the fermenter (i.e. fertilizer). - */ - public final ItemStack item; - /** - * How much is fermeted per work cycle, i.e. how much biomass is produced per cycle. - */ - public final int fermentPerCycle; - /** - * Amount of work cycles a single item of this fuel lasts before expiring. - */ - public final int burnDuration; + /** + * Item that is a valid fuel for the fermenter (i.e. fertilizer). + */ + public final ItemStack item; + /** + * How much is fermeted per work cycle, i.e. how much biomass is produced per cycle. + */ + public final int fermentPerCycle; + /** + * Amount of work cycles a single item of this fuel lasts before expiring. + */ + public final int burnDuration; - public FermenterFuel(ItemStack item, int fermentPerCycle, int burnDuration) { - this.item = item; - this.fermentPerCycle = fermentPerCycle; - this.burnDuration = burnDuration; - } + public FermenterFuel(ItemStack item, int fermentPerCycle, int burnDuration) { + this.item = item; + this.fermentPerCycle = fermentPerCycle; + this.burnDuration = burnDuration; + } } diff --git a/src/main/java/forestry/api/fuels/FuelManager.java b/src/main/java/forestry/api/fuels/FuelManager.java index f53d6fb71..606f4b95d 100644 --- a/src/main/java/forestry/api/fuels/FuelManager.java +++ b/src/main/java/forestry/api/fuels/FuelManager.java @@ -1,40 +1,37 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.fuels; +import java.util.HashMap; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.Fluid; -import java.util.HashMap; - - public class FuelManager { - /** - * Add new fuels for the fermenter here (i.e. fertilizer). - */ - public static HashMap fermenterFuel; - /** - * Add new resources for the moistener here (i.e. wheat) - */ - public static HashMap moistenerResource; - /** - * Add new substrates for the rainmaker here - */ - public static HashMap rainSubstrate; - /** - * Add new fuels for EngineBronze (= biogas engine) here - */ - public static HashMap bronzeEngineFuel; - /** - * Add new fuels for EngineCopper (= peat-fired engine) here - */ - public static HashMap copperEngineFuel; - /** - * Add new fuels for Generator here - */ - public static HashMap generatorFuel; - + /** + * Add new fuels for the fermenter here (i.e. fertilizer). + */ + public static HashMap fermenterFuel; + /** + * Add new resources for the moistener here (i.e. wheat) + */ + public static HashMap moistenerResource; + /** + * Add new substrates for the rainmaker here + */ + public static HashMap rainSubstrate; + /** + * Add new fuels for EngineBronze (= biogas engine) here + */ + public static HashMap bronzeEngineFuel; + /** + * Add new fuels for EngineCopper (= peat-fired engine) here + */ + public static HashMap copperEngineFuel; + /** + * Add new fuels for Generator here + */ + public static HashMap generatorFuel; } diff --git a/src/main/java/forestry/api/fuels/GeneratorFuel.java b/src/main/java/forestry/api/fuels/GeneratorFuel.java index 16e2ee4d3..9ecaa0246 100644 --- a/src/main/java/forestry/api/fuels/GeneratorFuel.java +++ b/src/main/java/forestry/api/fuels/GeneratorFuel.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.fuels; @@ -9,23 +9,22 @@ import net.minecraftforge.fluids.FluidStack; public class GeneratorFuel { - /** - * LiquidStack representing the fuel type and amount consumed per triggered cycle. - */ - public final FluidStack fuelConsumed; - /** - * EU emitted per tick while this fuel is being consumed in the generator (i.e. biofuel = 32, biomass = 8). - */ - public final int eu; - /** - * Rate at which the fuel is consumed. 1 - Every tick 2 - Every second tick 3 - Every third tick etc. - */ - public final int rate; - - public GeneratorFuel(FluidStack fuelConsumed, int eu, int rate) { - this.fuelConsumed = fuelConsumed; - this.eu = eu; - this.rate = rate; - } + /** + * LiquidStack representing the fuel type and amount consumed per triggered cycle. + */ + public final FluidStack fuelConsumed; + /** + * EU emitted per tick while this fuel is being consumed in the generator (i.e. biofuel = 32, biomass = 8). + */ + public final int eu; + /** + * Rate at which the fuel is consumed. 1 - Every tick 2 - Every second tick 3 - Every third tick etc. + */ + public final int rate; + public GeneratorFuel(FluidStack fuelConsumed, int eu, int rate) { + this.fuelConsumed = fuelConsumed; + this.eu = eu; + this.rate = rate; + } } diff --git a/src/main/java/forestry/api/fuels/MoistenerFuel.java b/src/main/java/forestry/api/fuels/MoistenerFuel.java index 4c4c7a0b6..15f5ab0fa 100644 --- a/src/main/java/forestry/api/fuels/MoistenerFuel.java +++ b/src/main/java/forestry/api/fuels/MoistenerFuel.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.fuels; @@ -8,27 +8,27 @@ package forestry.api.fuels; import net.minecraft.item.ItemStack; public class MoistenerFuel { - /** - * The item to use - */ - public final ItemStack item; - /** - * The item that leaves the moistener's working slot (i.e. mouldy wheat, decayed wheat, mulch) - */ - public final ItemStack product; - /** - * How much this item contributes to the final product of the moistener (i.e. mycelium) - */ - public final int moistenerValue; - /** - * What stage this product represents. Resources with lower stage value will be consumed first. - */ - public final int stage; + /** + * The item to use + */ + public final ItemStack item; + /** + * The item that leaves the moistener's working slot (i.e. mouldy wheat, decayed wheat, mulch) + */ + public final ItemStack product; + /** + * How much this item contributes to the final product of the moistener (i.e. mycelium) + */ + public final int moistenerValue; + /** + * What stage this product represents. Resources with lower stage value will be consumed first. + */ + public final int stage; - public MoistenerFuel(ItemStack item, ItemStack product, int stage, int moistenerValue) { - this.item = item; - this.product = product; - this.stage = stage; - this.moistenerValue = moistenerValue; - } + public MoistenerFuel(ItemStack item, ItemStack product, int stage, int moistenerValue) { + this.item = item; + this.product = product; + this.stage = stage; + this.moistenerValue = moistenerValue; + } } diff --git a/src/main/java/forestry/api/fuels/RainSubstrate.java b/src/main/java/forestry/api/fuels/RainSubstrate.java index ab0deb5a3..4373719c7 100644 --- a/src/main/java/forestry/api/fuels/RainSubstrate.java +++ b/src/main/java/forestry/api/fuels/RainSubstrate.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.fuels; @@ -8,33 +8,33 @@ package forestry.api.fuels; import net.minecraft.item.ItemStack; public class RainSubstrate { - /** - * Rain substrate capable of activating the rainmaker. - */ - public ItemStack item; - /** - * Duration of the rain shower triggered by this substrate in Minecraft ticks. - */ - public int duration; - /** - * Speed of activation sequence triggered. - */ - public float speed; + /** + * Rain substrate capable of activating the rainmaker. + */ + public ItemStack item; + /** + * Duration of the rain shower triggered by this substrate in Minecraft ticks. + */ + public int duration; + /** + * Speed of activation sequence triggered. + */ + public float speed; - public boolean reverse; + public boolean reverse; - public RainSubstrate(ItemStack item, int duration, float speed) { - this(item, duration, speed, false); - } + public RainSubstrate(ItemStack item, int duration, float speed) { + this(item, duration, speed, false); + } - public RainSubstrate(ItemStack item, float speed) { - this(item, 0, speed, true); - } + public RainSubstrate(ItemStack item, float speed) { + this(item, 0, speed, true); + } - public RainSubstrate(ItemStack item, int duration, float speed, boolean reverse) { - this.item = item; - this.duration = duration; - this.speed = speed; - this.reverse = reverse; - } + public RainSubstrate(ItemStack item, int duration, float speed, boolean reverse) { + this.item = item; + this.duration = duration; + this.speed = speed; + this.reverse = reverse; + } } diff --git a/src/main/java/forestry/api/fuels/package-info.java b/src/main/java/forestry/api/fuels/package-info.java index 748fa2286..f41c14e2c 100644 --- a/src/main/java/forestry/api/fuels/package-info.java +++ b/src/main/java/forestry/api/fuels/package-info.java @@ -1,8 +1,9 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ -@API(apiVersion="2.0.1", owner="ForestryAPI|core", provides="ForestryAPI|fuels") +@API(apiVersion = "2.0.1", owner = "ForestryAPI|core", provides = "ForestryAPI|fuels") package forestry.api.fuels; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/api/genetics/AlleleManager.java b/src/main/java/forestry/api/genetics/AlleleManager.java index 6e3511621..977c59d33 100644 --- a/src/main/java/forestry/api/genetics/AlleleManager.java +++ b/src/main/java/forestry/api/genetics/AlleleManager.java @@ -1,36 +1,35 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; import java.util.HashMap; - import net.minecraft.item.ItemStack; /** - * Holds a static reference to the {@link IAlleleRegistry}. + * Holds a static reference to the {@link IAlleleRegistry}. */ public class AlleleManager { - /** - * Main access point for all things related to genetics. See {@link IAlleleRegistry} for details. - */ - public static IAlleleRegistry alleleRegistry; - /** - * Translates plain leaf blocks into genetic data. Used by bees and butterflies to convert and pollinate foreign leaf blocks. - */ - public static HashMap ersatzSpecimen = new HashMap(); - /** - * Translates plain saplings into genetic data. Used by the treealyzer and the farm to convert foreign saplings. - */ - public static HashMap ersatzSaplings = new HashMap(); - /** - * Queryable instance of an {@link IClimateHelper} for easier implementation. - */ - public static IClimateHelper climateHelper; - /** - * Creates Forestry alleles. - */ - public static IAlleleFactory alleleFactory; + /** + * Main access point for all things related to genetics. See {@link IAlleleRegistry} for details. + */ + public static IAlleleRegistry alleleRegistry; + /** + * Translates plain leaf blocks into genetic data. Used by bees and butterflies to convert and pollinate foreign leaf blocks. + */ + public static HashMap ersatzSpecimen = new HashMap(); + /** + * Translates plain saplings into genetic data. Used by the treealyzer and the farm to convert foreign saplings. + */ + public static HashMap ersatzSaplings = new HashMap(); + /** + * Queryable instance of an {@link IClimateHelper} for easier implementation. + */ + public static IClimateHelper climateHelper; + /** + * Creates Forestry alleles. + */ + public static IAlleleFactory alleleFactory; } diff --git a/src/main/java/forestry/api/genetics/EnumTolerance.java b/src/main/java/forestry/api/genetics/EnumTolerance.java index 6ff0085eb..b17142b59 100644 --- a/src/main/java/forestry/api/genetics/EnumTolerance.java +++ b/src/main/java/forestry/api/genetics/EnumTolerance.java @@ -1,16 +1,28 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; public enum EnumTolerance { - NONE, + NONE, - BOTH_1, BOTH_2, BOTH_3, BOTH_4, BOTH_5, + BOTH_1, + BOTH_2, + BOTH_3, + BOTH_4, + BOTH_5, - UP_1, UP_2, UP_3, UP_4, UP_5, + UP_1, + UP_2, + UP_3, + UP_4, + UP_5, - DOWN_1, DOWN_2, DOWN_3, DOWN_4, DOWN_5 + DOWN_1, + DOWN_2, + DOWN_3, + DOWN_4, + DOWN_5 } diff --git a/src/main/java/forestry/api/genetics/IAllele.java b/src/main/java/forestry/api/genetics/IAllele.java index 527474102..cdb0d05a4 100644 --- a/src/main/java/forestry/api/genetics/IAllele.java +++ b/src/main/java/forestry/api/genetics/IAllele.java @@ -1,39 +1,38 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; /** * An {@link IIndividual}'s {@link IGenome} is composed of {@link IChromosome}s consisting each of a primary and secondary {@link IAllele}. - * + * * {@link IAllele}s hold all information regarding an {@link IIndividual}'s traits, from species to size, temperature tolerances, etc. - * + * * Should be extended for different types of alleles. ISpeciesAllele, IBiomeAllele, etc. - * + * * @author SirSengir */ public interface IAllele { - /** - * @return A unique string identifier for this allele. - */ - String getUID(); + /** + * @return A unique string identifier for this allele. + */ + String getUID(); - /** - * @return true if the allele is dominant, false otherwise. - */ - boolean isDominant(); - - /** - * @return Localized short, human-readable identifier used in tooltips and beealyzer. - */ - String getName(); + /** + * @return true if the allele is dominant, false otherwise. + */ + boolean isDominant(); - /** - * @return The unlocalized identifier - */ - String getUnlocalizedName(); + /** + * @return Localized short, human-readable identifier used in tooltips and beealyzer. + */ + String getName(); + /** + * @return The unlocalized identifier + */ + String getUnlocalizedName(); } diff --git a/src/main/java/forestry/api/genetics/IAlleleArea.java b/src/main/java/forestry/api/genetics/IAlleleArea.java index 7277ff0a1..2f975e52a 100644 --- a/src/main/java/forestry/api/genetics/IAlleleArea.java +++ b/src/main/java/forestry/api/genetics/IAlleleArea.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; @@ -10,6 +10,5 @@ package forestry.api.genetics; */ public interface IAlleleArea extends IAllele { - int[] getValue(); - + int[] getValue(); } diff --git a/src/main/java/forestry/api/genetics/IAlleleBoolean.java b/src/main/java/forestry/api/genetics/IAlleleBoolean.java index 887da3b90..ba05c672b 100644 --- a/src/main/java/forestry/api/genetics/IAlleleBoolean.java +++ b/src/main/java/forestry/api/genetics/IAlleleBoolean.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; @@ -10,7 +10,5 @@ package forestry.api.genetics; */ public interface IAlleleBoolean extends IAllele { - boolean getValue(); - - + boolean getValue(); } diff --git a/src/main/java/forestry/api/genetics/IAlleleEffect.java b/src/main/java/forestry/api/genetics/IAlleleEffect.java index 7b94e6b16..10aa4bfac 100644 --- a/src/main/java/forestry/api/genetics/IAlleleEffect.java +++ b/src/main/java/forestry/api/genetics/IAlleleEffect.java @@ -1,26 +1,25 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; /** - * Basic effect allele. + * Basic effect allele. */ public interface IAlleleEffect extends IAllele { - /** - * @return true if this effect can combine with the effect on other allele (i.e. run before or after). combination can only occur if both effects are - * combinable. - */ - boolean isCombinable(); - - /** - * Returns the passed data storage if it is valid for this effect or a new one if the passed storage object was invalid for this effect. - * - * @param storedData - * @return {@link IEffectData} for the next cycle. - */ - IEffectData validateStorage(IEffectData storedData); + /** + * @return true if this effect can combine with the effect on other allele (i.e. run before or after). combination can only occur if both effects are + * combinable. + */ + boolean isCombinable(); + /** + * Returns the passed data storage if it is valid for this effect or a new one if the passed storage object was invalid for this effect. + * + * @param storedData + * @return {@link IEffectData} for the next cycle. + */ + IEffectData validateStorage(IEffectData storedData); } diff --git a/src/main/java/forestry/api/genetics/IAlleleFactory.java b/src/main/java/forestry/api/genetics/IAlleleFactory.java index 573408007..8ce84a04f 100644 --- a/src/main/java/forestry/api/genetics/IAlleleFactory.java +++ b/src/main/java/forestry/api/genetics/IAlleleFactory.java @@ -25,129 +25,154 @@ package forestry.api.genetics; * forestry.allele.height.smallest=????? ?????? */ public interface IAlleleFactory { - /** - * @param modId mod prefix for uid and localization (i.e. "forestry") - * @param category allele category for uid and localization (i.e. "height") - * @param valueName allele value name for uid and localization (i.e. "smallest") - * @param value allele float value - * @param isDominant allele dominance - * @param types allele chromosome type for registration (i.e. EnumTreeChromosome.HEIGHT) - * @return a new IAlleleFloat, registered with the allele registry. - * @since Forestry 4.2 - */ - IAlleleFloat createFloat(String modId, String category, String valueName, float value, boolean isDominant, IChromosomeType... types); + /** + * @param modId mod prefix for uid and localization (i.e. "forestry") + * @param category allele category for uid and localization (i.e. "height") + * @param valueName allele value name for uid and localization (i.e. "smallest") + * @param value allele float value + * @param isDominant allele dominance + * @param types allele chromosome type for registration (i.e. EnumTreeChromosome.HEIGHT) + * @return a new IAlleleFloat, registered with the allele registry. + * @since Forestry 4.2 + */ + IAlleleFloat createFloat( + String modId, String category, String valueName, float value, boolean isDominant, IChromosomeType... types); - /** - * @param modId mod prefix for uid and localization (i.e. "forestry") - * @param category allele category for uid and localization (i.e. "territory") - * @param valueName allele value name for uid and localization (i.e. "large") - * @param xDimValue allele area X Size - * @param yDimValue allele area Y Size - * @param zDimValue allele area Z Size - * @param isDominant allele dominance - * @param types allele chromosome type for registration (i.e. EnumBeeChromosome.TERRITORY) - * @return a new IAlleleArea, registered with the allele registry. - * @since Forestry 4.2 - */ - IAlleleArea createArea(String modId, String category, String valueName, int xDimValue, int yDimValue, int zDimValue, boolean isDominant, IChromosomeType... types); + /** + * @param modId mod prefix for uid and localization (i.e. "forestry") + * @param category allele category for uid and localization (i.e. "territory") + * @param valueName allele value name for uid and localization (i.e. "large") + * @param xDimValue allele area X Size + * @param yDimValue allele area Y Size + * @param zDimValue allele area Z Size + * @param isDominant allele dominance + * @param types allele chromosome type for registration (i.e. EnumBeeChromosome.TERRITORY) + * @return a new IAlleleArea, registered with the allele registry. + * @since Forestry 4.2 + */ + IAlleleArea createArea( + String modId, + String category, + String valueName, + int xDimValue, + int yDimValue, + int zDimValue, + boolean isDominant, + IChromosomeType... types); - /** - * @param modId mod prefix for uid and localization (i.e. "forestry") - * @param category allele category for uid and localization (i.e. "fertility") - * @param valueName allele value name for uid and localization (i.e. "low") - * @param value allele int value - * @param isDominant allele dominance - * @param types allele chromosome type for registration (i.e. EnumBeeChromosome.FERTILITY) - * @return a new IAlleleInteger, registered with the allele registry. - * @since Forestry 4.2 - */ - IAlleleInteger createInteger(String modId, String category, String valueName, int value, boolean isDominant, IChromosomeType... types); + /** + * @param modId mod prefix for uid and localization (i.e. "forestry") + * @param category allele category for uid and localization (i.e. "fertility") + * @param valueName allele value name for uid and localization (i.e. "low") + * @param value allele int value + * @param isDominant allele dominance + * @param types allele chromosome type for registration (i.e. EnumBeeChromosome.FERTILITY) + * @return a new IAlleleInteger, registered with the allele registry. + * @since Forestry 4.2 + */ + IAlleleInteger createInteger( + String modId, String category, String valueName, int value, boolean isDominant, IChromosomeType... types); - /** - * @param modId mod prefix for uid and localization (i.e. "forestry") - * @param category allele category for uid and localization (i.e. "fireproof") - * @param value allele boolean value - * @param isDominant allele dominance - * @param types allele chromosome type for registration (i.e. EnumTreeChromosome.FIREPROOF) - * @return a new IAlleleBoolean, registered with the allele registry. - * Note that valueName will always be "true" or "false" - * @since Forestry 4.2 - */ - IAlleleBoolean createBoolean(String modId, String category, boolean value, boolean isDominant, IChromosomeType... types); + /** + * @param modId mod prefix for uid and localization (i.e. "forestry") + * @param category allele category for uid and localization (i.e. "fireproof") + * @param value allele boolean value + * @param isDominant allele dominance + * @param types allele chromosome type for registration (i.e. EnumTreeChromosome.FIREPROOF) + * @return a new IAlleleBoolean, registered with the allele registry. + * Note that valueName will always be "true" or "false" + * @since Forestry 4.2 + */ + IAlleleBoolean createBoolean( + String modId, String category, boolean value, boolean isDominant, IChromosomeType... types); - /** - * @param modId mod prefix for uid (i.e. "forestry") - * @param category allele category for uid (i.e. "flowers") - * @param valueName allele value name for uid (i.e. "vanilla") - * @param value allele IFlowerProvider value - * @param isDominant allele dominance - * @param types allele chromosome type for registration (i.e. EnumBeeChromosome.FLOWER_PROVIDER) - * @return a new IAlleleFlowers, registered with the allele registry. - * IAlleleFlowers localization is handled by the IFlowerProvider.getDescription(), unlike the other alleles. - * @since Forestry 4.2 - */ - IAlleleFlowers createFlowers(String modId, String category, String valueName, IFlowerProvider value, boolean isDominant, IChromosomeType... types); + /** + * @param modId mod prefix for uid (i.e. "forestry") + * @param category allele category for uid (i.e. "flowers") + * @param valueName allele value name for uid (i.e. "vanilla") + * @param value allele IFlowerProvider value + * @param isDominant allele dominance + * @param types allele chromosome type for registration (i.e. EnumBeeChromosome.FLOWER_PROVIDER) + * @return a new IAlleleFlowers, registered with the allele registry. + * IAlleleFlowers localization is handled by the IFlowerProvider.getDescription(), unlike the other alleles. + * @since Forestry 4.2 + */ + IAlleleFlowers createFlowers( + String modId, + String category, + String valueName, + IFlowerProvider value, + boolean isDominant, + IChromosomeType... types); - /** - * @param modId mod prefix for uid and localization (i.e. "forestry") - * @param category allele category for uid and localization (i.e. "height") - * @param valueName allele value name for uid and localization (i.e. "smallest") - * @param value allele float value - * @param isDominant allele dominance - * @return a new IAlleleFloat, registered with the allele registry. - * @deprecated since Forestry 4.2. Use the IChromosomeType version. - */ - @Deprecated - IAlleleFloat createFloat(String modId, String category, String valueName, float value, boolean isDominant); + /** + * @param modId mod prefix for uid and localization (i.e. "forestry") + * @param category allele category for uid and localization (i.e. "height") + * @param valueName allele value name for uid and localization (i.e. "smallest") + * @param value allele float value + * @param isDominant allele dominance + * @return a new IAlleleFloat, registered with the allele registry. + * @deprecated since Forestry 4.2. Use the IChromosomeType version. + */ + @Deprecated + IAlleleFloat createFloat(String modId, String category, String valueName, float value, boolean isDominant); - /** - * @param modId mod prefix for uid and localization (i.e. "forestry") - * @param category allele category for uid and localization (i.e. "territory") - * @param valueName allele value name for uid and localization (i.e. "large") - * @param xDimValue allele area X Size - * @param yDimValue allele area Y Size - * @param zDimValue allele area Z Size - * @param isDominant allele dominance - * @return a new IAlleleArea, registered with the allele registry. - * @deprecated since Forestry 4.2. Use the IChromosomeType version. - */ - @Deprecated - IAlleleArea createArea(String modId, String category, String valueName, int xDimValue, int yDimValue, int zDimValue, boolean isDominant); + /** + * @param modId mod prefix for uid and localization (i.e. "forestry") + * @param category allele category for uid and localization (i.e. "territory") + * @param valueName allele value name for uid and localization (i.e. "large") + * @param xDimValue allele area X Size + * @param yDimValue allele area Y Size + * @param zDimValue allele area Z Size + * @param isDominant allele dominance + * @return a new IAlleleArea, registered with the allele registry. + * @deprecated since Forestry 4.2. Use the IChromosomeType version. + */ + @Deprecated + IAlleleArea createArea( + String modId, + String category, + String valueName, + int xDimValue, + int yDimValue, + int zDimValue, + boolean isDominant); - /** - * @param modId mod prefix for uid and localization (i.e. "forestry") - * @param category allele category for uid and localization (i.e. "fertility") - * @param valueName allele value name for uid and localization (i.e. "low") - * @param value allele int value - * @param isDominant allele dominance - * @return a new IAlleleInteger, registered with the allele registry. - * @deprecated since Forestry 4.2. Use the IChromosomeType version. - */ - @Deprecated - IAlleleInteger createInteger(String modId, String category, String valueName, int value, boolean isDominant); + /** + * @param modId mod prefix for uid and localization (i.e. "forestry") + * @param category allele category for uid and localization (i.e. "fertility") + * @param valueName allele value name for uid and localization (i.e. "low") + * @param value allele int value + * @param isDominant allele dominance + * @return a new IAlleleInteger, registered with the allele registry. + * @deprecated since Forestry 4.2. Use the IChromosomeType version. + */ + @Deprecated + IAlleleInteger createInteger(String modId, String category, String valueName, int value, boolean isDominant); - /** - * @param modId mod prefix for uid and localization (i.e. "forestry") - * @param category allele category for uid and localization (i.e. "fireproof") - * @param value allele boolean value - * @param isDominant allele dominance - * @return a new IAlleleBoolean, registered with the allele registry. - * Note that valueName will always be "true" or "false" - * @deprecated since Forestry 4.2. Use the IChromosomeType version. - */ - @Deprecated - IAlleleBoolean createBoolean(String modId, String category, boolean value, boolean isDominant); + /** + * @param modId mod prefix for uid and localization (i.e. "forestry") + * @param category allele category for uid and localization (i.e. "fireproof") + * @param value allele boolean value + * @param isDominant allele dominance + * @return a new IAlleleBoolean, registered with the allele registry. + * Note that valueName will always be "true" or "false" + * @deprecated since Forestry 4.2. Use the IChromosomeType version. + */ + @Deprecated + IAlleleBoolean createBoolean(String modId, String category, boolean value, boolean isDominant); - /** - * @param modId mod prefix for uid (i.e. "forestry") - * @param category allele category for uid (i.e. "flowers") - * @param valueName allele value name for uid (i.e. "vanilla") - * @param value allele IFlowerProvider value - * @param isDominant allele dominance - * @return a new IAlleleFlowers, registered with the allele registry. - * IAlleleFlowers localization is handled by the IFlowerProvider.getDescription(), unlike the other alleles. - * @deprecated since Forestry 4.2. Use the IChromosomeType version. - */ - @Deprecated - IAlleleFlowers createFlowers(String modId, String category, String valueName, IFlowerProvider value, boolean isDominant); + /** + * @param modId mod prefix for uid (i.e. "forestry") + * @param category allele category for uid (i.e. "flowers") + * @param valueName allele value name for uid (i.e. "vanilla") + * @param value allele IFlowerProvider value + * @param isDominant allele dominance + * @return a new IAlleleFlowers, registered with the allele registry. + * IAlleleFlowers localization is handled by the IFlowerProvider.getDescription(), unlike the other alleles. + * @deprecated since Forestry 4.2. Use the IChromosomeType version. + */ + @Deprecated + IAlleleFlowers createFlowers( + String modId, String category, String valueName, IFlowerProvider value, boolean isDominant); } diff --git a/src/main/java/forestry/api/genetics/IAlleleFloat.java b/src/main/java/forestry/api/genetics/IAlleleFloat.java index 6ca28776a..abc3f2d72 100644 --- a/src/main/java/forestry/api/genetics/IAlleleFloat.java +++ b/src/main/java/forestry/api/genetics/IAlleleFloat.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; @@ -10,6 +10,5 @@ package forestry.api.genetics; */ public interface IAlleleFloat extends IAllele { - float getValue(); - + float getValue(); } diff --git a/src/main/java/forestry/api/genetics/IAlleleFlowers.java b/src/main/java/forestry/api/genetics/IAlleleFlowers.java index 0368ca41c..6fa8fa26f 100644 --- a/src/main/java/forestry/api/genetics/IAlleleFlowers.java +++ b/src/main/java/forestry/api/genetics/IAlleleFlowers.java @@ -1,16 +1,14 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; - public interface IAlleleFlowers extends IAllele { - /** - * @return FlowerProvider - */ - IFlowerProvider getProvider(); - + /** + * @return FlowerProvider + */ + IFlowerProvider getProvider(); } diff --git a/src/main/java/forestry/api/genetics/IAlleleHandler.java b/src/main/java/forestry/api/genetics/IAlleleHandler.java index 3d052afe4..e16e359c3 100644 --- a/src/main/java/forestry/api/genetics/IAlleleHandler.java +++ b/src/main/java/forestry/api/genetics/IAlleleHandler.java @@ -1,41 +1,40 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; /** * @author Alex Binnie - * + * * Handler for events that occur in IAlleleRegistry, such as registering alleles, branches etc. Useful for handling plugin specific behavior (i.e. * creating a list of all bee species etc.) - * + * */ public interface IAlleleHandler { - /** - * Called when an allele is registered with {@link IAlleleRegistry}. - * - * @param allele - * Allele which was registered. - */ - public void onRegisterAllele(IAllele allele); + /** + * Called when an allele is registered with {@link IAlleleRegistry}. + * + * @param allele + * Allele which was registered. + */ + public void onRegisterAllele(IAllele allele); - /** - * Called when a classification is registered with {@link IAlleleRegistry}. - * - * @param classification - * Classification which was registered. - */ - public void onRegisterClassification(IClassification classification); - - /** - * Called when a fruit family is registered with {@link IAlleleRegistry}. - * - * @param family - * Fruit family which was registered. - */ - public void onRegisterFruitFamily(IFruitFamily family); + /** + * Called when a classification is registered with {@link IAlleleRegistry}. + * + * @param classification + * Classification which was registered. + */ + public void onRegisterClassification(IClassification classification); + /** + * Called when a fruit family is registered with {@link IAlleleRegistry}. + * + * @param family + * Fruit family which was registered. + */ + public void onRegisterFruitFamily(IFruitFamily family); } diff --git a/src/main/java/forestry/api/genetics/IAlleleInteger.java b/src/main/java/forestry/api/genetics/IAlleleInteger.java index 6991efe5f..32b6fcb34 100644 --- a/src/main/java/forestry/api/genetics/IAlleleInteger.java +++ b/src/main/java/forestry/api/genetics/IAlleleInteger.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; @@ -10,6 +10,5 @@ package forestry.api.genetics; */ public interface IAlleleInteger extends IAllele { - int getValue(); - + int getValue(); } diff --git a/src/main/java/forestry/api/genetics/IAllelePlantType.java b/src/main/java/forestry/api/genetics/IAllelePlantType.java index 211237f20..9684bf25b 100644 --- a/src/main/java/forestry/api/genetics/IAllelePlantType.java +++ b/src/main/java/forestry/api/genetics/IAllelePlantType.java @@ -1,16 +1,14 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; import java.util.EnumSet; - import net.minecraftforge.common.EnumPlantType; public interface IAllelePlantType extends IAllele { - public EnumSet getPlantTypes(); - + public EnumSet getPlantTypes(); } diff --git a/src/main/java/forestry/api/genetics/IAlleleRegistry.java b/src/main/java/forestry/api/genetics/IAlleleRegistry.java index 90f89940e..af920e8ab 100644 --- a/src/main/java/forestry/api/genetics/IAlleleRegistry.java +++ b/src/main/java/forestry/api/genetics/IAlleleRegistry.java @@ -5,15 +5,12 @@ ******************************************************************************/ package forestry.api.genetics; +import com.mojang.authlib.GameProfile; +import forestry.api.genetics.IClassification.EnumClassLevel; import java.util.Collection; import java.util.Map; - import net.minecraft.item.ItemStack; -import com.mojang.authlib.GameProfile; - -import forestry.api.genetics.IClassification.EnumClassLevel; - /** * Manages {@link ISpeciesRoot}, {@link IAllele}s, {@link IFruitFamily}s, {@link IClassification}, the blacklist and allows creation of research notes. * @@ -21,218 +18,219 @@ import forestry.api.genetics.IClassification.EnumClassLevel; */ public interface IAlleleRegistry { - /* SPECIES ROOT CLASSES */ - /** - * Register a {@link ISpeciesRoot}. - * @param root {@link ISpeciesRoot} to register. - */ - void registerSpeciesRoot(ISpeciesRoot root); + /* SPECIES ROOT CLASSES */ + /** + * Register a {@link ISpeciesRoot}. + * @param root {@link ISpeciesRoot} to register. + */ + void registerSpeciesRoot(ISpeciesRoot root); - /** - * @return Map of all registered {@link ISpeciesRoot}. - */ - Map getSpeciesRoot(); + /** + * @return Map of all registered {@link ISpeciesRoot}. + */ + Map getSpeciesRoot(); - /** - * Retrieve the {@link ISpeciesRoot} with the given uid. - * @param uid Unique id for the species class, i.e. "rootBees", "rootTrees", "rootButterflies". - * @return {@link ISpeciesRoot} if it exists, null otherwise. - */ - ISpeciesRoot getSpeciesRoot(String uid); + /** + * Retrieve the {@link ISpeciesRoot} with the given uid. + * @param uid Unique id for the species class, i.e. "rootBees", "rootTrees", "rootButterflies". + * @return {@link ISpeciesRoot} if it exists, null otherwise. + */ + ISpeciesRoot getSpeciesRoot(String uid); - /** - * Retrieve a matching {@link ISpeciesRoot} for the given itemstack. - * @param stack An itemstack possibly containing NBT data which can be converted by a species root. - * @return {@link ISpeciesRoot} if found, null otherwise. - */ - ISpeciesRoot getSpeciesRoot(ItemStack stack); + /** + * Retrieve a matching {@link ISpeciesRoot} for the given itemstack. + * @param stack An itemstack possibly containing NBT data which can be converted by a species root. + * @return {@link ISpeciesRoot} if found, null otherwise. + */ + ISpeciesRoot getSpeciesRoot(ItemStack stack); - /** - * Retrieve a matching {@link ISpeciesRoot} for the given {@link IIndividual}-class. - * @param clz Class extending {@link IIndividual}. - * @return {@link ISpeciesRoot} if found, null otherwise. - */ - ISpeciesRoot getSpeciesRoot(Class clz); + /** + * Retrieve a matching {@link ISpeciesRoot} for the given {@link IIndividual}-class. + * @param clz Class extending {@link IIndividual}. + * @return {@link ISpeciesRoot} if found, null otherwise. + */ + ISpeciesRoot getSpeciesRoot(Class clz); - /* INDIVIDUAL */ - /** - * Tests the itemstack for genetic information. - * - * @param stack - * @return true if the itemstack is an individual. - */ - boolean isIndividual(ItemStack stack); + /* INDIVIDUAL */ + /** + * Tests the itemstack for genetic information. + * + * @param stack + * @return true if the itemstack is an individual. + */ + boolean isIndividual(ItemStack stack); - /** - * Retrieve genetic information from an itemstack. - * - * @param stack - * Stack to retrieve genetic information for. - * @return IIndividual containing genetic information, null if none could be extracted. - */ - IIndividual getIndividual(ItemStack stack); + /** + * Retrieve genetic information from an itemstack. + * + * @param stack + * Stack to retrieve genetic information for. + * @return IIndividual containing genetic information, null if none could be extracted. + */ + IIndividual getIndividual(ItemStack stack); - /* ALLELES */ + /* ALLELES */ - /** - * @return HashMap of all currently registered alleles. - */ - Map getRegisteredAlleles(); + /** + * @return HashMap of all currently registered alleles. + */ + Map getRegisteredAlleles(); - /** - * Registers an allele. - * - * @param allele IAllele to register. - * @deprecated since Forestry 4.2. Use the IChromosomeType-specific version. - */ - @Deprecated - void registerAllele(IAllele allele); + /** + * Registers an allele. + * + * @param allele IAllele to register. + * @deprecated since Forestry 4.2. Use the IChromosomeType-specific version. + */ + @Deprecated + void registerAllele(IAllele allele); - /** - * Registers an allele. - * - * NOTE: Where possible, it is recommended to use IAlleleFactory instead - * because it has built-in advanced localization support. - * - * @param allele IAllele to register. - * @param chromosomeTypes valid chromosomeTypes for this allele. - * @since Forestry 4.2 - */ - void registerAllele(IAllele allele, IChromosomeType... chromosomeTypes); + /** + * Registers an allele. + * + * NOTE: Where possible, it is recommended to use IAlleleFactory instead + * because it has built-in advanced localization support. + * + * @param allele IAllele to register. + * @param chromosomeTypes valid chromosomeTypes for this allele. + * @since Forestry 4.2 + */ + void registerAllele(IAllele allele, IChromosomeType... chromosomeTypes); - /** - * @return HashMap of all registered deprecated alleles and their corresponding replacements - */ - Map getDeprecatedAlleleReplacements(); + /** + * @return HashMap of all registered deprecated alleles and their corresponding replacements + */ + Map getDeprecatedAlleleReplacements(); - /** - * Registers an old allele UID and the new IAllele to replace instances of it with. - * - * @param deprecatedAlleleUID - * the old allele's UID - * @param replacement - * the IAllele that the deprecated Allele will be replaced with. - */ - void registerDeprecatedAlleleReplacement(String deprecatedAlleleUID, IAllele replacement); + /** + * Registers an old allele UID and the new IAllele to replace instances of it with. + * + * @param deprecatedAlleleUID + * the old allele's UID + * @param replacement + * the IAllele that the deprecated Allele will be replaced with. + */ + void registerDeprecatedAlleleReplacement(String deprecatedAlleleUID, IAllele replacement); - /** - * Gets an allele - * - * @param uid - * String based unique identifier of the allele to retrieve. - * @return IAllele if found or a replacement is found in the Deprecated Allele map, null otherwise. - */ - IAllele getAllele(String uid); + /** + * Gets an allele + * + * @param uid + * String based unique identifier of the allele to retrieve. + * @return IAllele if found or a replacement is found in the Deprecated Allele map, null otherwise. + */ + IAllele getAllele(String uid); - /** - * @return unmodifiable collection of all the known allele variations for the given chromosome type. - * @since Forestry 4.2 - */ - Collection getRegisteredAlleles(IChromosomeType type); + /** + * @return unmodifiable collection of all the known allele variations for the given chromosome type. + * @since Forestry 4.2 + */ + Collection getRegisteredAlleles(IChromosomeType type); - /* CLASSIFICATIONS */ - /** - * @return HashMap of all currently registered classifications. - */ - Map getRegisteredClassifications(); + /* CLASSIFICATIONS */ + /** + * @return HashMap of all currently registered classifications. + */ + Map getRegisteredClassifications(); - /** - * Registers a classification. - * - * @param classification - * IClassification to register. - */ - void registerClassification(IClassification classification); + /** + * Registers a classification. + * + * @param classification + * IClassification to register. + */ + void registerClassification(IClassification classification); - /** - * Creates and returns a classification. - * - * @param level - * EnumClassLevel of the classification to create. - * @param uid - * String based unique identifier. Implementation will throw an exception if the key is already taken. - * @param scientific - * Binomial for the given classification. - * @return Created {@link IClassification} for easier chaining. - */ - IClassification createAndRegisterClassification(EnumClassLevel level, String uid, String scientific); - IClassification createAndRegisterClassification(EnumClassLevel level, String uid, String scientific, IClassification... members); + /** + * Creates and returns a classification. + * + * @param level + * EnumClassLevel of the classification to create. + * @param uid + * String based unique identifier. Implementation will throw an exception if the key is already taken. + * @param scientific + * Binomial for the given classification. + * @return Created {@link IClassification} for easier chaining. + */ + IClassification createAndRegisterClassification(EnumClassLevel level, String uid, String scientific); - /** - * Gets a classification. - * - * @param uid - * String based unique identifier of the classification to retrieve. - * @return {@link IClassification} if found, null otherwise. - */ - IClassification getClassification(String uid); + IClassification createAndRegisterClassification( + EnumClassLevel level, String uid, String scientific, IClassification... members); - /* FRUIT FAMILIES */ - /** - * Get all registered fruit families. - * - * @return A map of registered fruit families and their UIDs. - */ - Map getRegisteredFruitFamilies(); + /** + * Gets a classification. + * + * @param uid + * String based unique identifier of the classification to retrieve. + * @return {@link IClassification} if found, null otherwise. + */ + IClassification getClassification(String uid); - /** - * Registers a new fruit family. - * - * @param family - */ - void registerFruitFamily(IFruitFamily family); + /* FRUIT FAMILIES */ + /** + * Get all registered fruit families. + * + * @return A map of registered fruit families and their UIDs. + */ + Map getRegisteredFruitFamilies(); - /** - * Retrieves a fruit family identified by uid. - * - * @param uid - * @return {IFruitFamily} if found, false otherwise. - */ - IFruitFamily getFruitFamily(String uid); + /** + * Registers a new fruit family. + * + * @param family + */ + void registerFruitFamily(IFruitFamily family); - /* ALLELE HANDLERS */ - /** - * Registers a new IAlleleHandler - * - * @param handler - * IAlleleHandler to register. - */ - void registerAlleleHandler(IAlleleHandler handler); + /** + * Retrieves a fruit family identified by uid. + * + * @param uid + * @return {IFruitFamily} if found, false otherwise. + */ + IFruitFamily getFruitFamily(String uid); - /* BLACKLIST */ - /** - * Blacklist an allele identified by its UID from mutation. - * - * @param uid - * UID of the allele to blacklist. - */ - void blacklistAllele(String uid); + /* ALLELE HANDLERS */ + /** + * Registers a new IAlleleHandler + * + * @param handler + * IAlleleHandler to register. + */ + void registerAlleleHandler(IAlleleHandler handler); - /** - * @return Current blacklisted alleles. - */ - Collection getAlleleBlacklist(); + /* BLACKLIST */ + /** + * Blacklist an allele identified by its UID from mutation. + * + * @param uid + * UID of the allele to blacklist. + */ + void blacklistAllele(String uid); - /** - * @param uid - * UID of the species to vet. - * @return true if the allele is blacklisted. - */ - boolean isBlacklisted(String uid); + /** + * @return Current blacklisted alleles. + */ + Collection getAlleleBlacklist(); - /* RESEARCH */ - /** - * @param researcher Username of the player who researched this note. - * @param species {@link IAlleleSpecies} to encode on the research note. - * @return An itemstack containing a research note with the given species encoded onto it. - */ - ItemStack getSpeciesNoteStack(GameProfile researcher, IAlleleSpecies species); + /** + * @param uid + * UID of the species to vet. + * @return true if the allele is blacklisted. + */ + boolean isBlacklisted(String uid); - /** - * @param researcher Username of the player who researched this note. - * @param mutation {@link IMutation} to encode on the research note. - * @return An itemstack containing a research note with the given mutation encoded onto it. - */ - ItemStack getMutationNoteStack(GameProfile researcher, IMutation mutation); + /* RESEARCH */ + /** + * @param researcher Username of the player who researched this note. + * @param species {@link IAlleleSpecies} to encode on the research note. + * @return An itemstack containing a research note with the given species encoded onto it. + */ + ItemStack getSpeciesNoteStack(GameProfile researcher, IAlleleSpecies species); + /** + * @param researcher Username of the player who researched this note. + * @param mutation {@link IMutation} to encode on the research note. + * @return An itemstack containing a research note with the given mutation encoded onto it. + */ + ItemStack getMutationNoteStack(GameProfile researcher, IMutation mutation); } diff --git a/src/main/java/forestry/api/genetics/IAlleleSpecies.java b/src/main/java/forestry/api/genetics/IAlleleSpecies.java index 5a75adefc..fbd62eb63 100644 --- a/src/main/java/forestry/api/genetics/IAlleleSpecies.java +++ b/src/main/java/forestry/api/genetics/IAlleleSpecies.java @@ -1,115 +1,111 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; import forestry.api.core.IIconProvider; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; /** * Basic species allele. */ public interface IAlleleSpecies extends IAllele { - /** - * @return the {@link ISpeciesRoot} associated with this species. - */ - ISpeciesRoot getRoot(); + /** + * @return the {@link ISpeciesRoot} associated with this species. + */ + ISpeciesRoot getRoot(); - /** - * @return Localized short description of this species. (May be null.) - */ - String getDescription(); + /** + * @return Localized short description of this species. (May be null.) + */ + String getDescription(); - /** - * Binomial name of the species sans genus ("Apis"). Returning "humboldti" will have the bee species flavour name be "Apis humboldti". Feel free to use fun - * names or return null. - * - * @return flavour text (may be null) - */ - String getBinomial(); + /** + * Binomial name of the species sans genus ("Apis"). Returning "humboldti" will have the bee species flavour name be "Apis humboldti". Feel free to use fun + * names or return null. + * + * @return flavour text (may be null) + */ + String getBinomial(); - /** - * Authority for the binomial name, e.g. "Sengir" on species of base Forestry. - * - * @return flavour text (may be null) - */ - String getAuthority(); + /** + * Authority for the binomial name, e.g. "Sengir" on species of base Forestry. + * + * @return flavour text (may be null) + */ + String getAuthority(); - /** - * @return Branch this species is associated with. - */ - IClassification getBranch(); + /** + * @return Branch this species is associated with. + */ + IClassification getBranch(); - /* RESEARCH */ - /** - * Complexity determines the difficulty researching a species. The values of primary and secondary are - * added together (and rounded) to determine the amount of pairs needed for successful research. - * @return Values between 3 - 11 are useful. - */ - int getComplexity(); + /* RESEARCH */ + /** + * Complexity determines the difficulty researching a species. The values of primary and secondary are + * added together (and rounded) to determine the amount of pairs needed for successful research. + * @return Values between 3 - 11 are useful. + */ + int getComplexity(); - /** - * @param itemstack - * @return A float signifying the chance for the passed itemstack to yield a research success. - */ - float getResearchSuitability(ItemStack itemstack); + /** + * @param itemstack + * @return A float signifying the chance for the passed itemstack to yield a research success. + */ + float getResearchSuitability(ItemStack itemstack); - /** - * @param world - * @param gameProfile - * @param individual - * @param bountyLevel - * @return Array of itemstacks representing the bounty for this research success. - */ - ItemStack[] getResearchBounty(World world, GameProfile gameProfile, IIndividual individual, int bountyLevel); + /** + * @param world + * @param gameProfile + * @param individual + * @param bountyLevel + * @return Array of itemstacks representing the bounty for this research success. + */ + ItemStack[] getResearchBounty(World world, GameProfile gameProfile, IIndividual individual, int bountyLevel); - /* CLIMATE */ - /** - * @return Preferred temperature - */ - EnumTemperature getTemperature(); + /* CLIMATE */ + /** + * @return Preferred temperature + */ + EnumTemperature getTemperature(); - /** - * @return Preferred humidity - */ - EnumHumidity getHumidity(); + /** + * @return Preferred humidity + */ + EnumHumidity getHumidity(); - /* MISC */ - /** - * @return true if the species icon should have a glowing effect. - */ - boolean hasEffect(); + /* MISC */ + /** + * @return true if the species icon should have a glowing effect. + */ + boolean hasEffect(); - /** - * @return true if the species should not be displayed in NEI or creative inventory. - */ - boolean isSecret(); + /** + * @return true if the species should not be displayed in NEI or creative inventory. + */ + boolean isSecret(); - /** - * @return true to have the species count against the species total. - */ - boolean isCounted(); + /** + * @return true to have the species count against the species total. + */ + boolean isCounted(); - /* APPEARANCE */ - /** - * @param renderPass Render pass to get the colour for. - * @return Colour to use for the render pass. - */ - int getIconColour(int renderPass); - - @SideOnly(Side.CLIENT) - IIconProvider getIconProvider(); + /* APPEARANCE */ + /** + * @param renderPass Render pass to get the colour for. + * @return Colour to use for the render pass. + */ + int getIconColour(int renderPass); + @SideOnly(Side.CLIENT) + IIconProvider getIconProvider(); } diff --git a/src/main/java/forestry/api/genetics/IAlleleSpeciesCustom.java b/src/main/java/forestry/api/genetics/IAlleleSpeciesCustom.java index ff1381628..7243d69ea 100644 --- a/src/main/java/forestry/api/genetics/IAlleleSpeciesCustom.java +++ b/src/main/java/forestry/api/genetics/IAlleleSpeciesCustom.java @@ -10,14 +10,15 @@ import forestry.api.core.EnumTemperature; public interface IAlleleSpeciesCustom extends IAlleleSpecies { - IAlleleSpeciesCustom setTemperature(EnumTemperature temperature); - IAlleleSpeciesCustom setHumidity(EnumHumidity humidity); + IAlleleSpeciesCustom setTemperature(EnumTemperature temperature); - IAlleleSpeciesCustom setHasEffect(); + IAlleleSpeciesCustom setHumidity(EnumHumidity humidity); - /** Secret species are not shown in creative mode. */ - IAlleleSpeciesCustom setIsSecret(); + IAlleleSpeciesCustom setHasEffect(); - /** Uncounted species do not count toward total species discovered. */ - IAlleleSpeciesCustom setIsNotCounted(); + /** Secret species are not shown in creative mode. */ + IAlleleSpeciesCustom setIsSecret(); + + /** Uncounted species do not count toward total species discovered. */ + IAlleleSpeciesCustom setIsNotCounted(); } diff --git a/src/main/java/forestry/api/genetics/IAlleleTolerance.java b/src/main/java/forestry/api/genetics/IAlleleTolerance.java index f5ba9e670..91df2df8f 100644 --- a/src/main/java/forestry/api/genetics/IAlleleTolerance.java +++ b/src/main/java/forestry/api/genetics/IAlleleTolerance.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; @@ -10,6 +10,5 @@ package forestry.api.genetics; */ public interface IAlleleTolerance extends IAllele { - EnumTolerance getValue(); - + EnumTolerance getValue(); } diff --git a/src/main/java/forestry/api/genetics/IBreedingTracker.java b/src/main/java/forestry/api/genetics/IBreedingTracker.java index 7533a59a6..fd1c62fbd 100644 --- a/src/main/java/forestry/api/genetics/IBreedingTracker.java +++ b/src/main/java/forestry/api/genetics/IBreedingTracker.java @@ -1,106 +1,104 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; +import forestry.api.apiculture.IBeekeepingMode; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; -import forestry.api.apiculture.IBeekeepingMode; - /** * Keeps track of who bred, discovered, and researched which species in a world. - * + * * @author SirSengir */ public interface IBreedingTracker { - /** - * @return Name of the current {@link IBeekeepingMode}. - */ - String getModeName(); + /** + * @return Name of the current {@link IBeekeepingMode}. + */ + String getModeName(); - /** - * Set the current {@link IBeekeepingMode}. - */ - void setModeName(String name); + /** + * Set the current {@link IBeekeepingMode}. + */ + void setModeName(String name); - /** - * @return Amount of species discovered. - */ - int getSpeciesBred(); + /** + * @return Amount of species discovered. + */ + int getSpeciesBred(); - /** - * Register the birth of an individual. Will mark it as discovered. - * - * @param individual - */ - void registerBirth(IIndividual individual); + /** + * Register the birth of an individual. Will mark it as discovered. + * + * @param individual + */ + void registerBirth(IIndividual individual); - /** - * Register the pickup of an individual. - * - * @param individual - */ - void registerPickup(IIndividual individual); - - /** - * Marks a species as discovered. Should only be called from registerIndividual normally. - * - * @param species - */ - void registerSpecies(IAlleleSpecies species); + /** + * Register the pickup of an individual. + * + * @param individual + */ + void registerPickup(IIndividual individual); - /** - * Register a successful mutation. Will mark it as discovered. - * - * @param mutation - */ - void registerMutation(IMutation mutation); + /** + * Marks a species as discovered. Should only be called from registerIndividual normally. + * + * @param species + */ + void registerSpecies(IAlleleSpecies species); - /** - * Queries the tracker for discovered species. - * - * @param mutation - * Mutation to query for. - * @return true if the mutation has been discovered. - */ - boolean isDiscovered(IMutation mutation); + /** + * Register a successful mutation. Will mark it as discovered. + * + * @param mutation + */ + void registerMutation(IMutation mutation); - /** - * Queries the tracker for discovered species. - * - * @param species - * Species to check. - * @return true if the species has been bred. - */ - boolean isDiscovered(IAlleleSpecies species); + /** + * Queries the tracker for discovered species. + * + * @param mutation + * Mutation to query for. + * @return true if the mutation has been discovered. + */ + boolean isDiscovered(IMutation mutation); - /** - * Register a successfully researched mutation. - * Mutations are normally researched in the Escritoire. - * Researched mutations may have bonuses such as occurring at a higher rate. - * Researched mutations count as discovered. - */ - void researchMutation(IMutation mutation); + /** + * Queries the tracker for discovered species. + * + * @param species + * Species to check. + * @return true if the species has been bred. + */ + boolean isDiscovered(IAlleleSpecies species); - /** - * @return true if the mutation has been researched. - */ - boolean isResearched(IMutation mutation); + /** + * Register a successfully researched mutation. + * Mutations are normally researched in the Escritoire. + * Researched mutations may have bonuses such as occurring at a higher rate. + * Researched mutations count as discovered. + */ + void researchMutation(IMutation mutation); - /** - * Synchronizes the tracker to the client side. - * Before Forestry 4.2.1: Should be called before opening any gui needing that information. - * Since Forestry 4.2.1: Breeding tracker should be automatically synced, only Forestry should need to call this. - */ - void synchToPlayer(EntityPlayer player); + /** + * @return true if the mutation has been researched. + */ + boolean isResearched(IMutation mutation); - /* LOADING & SAVING */ - void decodeFromNBT(NBTTagCompound nbttagcompound); + /** + * Synchronizes the tracker to the client side. + * Before Forestry 4.2.1: Should be called before opening any gui needing that information. + * Since Forestry 4.2.1: Breeding tracker should be automatically synced, only Forestry should need to call this. + */ + void synchToPlayer(EntityPlayer player); - void encodeToNBT(NBTTagCompound nbttagcompound); + /* LOADING & SAVING */ + void decodeFromNBT(NBTTagCompound nbttagcompound); + void encodeToNBT(NBTTagCompound nbttagcompound); } diff --git a/src/main/java/forestry/api/genetics/IChromosome.java b/src/main/java/forestry/api/genetics/IChromosome.java index d501efbac..9e757da93 100644 --- a/src/main/java/forestry/api/genetics/IChromosome.java +++ b/src/main/java/forestry/api/genetics/IChromosome.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; @@ -9,17 +9,16 @@ import forestry.api.core.INBTTagable; /** * Implementations other than Forestry's default one are not supported! - * + * * @author SirSengir */ public interface IChromosome extends INBTTagable { - IAllele getPrimaryAllele(); + IAllele getPrimaryAllele(); - IAllele getSecondaryAllele(); + IAllele getSecondaryAllele(); - IAllele getInactiveAllele(); - - IAllele getActiveAllele(); + IAllele getInactiveAllele(); + IAllele getActiveAllele(); } diff --git a/src/main/java/forestry/api/genetics/IChromosomeType.java b/src/main/java/forestry/api/genetics/IChromosomeType.java index a3b1f8e0c..5e239fc0d 100644 --- a/src/main/java/forestry/api/genetics/IChromosomeType.java +++ b/src/main/java/forestry/api/genetics/IChromosomeType.java @@ -1,24 +1,23 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; - + /* * Interface to be implemented by the enums representing the various chromosomes */ public interface IChromosomeType { - - /* - * Get class which all alleles on this chromosome must interface - */ - Class getAlleleClass(); - - String getName(); - - ISpeciesRoot getSpeciesRoot(); - - int ordinal(); - + + /* + * Get class which all alleles on this chromosome must interface + */ + Class getAlleleClass(); + + String getName(); + + ISpeciesRoot getSpeciesRoot(); + + int ordinal(); } diff --git a/src/main/java/forestry/api/genetics/IClassification.java b/src/main/java/forestry/api/genetics/IClassification.java index f365b915c..fac4850ad 100644 --- a/src/main/java/forestry/api/genetics/IClassification.java +++ b/src/main/java/forestry/api/genetics/IClassification.java @@ -1,107 +1,114 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; /** * Biological classifications from domain down to genus. - * + * * Used by the *alyzers to display hierarchies. */ public interface IClassification { - public enum EnumClassLevel { + public enum EnumClassLevel { + DOMAIN(0x777fff, true), + KINGDOM(0x77c3ff), + PHYLUM(0x77ffb6, true), + DIVISION(0x77ffb6, true), + CLASS(0x7bff77), + ORDER(0xbeff77), + FAMILY(0xfffd77), + SUBFAMILY(0xfffd77), + TRIBE(0xfffd77), + GENUS(0xffba77); - DOMAIN(0x777fff, true), KINGDOM(0x77c3ff), PHYLUM(0x77ffb6, true), DIVISION(0x77ffb6, true), CLASS(0x7bff77), ORDER(0xbeff77), FAMILY(0xfffd77), - SUBFAMILY(0xfffd77), TRIBE(0xfffd77), GENUS(0xffba77); + private int colour; + private boolean isDroppable; - private int colour; - private boolean isDroppable; + private EnumClassLevel(int colour) { + this(colour, false); + } - private EnumClassLevel(int colour) { - this(colour, false); - } + private EnumClassLevel(int colour, boolean isDroppable) { + this.colour = colour; + this.isDroppable = isDroppable; + } - private EnumClassLevel(int colour, boolean isDroppable) { - this.colour = colour; - this.isDroppable = isDroppable; - } + /** + * @return Colour to use for displaying this classification. + */ + public int getColour() { + return colour; + } - /** - * @return Colour to use for displaying this classification. - */ - public int getColour() { - return colour; - } + /** + * @return Indicates whether display of this classification level can be ommitted in case of space constraints. + */ + public boolean isDroppable() { + return isDroppable; + } + } - /** - * @return Indicates whether display of this classification level can be ommitted in case of space constraints. - */ - public boolean isDroppable() { - return isDroppable; - } - } + /** + * @return Level inside the full hierarchy this particular classification is located at. + */ + EnumClassLevel getLevel(); - /** - * @return Level inside the full hierarchy this particular classification is located at. - */ - EnumClassLevel getLevel(); + /** + * @return Unique String identifier. + */ + String getUID(); - /** - * @return Unique String identifier. - */ - String getUID(); + /** + * @return Localized branch name for user display. + */ + String getName(); - /** - * @return Localized branch name for user display. - */ - String getName(); + /** + * A branch approximates a "genus" in real life. Real life examples: "Micrapis", "Megapis" + * + * @return flavour text (may be null) + */ + String getScientific(); - /** - * A branch approximates a "genus" in real life. Real life examples: "Micrapis", "Megapis" - * - * @return flavour text (may be null) - */ - String getScientific(); + /** + * @return Localized description of this branch. (May be null.) + */ + String getDescription(); - /** - * @return Localized description of this branch. (May be null.) - */ - String getDescription(); + /** + * @return Member groups of this one. + */ + IClassification[] getMemberGroups(); - /** - * @return Member groups of this one. - */ - IClassification[] getMemberGroups(); + /** + * Adds subgroups to this group. + */ + void addMemberGroup(IClassification group); - /** - * Adds subgroups to this group. - */ - void addMemberGroup(IClassification group); + /** + * @return Member species of this group. + */ + IAlleleSpecies[] getMemberSpecies(); - /** - * @return Member species of this group. - */ - IAlleleSpecies[] getMemberSpecies(); + /** + * Used by the allele registry to populate internal collection of branch members on the fly. + * + * @param species + */ + void addMemberSpecies(IAlleleSpecies species); - /** - * Used by the allele registry to populate internal collection of branch members on the fly. - * - * @param species - */ - void addMemberSpecies(IAlleleSpecies species); + /** + * @return Parent classification, null if this is root. + */ + IClassification getParent(); - /** - * @return Parent classification, null if this is root. - */ - IClassification getParent(); - - /** - * Only used internally by the AlleleRegistry if this classification has been added to another one. - * - * @param parent - */ - void setParent(IClassification parent); + /** + * Only used internally by the AlleleRegistry if this classification has been added to another one. + * + * @param parent + */ + void setParent(IClassification parent); } diff --git a/src/main/java/forestry/api/genetics/IClimateHelper.java b/src/main/java/forestry/api/genetics/IClimateHelper.java index 481460427..6e7138fda 100644 --- a/src/main/java/forestry/api/genetics/IClimateHelper.java +++ b/src/main/java/forestry/api/genetics/IClimateHelper.java @@ -1,53 +1,57 @@ package forestry.api.genetics; -import java.util.Collection; - import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; +import java.util.Collection; public interface IClimateHelper { - /** - * Determines whether the given temperature and humidity are within the given constraints. - * @param temperature The temperature to test. - * @param humidity The humidity to test. - * @param baseTemp Base temperature for the test. - * @param tolTemp Temperature tolerance to apply. - * @param baseHumid Base humidity for the test. - * @param tolHumid Humidity tolerance to apply. - * @return true if both temperature and humidity fit the given constraints. - */ - boolean isWithinLimits(EnumTemperature temperature, EnumHumidity humidity, - EnumTemperature baseTemp, EnumTolerance tolTemp, - EnumHumidity baseHumid, EnumTolerance tolHumid); + /** + * Determines whether the given temperature and humidity are within the given constraints. + * @param temperature The temperature to test. + * @param humidity The humidity to test. + * @param baseTemp Base temperature for the test. + * @param tolTemp Temperature tolerance to apply. + * @param baseHumid Base humidity for the test. + * @param tolHumid Humidity tolerance to apply. + * @return true if both temperature and humidity fit the given constraints. + */ + boolean isWithinLimits( + EnumTemperature temperature, + EnumHumidity humidity, + EnumTemperature baseTemp, + EnumTolerance tolTemp, + EnumHumidity baseHumid, + EnumTolerance tolHumid); - boolean isWithinLimits(EnumTemperature temperature, EnumTemperature baseTemp, EnumTolerance tolTemp); - boolean isWithinLimits(EnumHumidity humidity, EnumHumidity baseHumid, EnumTolerance tolHumid); - - /** - * Gets a collection of humidities which fit the given parameters. - * @param prefered Base humidity from which to measure. - * @param tolerance Tolerance to apply to the base humidity. - * @return A collection of humidities which fall within the given parameters. - */ - Collection getToleratedHumidity(EnumHumidity prefered, EnumTolerance tolerance); - /** - * Gets a collection of temperatures which fit the given parameters. - * @param prefered Base temperature from which to measure. - * @param tolerance Tolerance to apply to the base temperatures. - * @return A collection of temperatures which fall within the given parameters. - */ - Collection getToleratedTemperature(EnumTemperature prefered, EnumTolerance tolerance); - - /** - * Gets a localized, human readable string for the given temperature. - * @param temperature Temperature to generate the string for. - * @return A localized, human readable string for the given temperature. - */ - String toDisplay(EnumTemperature temperature); - /** - * Gets a localized, human readable string for the given humidity. - * @param humidity Humidity to generate the string for. - * @return A localized, human readable string for the given humidity. - */ - String toDisplay(EnumHumidity humidity); -} \ No newline at end of file + boolean isWithinLimits(EnumTemperature temperature, EnumTemperature baseTemp, EnumTolerance tolTemp); + + boolean isWithinLimits(EnumHumidity humidity, EnumHumidity baseHumid, EnumTolerance tolHumid); + + /** + * Gets a collection of humidities which fit the given parameters. + * @param prefered Base humidity from which to measure. + * @param tolerance Tolerance to apply to the base humidity. + * @return A collection of humidities which fall within the given parameters. + */ + Collection getToleratedHumidity(EnumHumidity prefered, EnumTolerance tolerance); + /** + * Gets a collection of temperatures which fit the given parameters. + * @param prefered Base temperature from which to measure. + * @param tolerance Tolerance to apply to the base temperatures. + * @return A collection of temperatures which fall within the given parameters. + */ + Collection getToleratedTemperature(EnumTemperature prefered, EnumTolerance tolerance); + + /** + * Gets a localized, human readable string for the given temperature. + * @param temperature Temperature to generate the string for. + * @return A localized, human readable string for the given temperature. + */ + String toDisplay(EnumTemperature temperature); + /** + * Gets a localized, human readable string for the given humidity. + * @param humidity Humidity to generate the string for. + * @return A localized, human readable string for the given humidity. + */ + String toDisplay(EnumHumidity humidity); +} diff --git a/src/main/java/forestry/api/genetics/IEffectData.java b/src/main/java/forestry/api/genetics/IEffectData.java index 909ab78df..8493da433 100644 --- a/src/main/java/forestry/api/genetics/IEffectData.java +++ b/src/main/java/forestry/api/genetics/IEffectData.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; @@ -9,19 +9,19 @@ import forestry.api.core.INBTTagable; /** * Container to hold some temporary data for bee, tree and butterfly effects. - * + * * @author SirSengir */ public interface IEffectData extends INBTTagable { - void setInteger(int index, int val); + void setInteger(int index, int val); - void setFloat(int index, float val); + void setFloat(int index, float val); - void setBoolean(int index, boolean val); + void setBoolean(int index, boolean val); - int getInteger(int index); + int getInteger(int index); - float getFloat(int index); + float getFloat(int index); - boolean getBoolean(int index); + boolean getBoolean(int index); } diff --git a/src/main/java/forestry/api/genetics/IFlower.java b/src/main/java/forestry/api/genetics/IFlower.java index e37c16eaa..a46b98db2 100644 --- a/src/main/java/forestry/api/genetics/IFlower.java +++ b/src/main/java/forestry/api/genetics/IFlower.java @@ -13,12 +13,13 @@ import net.minecraft.block.Block; @Deprecated public interface IFlower extends Comparable { - Block getBlock(); - int getMeta(); + Block getBlock(); - double getWeight(); - void setWeight(double weight); + int getMeta(); - boolean isPlantable(); + double getWeight(); + void setWeight(double weight); + + boolean isPlantable(); } diff --git a/src/main/java/forestry/api/genetics/IFlowerAcceptableRule.java b/src/main/java/forestry/api/genetics/IFlowerAcceptableRule.java index cb53c673d..0b6f2c622 100644 --- a/src/main/java/forestry/api/genetics/IFlowerAcceptableRule.java +++ b/src/main/java/forestry/api/genetics/IFlowerAcceptableRule.java @@ -8,9 +8,9 @@ package forestry.api.genetics; import net.minecraft.world.World; public interface IFlowerAcceptableRule { - /** - * Checks if the flower at this position is accepted by this rule. - * flowerType is passed in case this rule is registered for multiple flower types. - */ - boolean isAcceptableFlower(String flowerType, World world, int x, int y, int z); + /** + * Checks if the flower at this position is accepted by this rule. + * flowerType is passed in case this rule is registered for multiple flower types. + */ + boolean isAcceptableFlower(String flowerType, World world, int x, int y, int z); } diff --git a/src/main/java/forestry/api/genetics/IFlowerGrowthHelper.java b/src/main/java/forestry/api/genetics/IFlowerGrowthHelper.java index 19d2e6fcc..f17357fe4 100644 --- a/src/main/java/forestry/api/genetics/IFlowerGrowthHelper.java +++ b/src/main/java/forestry/api/genetics/IFlowerGrowthHelper.java @@ -8,9 +8,9 @@ package forestry.api.genetics; import net.minecraft.world.World; public interface IFlowerGrowthHelper { - /** - * Plants a random flower from flowerType at the specified position. - * @return true if successful, false if it could not be planted. - */ - boolean plantRandomFlower(String flowerType, World world, int x, int y, int z); + /** + * Plants a random flower from flowerType at the specified position. + * @return true if successful, false if it could not be planted. + */ + boolean plantRandomFlower(String flowerType, World world, int x, int y, int z); } diff --git a/src/main/java/forestry/api/genetics/IFlowerGrowthRule.java b/src/main/java/forestry/api/genetics/IFlowerGrowthRule.java index 4cb2ce52f..1aefce01f 100644 --- a/src/main/java/forestry/api/genetics/IFlowerGrowthRule.java +++ b/src/main/java/forestry/api/genetics/IFlowerGrowthRule.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; @@ -11,20 +11,20 @@ import net.minecraft.world.World; * Basic condition for flower growing, such as checking that the soil is the correct type. */ public interface IFlowerGrowthRule { - /** - * Checks a position for suitability, and then plants a flower there. - * Returns true on success. - * For implementers, you can plant a random flower using IFlowerGrowthHelper.plantRandomFlower - * @since Forestry 4.0.8 - */ - boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z); + /** + * Checks a position for suitability, and then plants a flower there. + * Returns true on success. + * For implementers, you can plant a random flower using IFlowerGrowthHelper.plantRandomFlower + * @since Forestry 4.0.8 + */ + boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z); - /** - * Checks a position for suitability, and then plants a flower there. - * Returns true on success. - * For implementers, get a flower to grow using IFlowerRegistry.getRandomPlantableFlower - * @deprecated since Forestry 4.0 Use the IFlowerGrowthHelper version. - */ - @Deprecated - boolean growFlower(IFlowerRegistry fr, String flowerType, World world, IIndividual individual, int x, int y, int z); + /** + * Checks a position for suitability, and then plants a flower there. + * Returns true on success. + * For implementers, get a flower to grow using IFlowerRegistry.getRandomPlantableFlower + * @deprecated since Forestry 4.0 Use the IFlowerGrowthHelper version. + */ + @Deprecated + boolean growFlower(IFlowerRegistry fr, String flowerType, World world, IIndividual individual, int x, int y, int z); } diff --git a/src/main/java/forestry/api/genetics/IFlowerProvider.java b/src/main/java/forestry/api/genetics/IFlowerProvider.java index 03e413378..44e8e77e5 100644 --- a/src/main/java/forestry/api/genetics/IFlowerProvider.java +++ b/src/main/java/forestry/api/genetics/IFlowerProvider.java @@ -1,50 +1,49 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; import java.util.Set; - import net.minecraft.item.ItemStack; import net.minecraft.world.World; public interface IFlowerProvider { - boolean isAcceptedPollinatable(World world, IPollinatable pollinatable); + boolean isAcceptedPollinatable(World world, IPollinatable pollinatable); - /** - * @return The unique type used for the IFlowerRegistry - * @since Forestry 4.0.0 - */ - String getFlowerType(); + /** + * @return The unique type used for the IFlowerRegistry + * @since Forestry 4.0.0 + */ + String getFlowerType(); - /** - * @return Short, human-readable identifier used in the beealyzer. - */ - String getDescription(); + /** + * @return Short, human-readable identifier used in the beealyzer. + */ + String getDescription(); - /** - * Allows the flower provider to affect the produce at the given location. - * If this flowerProvider does not affect the products, it should return the products unchanged. - * @return Array of itemstacks being the (modified or unmodified) produce. - */ - ItemStack[] affectProducts(World world, IIndividual individual, int x, int y, int z, ItemStack[] products); + /** + * Allows the flower provider to affect the produce at the given location. + * If this flowerProvider does not affect the products, it should return the products unchanged. + * @return Array of itemstacks being the (modified or unmodified) produce. + */ + ItemStack[] affectProducts(World world, IIndividual individual, int x, int y, int z, ItemStack[] products); - /** - * @return Set of valid flowers for the flower provider. - * Returns an empty set if the flower provider does not have any valid flowers. - * @deprecated since Forestry 4.0.8 Use more specific methods in IFlowerRegistry. - */ - @Deprecated - Set getFlowers(); + /** + * @return Set of valid flowers for the flower provider. + * Returns an empty set if the flower provider does not have any valid flowers. + * @deprecated since Forestry 4.0.8 Use more specific methods in IFlowerRegistry. + */ + @Deprecated + Set getFlowers(); - /** - * @return True if a flower was planted. - * @deprecated since Forestry 4.0.8 Use IFlowerRegistry.growFlower. - * Implementers can move logic into a IFlowerGrowthRule and register with IFlowerRegistry.registerGrowthRule - */ - @Deprecated - boolean growFlower(World world, IIndividual individual, int x, int y, int z); + /** + * @return True if a flower was planted. + * @deprecated since Forestry 4.0.8 Use IFlowerRegistry.growFlower. + * Implementers can move logic into a IFlowerGrowthRule and register with IFlowerRegistry.registerGrowthRule + */ + @Deprecated + boolean growFlower(World world, IIndividual individual, int x, int y, int z); } diff --git a/src/main/java/forestry/api/genetics/IFlowerRegistry.java b/src/main/java/forestry/api/genetics/IFlowerRegistry.java index b53c35cbe..06ad8029b 100644 --- a/src/main/java/forestry/api/genetics/IFlowerRegistry.java +++ b/src/main/java/forestry/api/genetics/IFlowerRegistry.java @@ -1,92 +1,90 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; +import forestry.api.apiculture.IBee; +import forestry.api.apiculture.IBeeHousing; import java.util.Collection; import java.util.Random; import java.util.Set; - import net.minecraft.block.Block; import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.apiculture.IBee; -import forestry.api.apiculture.IBeeHousing; - // See {@link forestry.api.apiculture.FlowerManager}.FlowerType___ for basic Forestry flower types. // Each IFlowerProvider has one flower type, and multiple IFlowerProviders may share one type. // "Acceptable flowers" allow nearby bees to do work. // "Plantable flowers" are "Acceptable flowers" and are also planted randomly by bees. public interface IFlowerRegistry { - /** - * Register a new flower growth rule. - * This defines the flower planting logic for the specified flower types. - * Without a flower growth rule, no flowers of that type can be planted. - */ - void registerGrowthRule(IFlowerGrowthRule rule, String... flowerTypes); + /** + * Register a new flower growth rule. + * This defines the flower planting logic for the specified flower types. + * Without a flower growth rule, no flowers of that type can be planted. + */ + void registerGrowthRule(IFlowerGrowthRule rule, String... flowerTypes); - /** - * Registers an accepted flower with any meta value. - */ - void registerAcceptableFlower(Block flowerBlock, String... flowerTypes); - /** - * Registers an accepted flower with a specific meta value. - */ - void registerAcceptableFlower(Block flowerBlock, int flowerMeta, String... flowerTypes); + /** + * Registers an accepted flower with any meta value. + */ + void registerAcceptableFlower(Block flowerBlock, String... flowerTypes); + /** + * Registers an accepted flower with a specific meta value. + */ + void registerAcceptableFlower(Block flowerBlock, int flowerMeta, String... flowerTypes); - /** - * Registers custom logic for accepted flowers. - * These rules are inefficient compared to ones made with registerAcceptableFlower, but may be necessary for tile entity flowers. - * The flower types built into Forestry can not be used here. - * @since Forestry 4.0.8 - */ - void registerAcceptableFlowerRule(IFlowerAcceptableRule flowerAcceptableRule, String... flowerTypes); + /** + * Registers custom logic for accepted flowers. + * These rules are inefficient compared to ones made with registerAcceptableFlower, but may be necessary for tile entity flowers. + * The flower types built into Forestry can not be used here. + * @since Forestry 4.0.8 + */ + void registerAcceptableFlowerRule(IFlowerAcceptableRule flowerAcceptableRule, String... flowerTypes); - /** - * Registers a plantable flower. - * The distribution is based on its own weight and the total number of plants for this flowerType. - * - * @param weight Weight for the Flower (Vanilla = 1.0, Modded flowers < 1.0) - * @param flowerTypes See {@link forestry.api.apiculture.FlowerManager}.FlowerTypeXXX - */ - void registerPlantableFlower(Block flowerBlock, int flowerMeta, double weight, String... flowerTypes); + /** + * Registers a plantable flower. + * The distribution is based on its own weight and the total number of plants for this flowerType. + * + * @param weight Weight for the Flower (Vanilla = 1.0, Modded flowers < 1.0) + * @param flowerTypes See {@link forestry.api.apiculture.FlowerManager}.FlowerTypeXXX + */ + void registerPlantableFlower(Block flowerBlock, int flowerMeta, double weight, String... flowerTypes); - /** - * Calls the appropriate IFlowerGrowthRule to grow a flower at a specified position. - */ - boolean growFlower(String flowerType, World world, IIndividual individual, int x, int y, int z); + /** + * Calls the appropriate IFlowerGrowthRule to grow a flower at a specified position. + */ + boolean growFlower(String flowerType, World world, IIndividual individual, int x, int y, int z); - /** - * @return the coordinates of a nearby accepted flower or null if there is none. - */ - ChunkCoordinates getAcceptedFlowerCoordinates(IBeeHousing beeHousing, IBee bee, String flowerType); + /** + * @return the coordinates of a nearby accepted flower or null if there is none. + */ + ChunkCoordinates getAcceptedFlowerCoordinates(IBeeHousing beeHousing, IBee bee, String flowerType); - /** - * Checks a single coordinate to see if it is an accepted flower. - */ - boolean isAcceptedFlower(String flowerType, World world, int x, int y, int z); + /** + * Checks a single coordinate to see if it is an accepted flower. + */ + boolean isAcceptedFlower(String flowerType, World world, int x, int y, int z); - /** - * For use by IFlowerGrowthRule implementations - * @deprecated since Forestry 4.0.8 This will be accessible to IFlowerGrowthRule via IFlowerGrowthHelper - */ - @Deprecated - IFlower getRandomPlantableFlower(String flowerType, Random rand); + /** + * For use by IFlowerGrowthRule implementations + * @deprecated since Forestry 4.0.8 This will be accessible to IFlowerGrowthRule via IFlowerGrowthHelper + */ + @Deprecated + IFlower getRandomPlantableFlower(String flowerType, Random rand); - /** - * Returns all known flower types. - * @deprecated since Forestry 4.0.8 This should only be used internally. - */ - @Deprecated - Collection getFlowerTypes(); + /** + * Returns all known flower types. + * @deprecated since Forestry 4.0.8 This should only be used internally. + */ + @Deprecated + Collection getFlowerTypes(); - /** - * @deprecated since Forestry 4.0.8 This should only be used internally. - */ - @Deprecated - Set getAcceptableFlowers(String flowerType); + /** + * @deprecated since Forestry 4.0.8 This should only be used internally. + */ + @Deprecated + Set getAcceptableFlowers(String flowerType); } diff --git a/src/main/java/forestry/api/genetics/IFruitBearer.java b/src/main/java/forestry/api/genetics/IFruitBearer.java index 5316f9ebc..d5af699e2 100644 --- a/src/main/java/forestry/api/genetics/IFruitBearer.java +++ b/src/main/java/forestry/api/genetics/IFruitBearer.java @@ -1,50 +1,49 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; import java.util.Collection; - import net.minecraft.item.ItemStack; /** * Can be implemented by tile entities which can bear fruit. - * + * * @author SirSengir */ public interface IFruitBearer { - /** - * @return true if the actual tile can bear fruits. - */ - boolean hasFruit(); + /** + * @return true if the actual tile can bear fruits. + */ + boolean hasFruit(); - /** - * @return Family of the potential fruits on this tile. - */ - IFruitFamily getFruitFamily(); + /** + * @return Family of the potential fruits on this tile. + */ + IFruitFamily getFruitFamily(); - /** - * Picks the fruits of this tile, resetting it to unripe fruits. - * - * @param tool - * Tool used in picking the fruits. May be null. - * @return Picked fruits. - */ - Collection pickFruit(ItemStack tool); + /** + * Picks the fruits of this tile, resetting it to unripe fruits. + * + * @param tool + * Tool used in picking the fruits. May be null. + * @return Picked fruits. + */ + Collection pickFruit(ItemStack tool); - /** - * @return float indicating the ripeness of the fruit with >= 1.0f indicating full ripeness. - */ - float getRipeness(); + /** + * @return float indicating the ripeness of the fruit with >= 1.0f indicating full ripeness. + */ + float getRipeness(); - /** - * Increases the ripeness of the fruit. - * - * @param add - * Float to add to the ripeness. Will truncate to valid values. - */ - void addRipeness(float add); + /** + * Increases the ripeness of the fruit. + * + * @param add + * Float to add to the ripeness. Will truncate to valid values. + */ + void addRipeness(float add); } diff --git a/src/main/java/forestry/api/genetics/IFruitFamily.java b/src/main/java/forestry/api/genetics/IFruitFamily.java index d48a4d8a1..235429a5c 100644 --- a/src/main/java/forestry/api/genetics/IFruitFamily.java +++ b/src/main/java/forestry/api/genetics/IFruitFamily.java @@ -1,32 +1,31 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; public interface IFruitFamily { - /** - * @return Unique String identifier. - */ - String getUID(); + /** + * @return Unique String identifier. + */ + String getUID(); - /** - * @return Localized family name for user display. - */ - String getName(); + /** + * @return Localized family name for user display. + */ + String getName(); - /** - * A scientific-y name for this fruit family - * - * @return flavour text (may be null) - */ - String getScientific(); - - /** - * @return Localized description of this fruit family. (May be null.) - */ - String getDescription(); + /** + * A scientific-y name for this fruit family + * + * @return flavour text (may be null) + */ + String getScientific(); + /** + * @return Localized description of this fruit family. (May be null.) + */ + String getDescription(); } diff --git a/src/main/java/forestry/api/genetics/IGenome.java b/src/main/java/forestry/api/genetics/IGenome.java index 0d3ad2319..62ba26ad2 100644 --- a/src/main/java/forestry/api/genetics/IGenome.java +++ b/src/main/java/forestry/api/genetics/IGenome.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; @@ -9,22 +9,22 @@ import forestry.api.core.INBTTagable; /** * Holds the {@link IChromosome}s which comprise the traits of a given individual. - * + * * Only the default implementation is supported. */ public interface IGenome extends INBTTagable { - IAlleleSpecies getPrimary(); + IAlleleSpecies getPrimary(); - IAlleleSpecies getSecondary(); + IAlleleSpecies getSecondary(); - IChromosome[] getChromosomes(); + IChromosome[] getChromosomes(); - IAllele getActiveAllele(IChromosomeType chromosomeType); + IAllele getActiveAllele(IChromosomeType chromosomeType); - IAllele getInactiveAllele(IChromosomeType chromosomeType); + IAllele getInactiveAllele(IChromosomeType chromosomeType); - boolean isGeneticEqual(IGenome other); - - ISpeciesRoot getSpeciesRoot(); + boolean isGeneticEqual(IGenome other); + + ISpeciesRoot getSpeciesRoot(); } diff --git a/src/main/java/forestry/api/genetics/IHousing.java b/src/main/java/forestry/api/genetics/IHousing.java index c43854c3c..fcd2a12af 100644 --- a/src/main/java/forestry/api/genetics/IHousing.java +++ b/src/main/java/forestry/api/genetics/IHousing.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; @@ -12,6 +12,5 @@ import net.minecraft.util.ChunkCoordinates; */ public interface IHousing { - ChunkCoordinates getCoordinates(); - + ChunkCoordinates getCoordinates(); } diff --git a/src/main/java/forestry/api/genetics/IIndividual.java b/src/main/java/forestry/api/genetics/IIndividual.java index f86aa5829..9bc13c53a 100644 --- a/src/main/java/forestry/api/genetics/IIndividual.java +++ b/src/main/java/forestry/api/genetics/IIndividual.java @@ -1,53 +1,51 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; -import java.util.List; - import forestry.api.core.INBTTagable; +import java.util.List; /** * An actual individual with genetic information. - * + * * Only the default implementation is supported. */ public interface IIndividual extends INBTTagable { - String getIdent(); + String getIdent(); - String getDisplayName(); + String getDisplayName(); - void addTooltip(List list); + void addTooltip(List list); - /** - * Call to mark the IIndividual as analyzed. - * @return true if the IIndividual has not been analyzed previously. - */ - boolean analyze(); + /** + * Call to mark the IIndividual as analyzed. + * @return true if the IIndividual has not been analyzed previously. + */ + boolean analyze(); - boolean isAnalyzed(); + boolean isAnalyzed(); - boolean hasEffect(); + boolean hasEffect(); - boolean isSecret(); + boolean isSecret(); - IGenome getGenome(); + IGenome getGenome(); - /** - * Check whether the genetic makeup of two IIndividuals is identical. Ignores additional data like generations, irregular mating, etc.. - * @param other - * @return true if the given other IIndividual has the amount of chromosomes and their alleles are identical. - */ - boolean isGeneticEqual(IIndividual other); + /** + * Check whether the genetic makeup of two IIndividuals is identical. Ignores additional data like generations, irregular mating, etc.. + * @param other + * @return true if the given other IIndividual has the amount of chromosomes and their alleles are identical. + */ + boolean isGeneticEqual(IIndividual other); - /** - * @return A deep copy of this individual. - */ - IIndividual copy(); - - boolean isPureBred(IChromosomeType chromosomeType); + /** + * @return A deep copy of this individual. + */ + IIndividual copy(); + boolean isPureBred(IChromosomeType chromosomeType); } diff --git a/src/main/java/forestry/api/genetics/IIndividualLiving.java b/src/main/java/forestry/api/genetics/IIndividualLiving.java index 67ce0a975..8a08e46eb 100644 --- a/src/main/java/forestry/api/genetics/IIndividualLiving.java +++ b/src/main/java/forestry/api/genetics/IIndividualLiving.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; @@ -9,37 +9,36 @@ import net.minecraft.world.World; public interface IIndividualLiving extends IIndividual { - /** - * @return Genetic information of the mate, null if unmated. - */ - IGenome getMate(); + /** + * @return Genetic information of the mate, null if unmated. + */ + IGenome getMate(); - /** - * @return Current health of the individual. - */ - int getHealth(); + /** + * @return Current health of the individual. + */ + int getHealth(); - /** - * @return Maximum health of the individual. - */ - int getMaxHealth(); + /** + * @return Maximum health of the individual. + */ + int getMaxHealth(); - /** - * Age the individual. - * @param world - * @param ageModifier - */ - void age(World world, float ageModifier); + /** + * Age the individual. + * @param world + * @param ageModifier + */ + void age(World world, float ageModifier); - /** - * Mate with the given individual. - * @param individual the {@link IIndividual} to mate this one with. - */ - void mate(IIndividual individual); - - /** - * @return true if the individual is among the living. - */ - boolean isAlive(); + /** + * Mate with the given individual. + * @param individual the {@link IIndividual} to mate this one with. + */ + void mate(IIndividual individual); + /** + * @return true if the individual is among the living. + */ + boolean isAlive(); } diff --git a/src/main/java/forestry/api/genetics/IMutation.java b/src/main/java/forestry/api/genetics/IMutation.java index bf7ae62f1..faf91f0cf 100644 --- a/src/main/java/forestry/api/genetics/IMutation.java +++ b/src/main/java/forestry/api/genetics/IMutation.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; @@ -9,60 +9,59 @@ import java.util.Collection; /** * Individuals can be seeded either as hive drops or as mutation results. - * + * * {@link IAlleleRegistry} manages these. - * + * * @author SirSengir */ public interface IMutation { - /** - * @return {@link ISpeciesRoot} this mutation is associated with. - */ - ISpeciesRoot getRoot(); + /** + * @return {@link ISpeciesRoot} this mutation is associated with. + */ + ISpeciesRoot getRoot(); - /** - * @return first of the alleles implementing IAlleleSpecies required for this mutation. - */ - IAlleleSpecies getAllele0(); + /** + * @return first of the alleles implementing IAlleleSpecies required for this mutation. + */ + IAlleleSpecies getAllele0(); - /** - * @return second of the alleles implementing IAlleleSpecies required for this mutation. - */ - IAlleleSpecies getAllele1(); + /** + * @return second of the alleles implementing IAlleleSpecies required for this mutation. + */ + IAlleleSpecies getAllele1(); - /** - * @return Array of {@link IAllele} representing the full default genome of the mutated side. - * - * Make sure to return a proper array for the species class. Returning an allele of the wrong type will cause cast errors on runtime. - */ - IAllele[] getTemplate(); + /** + * @return Array of {@link IAllele} representing the full default genome of the mutated side. + * + * Make sure to return a proper array for the species class. Returning an allele of the wrong type will cause cast errors on runtime. + */ + IAllele[] getTemplate(); - /** - * @return Unmodified base chance for mutation to fire. - */ - float getBaseChance(); + /** + * @return Unmodified base chance for mutation to fire. + */ + float getBaseChance(); - /** - * @return Collection of localized, human-readable strings describing special mutation conditions, if any. - */ - Collection getSpecialConditions(); - - /** - * @param allele - * @return true if the passed allele is one of the alleles participating in this mutation. - */ - boolean isPartner(IAllele allele); + /** + * @return Collection of localized, human-readable strings describing special mutation conditions, if any. + */ + Collection getSpecialConditions(); - /** - * @param allele - * @return the other allele which was not passed as argument. - */ - IAllele getPartner(IAllele allele); + /** + * @param allele + * @return true if the passed allele is one of the alleles participating in this mutation. + */ + boolean isPartner(IAllele allele); - /** - * @return true if the mutation should not be displayed in the beealyzer. - */ - boolean isSecret(); + /** + * @param allele + * @return the other allele which was not passed as argument. + */ + IAllele getPartner(IAllele allele); + /** + * @return true if the mutation should not be displayed in the beealyzer. + */ + boolean isSecret(); } diff --git a/src/main/java/forestry/api/genetics/IMutationCondition.java b/src/main/java/forestry/api/genetics/IMutationCondition.java index bdf77742e..bc626d19c 100644 --- a/src/main/java/forestry/api/genetics/IMutationCondition.java +++ b/src/main/java/forestry/api/genetics/IMutationCondition.java @@ -5,21 +5,29 @@ ******************************************************************************/ package forestry.api.genetics; -import net.minecraft.world.World; - import forestry.api.core.IClimateProvider; +import net.minecraft.world.World; public interface IMutationCondition { - /** - * Returns a float from 0 to 1 representing the chance for mutation to occur. - * Most will return 1 if the condition is met and 0 otherwise, - * but the float offers flexibility for more advanced conditions. - */ - float getChance(World world, int x, int y, int z, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1, IClimateProvider climate); + /** + * Returns a float from 0 to 1 representing the chance for mutation to occur. + * Most will return 1 if the condition is met and 0 otherwise, + * but the float offers flexibility for more advanced conditions. + */ + float getChance( + World world, + int x, + int y, + int z, + IAllele allele0, + IAllele allele1, + IGenome genome0, + IGenome genome1, + IClimateProvider climate); - /** - * A localized description of the mutation condition. (i.e. "A temperature of HOT is required.") - */ - String getDescription(); + /** + * A localized description of the mutation condition. (i.e. "A temperature of HOT is required.") + */ + String getDescription(); } diff --git a/src/main/java/forestry/api/genetics/IMutationCustom.java b/src/main/java/forestry/api/genetics/IMutationCustom.java index 42235eee4..122fe9c09 100644 --- a/src/main/java/forestry/api/genetics/IMutationCustom.java +++ b/src/main/java/forestry/api/genetics/IMutationCustom.java @@ -5,44 +5,46 @@ ******************************************************************************/ package forestry.api.genetics; -import net.minecraft.block.Block; - -import net.minecraftforge.common.BiomeDictionary; - import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; +import net.minecraft.block.Block; +import net.minecraftforge.common.BiomeDictionary; /** Set custom mutation requirements */ public interface IMutationCustom extends IMutation { - /** Prevent this mutation from being shown in the analyzers */ - IMutationCustom setIsSecret(); + /** Prevent this mutation from being shown in the analyzers */ + IMutationCustom setIsSecret(); - /** Require a specific temperature for this mutation to occur */ - IMutationCustom restrictTemperature(EnumTemperature temperature); - IMutationCustom restrictTemperature(EnumTemperature minTemperature, EnumTemperature maxTemperature); + /** Require a specific temperature for this mutation to occur */ + IMutationCustom restrictTemperature(EnumTemperature temperature); - /** Require a specific humidity for this mutation to occur */ - IMutationCustom restrictHumidity(EnumHumidity humidity); - IMutationCustom restrictHumidity(EnumHumidity minHumidity, EnumHumidity maxHumidity); + IMutationCustom restrictTemperature(EnumTemperature minTemperature, EnumTemperature maxTemperature); - /** - * Restrict this mutation to certain types of biomes. - * @param types The types of biomes this mutation can occur. - */ - IMutationCustom restrictBiomeType(BiomeDictionary.Type... types); + /** Require a specific humidity for this mutation to occur */ + IMutationCustom restrictHumidity(EnumHumidity humidity); - /** Restrict the days of the year that this mutation can occur */ - IMutationCustom restrictDateRange(int startMonth, int startDay, int endMonth, int endDay); + IMutationCustom restrictHumidity(EnumHumidity minHumidity, EnumHumidity maxHumidity); - /** Restrict the time of day that this mutation can occur */ - IMutationCustom requireDay(); - IMutationCustom requireNight(); + /** + * Restrict this mutation to certain types of biomes. + * @param types The types of biomes this mutation can occur. + */ + IMutationCustom restrictBiomeType(BiomeDictionary.Type... types); - /** Require a specific resource to be under the location of the mutation */ - IMutationCustom requireResource(Block block, int meta); - IMutationCustom requireResource(String oreDictName); + /** Restrict the days of the year that this mutation can occur */ + IMutationCustom restrictDateRange(int startMonth, int startDay, int endMonth, int endDay); - /** Require some other custom mutation condition */ - IMutationCustom addMutationCondition(IMutationCondition mutationCondition); + /** Restrict the time of day that this mutation can occur */ + IMutationCustom requireDay(); + + IMutationCustom requireNight(); + + /** Require a specific resource to be under the location of the mutation */ + IMutationCustom requireResource(Block block, int meta); + + IMutationCustom requireResource(String oreDictName); + + /** Require some other custom mutation condition */ + IMutationCustom addMutationCondition(IMutationCondition mutationCondition); } diff --git a/src/main/java/forestry/api/genetics/IPollinatable.java b/src/main/java/forestry/api/genetics/IPollinatable.java index a3716789f..8d44d2559 100644 --- a/src/main/java/forestry/api/genetics/IPollinatable.java +++ b/src/main/java/forestry/api/genetics/IPollinatable.java @@ -1,53 +1,52 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; import java.util.EnumSet; - import net.minecraftforge.common.EnumPlantType; /** * Can be implemented by tile entities, if they wish to be pollinatable. - * + * * @author SirSengir */ public interface IPollinatable { - /** - * @return plant types this pollinatable is classified as. (Can be used by bees to determine whether to interact or not. - */ - EnumSet getPlantType(); + /** + * @return plant types this pollinatable is classified as. (Can be used by bees to determine whether to interact or not. + */ + EnumSet getPlantType(); - /** - * @return IIndividual containing the genetic information of this IPollinatable - */ - IIndividual getPollen(); + /** + * @return IIndividual containing the genetic information of this IPollinatable + */ + IIndividual getPollen(); - /** - * Checks whether this {@link IPollinatable} can mate with the given pollen. - * - * Must be the one to check genetic equivalency. - * - * @param pollen - * IIndividual representing the pollen. - * @return true if mating is possible, false otherwise. - */ - boolean canMateWith(IIndividual pollen); + /** + * Checks whether this {@link IPollinatable} can mate with the given pollen. + * + * Must be the one to check genetic equivalency. + * + * @param pollen + * IIndividual representing the pollen. + * @return true if mating is possible, false otherwise. + */ + boolean canMateWith(IIndividual pollen); - /** - * Pollinates this entity. - * - * @param pollen - * IIndividual representing the pollen. - */ - void mateWith(IIndividual pollen); + /** + * Pollinates this entity. + * + * @param pollen + * IIndividual representing the pollen. + */ + void mateWith(IIndividual pollen); - /** - * @return true if this IPollinatable has already been pollinated. - * @since Forestry 4.1.0 - */ - boolean isPollinated(); + /** + * @return true if this IPollinatable has already been pollinated. + * @since Forestry 4.1.0 + */ + boolean isPollinated(); } diff --git a/src/main/java/forestry/api/genetics/ISpeciesRoot.java b/src/main/java/forestry/api/genetics/ISpeciesRoot.java index f3652bea8..ea9ef59bd 100644 --- a/src/main/java/forestry/api/genetics/ISpeciesRoot.java +++ b/src/main/java/forestry/api/genetics/ISpeciesRoot.java @@ -1,179 +1,178 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.genetics; +import com.mojang.authlib.GameProfile; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Random; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import com.mojang.authlib.GameProfile; - /** * Describes a class of species (i.e. bees, trees, butterflies), provides helper functions and access to common functionality. */ public interface ISpeciesRoot { - /** - * @return A unique identifier for the species class. Should consist of "root" + a common name for the species class in camel-case, i.e. "rootBees", "rootTrees", "rootButterflies". - */ - String getUID(); + /** + * @return A unique identifier for the species class. Should consist of "root" + a common name for the species class in camel-case, i.e. "rootBees", "rootTrees", "rootButterflies". + */ + String getUID(); - /** - * @return Class of the sub-interface inheriting from {@link IIndividual}. - */ - Class getMemberClass(); + /** + * @return Class of the sub-interface inheriting from {@link IIndividual}. + */ + Class getMemberClass(); - /** - * @return Integer denoting the number of (counted) species of this type in the world. - */ - int getSpeciesCount(); + /** + * @return Integer denoting the number of (counted) species of this type in the world. + */ + int getSpeciesCount(); - /** - * Used to check whether a given itemstack contains genetic data corresponding to an {@link IIndividual} of this class. - * @param stack itemstack to check. - * @return true if the itemstack contains an {@link IIndividual} of this class, false otherwise. - */ - boolean isMember(ItemStack stack); + /** + * Used to check whether a given itemstack contains genetic data corresponding to an {@link IIndividual} of this class. + * @param stack itemstack to check. + * @return true if the itemstack contains an {@link IIndividual} of this class, false otherwise. + */ + boolean isMember(ItemStack stack); - /** - * Used to check whether a given itemstack contains genetic data corresponding to an {@link IIndividual} of this class and matches the given type. - * @param stack itemstack to check. - * @param type Integer denoting the type needed to match. (i.e. butterfly vs. butterfly serum; bee queens, princesses, drones; etc.) - * @return true if the itemstack contains an {@link IIndividual} of this class, false otherwise. - */ - boolean isMember(ItemStack stack, int type); + /** + * Used to check whether a given itemstack contains genetic data corresponding to an {@link IIndividual} of this class and matches the given type. + * @param stack itemstack to check. + * @param type Integer denoting the type needed to match. (i.e. butterfly vs. butterfly serum; bee queens, princesses, drones; etc.) + * @return true if the itemstack contains an {@link IIndividual} of this class, false otherwise. + */ + boolean isMember(ItemStack stack, int type); - /** - * Used to check whether the given {@link IIndividual} is member of this class. - * @param individual {@link IIndividual} to check. - * @return true if the individual is member of this class, false otherwise. - */ - boolean isMember(IIndividual individual); + /** + * Used to check whether the given {@link IIndividual} is member of this class. + * @param individual {@link IIndividual} to check. + * @return true if the individual is member of this class, false otherwise. + */ + boolean isMember(IIndividual individual); - IIndividual getMember(ItemStack stack); + IIndividual getMember(ItemStack stack); - IIndividual getMember(NBTTagCompound compound); + IIndividual getMember(NBTTagCompound compound); - ISpeciesType getType(ItemStack itemStack); + ISpeciesType getType(ItemStack itemStack); - ItemStack getMemberStack(IIndividual individual, int type); + ItemStack getMemberStack(IIndividual individual, int type); - /* BREEDING TRACKER */ - IBreedingTracker getBreedingTracker(World world, GameProfile player); + /* BREEDING TRACKER */ + IBreedingTracker getBreedingTracker(World world, GameProfile player); - /** - * @deprecated since Forestry 4.2.1. Breeding tracker should be automatically synced. - */ - @Deprecated - void syncBreedingTrackerToPlayer(EntityPlayer player); + /** + * @deprecated since Forestry 4.2.1. Breeding tracker should be automatically synced. + */ + @Deprecated + void syncBreedingTrackerToPlayer(EntityPlayer player); - /* GENOME MANIPULATION */ - IIndividual templateAsIndividual(IAllele[] template); + /* GENOME MANIPULATION */ + IIndividual templateAsIndividual(IAllele[] template); - IIndividual templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive); + IIndividual templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive); - IChromosome[] templateAsChromosomes(IAllele[] template); + IChromosome[] templateAsChromosomes(IAllele[] template); - IChromosome[] templateAsChromosomes(IAllele[] templateActive, IAllele[] templateInactive); + IChromosome[] templateAsChromosomes(IAllele[] templateActive, IAllele[] templateInactive); - IGenome templateAsGenome(IAllele[] template); + IGenome templateAsGenome(IAllele[] template); - IGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive); + IGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive); - /* TEMPLATES */ - /** - * Registers a bee template using the UID of the first allele as identifier. - * - * @param template - */ - void registerTemplate(IAllele[] template); + /* TEMPLATES */ + /** + * Registers a bee template using the UID of the first allele as identifier. + * + * @param template + */ + void registerTemplate(IAllele[] template); - /** - * Registers a bee template using the passed identifier. - * - * @param template - */ - void registerTemplate(String identifier, IAllele[] template); + /** + * Registers a bee template using the passed identifier. + * + * @param template + */ + void registerTemplate(String identifier, IAllele[] template); - /** - * Retrieves a registered template using the passed identifier. - * - * @param identifier - * @return Array of {@link IAllele} representing a genome. - */ - IAllele[] getTemplate(String identifier); + /** + * Retrieves a registered template using the passed identifier. + * + * @param identifier + * @return Array of {@link IAllele} representing a genome. + */ + IAllele[] getTemplate(String identifier); - /** - * @return Default individual template for use when stuff breaks. - */ - IAllele[] getDefaultTemplate(); + /** + * @return Default individual template for use when stuff breaks. + */ + IAllele[] getDefaultTemplate(); - /** - * @param rand Random to use. - * @return A random template from the pool of registered species templates. - */ - IAllele[] getRandomTemplate(Random rand); + /** + * @param rand Random to use. + * @return A random template from the pool of registered species templates. + */ + IAllele[] getRandomTemplate(Random rand); - Map getGenomeTemplates(); - ArrayList getIndividualTemplates(); + Map getGenomeTemplates(); - /* MUTATIONS */ - /** - * Use to register mutations. - * - * @param mutation - */ - void registerMutation(IMutation mutation); + ArrayList getIndividualTemplates(); - /** - * @return All registered mutations. - */ - Collection getMutations(boolean shuffle); + /* MUTATIONS */ + /** + * Use to register mutations. + * + * @param mutation + */ + void registerMutation(IMutation mutation); - /** - * @param other Allele to match mutations against. - * @return All registered mutations the given allele is part of. - */ - Collection getCombinations(IAllele other); + /** + * @return All registered mutations. + */ + Collection getMutations(boolean shuffle); - /** - * @since Forestry 3.7 - * @return all possible mutations that result from breeding two species - */ - List getCombinations(IAlleleSpecies parentSpecies0, IAlleleSpecies parentSpecies1, boolean shuffle); + /** + * @param other Allele to match mutations against. + * @return All registered mutations the given allele is part of. + */ + Collection getCombinations(IAllele other); - Collection getPaths(IAllele result, IChromosomeType chromosomeType); + /** + * @since Forestry 3.7 + * @return all possible mutations that result from breeding two species + */ + List getCombinations(IAlleleSpecies parentSpecies0, IAlleleSpecies parentSpecies1, boolean shuffle); - /* RESEARCH */ - /** - * @return List of generic catalysts which should be accepted for research by species of this class. - */ - Map getResearchCatalysts(); + Collection getPaths(IAllele result, IChromosomeType chromosomeType); - /** - * Sets an item stack as a valid (generic) research catalyst for this class. - * @param itemstack ItemStack to set as suitable. - * @param suitability Float between 0 and 1 to indicate suitability. - */ - void setResearchSuitability(ItemStack itemstack, float suitability); + /* RESEARCH */ + /** + * @return List of generic catalysts which should be accepted for research by species of this class. + */ + Map getResearchCatalysts(); - /** - * @return Array of {@link IChromosomeType} which are in this species genome - */ - IChromosomeType[] getKaryotype(); + /** + * Sets an item stack as a valid (generic) research catalyst for this class. + * @param itemstack ItemStack to set as suitable. + * @param suitability Float between 0 and 1 to indicate suitability. + */ + void setResearchSuitability(ItemStack itemstack, float suitability); - /** - * @return {@link IChromosomeType} which is the "key" for this species class, usually the species chromosome. - */ - IChromosomeType getKaryotypeKey(); + /** + * @return Array of {@link IChromosomeType} which are in this species genome + */ + IChromosomeType[] getKaryotype(); + + /** + * @return {@link IChromosomeType} which is the "key" for this species class, usually the species chromosome. + */ + IChromosomeType getKaryotypeKey(); } diff --git a/src/main/java/forestry/api/genetics/ISpeciesType.java b/src/main/java/forestry/api/genetics/ISpeciesType.java index 036b9b8cd..a677a0d44 100644 --- a/src/main/java/forestry/api/genetics/ISpeciesType.java +++ b/src/main/java/forestry/api/genetics/ISpeciesType.java @@ -6,5 +6,4 @@ package forestry.api.genetics; /** Species types, implemented by enums and compared with == */ -public interface ISpeciesType { -} +public interface ISpeciesType {} diff --git a/src/main/java/forestry/api/genetics/package-info.java b/src/main/java/forestry/api/genetics/package-info.java index ef863fb3f..a6659f924 100644 --- a/src/main/java/forestry/api/genetics/package-info.java +++ b/src/main/java/forestry/api/genetics/package-info.java @@ -1,8 +1,9 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ @API(apiVersion = "4.7.1", owner = "ForestryAPI|core", provides = "ForestryAPI|genetics") package forestry.api.genetics; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/api/lepidopterology/ButterflyManager.java b/src/main/java/forestry/api/lepidopterology/ButterflyManager.java index 1620b8849..81f224edb 100644 --- a/src/main/java/forestry/api/lepidopterology/ButterflyManager.java +++ b/src/main/java/forestry/api/lepidopterology/ButterflyManager.java @@ -12,10 +12,10 @@ package forestry.api.lepidopterology; public class ButterflyManager { - public static IButterflyRoot butterflyRoot; + public static IButterflyRoot butterflyRoot; - /** - * Used to create new butterflies. - */ - public static IButterflyFactory butterflyFactory; + /** + * Used to create new butterflies. + */ + public static IButterflyFactory butterflyFactory; } diff --git a/src/main/java/forestry/api/lepidopterology/EnumButterflyChromosome.java b/src/main/java/forestry/api/lepidopterology/EnumButterflyChromosome.java index 798c898f2..e4be1fd53 100644 --- a/src/main/java/forestry/api/lepidopterology/EnumButterflyChromosome.java +++ b/src/main/java/forestry/api/lepidopterology/EnumButterflyChromosome.java @@ -1,12 +1,10 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.lepidopterology; -import java.util.Locale; - import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleArea; import forestry.api.genetics.IAlleleBoolean; @@ -16,84 +14,85 @@ import forestry.api.genetics.IAlleleInteger; import forestry.api.genetics.IAlleleTolerance; import forestry.api.genetics.IChromosomeType; import forestry.api.genetics.ISpeciesRoot; +import java.util.Locale; public enum EnumButterflyChromosome implements IChromosomeType { - /** - * Species of the bee. Alleles here must implement {@link IAlleleButterflySpecies}. - */ - SPECIES(IAlleleButterflySpecies.class), - /** - * Physical size. - */ - SIZE(IAlleleFloat.class), - /** - * Flight speed. - */ - SPEED(IAlleleFloat.class), - /** - * How long the butterfly can last without access to matching pollinatables. - */ - LIFESPAN(IAlleleInteger.class), - /** - * Species with a higher metabolism have a higher appetite and may cause more damage to their environment. - */ - METABOLISM(IAlleleInteger.class), - /** - * Determines likelyhood of caterpillars and length of caterpillar/pupation phase. Also: Number of max caterpillars after mating? - */ - FERTILITY(IAlleleInteger.class), - /** - * Not sure yet. - */ - TEMPERATURE_TOLERANCE(IAlleleTolerance.class), - /** - * Not sure yet. - */ - HUMIDITY_TOLERANCE(IAlleleTolerance.class), - /** - * Only nocturnal butterflys/moths will fly at night. Allows daylight activity for naturally nocturnal species. - */ - NOCTURNAL(IAlleleBoolean.class), - /** - * Only tolerant flyers will fly in the rain. - */ - TOLERANT_FLYER(IAlleleBoolean.class), - /** - * Fire resistance. - */ - FIRE_RESIST(IAlleleBoolean.class), - /** - * Required flowers/leaves. - */ - FLOWER_PROVIDER(IAlleleFlowers.class), - /** - * Extra effect to surroundings. (?) - */ - EFFECT(IAlleleButterflyEffect.class), - /** - * Not used yet - */ - TERRITORY(IAlleleArea.class), - ; - - Class clss; - - EnumButterflyChromosome(Class clss) { - this.clss = clss; - } + /** + * Species of the bee. Alleles here must implement {@link IAlleleButterflySpecies}. + */ + SPECIES(IAlleleButterflySpecies.class), + /** + * Physical size. + */ + SIZE(IAlleleFloat.class), + /** + * Flight speed. + */ + SPEED(IAlleleFloat.class), + /** + * How long the butterfly can last without access to matching pollinatables. + */ + LIFESPAN(IAlleleInteger.class), + /** + * Species with a higher metabolism have a higher appetite and may cause more damage to their environment. + */ + METABOLISM(IAlleleInteger.class), + /** + * Determines likelyhood of caterpillars and length of caterpillar/pupation phase. Also: Number of max caterpillars after mating? + */ + FERTILITY(IAlleleInteger.class), + /** + * Not sure yet. + */ + TEMPERATURE_TOLERANCE(IAlleleTolerance.class), + /** + * Not sure yet. + */ + HUMIDITY_TOLERANCE(IAlleleTolerance.class), + /** + * Only nocturnal butterflys/moths will fly at night. Allows daylight activity for naturally nocturnal species. + */ + NOCTURNAL(IAlleleBoolean.class), + /** + * Only tolerant flyers will fly in the rain. + */ + TOLERANT_FLYER(IAlleleBoolean.class), + /** + * Fire resistance. + */ + FIRE_RESIST(IAlleleBoolean.class), + /** + * Required flowers/leaves. + */ + FLOWER_PROVIDER(IAlleleFlowers.class), + /** + * Extra effect to surroundings. (?) + */ + EFFECT(IAlleleButterflyEffect.class), + /** + * Not used yet + */ + TERRITORY(IAlleleArea.class), + ; - @Override - public Class getAlleleClass() { - return clss; - } + Class clss; - @Override - public String getName() { - return this.toString().toLowerCase(Locale.ENGLISH); - } + EnumButterflyChromosome(Class clss) { + this.clss = clss; + } - @Override - public ISpeciesRoot getSpeciesRoot() { - return ButterflyManager.butterflyRoot; - } + @Override + public Class getAlleleClass() { + return clss; + } + + @Override + public String getName() { + return this.toString().toLowerCase(Locale.ENGLISH); + } + + @Override + public ISpeciesRoot getSpeciesRoot() { + return ButterflyManager.butterflyRoot; + } } diff --git a/src/main/java/forestry/api/lepidopterology/EnumFlutterType.java b/src/main/java/forestry/api/lepidopterology/EnumFlutterType.java index d0c7aee60..e8e40b631 100644 --- a/src/main/java/forestry/api/lepidopterology/EnumFlutterType.java +++ b/src/main/java/forestry/api/lepidopterology/EnumFlutterType.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.lepidopterology; @@ -8,10 +8,10 @@ package forestry.api.lepidopterology; import forestry.api.genetics.ISpeciesType; public enum EnumFlutterType implements ISpeciesType { - BUTTERFLY, - SERUM, - CATERPILLAR, - NONE; - - public static final EnumFlutterType[] VALUES = values(); + BUTTERFLY, + SERUM, + CATERPILLAR, + NONE; + + public static final EnumFlutterType[] VALUES = values(); } diff --git a/src/main/java/forestry/api/lepidopterology/IAlleleButterflyEffect.java b/src/main/java/forestry/api/lepidopterology/IAlleleButterflyEffect.java index 6457dbe89..8617cf7b7 100644 --- a/src/main/java/forestry/api/lepidopterology/IAlleleButterflyEffect.java +++ b/src/main/java/forestry/api/lepidopterology/IAlleleButterflyEffect.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.lepidopterology; @@ -10,12 +10,11 @@ import forestry.api.genetics.IEffectData; public interface IAlleleButterflyEffect extends IAlleleEffect { - /** - * Used by butterflies to trigger effects in the world. - * @param butterfly {@link IEntityButterfly} - * @param storedData - * @return {@link forestry.api.genetics.IEffectData} for the next cycle. - */ - IEffectData doEffect(IEntityButterfly butterfly, IEffectData storedData); - + /** + * Used by butterflies to trigger effects in the world. + * @param butterfly {@link IEntityButterfly} + * @param storedData + * @return {@link forestry.api.genetics.IEffectData} for the next cycle. + */ + IEffectData doEffect(IEntityButterfly butterfly, IEffectData storedData); } diff --git a/src/main/java/forestry/api/lepidopterology/IAlleleButterflySpecies.java b/src/main/java/forestry/api/lepidopterology/IAlleleButterflySpecies.java index c1536118b..dfa2abd52 100644 --- a/src/main/java/forestry/api/lepidopterology/IAlleleButterflySpecies.java +++ b/src/main/java/forestry/api/lepidopterology/IAlleleButterflySpecies.java @@ -1,59 +1,56 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.lepidopterology; +import forestry.api.genetics.IAlleleSpecies; import java.util.EnumSet; import java.util.Map; - import net.minecraft.item.ItemStack; - import net.minecraftforge.common.BiomeDictionary; -import forestry.api.genetics.IAlleleSpecies; - public interface IAlleleButterflySpecies extends IAlleleSpecies { - - /** - * @return the IBeeRoot - */ - IButterflyRoot getRoot(); - /** - * @return Path of the texture to use for entity rendering. - */ - String getEntityTexture(); - - /** - * Allows butterflies to restrict random spawns beyond the restrictions set by getTemperature() and getHumidity(). - * - * @return EnumSet of biome tags this butterfly species can be spawned in. - */ - EnumSet getSpawnBiomes(); - - /** - * @return true if a prospective spawn biome must not match a biome tag outside of getSpawnBiomes. - */ - boolean strictSpawnMatch(); - - /** - * @return Float between 0 and 1 representing the rarity of the species, will affect spawn rate. - */ - float getRarity(); - - /** - * @return Float representing the distance below which this butterfly will take flight if it detects a player which is not sneaking. - */ - float getFlightDistance(); - - /** - * @return true if this species is only active at night. - */ - boolean isNocturnal(); - - Map getButterflyLoot(); - - Map getCaterpillarLoot(); + /** + * @return the IBeeRoot + */ + IButterflyRoot getRoot(); + + /** + * @return Path of the texture to use for entity rendering. + */ + String getEntityTexture(); + + /** + * Allows butterflies to restrict random spawns beyond the restrictions set by getTemperature() and getHumidity(). + * + * @return EnumSet of biome tags this butterfly species can be spawned in. + */ + EnumSet getSpawnBiomes(); + + /** + * @return true if a prospective spawn biome must not match a biome tag outside of getSpawnBiomes. + */ + boolean strictSpawnMatch(); + + /** + * @return Float between 0 and 1 representing the rarity of the species, will affect spawn rate. + */ + float getRarity(); + + /** + * @return Float representing the distance below which this butterfly will take flight if it detects a player which is not sneaking. + */ + float getFlightDistance(); + + /** + * @return true if this species is only active at night. + */ + boolean isNocturnal(); + + Map getButterflyLoot(); + + Map getCaterpillarLoot(); } diff --git a/src/main/java/forestry/api/lepidopterology/IAlleleButterflySpeciesCustom.java b/src/main/java/forestry/api/lepidopterology/IAlleleButterflySpeciesCustom.java index e89fd0fdd..9c1527197 100644 --- a/src/main/java/forestry/api/lepidopterology/IAlleleButterflySpeciesCustom.java +++ b/src/main/java/forestry/api/lepidopterology/IAlleleButterflySpeciesCustom.java @@ -13,7 +13,9 @@ package forestry.api.lepidopterology; import forestry.api.genetics.IAlleleSpeciesCustom; public interface IAlleleButterflySpeciesCustom extends IAlleleButterflySpecies, IAlleleSpeciesCustom { - IAlleleButterflySpeciesCustom setRarity(float rarity); - IAlleleButterflySpeciesCustom setFlightDistance(float flightDistance); - IAlleleButterflySpeciesCustom setNocturnal(); + IAlleleButterflySpeciesCustom setRarity(float rarity); + + IAlleleButterflySpeciesCustom setFlightDistance(float flightDistance); + + IAlleleButterflySpeciesCustom setNocturnal(); } diff --git a/src/main/java/forestry/api/lepidopterology/IButterfly.java b/src/main/java/forestry/api/lepidopterology/IButterfly.java index c30132475..cbb909c1a 100644 --- a/src/main/java/forestry/api/lepidopterology/IButterfly.java +++ b/src/main/java/forestry/api/lepidopterology/IButterfly.java @@ -1,77 +1,75 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.lepidopterology; +import forestry.api.genetics.IIndividualLiving; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import forestry.api.genetics.IIndividualLiving; - public interface IButterfly extends IIndividualLiving { - IButterflyGenome getGenome(); + IButterflyGenome getGenome(); - /** - * @return Genetic information of the mate, null if unmated. - */ - IButterflyGenome getMate(); + /** + * @return Genetic information of the mate, null if unmated. + */ + IButterflyGenome getMate(); - /** - * @return Physical size of the butterfly. - */ - float getSize(); - - /** - * @param world - * @param x - * @param y - * @param z - * @return true if the butterfly can naturally spawn at the given location at this time. (Used to auto-spawn butterflies from tree leaves.) - */ - boolean canSpawn(World world, double x, double y, double z); + /** + * @return Physical size of the butterfly. + */ + float getSize(); - /** - * @param world - * @param x - * @param y - * @param z - * @return true if the butterfly can take flight at the given location at this time. (Used to auto-spawn butterflies from dropped items.) - */ - boolean canTakeFlight(World world, double x, double y, double z); + /** + * @param world + * @param x + * @param y + * @param z + * @return true if the butterfly can naturally spawn at the given location at this time. (Used to auto-spawn butterflies from tree leaves.) + */ + boolean canSpawn(World world, double x, double y, double z); - /** - * @param world - * @param x - * @param y - * @param z - * @return true if the environment (temperature, humidity) is valid for the butterfly at the given location. - */ - boolean isAcceptedEnvironment(World world, double x, double y, double z); + /** + * @param world + * @param x + * @param y + * @param z + * @return true if the butterfly can take flight at the given location at this time. (Used to auto-spawn butterflies from dropped items.) + */ + boolean canTakeFlight(World world, double x, double y, double z); - IButterfly spawnCaterpillar(IButterflyNursery nursery); - - /** - * @param entity - * @param playerKill Whether or not the butterfly was killed by a player. - * @param lootLevel Loot level according to the weapon used to kill the butterfly. - * @return Array of itemstacks to drop on death of the given entity. - */ - ItemStack[] getLootDrop(IEntityButterfly entity, boolean playerKill, int lootLevel); + /** + * @param world + * @param x + * @param y + * @param z + * @return true if the environment (temperature, humidity) is valid for the butterfly at the given location. + */ + boolean isAcceptedEnvironment(World world, double x, double y, double z); - /** - * @param nursery - * @param playerKill Whether or not the nursery was broken by a player. - * @param lootLevel Fortune level. - * @return Array of itemstacks to drop on breaking of the nursery. - */ - ItemStack[] getCaterpillarDrop(IButterflyNursery nursery, boolean playerKill, int lootLevel); - - /** - * Create an exact copy of this butterfly. - */ - IButterfly copy(); + IButterfly spawnCaterpillar(IButterflyNursery nursery); + /** + * @param entity + * @param playerKill Whether or not the butterfly was killed by a player. + * @param lootLevel Loot level according to the weapon used to kill the butterfly. + * @return Array of itemstacks to drop on death of the given entity. + */ + ItemStack[] getLootDrop(IEntityButterfly entity, boolean playerKill, int lootLevel); + + /** + * @param nursery + * @param playerKill Whether or not the nursery was broken by a player. + * @param lootLevel Fortune level. + * @return Array of itemstacks to drop on breaking of the nursery. + */ + ItemStack[] getCaterpillarDrop(IButterflyNursery nursery, boolean playerKill, int lootLevel); + + /** + * Create an exact copy of this butterfly. + */ + IButterfly copy(); } diff --git a/src/main/java/forestry/api/lepidopterology/IButterflyFactory.java b/src/main/java/forestry/api/lepidopterology/IButterflyFactory.java index b66407ab1..2ed88623d 100644 --- a/src/main/java/forestry/api/lepidopterology/IButterflyFactory.java +++ b/src/main/java/forestry/api/lepidopterology/IButterflyFactory.java @@ -10,26 +10,34 @@ ******************************************************************************/ package forestry.api.lepidopterology; +import forestry.api.genetics.IClassification; import java.awt.Color; -import forestry.api.genetics.IClassification; - public interface IButterflyFactory { - /** - * Creates a new butterfly species. - * Automatically registered with AlleleManager.alleleRegistry.registerAllele() - * See IAlleleButterflySpeciesCustom and IAlleleSpeciesCustom for adding additional properties to the returned species. - * - * @param uid Unique Identifier for this species - * @param unlocalizedName Unlocalized name for this species - * @param authority Authority for the binomial name, e.g. "Sengir" on species of base Forestry. - * @param unlocalizedDescription Unlocalized description for this species - * @param texturePath String texture path for this butterfly e.g. "forestry:textures/entities/butterfly/..." - * @param dominant Whether this species is genetically dominant (false means it is recessive) - * @param branch Classification of this species - * @param binomial Binomial name of the species sans genus. "humboldti" will have the bee species flavour name be "Apis humboldti". Feel free to use fun names or null. - * @param serumColour The color of this butterfly's serum. - * @return a new butterfly species allele. - */ - IAlleleButterflySpeciesCustom createSpecies(String uid, String unlocalizedName, String authority, String unlocalizedDescription, String texturePath, boolean dominant, IClassification branch, String binomial, Color serumColour); + /** + * Creates a new butterfly species. + * Automatically registered with AlleleManager.alleleRegistry.registerAllele() + * See IAlleleButterflySpeciesCustom and IAlleleSpeciesCustom for adding additional properties to the returned species. + * + * @param uid Unique Identifier for this species + * @param unlocalizedName Unlocalized name for this species + * @param authority Authority for the binomial name, e.g. "Sengir" on species of base Forestry. + * @param unlocalizedDescription Unlocalized description for this species + * @param texturePath String texture path for this butterfly e.g. "forestry:textures/entities/butterfly/..." + * @param dominant Whether this species is genetically dominant (false means it is recessive) + * @param branch Classification of this species + * @param binomial Binomial name of the species sans genus. "humboldti" will have the bee species flavour name be "Apis humboldti". Feel free to use fun names or null. + * @param serumColour The color of this butterfly's serum. + * @return a new butterfly species allele. + */ + IAlleleButterflySpeciesCustom createSpecies( + String uid, + String unlocalizedName, + String authority, + String unlocalizedDescription, + String texturePath, + boolean dominant, + IClassification branch, + String binomial, + Color serumColour); } diff --git a/src/main/java/forestry/api/lepidopterology/IButterflyGenome.java b/src/main/java/forestry/api/lepidopterology/IButterflyGenome.java index 938166005..1964c763f 100644 --- a/src/main/java/forestry/api/lepidopterology/IButterflyGenome.java +++ b/src/main/java/forestry/api/lepidopterology/IButterflyGenome.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.lepidopterology; @@ -10,33 +10,32 @@ import forestry.api.genetics.IFlowerProvider; import forestry.api.genetics.IGenome; public interface IButterflyGenome extends IGenome { - - IAlleleButterflySpecies getPrimary(); - IAlleleButterflySpecies getSecondary(); + IAlleleButterflySpecies getPrimary(); - float getSize(); + IAlleleButterflySpecies getSecondary(); - int getLifespan(); + float getSize(); - int getMetabolism(); - - int getFertility(); + int getLifespan(); - float getSpeed(); + int getMetabolism(); - EnumTolerance getToleranceTemp(); + int getFertility(); - EnumTolerance getToleranceHumid(); + float getSpeed(); - boolean getNocturnal(); + EnumTolerance getToleranceTemp(); - boolean getTolerantFlyer(); + EnumTolerance getToleranceHumid(); - boolean getFireResist(); + boolean getNocturnal(); - IFlowerProvider getFlowerProvider(); + boolean getTolerantFlyer(); - IAlleleButterflyEffect getEffect(); + boolean getFireResist(); + IFlowerProvider getFlowerProvider(); + + IAlleleButterflyEffect getEffect(); } diff --git a/src/main/java/forestry/api/lepidopterology/IButterflyMutation.java b/src/main/java/forestry/api/lepidopterology/IButterflyMutation.java index 027e96eb2..413d21799 100644 --- a/src/main/java/forestry/api/lepidopterology/IButterflyMutation.java +++ b/src/main/java/forestry/api/lepidopterology/IButterflyMutation.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.lepidopterology; @@ -10,5 +10,5 @@ import forestry.api.genetics.IGenome; import forestry.api.genetics.IMutation; public interface IButterflyMutation extends IMutation { - float getChance(IButterflyNursery housing, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1); + float getChance(IButterflyNursery housing, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1); } diff --git a/src/main/java/forestry/api/lepidopterology/IButterflyNursery.java b/src/main/java/forestry/api/lepidopterology/IButterflyNursery.java index fd5bf64cb..f3c8f7ce6 100644 --- a/src/main/java/forestry/api/lepidopterology/IButterflyNursery.java +++ b/src/main/java/forestry/api/lepidopterology/IButterflyNursery.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.lepidopterology; @@ -10,13 +10,12 @@ import forestry.api.genetics.IHousing; import forestry.api.genetics.IIndividual; public interface IButterflyNursery extends IHousing, IClimateProvider { - - IButterfly getCaterpillar(); - - IIndividual getNanny(); - - void setCaterpillar(IButterfly butterfly); - - boolean canNurse(IButterfly butterfly); - + + IButterfly getCaterpillar(); + + IIndividual getNanny(); + + void setCaterpillar(IButterfly butterfly); + + boolean canNurse(IButterfly butterfly); } diff --git a/src/main/java/forestry/api/lepidopterology/IButterflyRoot.java b/src/main/java/forestry/api/lepidopterology/IButterflyRoot.java index 3afe30550..b597b7333 100644 --- a/src/main/java/forestry/api/lepidopterology/IButterflyRoot.java +++ b/src/main/java/forestry/api/lepidopterology/IButterflyRoot.java @@ -1,75 +1,71 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.lepidopterology; +import com.mojang.authlib.GameProfile; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.ISpeciesRoot; import java.util.ArrayList; import java.util.Collection; - import net.minecraft.entity.EntityLiving; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import com.mojang.authlib.GameProfile; - -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.ISpeciesRoot; - public interface IButterflyRoot extends ISpeciesRoot { - @Override - boolean isMember(ItemStack stack); + @Override + boolean isMember(ItemStack stack); - @Override - IButterfly getMember(ItemStack stack); + @Override + IButterfly getMember(ItemStack stack); - @Override - IButterfly getMember(NBTTagCompound compound); + @Override + IButterfly getMember(NBTTagCompound compound); - @Override - ItemStack getMemberStack(IIndividual butterfly, int type); + @Override + ItemStack getMemberStack(IIndividual butterfly, int type); - /* GENOME CONVERSION */ - @Override - IButterfly templateAsIndividual(IAllele[] template); + /* GENOME CONVERSION */ + @Override + IButterfly templateAsIndividual(IAllele[] template); - @Override - IButterfly templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive); + @Override + IButterfly templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive); - @Override - IButterflyGenome templateAsGenome(IAllele[] template); + @Override + IButterflyGenome templateAsGenome(IAllele[] template); - @Override - IButterflyGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive); + @Override + IButterflyGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive); - /* BUTTERFLY SPECIFIC */ - ILepidopteristTracker getBreedingTracker(World world, GameProfile player); + /* BUTTERFLY SPECIFIC */ + ILepidopteristTracker getBreedingTracker(World world, GameProfile player); - /** - * Spawns the given butterfly in the world. - * @param butterfly - * @return butterfly entity on success, null otherwise. - */ - EntityLiving spawnButterflyInWorld(World world, IButterfly butterfly, double x, double y, double z); + /** + * Spawns the given butterfly in the world. + * @param butterfly + * @return butterfly entity on success, null otherwise. + */ + EntityLiving spawnButterflyInWorld(World world, IButterfly butterfly, double x, double y, double z); - /** - * @return true if passed item is mated. - */ - boolean isMated(ItemStack stack); + /** + * @return true if passed item is mated. + */ + boolean isMated(ItemStack stack); - /* TEMPLATES */ - @Override - ArrayList getIndividualTemplates(); + /* TEMPLATES */ + @Override + ArrayList getIndividualTemplates(); - /* MUTATIONS */ - @Override - Collection getMutations(boolean shuffle); - - @Override - EnumFlutterType getType(ItemStack stack); + /* MUTATIONS */ + @Override + Collection getMutations(boolean shuffle); + @Override + EnumFlutterType getType(ItemStack stack); } diff --git a/src/main/java/forestry/api/lepidopterology/IEntityButterfly.java b/src/main/java/forestry/api/lepidopterology/IEntityButterfly.java index 963c72103..72906889a 100644 --- a/src/main/java/forestry/api/lepidopterology/IEntityButterfly.java +++ b/src/main/java/forestry/api/lepidopterology/IEntityButterfly.java @@ -1,29 +1,28 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.lepidopterology; +import forestry.api.genetics.IIndividual; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.passive.IAnimals; -import forestry.api.genetics.IIndividual; - public interface IEntityButterfly extends IAnimals { - void changeExhaustion(int change); + void changeExhaustion(int change); - int getExhaustion(); + int getExhaustion(); - IButterfly getButterfly(); + IButterfly getButterfly(); - /** - * @return The entity as an EntityCreature to save casting. - */ - EntityCreature getEntity(); + /** + * @return The entity as an EntityCreature to save casting. + */ + EntityCreature getEntity(); - IIndividual getPollen(); + IIndividual getPollen(); - void setPollen(IIndividual pollen); + void setPollen(IIndividual pollen); } diff --git a/src/main/java/forestry/api/lepidopterology/ILepidopteristTracker.java b/src/main/java/forestry/api/lepidopterology/ILepidopteristTracker.java index 79926975f..ca13e4d2c 100644 --- a/src/main/java/forestry/api/lepidopterology/ILepidopteristTracker.java +++ b/src/main/java/forestry/api/lepidopterology/ILepidopteristTracker.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.lepidopterology; @@ -9,6 +9,5 @@ import forestry.api.genetics.IBreedingTracker; public interface ILepidopteristTracker extends IBreedingTracker { - void registerCatch(IButterfly butterfly); - + void registerCatch(IButterfly butterfly); } diff --git a/src/main/java/forestry/api/lepidopterology/package-info.java b/src/main/java/forestry/api/lepidopterology/package-info.java index 369dbe62a..0ed8f86c5 100644 --- a/src/main/java/forestry/api/lepidopterology/package-info.java +++ b/src/main/java/forestry/api/lepidopterology/package-info.java @@ -1,8 +1,9 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ -@API(apiVersion="1.3.0", owner="ForestryAPI|core", provides="ForestryAPI|lepidopterology") +@API(apiVersion = "1.3.0", owner = "ForestryAPI|core", provides = "ForestryAPI|lepidopterology") package forestry.api.lepidopterology; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/api/mail/EnumAddressee.java b/src/main/java/forestry/api/mail/EnumAddressee.java index 28c738473..630362da7 100644 --- a/src/main/java/forestry/api/mail/EnumAddressee.java +++ b/src/main/java/forestry/api/mail/EnumAddressee.java @@ -8,19 +8,19 @@ package forestry.api.mail; import java.util.Locale; public enum EnumAddressee { - PLAYER, TRADER; - - public static EnumAddressee fromString(String ident) { - ident = ident.toLowerCase(Locale.ENGLISH); - for(EnumAddressee addr : values()) { - if(addr.toString().equals(ident)) - return addr; - } - - return null; - } + PLAYER, + TRADER; - public String toString() { - return super.toString().toLowerCase(Locale.ENGLISH); - } + public static EnumAddressee fromString(String ident) { + ident = ident.toLowerCase(Locale.ENGLISH); + for (EnumAddressee addr : values()) { + if (addr.toString().equals(ident)) return addr; + } + + return null; + } + + public String toString() { + return super.toString().toLowerCase(Locale.ENGLISH); + } } diff --git a/src/main/java/forestry/api/mail/EnumPostage.java b/src/main/java/forestry/api/mail/EnumPostage.java index 772114fb0..385053bc6 100644 --- a/src/main/java/forestry/api/mail/EnumPostage.java +++ b/src/main/java/forestry/api/mail/EnumPostage.java @@ -1,20 +1,28 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.mail; public enum EnumPostage { - P_0(0), P_1(1), P_2(2), P_5(5), P_10(10), P_20(20), P_50(50), P_100(100), P_200(200); + P_0(0), + P_1(1), + P_2(2), + P_5(5), + P_10(10), + P_20(20), + P_50(50), + P_100(100), + P_200(200); - private final int value; + private final int value; - private EnumPostage(int value) { - this.value = value; - } + private EnumPostage(int value) { + this.value = value; + } - public int getValue() { - return this.value; - } + public int getValue() { + return this.value; + } } diff --git a/src/main/java/forestry/api/mail/ILetter.java b/src/main/java/forestry/api/mail/ILetter.java index 42df8acb5..f53932dbc 100644 --- a/src/main/java/forestry/api/mail/ILetter.java +++ b/src/main/java/forestry/api/mail/ILetter.java @@ -1,59 +1,56 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.mail; +import forestry.api.core.INBTTagable; import java.util.List; - import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import forestry.api.core.INBTTagable; - public interface ILetter extends IInventory, INBTTagable { - ItemStack[] getPostage(); + ItemStack[] getPostage(); - void setProcessed(boolean flag); + void setProcessed(boolean flag); - boolean isProcessed(); + boolean isProcessed(); - boolean isMailable(); + boolean isMailable(); - void setSender(IMailAddress address); + void setSender(IMailAddress address); - IMailAddress getSender(); + IMailAddress getSender(); - boolean hasRecipient(); + boolean hasRecipient(); - void setRecipient(IMailAddress address); + void setRecipient(IMailAddress address); - IMailAddress[] getRecipients(); + IMailAddress[] getRecipients(); - String getRecipientString(); + String getRecipientString(); - void setText(String text); + void setText(String text); - String getText(); + String getText(); - void addTooltip(List list); + void addTooltip(List list); - boolean isPostPaid(); + boolean isPostPaid(); - int requiredPostage(); + int requiredPostage(); - void invalidatePostage(); + void invalidatePostage(); - ItemStack[] getAttachments(); + ItemStack[] getAttachments(); - void addAttachment(ItemStack itemstack); + void addAttachment(ItemStack itemstack); - void addAttachments(ItemStack[] itemstacks); + void addAttachments(ItemStack[] itemstacks); - int countAttachments(); - - void addStamps(ItemStack stamps); + int countAttachments(); + void addStamps(ItemStack stamps); } diff --git a/src/main/java/forestry/api/mail/ILetterHandler.java b/src/main/java/forestry/api/mail/ILetterHandler.java index 576a0d7da..1df3db80a 100644 --- a/src/main/java/forestry/api/mail/ILetterHandler.java +++ b/src/main/java/forestry/api/mail/ILetterHandler.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.mail; @@ -9,5 +9,5 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.World; public interface ILetterHandler { - IPostalState handleLetter(World world, IMailAddress recipient, ItemStack letterStack, boolean doLodge); + IPostalState handleLetter(World world, IMailAddress recipient, ItemStack letterStack, boolean doLodge); } diff --git a/src/main/java/forestry/api/mail/IMailAddress.java b/src/main/java/forestry/api/mail/IMailAddress.java index 8441b09a4..e86d2a54b 100644 --- a/src/main/java/forestry/api/mail/IMailAddress.java +++ b/src/main/java/forestry/api/mail/IMailAddress.java @@ -6,18 +6,19 @@ package forestry.api.mail; import com.mojang.authlib.GameProfile; - import forestry.api.core.INBTTagable; public interface IMailAddress extends INBTTagable { - EnumAddressee getType(); - String getName(); + EnumAddressee getType(); - boolean isValid(); + String getName(); - boolean isPlayer(); - boolean isTrader(); + boolean isValid(); - GameProfile getPlayerProfile(); + boolean isPlayer(); + + boolean isTrader(); + + GameProfile getPlayerProfile(); } diff --git a/src/main/java/forestry/api/mail/IPostOffice.java b/src/main/java/forestry/api/mail/IPostOffice.java index a8a14eac1..10af3eb0b 100644 --- a/src/main/java/forestry/api/mail/IPostOffice.java +++ b/src/main/java/forestry/api/mail/IPostOffice.java @@ -1,30 +1,29 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.mail; import java.util.Map; - import net.minecraft.item.ItemStack; import net.minecraft.world.World; public interface IPostOffice { - void collectPostage(ItemStack[] stamps); + void collectPostage(ItemStack[] stamps); - IPostalState lodgeLetter(World world, ItemStack itemstack, boolean doLodge); + IPostalState lodgeLetter(World world, ItemStack itemstack, boolean doLodge); - ItemStack getAnyStamp(int max); + ItemStack getAnyStamp(int max); - ItemStack getAnyStamp(EnumPostage postage, int max); + ItemStack getAnyStamp(EnumPostage postage, int max); - ItemStack getAnyStamp(EnumPostage[] postages, int max); + ItemStack getAnyStamp(EnumPostage[] postages, int max); - void registerTradeStation(ITradeStation trade); + void registerTradeStation(ITradeStation trade); - void deregisterTradeStation(ITradeStation trade); + void deregisterTradeStation(ITradeStation trade); - Map getActiveTradeStations(World world); + Map getActiveTradeStations(World world); } diff --git a/src/main/java/forestry/api/mail/IPostRegistry.java b/src/main/java/forestry/api/mail/IPostRegistry.java index f20352d93..648c4c972 100644 --- a/src/main/java/forestry/api/mail/IPostRegistry.java +++ b/src/main/java/forestry/api/mail/IPostRegistry.java @@ -1,58 +1,56 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.mail; +import com.mojang.authlib.GameProfile; import java.util.Map; - import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import com.mojang.authlib.GameProfile; - public interface IPostRegistry { - /* POST OFFICE */ - IPostOffice getPostOffice(World world); + /* POST OFFICE */ + IPostOffice getPostOffice(World world); - /* MAIL ADDRESSES */ - IMailAddress getMailAddress(GameProfile gameProfile); - IMailAddress getMailAddress(String traderName); + /* MAIL ADDRESSES */ + IMailAddress getMailAddress(GameProfile gameProfile); - /* LETTERS */ - boolean isLetter(ItemStack itemstack); + IMailAddress getMailAddress(String traderName); - ILetter createLetter(IMailAddress sender, IMailAddress recipient); + /* LETTERS */ + boolean isLetter(ItemStack itemstack); - ILetter getLetter(ItemStack itemstack); + ILetter createLetter(IMailAddress sender, IMailAddress recipient); - ItemStack createLetterStack(ILetter letter); + ILetter getLetter(ItemStack itemstack); - /* CARRIERS */ - /** - * Registers a new {@link IPostalCarrier}. See {@link IPostalCarrier} for details. - * @param carrier {@link IPostalCarrier} to register. - */ - void registerCarrier(IPostalCarrier carrier); + ItemStack createLetterStack(ILetter letter); - IPostalCarrier getCarrier(EnumAddressee uid); + /* CARRIERS */ + /** + * Registers a new {@link IPostalCarrier}. See {@link IPostalCarrier} for details. + * @param carrier {@link IPostalCarrier} to register. + */ + void registerCarrier(IPostalCarrier carrier); - Map getRegisteredCarriers(); + IPostalCarrier getCarrier(EnumAddressee uid); - /* TRADE STATIONS */ - void deleteTradeStation(World world, IMailAddress address); + Map getRegisteredCarriers(); - ITradeStation getOrCreateTradeStation(World world, GameProfile owner, IMailAddress address); + /* TRADE STATIONS */ + void deleteTradeStation(World world, IMailAddress address); - ITradeStation getTradeStation(World world, IMailAddress address); + ITradeStation getOrCreateTradeStation(World world, GameProfile owner, IMailAddress address); - boolean isAvailableTradeAddress(World world, IMailAddress address); + ITradeStation getTradeStation(World world, IMailAddress address); - boolean isValidTradeAddress(World world, IMailAddress address); + boolean isAvailableTradeAddress(World world, IMailAddress address); - /* PO BOXES */ - boolean isValidPOBox(World world, IMailAddress address); + boolean isValidTradeAddress(World world, IMailAddress address); + /* PO BOXES */ + boolean isValidPOBox(World world, IMailAddress address); } diff --git a/src/main/java/forestry/api/mail/IPostalCarrier.java b/src/main/java/forestry/api/mail/IPostalCarrier.java index 28db78ae8..8afe2680b 100644 --- a/src/main/java/forestry/api/mail/IPostalCarrier.java +++ b/src/main/java/forestry/api/mail/IPostalCarrier.java @@ -1,48 +1,47 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.mail; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - /** * Postal Carriers are systems which can be hooked into Forestry's mail system to handle mail delivery. - * + * * The two available carriers in vanilla Forestry are * "player" - Delivers mail to individual players. * "trader" - Handles mail addressed to trade stations. */ public interface IPostalCarrier { - /** - * @return An EnumAddressee identifying the type of carrier - */ - EnumAddressee getType(); + /** + * @return An EnumAddressee identifying the type of carrier + */ + EnumAddressee getType(); - /** - * @return A human-readable name for this carrier. - */ - String getName(); + /** + * @return A human-readable name for this carrier. + */ + String getName(); - @SideOnly(Side.CLIENT) - IIcon getIcon(); - - /** - * Handle delivery of a letter addressed to this carrier. - * @param world The world the {@link IPostOffice} handles. - * @param office {link @IPostOffice} which received this letter and handed it to the carrier. - * @param recipient An identifier for the recipient as typed by the player into the address field. - * @param letterstack ItemStack representing the letter. See {@link IPostRegistry} for helper functions to validate and extract it. - * @param doDeliver Whether or not the letter is supposed to actually be delivered or if delivery is only to be simulated. - * @return {link IPostalState} holding information on success or failure for delivery. - */ - IPostalState deliverLetter(World world, IPostOffice office, IMailAddress recipient, ItemStack letterstack, boolean doDeliver); + @SideOnly(Side.CLIENT) + IIcon getIcon(); + /** + * Handle delivery of a letter addressed to this carrier. + * @param world The world the {@link IPostOffice} handles. + * @param office {link @IPostOffice} which received this letter and handed it to the carrier. + * @param recipient An identifier for the recipient as typed by the player into the address field. + * @param letterstack ItemStack representing the letter. See {@link IPostRegistry} for helper functions to validate and extract it. + * @param doDeliver Whether or not the letter is supposed to actually be delivered or if delivery is only to be simulated. + * @return {link IPostalState} holding information on success or failure for delivery. + */ + IPostalState deliverLetter( + World world, IPostOffice office, IMailAddress recipient, ItemStack letterstack, boolean doDeliver); } diff --git a/src/main/java/forestry/api/mail/IPostalState.java b/src/main/java/forestry/api/mail/IPostalState.java index bc843621a..97fe77d61 100644 --- a/src/main/java/forestry/api/mail/IPostalState.java +++ b/src/main/java/forestry/api/mail/IPostalState.java @@ -1,14 +1,14 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.mail; public interface IPostalState { - boolean isOk(); + boolean isOk(); - String getIdentifier(); - - int ordinal(); + String getIdentifier(); + + int ordinal(); } diff --git a/src/main/java/forestry/api/mail/IStamps.java b/src/main/java/forestry/api/mail/IStamps.java index 4332a811c..ba94ca679 100644 --- a/src/main/java/forestry/api/mail/IStamps.java +++ b/src/main/java/forestry/api/mail/IStamps.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.mail; @@ -9,6 +9,5 @@ import net.minecraft.item.ItemStack; public interface IStamps { - EnumPostage getPostage(ItemStack itemstack); - + EnumPostage getPostage(ItemStack itemstack); } diff --git a/src/main/java/forestry/api/mail/ITradeStation.java b/src/main/java/forestry/api/mail/ITradeStation.java index 78a498a04..de95f9dca 100644 --- a/src/main/java/forestry/api/mail/ITradeStation.java +++ b/src/main/java/forestry/api/mail/ITradeStation.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.mail; @@ -9,16 +9,15 @@ import net.minecraft.inventory.IInventory; public interface ITradeStation extends ILetterHandler, IInventory { - IMailAddress getAddress(); + IMailAddress getAddress(); - boolean isValid(); + boolean isValid(); - void invalidate(); + void invalidate(); - void setVirtual(boolean isVirtual); + void setVirtual(boolean isVirtual); - boolean isVirtual(); - - TradeStationInfo getTradeInfo(); + boolean isVirtual(); + TradeStationInfo getTradeInfo(); } diff --git a/src/main/java/forestry/api/mail/PostManager.java b/src/main/java/forestry/api/mail/PostManager.java index c3f0e45bb..98bd34375 100644 --- a/src/main/java/forestry/api/mail/PostManager.java +++ b/src/main/java/forestry/api/mail/PostManager.java @@ -1,11 +1,10 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.mail; - public class PostManager { - public static IPostRegistry postRegistry; + public static IPostRegistry postRegistry; } diff --git a/src/main/java/forestry/api/mail/TradeStationInfo.java b/src/main/java/forestry/api/mail/TradeStationInfo.java index 14424bedf..e37dc8474 100644 --- a/src/main/java/forestry/api/mail/TradeStationInfo.java +++ b/src/main/java/forestry/api/mail/TradeStationInfo.java @@ -1,29 +1,29 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.mail; -import java.lang.IllegalArgumentException; -import net.minecraft.item.ItemStack; import com.mojang.authlib.GameProfile; +import net.minecraft.item.ItemStack; public class TradeStationInfo { - public final IMailAddress address; - public final GameProfile owner; - public final ItemStack tradegood; - public final ItemStack[] required; - public final IPostalState state; + public final IMailAddress address; + public final GameProfile owner; + public final ItemStack tradegood; + public final ItemStack[] required; + public final IPostalState state; - public TradeStationInfo(IMailAddress address, GameProfile owner, ItemStack tradegood, ItemStack[] required, IPostalState state) { + public TradeStationInfo( + IMailAddress address, GameProfile owner, ItemStack tradegood, ItemStack[] required, IPostalState state) { if (!address.isTrader()) { throw new IllegalArgumentException("TradeStation address must be a trader"); } - this.address = address; - this.owner = owner; - this.tradegood = tradegood; - this.required = required; - this.state = state; - } + this.address = address; + this.owner = owner; + this.tradegood = tradegood; + this.required = required; + this.state = state; + } } diff --git a/src/main/java/forestry/api/mail/package-info.java b/src/main/java/forestry/api/mail/package-info.java index a10507276..926c024df 100644 --- a/src/main/java/forestry/api/mail/package-info.java +++ b/src/main/java/forestry/api/mail/package-info.java @@ -1,8 +1,9 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ -@API(apiVersion="3.0.0", owner="ForestryAPI|core", provides="ForestryAPI|mail") +@API(apiVersion = "3.0.0", owner = "ForestryAPI|core", provides = "ForestryAPI|mail") package forestry.api.mail; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/api/multiblock/IAlvearyComponent.java b/src/main/java/forestry/api/multiblock/IAlvearyComponent.java index fd1e487a8..1d52f25f9 100644 --- a/src/main/java/forestry/api/multiblock/IAlvearyComponent.java +++ b/src/main/java/forestry/api/multiblock/IAlvearyComponent.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.multiblock; @@ -15,43 +15,43 @@ import forestry.api.core.IClimateControlled; * They are automatically detected and handled by the alveary when they join its structure. */ public interface IAlvearyComponent extends IMultiblockComponent { - /** - * @return the multiblock logic for this component - */ - T getMultiblockLogic(); + /** + * @return the multiblock logic for this component + */ + T getMultiblockLogic(); - /** - * Implemented by alveary parts to apply a beeListener to the completed structure. - */ - interface BeeListener extends IAlvearyComponent { - IBeeListener getBeeListener(); - } + /** + * Implemented by alveary parts to apply a beeListener to the completed structure. + */ + interface BeeListener extends IAlvearyComponent { + IBeeListener getBeeListener(); + } - /** - * Implemented by alveary parts to apply a beeModifier to the completed structure. - */ - interface BeeModifier extends IAlvearyComponent { - IBeeModifier getBeeModifier(); - } + /** + * Implemented by alveary parts to apply a beeModifier to the completed structure. + */ + interface BeeModifier extends IAlvearyComponent { + IBeeModifier getBeeModifier(); + } - /** - * Implemented by alveary parts to apply a climate change to the completed structure. - */ - interface Climatiser extends IAlvearyComponent { - /** - * Called every tick by the alveary. - * @param tickCount the number of ticks in the world - * @param alveary the climate controlled alveary - */ - void changeClimate(int tickCount, IClimateControlled alveary); - } + /** + * Implemented by alveary parts to apply a climate change to the completed structure. + */ + interface Climatiser extends IAlvearyComponent { + /** + * Called every tick by the alveary. + * @param tickCount the number of ticks in the world + * @param alveary the climate controlled alveary + */ + void changeClimate(int tickCount, IClimateControlled alveary); + } - /** - * Implemented by alveary parts to receive ticks from the completed structure. - */ - interface Active extends IAlvearyComponent { - void updateServer(int tickCount); - void updateClient(int tickCount); - } + /** + * Implemented by alveary parts to receive ticks from the completed structure. + */ + interface Active extends IAlvearyComponent { + void updateServer(int tickCount); + void updateClient(int tickCount); + } } diff --git a/src/main/java/forestry/api/multiblock/IAlvearyController.java b/src/main/java/forestry/api/multiblock/IAlvearyController.java index 9645fc794..cb24ca218 100644 --- a/src/main/java/forestry/api/multiblock/IAlvearyController.java +++ b/src/main/java/forestry/api/multiblock/IAlvearyController.java @@ -11,6 +11,4 @@ import forestry.api.apiculture.IBeeHousing; * The IAlvearyController provides access to all the IMultiblockController and IBeeHousing methods * necessary for an IAlvearyComponent to function. */ -public interface IAlvearyController extends IMultiblockController, IBeeHousing { - -} +public interface IAlvearyController extends IMultiblockController, IBeeHousing {} diff --git a/src/main/java/forestry/api/multiblock/IFarmComponent.java b/src/main/java/forestry/api/multiblock/IFarmComponent.java index 5858d2d78..890ac13d9 100644 --- a/src/main/java/forestry/api/multiblock/IFarmComponent.java +++ b/src/main/java/forestry/api/multiblock/IFarmComponent.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.multiblock; @@ -14,23 +14,24 @@ import forestry.api.farming.IFarmListener; */ public interface IFarmComponent extends IMultiblockComponent { - /** - * @return the multiblock logic for this component - */ - T getMultiblockLogic(); + /** + * @return the multiblock logic for this component + */ + T getMultiblockLogic(); - /** - * Implemented by farm parts to apply a farmListener to the completed structure. - */ - interface Listener extends IFarmComponent { - IFarmListener getFarmListener(); - } + /** + * Implemented by farm parts to apply a farmListener to the completed structure. + */ + interface Listener extends IFarmComponent { + IFarmListener getFarmListener(); + } - /** - * Implemented by farm parts to receive ticks from the completed structure. - */ - interface Active extends IFarmComponent { - void updateServer(int tickCount); - void updateClient(int tickCount); - } + /** + * Implemented by farm parts to receive ticks from the completed structure. + */ + interface Active extends IFarmComponent { + void updateServer(int tickCount); + + void updateClient(int tickCount); + } } diff --git a/src/main/java/forestry/api/multiblock/IFarmController.java b/src/main/java/forestry/api/multiblock/IFarmController.java index 7629a0e80..0e6872418 100644 --- a/src/main/java/forestry/api/multiblock/IFarmController.java +++ b/src/main/java/forestry/api/multiblock/IFarmController.java @@ -11,6 +11,4 @@ import forestry.api.farming.IFarmHousing; * The IFarmController provides access to all the IMultiblockController and IFarmHousing methods * necessary for an IFarmComponent to function. */ -public interface IFarmController extends IMultiblockController, IFarmHousing { - -} +public interface IFarmController extends IMultiblockController, IFarmHousing {} diff --git a/src/main/java/forestry/api/multiblock/IMultiblockComponent.java b/src/main/java/forestry/api/multiblock/IMultiblockComponent.java index 7882d38ce..6bb0d918d 100644 --- a/src/main/java/forestry/api/multiblock/IMultiblockComponent.java +++ b/src/main/java/forestry/api/multiblock/IMultiblockComponent.java @@ -5,44 +5,44 @@ ******************************************************************************/ package forestry.api.multiblock; -import net.minecraft.util.ChunkCoordinates; - import com.mojang.authlib.GameProfile; +import net.minecraft.util.ChunkCoordinates; /** * Basic interface for a multiblock machine component. * Implemented by TileEntities. */ public interface IMultiblockComponent { - - /** - * Returns the location of this tile entity in the world. - * @return ChunkCoordinates set to the location of this tile entity in the world. - */ - ChunkCoordinates getCoordinates(); - /** - * @return the gameProfile of the player who owns this single component (not the entire multiblock) - */ - GameProfile getOwner(); + /** + * Returns the location of this tile entity in the world. + * @return ChunkCoordinates set to the location of this tile entity in the world. + */ + ChunkCoordinates getCoordinates(); - /** - * @return the multiblock logic for this part - */ - IMultiblockLogic getMultiblockLogic(); + /** + * @return the gameProfile of the player who owns this single component (not the entire multiblock) + */ + GameProfile getOwner(); - /** - * Called when a machine is fully assembled from the disassembled state, meaning - * it was constructed by a player/entity action, not by chunks loading. - * Note that, for non-square machines, the min/max coordinates may not actually be part - * of the machine! They form an outer bounding box for the whole machine itself. - * @param multiblockController The controller to which this part is being assembled. - */ - void onMachineAssembled(IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord); + /** + * @return the multiblock logic for this part + */ + IMultiblockLogic getMultiblockLogic(); - /** - * Called when the machine is broken for game reasons, e.g. a player removed a block - * or an explosion occurred. - */ - void onMachineBroken(); + /** + * Called when a machine is fully assembled from the disassembled state, meaning + * it was constructed by a player/entity action, not by chunks loading. + * Note that, for non-square machines, the min/max coordinates may not actually be part + * of the machine! They form an outer bounding box for the whole machine itself. + * @param multiblockController The controller to which this part is being assembled. + */ + void onMachineAssembled( + IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord); + + /** + * Called when the machine is broken for game reasons, e.g. a player removed a block + * or an explosion occurred. + */ + void onMachineBroken(); } diff --git a/src/main/java/forestry/api/multiblock/IMultiblockController.java b/src/main/java/forestry/api/multiblock/IMultiblockController.java index f9e86bdd8..07b104e32 100644 --- a/src/main/java/forestry/api/multiblock/IMultiblockController.java +++ b/src/main/java/forestry/api/multiblock/IMultiblockController.java @@ -5,8 +5,8 @@ ******************************************************************************/ package forestry.api.multiblock; -import javax.annotation.Nonnull; import java.util.Collection; +import javax.annotation.Nonnull; /** * IMultiblockController is used to handle the assembly of Multiblocks. @@ -14,28 +14,28 @@ import java.util.Collection; * This is a minimal interface to hide the ugly details from the multiblock tile entities. */ public interface IMultiblockController { - /** - * @return True if this multiblock machine is considered assembled and ready to go. - */ - boolean isAssembled(); + /** + * @return True if this multiblock machine is considered assembled and ready to go. + */ + boolean isAssembled(); - /** - * Call to force the controller to check the multiblock's validity. - * Use when important conditions around the multiblock change - * (i.e. Alveary slabs are removed and the alveary block detects it's neighbor changed) - * Changes to multiblock components are handled automatically and should not call this. - */ - void reassemble(); + /** + * Call to force the controller to check the multiblock's validity. + * Use when important conditions around the multiblock change + * (i.e. Alveary slabs are removed and the alveary block detects it's neighbor changed) + * Changes to multiblock components are handled automatically and should not call this. + */ + void reassemble(); - /** - * @return A string representing the last error encountered when trying to assemble this - * multiblock, or null if there is no error. - */ - String getLastValidationError(); + /** + * @return A string representing the last error encountered when trying to assemble this + * multiblock, or null if there is no error. + */ + String getLastValidationError(); - /** - * @return all the multiblock components attached to this controller - */ - @Nonnull - Collection getComponents(); + /** + * @return all the multiblock components attached to this controller + */ + @Nonnull + Collection getComponents(); } diff --git a/src/main/java/forestry/api/multiblock/IMultiblockLogic.java b/src/main/java/forestry/api/multiblock/IMultiblockLogic.java index cd1f4c531..5183b983f 100644 --- a/src/main/java/forestry/api/multiblock/IMultiblockLogic.java +++ b/src/main/java/forestry/api/multiblock/IMultiblockLogic.java @@ -5,11 +5,10 @@ ******************************************************************************/ package forestry.api.multiblock; +import forestry.api.core.INBTTagable; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import forestry.api.core.INBTTagable; - /** * Multiblock Logic implements the basic logic for IMultiblockComponent tile entities. * Instances must come from MultiblockManager.logicFactory, most of the implementation is hidden. @@ -19,56 +18,56 @@ import forestry.api.core.INBTTagable; */ public interface IMultiblockLogic extends INBTTagable { - /** - * @return True if this block is connected to a multiblock controller. False otherwise. - */ - boolean isConnected(); + /** + * @return True if this block is connected to a multiblock controller. False otherwise. + */ + boolean isConnected(); - /** - * @return the multiblock controller for this logic - */ - IMultiblockController getController(); + /** + * @return the multiblock controller for this logic + */ + IMultiblockController getController(); - /* Updating and Synchronization */ + /* Updating and Synchronization */ - /** - * call on Tile.validate() - **/ - void validate(World world, IMultiblockComponent part); + /** + * call on Tile.validate() + **/ + void validate(World world, IMultiblockComponent part); - /** - * call on Tile.invalidate() - **/ - void invalidate(World world, IMultiblockComponent part); + /** + * call on Tile.invalidate() + **/ + void invalidate(World world, IMultiblockComponent part); - /** - * call on Tile.onChunkUnload() - **/ - void onChunkUnload(World world, IMultiblockComponent part); + /** + * call on Tile.onChunkUnload() + **/ + void onChunkUnload(World world, IMultiblockComponent part); - /** - * Writes data for client synchronization. - * Use this in Tile.getDescriptionPacket() - */ - void encodeDescriptionPacket(NBTTagCompound packetData); + /** + * Writes data for client synchronization. + * Use this in Tile.getDescriptionPacket() + */ + void encodeDescriptionPacket(NBTTagCompound packetData); - /** - * Reads data for client synchronization. - * Use this in Tile.onDataPacket() - */ - void decodeDescriptionPacket(NBTTagCompound packetData); + /** + * Reads data for client synchronization. + * Use this in Tile.onDataPacket() + */ + void decodeDescriptionPacket(NBTTagCompound packetData); - /** - * Read the logic's data from file. - * Use this in Tile.readFromNBT() - */ - @Override - void readFromNBT(NBTTagCompound nbttagcompound); + /** + * Read the logic's data from file. + * Use this in Tile.readFromNBT() + */ + @Override + void readFromNBT(NBTTagCompound nbttagcompound); - /** - * Write the logic's data to file. - * Use this in Tile.writeToNBT() - */ - @Override - void writeToNBT(NBTTagCompound nbttagcompound); + /** + * Write the logic's data to file. + * Use this in Tile.writeToNBT() + */ + @Override + void writeToNBT(NBTTagCompound nbttagcompound); } diff --git a/src/main/java/forestry/api/multiblock/IMultiblockLogicAlveary.java b/src/main/java/forestry/api/multiblock/IMultiblockLogicAlveary.java index 611f3c803..1af46e819 100644 --- a/src/main/java/forestry/api/multiblock/IMultiblockLogicAlveary.java +++ b/src/main/java/forestry/api/multiblock/IMultiblockLogicAlveary.java @@ -6,9 +6,9 @@ package forestry.api.multiblock; public interface IMultiblockLogicAlveary extends IMultiblockLogic { - /** - * @return the multiblock controller for this logic - */ - @Override - IAlvearyController getController(); + /** + * @return the multiblock controller for this logic + */ + @Override + IAlvearyController getController(); } diff --git a/src/main/java/forestry/api/multiblock/IMultiblockLogicFactory.java b/src/main/java/forestry/api/multiblock/IMultiblockLogicFactory.java index 50eb52a13..4ceabb54b 100644 --- a/src/main/java/forestry/api/multiblock/IMultiblockLogicFactory.java +++ b/src/main/java/forestry/api/multiblock/IMultiblockLogicFactory.java @@ -10,7 +10,7 @@ package forestry.api.multiblock; * Each IMultiblockComponent needs its own instance of IMultiblockLogic. */ public interface IMultiblockLogicFactory { - IMultiblockLogicAlveary createAlvearyLogic(); + IMultiblockLogicAlveary createAlvearyLogic(); - IMultiblockLogicFarm createFarmLogic(); + IMultiblockLogicFarm createFarmLogic(); } diff --git a/src/main/java/forestry/api/multiblock/IMultiblockLogicFarm.java b/src/main/java/forestry/api/multiblock/IMultiblockLogicFarm.java index 78f599ce6..e32661e2a 100644 --- a/src/main/java/forestry/api/multiblock/IMultiblockLogicFarm.java +++ b/src/main/java/forestry/api/multiblock/IMultiblockLogicFarm.java @@ -6,9 +6,9 @@ package forestry.api.multiblock; public interface IMultiblockLogicFarm extends IMultiblockLogic { - /** - * @return the multiblock controller for this logic - */ - @Override - IFarmController getController(); + /** + * @return the multiblock controller for this logic + */ + @Override + IFarmController getController(); } diff --git a/src/main/java/forestry/api/multiblock/MultiblockManager.java b/src/main/java/forestry/api/multiblock/MultiblockManager.java index c75b03f1b..9b0017ee9 100644 --- a/src/main/java/forestry/api/multiblock/MultiblockManager.java +++ b/src/main/java/forestry/api/multiblock/MultiblockManager.java @@ -6,5 +6,5 @@ package forestry.api.multiblock; public class MultiblockManager { - public static IMultiblockLogicFactory logicFactory; + public static IMultiblockLogicFactory logicFactory; } diff --git a/src/main/java/forestry/api/multiblock/MultiblockTileEntityBase.java b/src/main/java/forestry/api/multiblock/MultiblockTileEntityBase.java index 7f5efc0c1..99373542b 100644 --- a/src/main/java/forestry/api/multiblock/MultiblockTileEntityBase.java +++ b/src/main/java/forestry/api/multiblock/MultiblockTileEntityBase.java @@ -17,98 +17,96 @@ import net.minecraft.util.ChunkCoordinates; * Most multiblock components should derive from this. * Supply it an IMultiblockLogic from MultiblockManager.logicFactory */ -public abstract class MultiblockTileEntityBase extends TileEntity implements IMultiblockComponent { - private final T multiblockLogic; +public abstract class MultiblockTileEntityBase extends TileEntity + implements IMultiblockComponent { + private final T multiblockLogic; - public MultiblockTileEntityBase(T multiblockLogic) { - this.multiblockLogic = multiblockLogic; - } + public MultiblockTileEntityBase(T multiblockLogic) { + this.multiblockLogic = multiblockLogic; + } - @Override - public ChunkCoordinates getCoordinates() { - return new ChunkCoordinates(this.xCoord, this.yCoord, this.zCoord); - } + @Override + public ChunkCoordinates getCoordinates() { + return new ChunkCoordinates(this.xCoord, this.yCoord, this.zCoord); + } - @Override - public T getMultiblockLogic() { - return multiblockLogic; - } + @Override + public T getMultiblockLogic() { + return multiblockLogic; + } - @Override - public abstract void onMachineAssembled(IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord); + @Override + public abstract void onMachineAssembled( + IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord); - @Override - public abstract void onMachineBroken(); + @Override + public abstract void onMachineBroken(); - @Override - public void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - multiblockLogic.readFromNBT(data); - } - - @Override - public void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - multiblockLogic.writeToNBT(data); - } + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + multiblockLogic.readFromNBT(data); + } - /** - * Generally, TileEntities that are part of a multiblock should not subscribe to updates - * from the main game loop. Instead, you should have lists of TileEntities which need to - * be notified during an update() in your Controller and perform callbacks from there. - * @see net.minecraft.tileentity.TileEntity#canUpdate() - */ - @Override - public boolean canUpdate() { - return false; - } + @Override + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + multiblockLogic.writeToNBT(data); + } - @Override - public final void invalidate() { - super.invalidate(); - multiblockLogic.invalidate(worldObj, this); - } + /** + * Generally, TileEntities that are part of a multiblock should not subscribe to updates + * from the main game loop. Instead, you should have lists of TileEntities which need to + * be notified during an update() in your Controller and perform callbacks from there. + * @see net.minecraft.tileentity.TileEntity#canUpdate() + */ + @Override + public boolean canUpdate() { + return false; + } - @Override - public final void onChunkUnload() { - super.onChunkUnload(); - multiblockLogic.onChunkUnload(worldObj, this); - } + @Override + public final void invalidate() { + super.invalidate(); + multiblockLogic.invalidate(worldObj, this); + } - @Override - public final void validate() { - super.validate(); - multiblockLogic.validate(worldObj, this); - } + @Override + public final void onChunkUnload() { + super.onChunkUnload(); + multiblockLogic.onChunkUnload(worldObj, this); + } - /* Network Communication */ + @Override + public final void validate() { + super.validate(); + multiblockLogic.validate(worldObj, this); + } - @Override - public final Packet getDescriptionPacket() { - NBTTagCompound packetData = new NBTTagCompound(); - multiblockLogic.encodeDescriptionPacket(packetData); - this.encodeDescriptionPacket(packetData); - return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 0, packetData); - } - - @Override - public final void onDataPacket(NetworkManager network, S35PacketUpdateTileEntity packet) { - NBTTagCompound nbtData = packet.func_148857_g(); - multiblockLogic.decodeDescriptionPacket(nbtData); - this.decodeDescriptionPacket(nbtData); - } + /* Network Communication */ - /** - * Used to write tileEntity-specific data to the descriptionPacket - */ - protected void encodeDescriptionPacket(NBTTagCompound packetData) { + @Override + public final Packet getDescriptionPacket() { + NBTTagCompound packetData = new NBTTagCompound(); + multiblockLogic.encodeDescriptionPacket(packetData); + this.encodeDescriptionPacket(packetData); + return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 0, packetData); + } - } + @Override + public final void onDataPacket(NetworkManager network, S35PacketUpdateTileEntity packet) { + NBTTagCompound nbtData = packet.func_148857_g(); + multiblockLogic.decodeDescriptionPacket(nbtData); + this.decodeDescriptionPacket(nbtData); + } - /** - * Used to read tileEntity-specific data from the descriptionPacket (onDataPacket) - */ - protected void decodeDescriptionPacket(NBTTagCompound packetData) { + /** + * Used to write tileEntity-specific data to the descriptionPacket + */ + protected void encodeDescriptionPacket(NBTTagCompound packetData) {} - } + /** + * Used to read tileEntity-specific data from the descriptionPacket (onDataPacket) + */ + protected void decodeDescriptionPacket(NBTTagCompound packetData) {} } diff --git a/src/main/java/forestry/api/recipes/ICarpenterManager.java b/src/main/java/forestry/api/recipes/ICarpenterManager.java index 9dc700ac8..13d10fb2e 100644 --- a/src/main/java/forestry/api/recipes/ICarpenterManager.java +++ b/src/main/java/forestry/api/recipes/ICarpenterManager.java @@ -1,67 +1,66 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.recipes; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.ShapedRecipes; - import net.minecraftforge.fluids.FluidStack; /** * Provides an interface to the recipe manager of the carpenter. - * + * * The manager is initialized at the beginning of Forestry's BaseMod.load() cycle. Begin adding recipes in BaseMod.ModsLoaded() and this shouldn't be null even * if your mod loads before Forestry. - * + * * Accessible via {@link RecipeManagers} - * + * * Only shaped recipes can be added currently. - * + * * @author SirSengir */ public interface ICarpenterManager extends ICraftingProvider { - /** - * Add a shaped recipe to the carpenter. - * - * @param box - * ItemStack of one item representing the required box (carton, crate) for this recipe. May be null. - * @param product - * Crafting result. - * @param materials - * Materials needed in the crafting matrix. This gets passed directly to {@link ShapedRecipes}. Notation is the same. - */ - public void addRecipe(ItemStack box, ItemStack product, Object... materials); + /** + * Add a shaped recipe to the carpenter. + * + * @param box + * ItemStack of one item representing the required box (carton, crate) for this recipe. May be null. + * @param product + * Crafting result. + * @param materials + * Materials needed in the crafting matrix. This gets passed directly to {@link ShapedRecipes}. Notation is the same. + */ + public void addRecipe(ItemStack box, ItemStack product, Object... materials); - /** - * Add a shaped recipe to the carpenter. - * - * @param packagingTime - * Number of work cycles required to craft the recipe once. - * @param box - * ItemStack of one item representing the required box (carton, crate) for this recipe. May be null. - * @param product - * Crafting result. - * @param materials - * Materials needed in the crafting matrix. This gets passed directly to {@link ShapedRecipes}. Notation is the same. - */ - public void addRecipe(int packagingTime, ItemStack box, ItemStack product, Object... materials); + /** + * Add a shaped recipe to the carpenter. + * + * @param packagingTime + * Number of work cycles required to craft the recipe once. + * @param box + * ItemStack of one item representing the required box (carton, crate) for this recipe. May be null. + * @param product + * Crafting result. + * @param materials + * Materials needed in the crafting matrix. This gets passed directly to {@link ShapedRecipes}. Notation is the same. + */ + public void addRecipe(int packagingTime, ItemStack box, ItemStack product, Object... materials); - /** - * Add a shaped recipe to the carpenter. - * - * @param packagingTime - * Number of work cycles required to craft the recipe once. - * @param liquid - * Liquid required in carpenter's tank. - * @param box - * ItemStack of one item representing the required box (carton, crate) for this recipe. May be null. - * @param product - * Crafting result. - * @param materials - * Materials needed in the crafting matrix. This gets passed directly to {@link ShapedRecipes}. Notation is the same. - */ - public void addRecipe(int packagingTime, FluidStack liquid, ItemStack box, ItemStack product, Object... materials); + /** + * Add a shaped recipe to the carpenter. + * + * @param packagingTime + * Number of work cycles required to craft the recipe once. + * @param liquid + * Liquid required in carpenter's tank. + * @param box + * ItemStack of one item representing the required box (carton, crate) for this recipe. May be null. + * @param product + * Crafting result. + * @param materials + * Materials needed in the crafting matrix. This gets passed directly to {@link ShapedRecipes}. Notation is the same. + */ + public void addRecipe(int packagingTime, FluidStack liquid, ItemStack box, ItemStack product, Object... materials); } diff --git a/src/main/java/forestry/api/recipes/ICarpenterRecipe.java b/src/main/java/forestry/api/recipes/ICarpenterRecipe.java index cb3e88b77..287e6a94f 100644 --- a/src/main/java/forestry/api/recipes/ICarpenterRecipe.java +++ b/src/main/java/forestry/api/recipes/ICarpenterRecipe.java @@ -6,34 +6,31 @@ package forestry.api.recipes; import javax.annotation.Nullable; - import net.minecraft.item.ItemStack; - import net.minecraftforge.fluids.FluidStack; public interface ICarpenterRecipe extends IForestryRecipe { - /** - * @return Number of work cycles required to craft the recipe once. - */ - int getPackagingTime(); + /** + * @return Number of work cycles required to craft the recipe once. + */ + int getPackagingTime(); - /** - * @return the crafting grid recipe. The crafting recipe's getRecipeOutput() is used as the ICarpenterRecipe's output. - */ - IDescriptiveRecipe getCraftingGridRecipe(); + /** + * @return the crafting grid recipe. The crafting recipe's getRecipeOutput() is used as the ICarpenterRecipe's output. + */ + IDescriptiveRecipe getCraftingGridRecipe(); - /** - * @return the box required for this recipe. return null if there is no required box. - * Examples of boxes are the Forestry cartons and crates. - */ - @Nullable - ItemStack getBox(); - - /** - * @return the fluid required for this recipe. return null if there is no required fluid. - */ - @Nullable - FluidStack getFluidResource(); + /** + * @return the box required for this recipe. return null if there is no required box. + * Examples of boxes are the Forestry cartons and crates. + */ + @Nullable + ItemStack getBox(); + /** + * @return the fluid required for this recipe. return null if there is no required fluid. + */ + @Nullable + FluidStack getFluidResource(); } diff --git a/src/main/java/forestry/api/recipes/ICentrifugeManager.java b/src/main/java/forestry/api/recipes/ICentrifugeManager.java index 1d407f07d..8c655dab1 100644 --- a/src/main/java/forestry/api/recipes/ICentrifugeManager.java +++ b/src/main/java/forestry/api/recipes/ICentrifugeManager.java @@ -1,34 +1,32 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.recipes; import java.util.Map; - import net.minecraft.item.ItemStack; /** * Provides an interface to the recipe manager of the centrifuge. - * + * * The manager is initialized at the beginning of Forestry's BaseMod.load() cycle. Begin adding recipes in BaseMod.ModsLoaded() and this shouldn't be null even * if your mod loads before Forestry. - * + * * Accessible via {@link RecipeManagers} - * + * * @author SirSengir */ public interface ICentrifugeManager extends ICraftingProvider { - /** - * Add a recipe to the centrifuge - * - * @param timePerItem Time to centrifugate one item of the given type. Default is 20. - * @param input ItemStack containing information on item id and damage. Stack size will be ignored. - * @param products Specifies the possible products and the chances of them resulting from centrifuging. - * Chances are from (0.0 to 1.0] - */ - void addRecipe(int timePerItem, ItemStack input, Map products); - + /** + * Add a recipe to the centrifuge + * + * @param timePerItem Time to centrifugate one item of the given type. Default is 20. + * @param input ItemStack containing information on item id and damage. Stack size will be ignored. + * @param products Specifies the possible products and the chances of them resulting from centrifuging. + * Chances are from (0.0 to 1.0] + */ + void addRecipe(int timePerItem, ItemStack input, Map products); } diff --git a/src/main/java/forestry/api/recipes/ICentrifugeRecipe.java b/src/main/java/forestry/api/recipes/ICentrifugeRecipe.java index 595123f43..2f6a7d321 100644 --- a/src/main/java/forestry/api/recipes/ICentrifugeRecipe.java +++ b/src/main/java/forestry/api/recipes/ICentrifugeRecipe.java @@ -8,23 +8,22 @@ package forestry.api.recipes; import java.util.Collection; import java.util.Map; import java.util.Random; - import net.minecraft.item.ItemStack; public interface ICentrifugeRecipe extends IForestryRecipe { - /** The item for this recipe to match against. **/ - ItemStack getInput(); + /** The item for this recipe to match against. **/ + ItemStack getInput(); - /** The time it takes to process one item. Default is 20. **/ - int getProcessingTime(); + /** The time it takes to process one item. Default is 20. **/ + int getProcessingTime(); - /** Returns the randomized products from processing one input item. **/ - Collection getProducts(Random random); + /** Returns the randomized products from processing one input item. **/ + Collection getProducts(Random random); - /** - * Returns a list of all possible products and their estimated probabilities (0.0 to 1.0], - * to help mods that display recipes - **/ - Map getAllProducts(); + /** + * Returns a list of all possible products and their estimated probabilities (0.0 to 1.0], + * to help mods that display recipes + **/ + Map getAllProducts(); } diff --git a/src/main/java/forestry/api/recipes/ICraftingProvider.java b/src/main/java/forestry/api/recipes/ICraftingProvider.java index 9e6ca8945..e49a168d5 100644 --- a/src/main/java/forestry/api/recipes/ICraftingProvider.java +++ b/src/main/java/forestry/api/recipes/ICraftingProvider.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.recipes; @@ -9,32 +9,32 @@ import java.util.Collection; import java.util.Map; public interface ICraftingProvider { - /** - * Add a new recipe to the crafting provider. - * @return true if this collection changed as a result of the call - * @since Forestry 4.1.0 - */ - boolean addRecipe(T recipe); + /** + * Add a new recipe to the crafting provider. + * @return true if this collection changed as a result of the call + * @since Forestry 4.1.0 + */ + boolean addRecipe(T recipe); - /** - * Remove a specific recipe from the crafting provider. - * @return true if an element was removed as a result of this call - * @since Forestry 4.1.0 - */ - boolean removeRecipe(T recipe); + /** + * Remove a specific recipe from the crafting provider. + * @return true if an element was removed as a result of this call + * @since Forestry 4.1.0 + */ + boolean removeRecipe(T recipe); - /** - * @return an unmodifiable collection of all recipes registered to the crafting provider. - * @since Forestry 4.1.0 - */ - Collection recipes(); + /** + * @return an unmodifiable collection of all recipes registered to the crafting provider. + * @since Forestry 4.1.0 + */ + Collection recipes(); - /** - * Access to the full list of recipes contained in the crafting provider. - * - * @return List of the given format where the first array represents inputs and the second outputs. Objects can be either ItemStack or LiquidStack. - * @deprecated since Forestry 4.1.0. Use recipes() - */ - @Deprecated - Map getRecipes(); + /** + * Access to the full list of recipes contained in the crafting provider. + * + * @return List of the given format where the first array represents inputs and the second outputs. Objects can be either ItemStack or LiquidStack. + * @deprecated since Forestry 4.1.0. Use recipes() + */ + @Deprecated + Map getRecipes(); } diff --git a/src/main/java/forestry/api/recipes/IDescriptiveRecipe.java b/src/main/java/forestry/api/recipes/IDescriptiveRecipe.java index 654a47a5e..6020ddc93 100644 --- a/src/main/java/forestry/api/recipes/IDescriptiveRecipe.java +++ b/src/main/java/forestry/api/recipes/IDescriptiveRecipe.java @@ -16,34 +16,34 @@ import net.minecraft.world.World; */ public interface IDescriptiveRecipe extends IRecipe { - /** - * @return width of the crafting ingredients in the crafting table - */ - int getWidth(); + /** + * @return width of the crafting ingredients in the crafting table + */ + int getWidth(); - /** - * @return height of the crafting ingredients in the crafting table - */ - int getHeight(); + /** + * @return height of the crafting ingredients in the crafting table + */ + int getHeight(); - /** - * @return array of all the ingredients in the crafting table. - * Ingredients may be null, ItemStack, ItemStack[], or a List of ItemStack - */ - Object[] getIngredients(); + /** + * @return array of all the ingredients in the crafting table. + * Ingredients may be null, ItemStack, ItemStack[], or a List of ItemStack + */ + Object[] getIngredients(); - /** - * @return true if the recipe manager should copy NBT from input items to the output item. - * If true, all input items must have the same NBT for it to succeed. - * @deprecated since Forestry 4.2 wood itemStacks use item damage (meta) instead of NBT - */ - @Deprecated - boolean preserveNBT(); + /** + * @return true if the recipe manager should copy NBT from input items to the output item. + * If true, all input items must have the same NBT for it to succeed. + * @deprecated since Forestry 4.2 wood itemStacks use item damage (meta) instead of NBT + */ + @Deprecated + boolean preserveNBT(); - /** - * Used to check if a recipe matches current crafting inventory - * @deprecated Since Forestry 4.1. This is handled by Forestry. - */ - @Deprecated - boolean matches(IInventory inventoryCrafting, World world); + /** + * Used to check if a recipe matches current crafting inventory + * @deprecated Since Forestry 4.1. This is handled by Forestry. + */ + @Deprecated + boolean matches(IInventory inventoryCrafting, World world); } diff --git a/src/main/java/forestry/api/recipes/IFabricatorManager.java b/src/main/java/forestry/api/recipes/IFabricatorManager.java index 342e0a3ee..a24f77e6c 100644 --- a/src/main/java/forestry/api/recipes/IFabricatorManager.java +++ b/src/main/java/forestry/api/recipes/IFabricatorManager.java @@ -1,22 +1,20 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.recipes; import net.minecraft.item.ItemStack; - import net.minecraftforge.fluids.FluidStack; public interface IFabricatorManager extends ICraftingProvider { - void addRecipe(ItemStack plan, FluidStack molten, ItemStack result, Object[] pattern); - - /** - * @deprecated since Forestry 4.1. Use IFabricatorSmeltingManager - */ - @Deprecated - void addSmelting(ItemStack resource, FluidStack molten, int meltingPoint); + void addRecipe(ItemStack plan, FluidStack molten, ItemStack result, Object[] pattern); + /** + * @deprecated since Forestry 4.1. Use IFabricatorSmeltingManager + */ + @Deprecated + void addSmelting(ItemStack resource, FluidStack molten, int meltingPoint); } diff --git a/src/main/java/forestry/api/recipes/IFabricatorRecipe.java b/src/main/java/forestry/api/recipes/IFabricatorRecipe.java index aea28eefa..cba4871b9 100644 --- a/src/main/java/forestry/api/recipes/IFabricatorRecipe.java +++ b/src/main/java/forestry/api/recipes/IFabricatorRecipe.java @@ -6,65 +6,63 @@ package forestry.api.recipes; import javax.annotation.Nullable; - import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - import net.minecraftforge.fluids.FluidStack; public interface IFabricatorRecipe extends IForestryRecipe { - /** - * @return the molten liquid (and amount) required for this recipe. - */ - FluidStack getLiquid(); + /** + * @return the molten liquid (and amount) required for this recipe. + */ + FluidStack getLiquid(); - /** - * @return the list of ingredients in the crafting grid to create this recipe. - */ - Object[] getIngredients(); + /** + * @return the list of ingredients in the crafting grid to create this recipe. + */ + Object[] getIngredients(); - /** - * @return the width of ingredients in the crafting grid to create this recipe. - */ - int getWidth(); + /** + * @return the width of ingredients in the crafting grid to create this recipe. + */ + int getWidth(); - /** - * @return the height of ingredients in the crafting grid to create this recipe. - */ - int getHeight(); + /** + * @return the height of ingredients in the crafting grid to create this recipe. + */ + int getHeight(); - /** - * @return true if this recipe copies the NBT from input items to output items - * @deprecated since Forestry 4.2 wood itemStacks use item damage (meta) instead of NBT - */ - @Deprecated - boolean preservesNbt(); + /** + * @return true if this recipe copies the NBT from input items to output items + * @deprecated since Forestry 4.2 wood itemStacks use item damage (meta) instead of NBT + */ + @Deprecated + boolean preservesNbt(); - /** - * @return the plan for this recipe (the item in the top right slot). - */ - @Nullable - ItemStack getPlan(); + /** + * @return the plan for this recipe (the item in the top right slot). + */ + @Nullable + ItemStack getPlan(); - /** - * @return the result of this recipe - */ - ItemStack getRecipeOutput(); + /** + * @return the result of this recipe + */ + ItemStack getRecipeOutput(); - /** - * Returns an Item that is the result of this recipe - * @deprecated since Forestry 4.1. Forestry uses getRecipeOutput() and preservesNbt() to determine the result. - */ - @Deprecated - ItemStack getCraftingResult(IInventory craftingInventory); + /** + * Returns an Item that is the result of this recipe + * @deprecated since Forestry 4.1. Forestry uses getRecipeOutput() and preservesNbt() to determine the result. + */ + @Deprecated + ItemStack getCraftingResult(IInventory craftingInventory); - /** - * @param plan The Fabricator plan, the item in the top right slot. - * @param resources The resources in the crafting grid. - * @return true if the plan and resources match this recipe. - * @deprecated since Forestry 4.1. This is handled by Forestry instead. - */ - @Deprecated - boolean matches(@Nullable ItemStack plan, ItemStack[][] resources); + /** + * @param plan The Fabricator plan, the item in the top right slot. + * @param resources The resources in the crafting grid. + * @return true if the plan and resources match this recipe. + * @deprecated since Forestry 4.1. This is handled by Forestry instead. + */ + @Deprecated + boolean matches(@Nullable ItemStack plan, ItemStack[][] resources); } diff --git a/src/main/java/forestry/api/recipes/IFabricatorSmeltingManager.java b/src/main/java/forestry/api/recipes/IFabricatorSmeltingManager.java index 5ec9ef230..3d752a5c9 100644 --- a/src/main/java/forestry/api/recipes/IFabricatorSmeltingManager.java +++ b/src/main/java/forestry/api/recipes/IFabricatorSmeltingManager.java @@ -11,15 +11,14 @@ package forestry.api.recipes; import net.minecraft.item.ItemStack; - import net.minecraftforge.fluids.FluidStack; public interface IFabricatorSmeltingManager extends ICraftingProvider { - /** - * Add a smelting recipe to the Fabricator - * @param resource item to be melted down - * @param molten resulting fluid - * @param meltingPoint temperature at which the item melts. Glass is 1000, Sand is 3000. - */ - void addSmelting(ItemStack resource, FluidStack molten, int meltingPoint); + /** + * Add a smelting recipe to the Fabricator + * @param resource item to be melted down + * @param molten resulting fluid + * @param meltingPoint temperature at which the item melts. Glass is 1000, Sand is 3000. + */ + void addSmelting(ItemStack resource, FluidStack molten, int meltingPoint); } diff --git a/src/main/java/forestry/api/recipes/IFabricatorSmeltingRecipe.java b/src/main/java/forestry/api/recipes/IFabricatorSmeltingRecipe.java index 3b0a3565b..88094cd8a 100644 --- a/src/main/java/forestry/api/recipes/IFabricatorSmeltingRecipe.java +++ b/src/main/java/forestry/api/recipes/IFabricatorSmeltingRecipe.java @@ -11,22 +11,21 @@ package forestry.api.recipes; import net.minecraft.item.ItemStack; - import net.minecraftforge.fluids.FluidStack; public interface IFabricatorSmeltingRecipe extends IForestryRecipe { - /** - * @return item to be melted down - */ - ItemStack getResource(); + /** + * @return item to be melted down + */ + ItemStack getResource(); - /** - * @return temperature at which the item melts. Glass is 1000, Sand is 3000. - */ - int getMeltingPoint(); + /** + * @return temperature at which the item melts. Glass is 1000, Sand is 3000. + */ + int getMeltingPoint(); - /** - * @return resulting fluid - */ - FluidStack getProduct(); + /** + * @return resulting fluid + */ + FluidStack getProduct(); } diff --git a/src/main/java/forestry/api/recipes/IFermenterManager.java b/src/main/java/forestry/api/recipes/IFermenterManager.java index 5aa926ddf..a571e1244 100644 --- a/src/main/java/forestry/api/recipes/IFermenterManager.java +++ b/src/main/java/forestry/api/recipes/IFermenterManager.java @@ -1,12 +1,11 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.recipes; import net.minecraft.item.ItemStack; - import net.minecraftforge.fluids.FluidStack; /** @@ -22,32 +21,33 @@ import net.minecraftforge.fluids.FluidStack; */ public interface IFermenterManager extends ICraftingProvider { - /** - * Add a recipe to the fermenter - * - * @param resource ItemStack representing the resource. - * @param fermentationValue Value of the given resource, i.e. how much needs - * to be fermented for the output to be deposited into the product tank. - * @param modifier Modifies the amount of liquid output per work cycle. - * (water = 1.0f, honey = 1.5f) - * @param output LiquidStack representing output liquid. Amount is - * determined by fermentationValue*modifier. - * @param liquid LiquidStack representing resource liquid and amount. - * @throws NullPointerException if resource, output or liquid is null - */ - public void addRecipe(ItemStack resource, int fermentationValue, float modifier, FluidStack output, FluidStack liquid); + /** + * Add a recipe to the fermenter + * + * @param resource ItemStack representing the resource. + * @param fermentationValue Value of the given resource, i.e. how much needs + * to be fermented for the output to be deposited into the product tank. + * @param modifier Modifies the amount of liquid output per work cycle. + * (water = 1.0f, honey = 1.5f) + * @param output LiquidStack representing output liquid. Amount is + * determined by fermentationValue*modifier. + * @param liquid LiquidStack representing resource liquid and amount. + * @throws NullPointerException if resource, output or liquid is null + */ + public void addRecipe( + ItemStack resource, int fermentationValue, float modifier, FluidStack output, FluidStack liquid); - /** - * Add a recipe to the fermenter. Defaults to water as input liquid. - * - * @param resource ItemStack representing the resource. - * @param modifier Modifies the amount of liquid output per work cycle. - * (water = 1.0f, honey = 1.5f) - * @param fermentationValue Value of the given resource, i.e. how much needs - * to be fermented for the output to be deposited into the product tank. - * @param output LiquidStack representing output liquid. Amount is - * determined by fermentationValue*modifier. - * @throws NullPointerException if resource, output or liquid is null - */ - public void addRecipe(ItemStack resource, int fermentationValue, float modifier, FluidStack output); + /** + * Add a recipe to the fermenter. Defaults to water as input liquid. + * + * @param resource ItemStack representing the resource. + * @param modifier Modifies the amount of liquid output per work cycle. + * (water = 1.0f, honey = 1.5f) + * @param fermentationValue Value of the given resource, i.e. how much needs + * to be fermented for the output to be deposited into the product tank. + * @param output LiquidStack representing output liquid. Amount is + * determined by fermentationValue*modifier. + * @throws NullPointerException if resource, output or liquid is null + */ + public void addRecipe(ItemStack resource, int fermentationValue, float modifier, FluidStack output); } diff --git a/src/main/java/forestry/api/recipes/IFermenterRecipe.java b/src/main/java/forestry/api/recipes/IFermenterRecipe.java index 4bbd0f54b..7c505d9a7 100644 --- a/src/main/java/forestry/api/recipes/IFermenterRecipe.java +++ b/src/main/java/forestry/api/recipes/IFermenterRecipe.java @@ -6,34 +6,33 @@ package forestry.api.recipes; import net.minecraft.item.ItemStack; - import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; public interface IFermenterRecipe extends IForestryRecipe { - /** - * @return ItemStack representing the input resource. - */ - ItemStack getResource(); + /** + * @return ItemStack representing the input resource. + */ + ItemStack getResource(); - /** - * @return FluidStack representing the input fluid resource. - */ - FluidStack getFluidResource(); + /** + * @return FluidStack representing the input fluid resource. + */ + FluidStack getFluidResource(); - /** - * @return Value of the given resource, i.e. how much needs to be fermented for the output to be deposited into the product tank. - */ - int getFermentationValue(); + /** + * @return Value of the given resource, i.e. how much needs to be fermented for the output to be deposited into the product tank. + */ + int getFermentationValue(); - /** - * @return Modifies the amount of liquid output per work cycle. - * (water = 1.0f, honey = 1.5f) - */ - float getModifier(); + /** + * @return Modifies the amount of liquid output per work cycle. + * (water = 1.0f, honey = 1.5f) + */ + float getModifier(); - /** - * @return Fluid representing output. Amount is determined by fermentationValue * modifier. - */ - Fluid getOutput(); + /** + * @return Fluid representing output. Amount is determined by fermentationValue * modifier. + */ + Fluid getOutput(); } diff --git a/src/main/java/forestry/api/recipes/IForestryRecipe.java b/src/main/java/forestry/api/recipes/IForestryRecipe.java index 7153ffa0b..af358ed25 100644 --- a/src/main/java/forestry/api/recipes/IForestryRecipe.java +++ b/src/main/java/forestry/api/recipes/IForestryRecipe.java @@ -5,5 +5,4 @@ ******************************************************************************/ package forestry.api.recipes; -public interface IForestryRecipe { -} +public interface IForestryRecipe {} diff --git a/src/main/java/forestry/api/recipes/IMoistenerManager.java b/src/main/java/forestry/api/recipes/IMoistenerManager.java index 3bbd59d44..ca98314fa 100644 --- a/src/main/java/forestry/api/recipes/IMoistenerManager.java +++ b/src/main/java/forestry/api/recipes/IMoistenerManager.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.recipes; @@ -9,25 +9,25 @@ import net.minecraft.item.ItemStack; /** * Provides an interface to the recipe manager of the moistener. - * + * * The manager is initialized at the beginning of Forestry's BaseMod.load() cycle. Begin adding recipes in BaseMod.ModsLoaded() and this shouldn't be null even * if your mod loads before Forestry. - * + * * Accessible via {@link RecipeManagers} - * + * * @author SirSengir */ public interface IMoistenerManager extends ICraftingProvider { - /** - * Add a recipe to the moistener - * - * @param resource - * Item required in resource stack. Will be reduced by one per produced item. - * @param product - * Item to produce per resource processed. - * @param timePerItem - * Moistener runs at 1 - 4 time ticks per ingame tick depending on light level. For mycelium this value is currently 5000. - */ - public void addRecipe(ItemStack resource, ItemStack product, int timePerItem); + /** + * Add a recipe to the moistener + * + * @param resource + * Item required in resource stack. Will be reduced by one per produced item. + * @param product + * Item to produce per resource processed. + * @param timePerItem + * Moistener runs at 1 - 4 time ticks per ingame tick depending on light level. For mycelium this value is currently 5000. + */ + public void addRecipe(ItemStack resource, ItemStack product, int timePerItem); } diff --git a/src/main/java/forestry/api/recipes/IMoistenerRecipe.java b/src/main/java/forestry/api/recipes/IMoistenerRecipe.java index 73eaf5a92..c3385d6b9 100644 --- a/src/main/java/forestry/api/recipes/IMoistenerRecipe.java +++ b/src/main/java/forestry/api/recipes/IMoistenerRecipe.java @@ -8,19 +8,19 @@ package forestry.api.recipes; import net.minecraft.item.ItemStack; public interface IMoistenerRecipe extends IForestryRecipe { - /** - * Moistener runs at 1 - 4 time ticks per ingame tick depending on light level. For mycelium this value is currently 5000. - * @return moistener ticks to process one item. - */ - int getTimePerItem(); + /** + * Moistener runs at 1 - 4 time ticks per ingame tick depending on light level. For mycelium this value is currently 5000. + * @return moistener ticks to process one item. + */ + int getTimePerItem(); - /** - * @return Item required in resource stack. Will be reduced by one per produced item. - */ - ItemStack getResource(); + /** + * @return Item required in resource stack. Will be reduced by one per produced item. + */ + ItemStack getResource(); - /** - * @return Item to produce per resource processed. - */ - ItemStack getProduct(); + /** + * @return Item to produce per resource processed. + */ + ItemStack getProduct(); } diff --git a/src/main/java/forestry/api/recipes/ISqueezerManager.java b/src/main/java/forestry/api/recipes/ISqueezerManager.java index e02bf4dc2..cccb865d8 100644 --- a/src/main/java/forestry/api/recipes/ISqueezerManager.java +++ b/src/main/java/forestry/api/recipes/ISqueezerManager.java @@ -1,56 +1,54 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.recipes; import javax.annotation.Nullable; - import net.minecraft.item.ItemStack; - import net.minecraftforge.fluids.FluidStack; /** * Provides an interface to the recipe manager of the suqeezer. - * + * * The manager is initialized at the beginning of Forestry's BaseMod.load() cycle. Begin adding recipes in BaseMod.ModsLoaded() and this shouldn't be null even * if your mod loads before Forestry. - * + * * Accessible via {@link RecipeManagers} - * + * * @author SirSengir */ public interface ISqueezerManager extends ICraftingProvider { - /** - * Add a recipe to the squeezer. - * - * @param timePerItem Number of work cycles required to squeeze one set of resources. - * @param resources Array of item stacks representing the required resources for one process. Stack size will be taken into account. - * @param liquid {@link FluidStack} representing the output of this recipe. - * @param remnants Item stack representing the possible remnants from this recipe. - * @param chance Chance remnants will be produced by a single recipe cycle, from 0 to 100. - */ - public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid, ItemStack remnants, int chance); + /** + * Add a recipe to the squeezer. + * + * @param timePerItem Number of work cycles required to squeeze one set of resources. + * @param resources Array of item stacks representing the required resources for one process. Stack size will be taken into account. + * @param liquid {@link FluidStack} representing the output of this recipe. + * @param remnants Item stack representing the possible remnants from this recipe. + * @param chance Chance remnants will be produced by a single recipe cycle, from 0 to 100. + */ + public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid, ItemStack remnants, int chance); - /** - * Add a recipe to the squeezer. - * - * @param timePerItem Number of work cycles required to squeeze one set of resources. - * @param resources Array of item stacks representing the required resources for one process. Stack size will be taken into account. - * @param liquid {@link FluidStack} representing the output of this recipe. - */ - public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid); + /** + * Add a recipe to the squeezer. + * + * @param timePerItem Number of work cycles required to squeeze one set of resources. + * @param resources Array of item stacks representing the required resources for one process. Stack size will be taken into account. + * @param liquid {@link FluidStack} representing the output of this recipe. + */ + public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid); - /** - * Add a recipe for a fluid container to the squeezer. - * This will add recipes to get all types of liquids out of this type of fluid container. - * - * @param timePerItem Number of work cycles required to squeeze one set of resources. - * @param emptyContainer The empty version of the fluid container that will be squeezed. - * @param remnants Item stack representing the possible remnants from this recipe. - * @param chance Chance remnants will be produced by a single recipe cycle, from 0 to 1. - */ - void addContainerRecipe(int timePerItem, ItemStack emptyContainer, @Nullable ItemStack remnants, float chance); + /** + * Add a recipe for a fluid container to the squeezer. + * This will add recipes to get all types of liquids out of this type of fluid container. + * + * @param timePerItem Number of work cycles required to squeeze one set of resources. + * @param emptyContainer The empty version of the fluid container that will be squeezed. + * @param remnants Item stack representing the possible remnants from this recipe. + * @param chance Chance remnants will be produced by a single recipe cycle, from 0 to 1. + */ + void addContainerRecipe(int timePerItem, ItemStack emptyContainer, @Nullable ItemStack remnants, float chance); } diff --git a/src/main/java/forestry/api/recipes/ISqueezerRecipe.java b/src/main/java/forestry/api/recipes/ISqueezerRecipe.java index 385b33799..23600f706 100644 --- a/src/main/java/forestry/api/recipes/ISqueezerRecipe.java +++ b/src/main/java/forestry/api/recipes/ISqueezerRecipe.java @@ -6,34 +6,32 @@ package forestry.api.recipes; import net.minecraft.item.ItemStack; - import net.minecraftforge.fluids.FluidStack; public interface ISqueezerRecipe extends IForestryRecipe { - /** - * @return Array of item stacks representing the required resources for one process. Stack size will be taken into account. - */ - ItemStack[] getResources(); + /** + * @return Array of item stacks representing the required resources for one process. Stack size will be taken into account. + */ + ItemStack[] getResources(); - /** - * @return Number of work cycles required to squeeze one set of resources. - */ - int getProcessingTime(); + /** + * @return Number of work cycles required to squeeze one set of resources. + */ + int getProcessingTime(); - /** - * @return Item stack representing the possible remnants from this recipe. (i.e. tin left over from tin cans) - */ - ItemStack getRemnants(); + /** + * @return Item stack representing the possible remnants from this recipe. (i.e. tin left over from tin cans) + */ + ItemStack getRemnants(); - /** - * @return Chance remnants will be produced by a single recipe cycle, from 0 to 1. - */ - float getRemnantsChance(); - - /** - * @return {@link FluidStack} representing the output of this recipe. - */ - FluidStack getFluidOutput(); + /** + * @return Chance remnants will be produced by a single recipe cycle, from 0 to 1. + */ + float getRemnantsChance(); + /** + * @return {@link FluidStack} representing the output of this recipe. + */ + FluidStack getFluidOutput(); } diff --git a/src/main/java/forestry/api/recipes/IStillManager.java b/src/main/java/forestry/api/recipes/IStillManager.java index 72cd7398f..c634ce5a8 100644 --- a/src/main/java/forestry/api/recipes/IStillManager.java +++ b/src/main/java/forestry/api/recipes/IStillManager.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.recipes; @@ -9,26 +9,26 @@ import net.minecraftforge.fluids.FluidStack; /** * Provides an interface to the recipe manager of the still. - * + * * The manager is initialized at the beginning of Forestry's BaseMod.load() cycle. Begin adding recipes in BaseMod.ModsLoaded() and this shouldn't be null even * if your mod loads before Forestry. - * + * * Accessible via {@link RecipeManagers} - * + * * Note that this is untested with anything other than biomass->biofuel conversion. - * + * * @author SirSengir */ public interface IStillManager extends ICraftingProvider { - /** - * Add a recipe to the still - * - * @param cyclesPerUnit - * Amount of work cycles required to run through the conversion once. - * @param input - * FluidStack representing the input liquid. - * @param output - * FluidStack representing the output liquid - */ - public void addRecipe(int cyclesPerUnit, FluidStack input, FluidStack output); + /** + * Add a recipe to the still + * + * @param cyclesPerUnit + * Amount of work cycles required to run through the conversion once. + * @param input + * FluidStack representing the input liquid. + * @param output + * FluidStack representing the output liquid + */ + public void addRecipe(int cyclesPerUnit, FluidStack input, FluidStack output); } diff --git a/src/main/java/forestry/api/recipes/IStillRecipe.java b/src/main/java/forestry/api/recipes/IStillRecipe.java index 384aa3e14..35bcbe9c8 100644 --- a/src/main/java/forestry/api/recipes/IStillRecipe.java +++ b/src/main/java/forestry/api/recipes/IStillRecipe.java @@ -8,18 +8,18 @@ package forestry.api.recipes; import net.minecraftforge.fluids.FluidStack; public interface IStillRecipe extends IForestryRecipe { - /** - * @return Amount of work cycles required to run through the conversion once. - */ - int getCyclesPerUnit(); + /** + * @return Amount of work cycles required to run through the conversion once. + */ + int getCyclesPerUnit(); - /** - * @return FluidStack representing the input liquid. - */ - FluidStack getInput(); + /** + * @return FluidStack representing the input liquid. + */ + FluidStack getInput(); - /** - * @return FluidStack representing the output liquid. - */ - FluidStack getOutput(); + /** + * @return FluidStack representing the output liquid. + */ + FluidStack getOutput(); } diff --git a/src/main/java/forestry/api/recipes/IVariableFermentable.java b/src/main/java/forestry/api/recipes/IVariableFermentable.java index f0997f531..0469d0427 100644 --- a/src/main/java/forestry/api/recipes/IVariableFermentable.java +++ b/src/main/java/forestry/api/recipes/IVariableFermentable.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.recipes; @@ -12,10 +12,10 @@ import net.minecraft.item.ItemStack; * This does not supersede adding a proper recipe to the fermenter! */ public interface IVariableFermentable { - - /** - * @param itemstack - * @return Float representing the modification to be applied to the matching recipe's biomass output. - */ - float getFermentationModifier(ItemStack itemstack); + + /** + * @param itemstack + * @return Float representing the modification to be applied to the matching recipe's biomass output. + */ + float getFermentationModifier(ItemStack itemstack); } diff --git a/src/main/java/forestry/api/recipes/RecipeManagers.java b/src/main/java/forestry/api/recipes/RecipeManagers.java index 9a2973471..cfce9ff56 100644 --- a/src/main/java/forestry/api/recipes/RecipeManagers.java +++ b/src/main/java/forestry/api/recipes/RecipeManagers.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.recipes; @@ -9,46 +9,46 @@ import java.util.Collection; /** * Contains all available recipe managers for Forestry machines and items. - * + * * @author SirSengir */ public class RecipeManagers { - /** - * @deprecated since Forestry 4.1.0. Use the specific recipe managers below instead. - */ - public static Collection craftingProviders; - - /** - * Allows you to add recipes to the carpenter. See {@link ICarpenterManager} for details. - */ - public static ICarpenterManager carpenterManager; - /** - * Allows you to add recipes to the centrifuge. See {@link ICentrifugeManager} for details. - */ - public static ICentrifugeManager centrifugeManager; - /** - * Allows you to add recipes to the fermenter. See {@link IFermenterManager} for details. - */ - public static IFermenterManager fermenterManager; - /** - * Allows you to add recipes to the moistener. See {@link IMoistenerManager} for details. - */ - public static IMoistenerManager moistenerManager; - /** - * Allows you to add recipes to the squeezer. See {@link ISqueezerManager} for details. - */ - public static ISqueezerManager squeezerManager; - /** - * Allows you to add recipes to the still. See {@link IStillManager} for details. - */ - public static IStillManager stillManager; - /** - * Allows you to add recipes to the fabricator. See {@link IFabricatorManager} for details. - */ - public static IFabricatorManager fabricatorManager; - /** - * Allows you to add smelting recipes to the fabricator. See {@link IFabricatorSmeltingManager} for details. - */ - public static IFabricatorSmeltingManager fabricatorSmeltingManager; + /** + * @deprecated since Forestry 4.1.0. Use the specific recipe managers below instead. + */ + public static Collection craftingProviders; + + /** + * Allows you to add recipes to the carpenter. See {@link ICarpenterManager} for details. + */ + public static ICarpenterManager carpenterManager; + /** + * Allows you to add recipes to the centrifuge. See {@link ICentrifugeManager} for details. + */ + public static ICentrifugeManager centrifugeManager; + /** + * Allows you to add recipes to the fermenter. See {@link IFermenterManager} for details. + */ + public static IFermenterManager fermenterManager; + /** + * Allows you to add recipes to the moistener. See {@link IMoistenerManager} for details. + */ + public static IMoistenerManager moistenerManager; + /** + * Allows you to add recipes to the squeezer. See {@link ISqueezerManager} for details. + */ + public static ISqueezerManager squeezerManager; + /** + * Allows you to add recipes to the still. See {@link IStillManager} for details. + */ + public static IStillManager stillManager; + /** + * Allows you to add recipes to the fabricator. See {@link IFabricatorManager} for details. + */ + public static IFabricatorManager fabricatorManager; + /** + * Allows you to add smelting recipes to the fabricator. See {@link IFabricatorSmeltingManager} for details. + */ + public static IFabricatorSmeltingManager fabricatorSmeltingManager; } diff --git a/src/main/java/forestry/api/recipes/package-info.java b/src/main/java/forestry/api/recipes/package-info.java index 20ee04415..bd7a6a9cf 100644 --- a/src/main/java/forestry/api/recipes/package-info.java +++ b/src/main/java/forestry/api/recipes/package-info.java @@ -1,8 +1,9 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ -@API(apiVersion="5.4.0", owner="ForestryAPI|core", provides="ForestryAPI|recipes") +@API(apiVersion = "5.4.0", owner = "ForestryAPI|core", provides = "ForestryAPI|recipes") package forestry.api.recipes; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/api/storage/BackpackEvent.java b/src/main/java/forestry/api/storage/BackpackEvent.java index 374277881..39d30c3a5 100644 --- a/src/main/java/forestry/api/storage/BackpackEvent.java +++ b/src/main/java/forestry/api/storage/BackpackEvent.java @@ -1,25 +1,23 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.storage; +import cpw.mods.fml.common.eventhandler.Event; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; -import cpw.mods.fml.common.eventhandler.Event; - - public abstract class BackpackEvent extends Event { - public final EntityPlayer player; - public final IBackpackDefinition backpackDefinition; - public final IInventory backpackInventory; + public final EntityPlayer player; + public final IBackpackDefinition backpackDefinition; + public final IInventory backpackInventory; - public BackpackEvent(EntityPlayer player, IBackpackDefinition backpackDefinition, IInventory backpackInventory) { - this.player = player; - this.backpackDefinition = backpackDefinition; - this.backpackInventory = backpackInventory; - } + public BackpackEvent(EntityPlayer player, IBackpackDefinition backpackDefinition, IInventory backpackInventory) { + this.player = player; + this.backpackDefinition = backpackDefinition; + this.backpackInventory = backpackInventory; + } } diff --git a/src/main/java/forestry/api/storage/BackpackManager.java b/src/main/java/forestry/api/storage/BackpackManager.java index 8805904d6..54086b858 100644 --- a/src/main/java/forestry/api/storage/BackpackManager.java +++ b/src/main/java/forestry/api/storage/BackpackManager.java @@ -1,27 +1,26 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.storage; import java.util.ArrayList; import java.util.HashMap; - import net.minecraft.item.ItemStack; public class BackpackManager { - /** - * 0 - Miner's Backpack 1 - Digger's Backpack 2 - Forester's Backpack 3 - Hunter's Backpack 4 - Adventurer's Backpack - * - * Use IMC messages to achieve the same effect! - */ - public static ArrayList[] backpackItems; + /** + * 0 - Miner's Backpack 1 - Digger's Backpack 2 - Forester's Backpack 3 - Hunter's Backpack 4 - Adventurer's Backpack + * + * Use IMC messages to achieve the same effect! + */ + public static ArrayList[] backpackItems; - public static IBackpackInterface backpackInterface; + public static IBackpackInterface backpackInterface; - /** - * Only use this if you know what you are doing. Prefer backpackInterface. - */ - public static HashMap definitions = new HashMap(); + /** + * Only use this if you know what you are doing. Prefer backpackInterface. + */ + public static HashMap definitions = new HashMap(); } diff --git a/src/main/java/forestry/api/storage/BackpackResupplyEvent.java b/src/main/java/forestry/api/storage/BackpackResupplyEvent.java index e6e5e1198..95e506374 100644 --- a/src/main/java/forestry/api/storage/BackpackResupplyEvent.java +++ b/src/main/java/forestry/api/storage/BackpackResupplyEvent.java @@ -1,15 +1,14 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.storage; +import cpw.mods.fml.common.eventhandler.Cancelable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; -import cpw.mods.fml.common.eventhandler.Cancelable; - /** * Use @SubscribeEvent on a method taking this event as an argument. Will fire whenever a backpack tries to resupply to a player inventory. Processing will stop * if the event is canceled. @@ -17,8 +16,8 @@ import cpw.mods.fml.common.eventhandler.Cancelable; @Cancelable public class BackpackResupplyEvent extends BackpackEvent { - public BackpackResupplyEvent(EntityPlayer player, IBackpackDefinition backpackDefinition, IInventory backpackInventory) { - super(player, backpackDefinition, backpackInventory); - } - + public BackpackResupplyEvent( + EntityPlayer player, IBackpackDefinition backpackDefinition, IInventory backpackInventory) { + super(player, backpackDefinition, backpackInventory); + } } diff --git a/src/main/java/forestry/api/storage/BackpackStowEvent.java b/src/main/java/forestry/api/storage/BackpackStowEvent.java index 3afbf7a1d..24bfa1b00 100644 --- a/src/main/java/forestry/api/storage/BackpackStowEvent.java +++ b/src/main/java/forestry/api/storage/BackpackStowEvent.java @@ -1,16 +1,15 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.storage; +import cpw.mods.fml.common.eventhandler.Cancelable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import cpw.mods.fml.common.eventhandler.Cancelable; - /** * Use @SubscribeEvent on a method taking this event as an argument. Will fire whenever a backpack tries to store an item. Processing will stop if the stacksize * of stackToStow drops to 0 or less or the event is canceled. @@ -18,10 +17,14 @@ import cpw.mods.fml.common.eventhandler.Cancelable; @Cancelable public class BackpackStowEvent extends BackpackEvent { - public final ItemStack stackToStow; + public final ItemStack stackToStow; - public BackpackStowEvent(EntityPlayer player, IBackpackDefinition backpackDefinition, IInventory backpackInventory, ItemStack stackToStow) { - super(player, backpackDefinition, backpackInventory); - this.stackToStow = stackToStow; - } + public BackpackStowEvent( + EntityPlayer player, + IBackpackDefinition backpackDefinition, + IInventory backpackInventory, + ItemStack stackToStow) { + super(player, backpackDefinition, backpackInventory); + this.stackToStow = stackToStow; + } } diff --git a/src/main/java/forestry/api/storage/EnumBackpackType.java b/src/main/java/forestry/api/storage/EnumBackpackType.java index 48ad7ee09..86170267e 100644 --- a/src/main/java/forestry/api/storage/EnumBackpackType.java +++ b/src/main/java/forestry/api/storage/EnumBackpackType.java @@ -1,10 +1,12 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.storage; public enum EnumBackpackType { - APIARIST, T1, T2 + APIARIST, + T1, + T2 } diff --git a/src/main/java/forestry/api/storage/IBackpackDefinition.java b/src/main/java/forestry/api/storage/IBackpackDefinition.java index 31c666312..fa0085ee5 100644 --- a/src/main/java/forestry/api/storage/IBackpackDefinition.java +++ b/src/main/java/forestry/api/storage/IBackpackDefinition.java @@ -1,47 +1,46 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.storage; import java.util.List; - import net.minecraft.item.ItemStack; public interface IBackpackDefinition { - /** - * @return A unique string identifier - */ - String getKey(); + /** + * @return A unique string identifier + */ + String getKey(); - /** - * @return Human-readable name of the backpack. - */ - String getName(ItemStack backpack); + /** + * @return Human-readable name of the backpack. + */ + String getName(ItemStack backpack); - /** - * @return Primary colour for the backpack icon. - */ - int getPrimaryColour(); + /** + * @return Primary colour for the backpack icon. + */ + int getPrimaryColour(); - /** - * @return Secondary colour for backpack icon. - */ - int getSecondaryColour(); + /** + * @return Secondary colour for backpack icon. + */ + int getSecondaryColour(); - /** - * Adds an item as valid for this backpack. - * - * @param validItem - */ - void addValidItem(ItemStack validItem); - void addValidItems(List validItems); + /** + * Adds an item as valid for this backpack. + * + * @param validItem + */ + void addValidItem(ItemStack validItem); - /** - * Returns true if the itemstack is a valid item for this backpack type. - */ - boolean isValidItem(ItemStack itemstack); + void addValidItems(List validItems); + /** + * Returns true if the itemstack is a valid item for this backpack type. + */ + boolean isValidItem(ItemStack itemstack); } diff --git a/src/main/java/forestry/api/storage/IBackpackInterface.java b/src/main/java/forestry/api/storage/IBackpackInterface.java index 27a2eba56..e64b0641f 100644 --- a/src/main/java/forestry/api/storage/IBackpackInterface.java +++ b/src/main/java/forestry/api/storage/IBackpackInterface.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.storage; @@ -9,14 +9,14 @@ import net.minecraft.item.Item; public interface IBackpackInterface { - /** - * Adds a backpack with the given definition and type, returning the item. - * - * @param definition - * Definition of backpack behaviour. - * @param type - * Type of backpack. (T1 or T2 (= Woven) - * @return Created backpack item. - */ - Item addBackpack(IBackpackDefinition definition, EnumBackpackType type); + /** + * Adds a backpack with the given definition and type, returning the item. + * + * @param definition + * Definition of backpack behaviour. + * @param type + * Type of backpack. (T1 or T2 (= Woven) + * @return Created backpack item. + */ + Item addBackpack(IBackpackDefinition definition, EnumBackpackType type); } diff --git a/src/main/java/forestry/api/storage/ICrateRegistry.java b/src/main/java/forestry/api/storage/ICrateRegistry.java index 868511e3d..7c4a0dcf8 100644 --- a/src/main/java/forestry/api/storage/ICrateRegistry.java +++ b/src/main/java/forestry/api/storage/ICrateRegistry.java @@ -11,22 +11,25 @@ import net.minecraft.item.ItemStack; public interface ICrateRegistry { - /** - * Makes a new crate, registers it with the game registry with uid, - * and creates crating and uncrating recipes for the Carpenter. - * The icon is rendered automatically from the contained item. - * - * Can only be called during the Init stage. - */ - void registerCrate(Item item, String uid); - void registerCrate(Block block, String uid); - void registerCrate(ItemStack stack, String uid); + /** + * Makes a new crate, registers it with the game registry with uid, + * and creates crating and uncrating recipes for the Carpenter. + * The icon is rendered automatically from the contained item. + * + * Can only be called during the Init stage. + */ + void registerCrate(Item item, String uid); - /** - * Same as the above, but uses the ore dictionary for the Carpenter crating recipe. - */ - void registerCrateUsingOreDict(Item item, String uid); - void registerCrateUsingOreDict(Block block, String uid); - void registerCrateUsingOreDict(ItemStack stack, String uid); + void registerCrate(Block block, String uid); + void registerCrate(ItemStack stack, String uid); + + /** + * Same as the above, but uses the ore dictionary for the Carpenter crating recipe. + */ + void registerCrateUsingOreDict(Item item, String uid); + + void registerCrateUsingOreDict(Block block, String uid); + + void registerCrateUsingOreDict(ItemStack stack, String uid); } diff --git a/src/main/java/forestry/api/storage/StorageManager.java b/src/main/java/forestry/api/storage/StorageManager.java index ef4ec4cf8..8f8c6b7e3 100644 --- a/src/main/java/forestry/api/storage/StorageManager.java +++ b/src/main/java/forestry/api/storage/StorageManager.java @@ -7,6 +7,5 @@ package forestry.api.storage; public class StorageManager { - public static ICrateRegistry crateRegistry; - + public static ICrateRegistry crateRegistry; } diff --git a/src/main/java/forestry/api/storage/package-info.java b/src/main/java/forestry/api/storage/package-info.java index 3d0c1e9d3..88f854490 100644 --- a/src/main/java/forestry/api/storage/package-info.java +++ b/src/main/java/forestry/api/storage/package-info.java @@ -1,8 +1,9 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ -@API(apiVersion="3.0.0", owner="ForestryAPI|core", provides="ForestryAPI|storage") +@API(apiVersion = "3.0.0", owner = "ForestryAPI|core", provides = "ForestryAPI|storage") package forestry.api.storage; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/api/world/ITreeGenData.java b/src/main/java/forestry/api/world/ITreeGenData.java index 6fc114f07..f42c013f2 100644 --- a/src/main/java/forestry/api/world/ITreeGenData.java +++ b/src/main/java/forestry/api/world/ITreeGenData.java @@ -1,34 +1,32 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.world; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.util.ForgeDirection; - import forestry.api.arboriculture.ITreeGenome; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; public interface ITreeGenData { - int getGirth(World world, int x, int y, int z); + int getGirth(World world, int x, int y, int z); - float getHeightModifier(); + float getHeightModifier(); - boolean canGrow(World world, int x, int y, int z, int expectedGirth, int expectedHeight); + boolean canGrow(World world, int x, int y, int z, int expectedGirth, int expectedHeight); - void setLeaves(World world, GameProfile owner, int x, int y, int z); - void setLeavesDecorative(World world, GameProfile owner, int x, int y, int z); + void setLeaves(World world, GameProfile owner, int x, int y, int z); - void setLogBlock(World world, int x, int y, int z, ForgeDirection facing); + void setLeavesDecorative(World world, GameProfile owner, int x, int y, int z); - boolean allowsFruitBlocks(); + void setLogBlock(World world, int x, int y, int z, ForgeDirection facing); - boolean trySpawnFruitBlock(World world, int x, int y, int z); + boolean allowsFruitBlocks(); - ITreeGenome getGenome(); + boolean trySpawnFruitBlock(World world, int x, int y, int z); + + ITreeGenome getGenome(); } diff --git a/src/main/java/forestry/api/world/IWorldGenInterface.java b/src/main/java/forestry/api/world/IWorldGenInterface.java index b82b32277..636895fa2 100644 --- a/src/main/java/forestry/api/world/IWorldGenInterface.java +++ b/src/main/java/forestry/api/world/IWorldGenInterface.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.world; @@ -13,14 +13,14 @@ import net.minecraft.world.gen.feature.WorldGenerator; @Deprecated public interface IWorldGenInterface { - /** - * Retrieves generators for trees identified by a given string. - * - * Returned generator classes take an {@link ITreeGenData} in the constructor. - * - * @param ident - * Unique identifier for tree type. Forestry's convention is 'treeSpecies', i.e. 'treeBaobab', 'treeSequoia'. - * @return All generators matching the given ident. - */ - Class[] getTreeGenerators(String ident); + /** + * Retrieves generators for trees identified by a given string. + * + * Returned generator classes take an {@link ITreeGenData} in the constructor. + * + * @param ident + * Unique identifier for tree type. Forestry's convention is 'treeSpecies', i.e. 'treeBaobab', 'treeSequoia'. + * @return All generators matching the given ident. + */ + Class[] getTreeGenerators(String ident); } diff --git a/src/main/java/forestry/api/world/WorldGenManager.java b/src/main/java/forestry/api/world/WorldGenManager.java index 528371817..927539a01 100644 --- a/src/main/java/forestry/api/world/WorldGenManager.java +++ b/src/main/java/forestry/api/world/WorldGenManager.java @@ -1,6 +1,6 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.world; @@ -10,5 +10,5 @@ package forestry.api.world; */ @Deprecated public class WorldGenManager { - public static IWorldGenInterface worldgenInterface; + public static IWorldGenInterface worldgenInterface; } diff --git a/src/main/java/forestry/api/world/package-info.java b/src/main/java/forestry/api/world/package-info.java index 8e6da0c27..186520eb7 100644 --- a/src/main/java/forestry/api/world/package-info.java +++ b/src/main/java/forestry/api/world/package-info.java @@ -1,8 +1,9 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ -@API(apiVersion="2.1.0", owner="ForestryAPI|core", provides="ForestryAPI|world") +@API(apiVersion = "2.1.0", owner = "ForestryAPI|core", provides = "ForestryAPI|world") package forestry.api.world; + import cpw.mods.fml.common.API; diff --git a/src/main/java/forestry/apiculture/AlvearyBeeModifier.java b/src/main/java/forestry/apiculture/AlvearyBeeModifier.java index c3f8f3a9b..7cfc14e29 100644 --- a/src/main/java/forestry/apiculture/AlvearyBeeModifier.java +++ b/src/main/java/forestry/apiculture/AlvearyBeeModifier.java @@ -1,21 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture; - -import forestry.api.apiculture.DefaultBeeModifier; -import forestry.api.apiculture.IBeeGenome; - -public class AlvearyBeeModifier extends DefaultBeeModifier { - @Override - public float getTerritoryModifier(IBeeGenome genome, float currentModifier) { - return 2.0f; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture; + +import forestry.api.apiculture.DefaultBeeModifier; +import forestry.api.apiculture.IBeeGenome; + +public class AlvearyBeeModifier extends DefaultBeeModifier { + @Override + public float getTerritoryModifier(IBeeGenome genome, float currentModifier) { + return 2.0f; + } +} diff --git a/src/main/java/forestry/apiculture/ApiaryBeeListener.java b/src/main/java/forestry/apiculture/ApiaryBeeListener.java index f2e0b3541..6df2f2247 100644 --- a/src/main/java/forestry/apiculture/ApiaryBeeListener.java +++ b/src/main/java/forestry/apiculture/ApiaryBeeListener.java @@ -1,28 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture; - -import forestry.api.apiculture.DefaultBeeListener; -import forestry.apiculture.inventory.IApiaryInventory; - -public class ApiaryBeeListener extends DefaultBeeListener { - private final IApiary apiary; - - public ApiaryBeeListener(IApiary apiary) { - this.apiary = apiary; - } - - @Override - public void wearOutEquipment(int amount) { - IApiaryInventory apiaryInventory = apiary.getApiaryInventory(); - apiaryInventory.wearOutFrames(apiary, amount); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture; + +import forestry.api.apiculture.DefaultBeeListener; +import forestry.apiculture.inventory.IApiaryInventory; + +public class ApiaryBeeListener extends DefaultBeeListener { + private final IApiary apiary; + + public ApiaryBeeListener(IApiary apiary) { + this.apiary = apiary; + } + + @Override + public void wearOutEquipment(int amount) { + IApiaryInventory apiaryInventory = apiary.getApiaryInventory(); + apiaryInventory.wearOutFrames(apiary, amount); + } +} diff --git a/src/main/java/forestry/apiculture/ApiaryBeeModifier.java b/src/main/java/forestry/apiculture/ApiaryBeeModifier.java index 11219b096..37acca238 100644 --- a/src/main/java/forestry/apiculture/ApiaryBeeModifier.java +++ b/src/main/java/forestry/apiculture/ApiaryBeeModifier.java @@ -1,21 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture; - -import forestry.api.apiculture.DefaultBeeModifier; -import forestry.api.apiculture.IBeeGenome; - -public class ApiaryBeeModifier extends DefaultBeeModifier { - @Override - public float getProductionModifier(IBeeGenome genome, float currentModifier) { - return 0.1f; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture; + +import forestry.api.apiculture.DefaultBeeModifier; +import forestry.api.apiculture.IBeeGenome; + +public class ApiaryBeeModifier extends DefaultBeeModifier { + @Override + public float getProductionModifier(IBeeGenome genome, float currentModifier) { + return 0.1f; + } +} diff --git a/src/main/java/forestry/apiculture/ArmorApiaristHelper.java b/src/main/java/forestry/apiculture/ArmorApiaristHelper.java index 6b4fd448e..f26e5d91c 100644 --- a/src/main/java/forestry/apiculture/ArmorApiaristHelper.java +++ b/src/main/java/forestry/apiculture/ArmorApiaristHelper.java @@ -1,69 +1,68 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture; - -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import forestry.api.apiculture.IArmorApiarist; -import forestry.api.apiculture.IArmorApiaristHelper; - -public class ArmorApiaristHelper implements IArmorApiaristHelper { - - @Override - public boolean isArmorApiarist(ItemStack stack, EntityLivingBase entity, String cause, boolean doProtect) { - if (stack == null) { - return false; - } - - Item item = stack.getItem(); - if (!(item instanceof IArmorApiarist)) { - return false; - } - - IArmorApiarist armorApiarist = (IArmorApiarist) item; - try { - return armorApiarist.protectEntity(entity, stack, cause, doProtect); - } catch (Throwable ignored) { // protectEntity is new to the API and may not be implemented by the armor - if (entity instanceof EntityPlayer) { - return armorApiarist.protectPlayer((EntityPlayer) entity, stack, cause, doProtect); - } else { - return true; // fallback on assuming IArmorApiarist will protect the entity - } - } - } - - @Override - public int wearsItems(EntityLivingBase entity, String cause, boolean doProtect) { - int count = 0; - - for (int i = 1; i <= 4; i++) { - ItemStack armorItem = entity.getEquipmentInSlot(i); - if (isArmorApiarist(armorItem, entity, cause, doProtect)) { - count++; - } - } - - return count; - } - - @Override - public boolean isArmorApiarist(ItemStack stack, EntityPlayer player, String cause, boolean doProtect) { - return isArmorApiarist(stack, (EntityLivingBase) player, cause, doProtect); - } - - @Override - public int wearsItems(EntityPlayer player, String cause, boolean doProtect) { - return wearsItems((EntityLivingBase) player, cause, doProtect); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture; + +import forestry.api.apiculture.IArmorApiarist; +import forestry.api.apiculture.IArmorApiaristHelper; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +public class ArmorApiaristHelper implements IArmorApiaristHelper { + + @Override + public boolean isArmorApiarist(ItemStack stack, EntityLivingBase entity, String cause, boolean doProtect) { + if (stack == null) { + return false; + } + + Item item = stack.getItem(); + if (!(item instanceof IArmorApiarist)) { + return false; + } + + IArmorApiarist armorApiarist = (IArmorApiarist) item; + try { + return armorApiarist.protectEntity(entity, stack, cause, doProtect); + } catch (Throwable ignored) { // protectEntity is new to the API and may not be implemented by the armor + if (entity instanceof EntityPlayer) { + return armorApiarist.protectPlayer((EntityPlayer) entity, stack, cause, doProtect); + } else { + return true; // fallback on assuming IArmorApiarist will protect the entity + } + } + } + + @Override + public int wearsItems(EntityLivingBase entity, String cause, boolean doProtect) { + int count = 0; + + for (int i = 1; i <= 4; i++) { + ItemStack armorItem = entity.getEquipmentInSlot(i); + if (isArmorApiarist(armorItem, entity, cause, doProtect)) { + count++; + } + } + + return count; + } + + @Override + public boolean isArmorApiarist(ItemStack stack, EntityPlayer player, String cause, boolean doProtect) { + return isArmorApiarist(stack, (EntityLivingBase) player, cause, doProtect); + } + + @Override + public int wearsItems(EntityPlayer player, String cause, boolean doProtect) { + return wearsItems((EntityLivingBase) player, cause, doProtect); + } +} diff --git a/src/main/java/forestry/apiculture/BeeHousingListener.java b/src/main/java/forestry/apiculture/BeeHousingListener.java index f24d8deb1..343cba868 100644 --- a/src/main/java/forestry/apiculture/BeeHousingListener.java +++ b/src/main/java/forestry/apiculture/BeeHousingListener.java @@ -1,49 +1,48 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture; - -import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeeListener; -import forestry.api.genetics.IIndividual; - -public class BeeHousingListener implements IBeeListener { - private final IBeeHousing beeHousing; - - public BeeHousingListener(IBeeHousing beeHousing) { - this.beeHousing = beeHousing; - } - - @Override - public void wearOutEquipment(int amount) { - for (IBeeListener beeListener : beeHousing.getBeeListeners()) { - beeListener.wearOutEquipment(amount); - } - } - - @Override - public void onQueenDeath() { - for (IBeeListener beeListener : beeHousing.getBeeListeners()) { - beeListener.onQueenDeath(); - } - } - - @Override - public boolean onPollenRetrieved(IIndividual pollen) { - for (IBeeListener beeListener : beeHousing.getBeeListeners()) { - if (beeListener.onPollenRetrieved(pollen)) { - return true; - } - } - - return false; - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture; + +import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeeListener; +import forestry.api.genetics.IIndividual; + +public class BeeHousingListener implements IBeeListener { + private final IBeeHousing beeHousing; + + public BeeHousingListener(IBeeHousing beeHousing) { + this.beeHousing = beeHousing; + } + + @Override + public void wearOutEquipment(int amount) { + for (IBeeListener beeListener : beeHousing.getBeeListeners()) { + beeListener.wearOutEquipment(amount); + } + } + + @Override + public void onQueenDeath() { + for (IBeeListener beeListener : beeHousing.getBeeListeners()) { + beeListener.onQueenDeath(); + } + } + + @Override + public boolean onPollenRetrieved(IIndividual pollen) { + for (IBeeListener beeListener : beeHousing.getBeeListeners()) { + if (beeListener.onPollenRetrieved(pollen)) { + return true; + } + } + + return false; + } +} diff --git a/src/main/java/forestry/apiculture/BeeHousingModifier.java b/src/main/java/forestry/apiculture/BeeHousingModifier.java index ede25600b..628c8b445 100644 --- a/src/main/java/forestry/apiculture/BeeHousingModifier.java +++ b/src/main/java/forestry/apiculture/BeeHousingModifier.java @@ -1,117 +1,117 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture; - -import forestry.api.apiculture.IBeeGenome; -import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeeModifier; - -public class BeeHousingModifier implements IBeeModifier { - private final IBeeHousing beeHousing; - - public BeeHousingModifier(IBeeHousing beeHousing) { - this.beeHousing = beeHousing; - } - - @Override - public float getTerritoryModifier(IBeeGenome genome, final float currentModifier) { - float modifierValue = 1.0f; - for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { - modifierValue *= modifier.getTerritoryModifier(genome, modifierValue * currentModifier); - } - return modifierValue; - } - - @Override - public float getMutationModifier(IBeeGenome genome, IBeeGenome mate, final float currentModifier) { - float modifierValue = 1.0f; - for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { - modifierValue *= modifier.getMutationModifier(genome, mate, modifierValue * currentModifier); - } - return modifierValue; - } - - @Override - public float getLifespanModifier(IBeeGenome genome, IBeeGenome mate, final float currentModifier) { - float modifierValue = 1.0f; - for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { - modifierValue *= modifier.getLifespanModifier(genome, mate, modifierValue * currentModifier); - } - return modifierValue; - } - - @Override - public float getProductionModifier(IBeeGenome genome, final float currentModifier) { - float modifierValue = 1.0f; - for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { - modifierValue *= modifier.getProductionModifier(genome, modifierValue * currentModifier); - } - return modifierValue; - } - - @Override - public float getFloweringModifier(IBeeGenome genome, final float currentModifier) { - float modifierValue = 1.0f; - for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { - modifierValue *= modifier.getFloweringModifier(genome, modifierValue * currentModifier); - } - return modifierValue; - } - - @Override - public float getGeneticDecay(IBeeGenome genome, final float currentModifier) { - float modifierValue = 1.0f; - for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { - modifierValue *= modifier.getGeneticDecay(genome, modifierValue * currentModifier); - } - return modifierValue; - } - - @Override - public boolean isSealed() { - for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { - if (modifier.isSealed()) { - return true; - } - } - return false; - } - - @Override - public boolean isSelfLighted() { - for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { - if (modifier.isSelfLighted()) { - return true; - } - } - return false; - } - - @Override - public boolean isSunlightSimulated() { - for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { - if (modifier.isSunlightSimulated()) { - return true; - } - } - return false; - } - - @Override - public boolean isHellish() { - for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { - if (modifier.isHellish()) { - return true; - } - } - return false; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture; + +import forestry.api.apiculture.IBeeGenome; +import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeeModifier; + +public class BeeHousingModifier implements IBeeModifier { + private final IBeeHousing beeHousing; + + public BeeHousingModifier(IBeeHousing beeHousing) { + this.beeHousing = beeHousing; + } + + @Override + public float getTerritoryModifier(IBeeGenome genome, final float currentModifier) { + float modifierValue = 1.0f; + for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { + modifierValue *= modifier.getTerritoryModifier(genome, modifierValue * currentModifier); + } + return modifierValue; + } + + @Override + public float getMutationModifier(IBeeGenome genome, IBeeGenome mate, final float currentModifier) { + float modifierValue = 1.0f; + for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { + modifierValue *= modifier.getMutationModifier(genome, mate, modifierValue * currentModifier); + } + return modifierValue; + } + + @Override + public float getLifespanModifier(IBeeGenome genome, IBeeGenome mate, final float currentModifier) { + float modifierValue = 1.0f; + for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { + modifierValue *= modifier.getLifespanModifier(genome, mate, modifierValue * currentModifier); + } + return modifierValue; + } + + @Override + public float getProductionModifier(IBeeGenome genome, final float currentModifier) { + float modifierValue = 1.0f; + for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { + modifierValue *= modifier.getProductionModifier(genome, modifierValue * currentModifier); + } + return modifierValue; + } + + @Override + public float getFloweringModifier(IBeeGenome genome, final float currentModifier) { + float modifierValue = 1.0f; + for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { + modifierValue *= modifier.getFloweringModifier(genome, modifierValue * currentModifier); + } + return modifierValue; + } + + @Override + public float getGeneticDecay(IBeeGenome genome, final float currentModifier) { + float modifierValue = 1.0f; + for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { + modifierValue *= modifier.getGeneticDecay(genome, modifierValue * currentModifier); + } + return modifierValue; + } + + @Override + public boolean isSealed() { + for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { + if (modifier.isSealed()) { + return true; + } + } + return false; + } + + @Override + public boolean isSelfLighted() { + for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { + if (modifier.isSelfLighted()) { + return true; + } + } + return false; + } + + @Override + public boolean isSunlightSimulated() { + for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { + if (modifier.isSunlightSimulated()) { + return true; + } + } + return false; + } + + @Override + public boolean isHellish() { + for (IBeeModifier modifier : beeHousing.getBeeModifiers()) { + if (modifier.isHellish()) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/forestry/apiculture/BeehouseBeeModifier.java b/src/main/java/forestry/apiculture/BeehouseBeeModifier.java index 2e717273e..37fda3ccc 100644 --- a/src/main/java/forestry/apiculture/BeehouseBeeModifier.java +++ b/src/main/java/forestry/apiculture/BeehouseBeeModifier.java @@ -1,46 +1,46 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture; - -import forestry.api.apiculture.DefaultBeeModifier; -import forestry.api.apiculture.IBeeGenome; - -public class BeehouseBeeModifier extends DefaultBeeModifier { - @Override - public float getTerritoryModifier(IBeeGenome genome, float currentModifier) { - return 1.0f; - } - - @Override - public float getProductionModifier(IBeeGenome genome, float currentModifier) { - return 0.25f; - } - - @Override - public float getMutationModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { - return 0.0f; - } - - @Override - public float getLifespanModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { - return 3.0f; - } - - @Override - public float getFloweringModifier(IBeeGenome genome, float currentModifier) { - return 3.0f; - } - - @Override - public float getGeneticDecay(IBeeGenome genome, float currentModifier) { - return 0.0f; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture; + +import forestry.api.apiculture.DefaultBeeModifier; +import forestry.api.apiculture.IBeeGenome; + +public class BeehouseBeeModifier extends DefaultBeeModifier { + @Override + public float getTerritoryModifier(IBeeGenome genome, float currentModifier) { + return 1.0f; + } + + @Override + public float getProductionModifier(IBeeGenome genome, float currentModifier) { + return 0.25f; + } + + @Override + public float getMutationModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { + return 0.0f; + } + + @Override + public float getLifespanModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { + return 3.0f; + } + + @Override + public float getFloweringModifier(IBeeGenome genome, float currentModifier) { + return 3.0f; + } + + @Override + public float getGeneticDecay(IBeeGenome genome, float currentModifier) { + return 0.0f; + } +} diff --git a/src/main/java/forestry/apiculture/BeekeepingLogic.java b/src/main/java/forestry/apiculture/BeekeepingLogic.java index d666ba107..7de89fd91 100755 --- a/src/main/java/forestry/apiculture/BeekeepingLogic.java +++ b/src/main/java/forestry/apiculture/BeekeepingLogic.java @@ -10,21 +10,6 @@ ******************************************************************************/ package forestry.apiculture; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Set; -import java.util.Stack; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.IApiaristTracker; @@ -48,476 +33,487 @@ import forestry.core.network.IStreamable; import forestry.core.proxy.Proxies; import forestry.core.utils.Log; import forestry.plugins.PluginApiculture; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Set; +import java.util.Stack; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { - private static final int totalBreedingTime = Constants.APIARY_BREEDING_TIME; - - private final IBeeHousing housing; - private final IBeeModifier beeModifier; - private final IBeeListener beeListener; - - private int beeProgress; - private int beeProgressMax; - - private int queenWorkCycleThrottle; - private IEffectData effectData[] = new IEffectData[2]; - - private final Stack spawn = new Stack<>(); - - private final HasFlowersCache hasFlowersCache = new HasFlowersCache(); - private final QueenCanWorkCache queenCanWorkCache = new QueenCanWorkCache(); - private final PollenHandler pollenHandler = new PollenHandler(); - - // Client - private boolean active; - private IBee queen; - private ItemStack queenStack; // used to detect server changes and sync clientQueen - - public BeekeepingLogic(IBeeHousing housing) { - this.housing = housing; - this.beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - this.beeListener = BeeManager.beeRoot.createBeeHousingListener(housing); - } - - // / SAVING & LOADING - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - beeProgress = nbttagcompound.getInteger("BreedingTime"); - queenWorkCycleThrottle = nbttagcompound.getInteger("Throttle"); - - NBTTagCompound queenNBT = nbttagcompound.getCompoundTag("queen"); - queenStack = ItemStack.loadItemStackFromNBT(queenNBT); - queen = BeeManager.beeRoot.getMember(queenStack); - - setActive(nbttagcompound.getBoolean("Active")); - - hasFlowersCache.readFromNBT(nbttagcompound); - - NBTTagList nbttaglist = nbttagcompound.getTagList("Offspring", 10); - for (int i = 0; i < nbttaglist.tagCount(); i++) { - spawn.add(ItemStack.loadItemStackFromNBT(nbttaglist.getCompoundTagAt(i))); - } - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setInteger("BreedingTime", beeProgress); - nbttagcompound.setInteger("Throttle", queenWorkCycleThrottle); - - if (queenStack != null) { - NBTTagCompound queenNBT = new NBTTagCompound(); - queenStack.writeToNBT(queenNBT); - nbttagcompound.setTag("queen", queenNBT); - } - - nbttagcompound.setBoolean("Active", active); - - hasFlowersCache.writeToNBT(nbttagcompound); - - Stack spawnCopy = new Stack<>(); - if (spawn.size()<128) - spawnCopy.addAll(spawn); - else - for (byte b=0;b<128;++b) - spawnCopy.add(spawn.get(b)); - NBTTagList nbttaglist = new NBTTagList(); - while (!spawnCopy.isEmpty() && spawnCopy.size()<=128) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - spawnCopy.pop().writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); - } - nbttagcompound.setTag("Offspring", nbttaglist); - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeBoolean(active); - if (active) { - data.writeItemStack(queenStack); - } - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - boolean active = data.readBoolean(); - setActive(active); - if (active) { - queenStack = data.readItemStack(); - queen = BeeManager.beeRoot.getMember(queenStack); - } - } - - /* Activatable */ - private void setActive(boolean active) { - if (this.active == active) { - return; - } - this.active = active; - - syncToClient(); - } - - /* UPDATING */ - - @Override - public boolean canWork() { - - IErrorLogic errorLogic = housing.getErrorLogic(); - errorLogic.clearErrors(); - - IBeeHousingInventory beeInventory = housing.getBeeInventory(); - - boolean hasSpace = addPendingProducts(beeInventory, spawn); - errorLogic.setCondition(!hasSpace, EnumErrorCode.NO_SPACE_INVENTORY); - - ItemStack queenStack = beeInventory.getQueen(); - EnumBeeType beeType = BeeManager.beeRoot.getType(queenStack); - // check if we're breeding - if (beeType == EnumBeeType.PRINCESS) { - boolean hasDrone = BeeManager.beeRoot.isDrone(beeInventory.getDrone()); - errorLogic.setCondition(!hasDrone, EnumErrorCode.NO_DRONE); - - setActive(false); // not active (no bee FX) when we are breeding - return !errorLogic.hasErrors(); - } - - if (beeType == EnumBeeType.QUEEN) { - if (!isQueenAlive(queenStack)) { - IBee dyingQueen = BeeManager.beeRoot.getMember(queenStack); - Collection spawned = killQueen(dyingQueen, housing, beeListener); - spawn.addAll(spawned); - queenStack = null; - } - } else { - queenStack = null; - } - - if (!ItemStack.areItemStacksEqual(this.queenStack, queenStack)) { - this.queen = BeeManager.beeRoot.getMember(queenStack); - this.queenStack = queenStack; - } - - if (errorLogic.setCondition(queen == null, EnumErrorCode.NO_QUEEN)) { - setActive(false); - beeProgress = 0; - return false; - } - - Set queenErrors = queenCanWorkCache.queenCanWork(queen, housing); - for (IErrorState errorState : queenErrors) { - errorLogic.setCondition(true, errorState); - } - - boolean hasFlowers = hasFlowersCache.hasFlowers(queen, housing); - errorLogic.setCondition(!hasFlowers, EnumErrorCode.NO_FLOWER); - - boolean canWork = !errorLogic.hasErrors(); - setActive(canWork); - return canWork; - } - - @Override - public void doWork() { - IBeeHousingInventory beeInventory = housing.getBeeInventory(); - ItemStack queenStack = beeInventory.getQueen(); - EnumBeeType beeType = BeeManager.beeRoot.getType(queenStack); - if (beeType == EnumBeeType.PRINCESS) { - tickBreed(); - } else { - queenWorkTick(queen); - } - } - - private void queenWorkTick(IBee queen) { - if (queen == null) { - return; - } - - // Effects only fire when queen can work. - effectData = queen.doEffect(effectData, housing); - - // Work cycles are throttled, rather than occurring every game tick. - queenWorkCycleThrottle++; - if (queenWorkCycleThrottle >= PluginApiculture.ticksPerBeeWorkCycle) { - queenWorkCycleThrottle = 0; - - doProduction(queen, housing, beeListener); - queen.plantFlowerRandom(housing); - pollenHandler.doPollination(queen, housing, beeListener); - - // Age the queen - float lifespanModifier = beeModifier.getLifespanModifier(queen.getGenome(), queen.getMate(), 1.0f); - queen.age(housing.getWorld(), lifespanModifier); - - // Write the changed queen back into the item stack. - NBTTagCompound nbttagcompound = new NBTTagCompound(); - queen.writeToNBT(nbttagcompound); - housing.getBeeInventory().getQueen().setTagCompound(nbttagcompound); - } - - beeProgress = queen.getHealth(); - beeProgressMax = queen.getMaxHealth(); - } - - private static void doProduction(IBee queen, IBeeHousing beeHousing, IBeeListener beeListener) { - // Produce and add stacks - ItemStack[] products = queen.produceStacks(beeHousing); - if (products == null) { - return; - } - beeListener.wearOutEquipment(1); - - IBeeHousingInventory beeInventory = beeHousing.getBeeInventory(); - - for (ItemStack stack : products) { - beeInventory.addProduct(stack, false); - } - } - - private static boolean addPendingProducts(IBeeHousingInventory beeInventory, Stack spawn) { - boolean housingHasSpace = true; - - while (!spawn.isEmpty()) { - ItemStack next = spawn.peek(); - if (beeInventory.addProduct(next, true)) { - spawn.pop(); - } else { - housingHasSpace = false; - break; - } - } - - return housingHasSpace; - } - - /** Checks if a queen is alive. Much faster than reading the whole bee nbt */ - private static boolean isQueenAlive(ItemStack queenStack) { - if (queenStack == null) { - return false; - } - NBTTagCompound nbtTagCompound = queenStack.getTagCompound(); - if (nbtTagCompound == null) { - return false; - } - int health = nbtTagCompound.getInteger("Health"); - return health > 0; - } - - // / BREEDING - private void tickBreed() { - beeProgressMax = totalBreedingTime; - - IBeeHousingInventory beeInventory = housing.getBeeInventory(); - - ItemStack droneStack = beeInventory.getDrone(); - ItemStack princessStack = beeInventory.getQueen(); - - EnumBeeType droneType = BeeManager.beeRoot.getType(droneStack); - EnumBeeType princessType = BeeManager.beeRoot.getType(princessStack); - if (droneType != EnumBeeType.DRONE || princessType != EnumBeeType.PRINCESS) { - beeProgress = 0; - return; - } - - if (beeProgress < totalBreedingTime) { - beeProgress++; - } - if (beeProgress < totalBreedingTime) { - return; - } - - // Mate and replace princess with queen - IBee princess = BeeManager.beeRoot.getMember(princessStack); - IBee drone = BeeManager.beeRoot.getMember(droneStack); - princess.mate(drone); - - NBTTagCompound nbttagcompound = new NBTTagCompound(); - princess.writeToNBT(nbttagcompound); - queenStack = new ItemStack(PluginApiculture.items.beeQueenGE); - queenStack.setTagCompound(nbttagcompound); - - beeInventory.setQueen(queenStack); - - // Register the new queen with the breeding tracker - BeeManager.beeRoot.getBreedingTracker(housing.getWorld(), housing.getOwner()).registerQueen(princess); - - // Remove drone - beeInventory.getDrone().stackSize--; - if (beeInventory.getDrone().stackSize <= 0) { - beeInventory.setDrone(null); - } - - // Reset breeding time - queen = princess; - beeProgress = princess.getHealth(); - beeProgressMax = princess.getMaxHealth(); - } - - private static Collection killQueen(IBee queen, IBeeHousing beeHousing, IBeeListener beeListener) { - if (queen == null) { - return Collections.emptySet(); - } - - IBeeHousingInventory beeInventory = beeHousing.getBeeInventory(); - - Collection spawn; - - if (queen.canSpawn()) { - spawn = spawnOffspring(queen, beeHousing); - beeListener.onQueenDeath(); - beeInventory.getQueen().stackSize = 0; - beeInventory.setQueen(null); - } else { - Log.warning("Tried to spawn offspring off an unmated queen. Devolving her to a princess."); - - ItemStack convert = new ItemStack(PluginApiculture.items.beePrincessGE); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - queen.writeToNBT(nbttagcompound); - convert.setTagCompound(nbttagcompound); - - spawn = Collections.singleton(convert); - beeInventory.setQueen(null); - } - - return spawn; - } - - /** - * Creates the succeeding princess and between one and three drones. - */ - private static Collection spawnOffspring(IBee queen, IBeeHousing beeHousing) { - - World world = beeHousing.getWorld(); - - Stack offspring = new Stack<>(); - IApiaristTracker breedingTracker = BeeManager.beeRoot.getBreedingTracker(world, beeHousing.getOwner()); - - // Princess - boolean secondPrincess = world.rand.nextInt(10000) < PluginApiculture.getSecondPrincessChance() * 100; - int count = secondPrincess ? 2 : 1; - while (count > 0) { - count--; - IBee heiress = queen.spawnPrincess(beeHousing); - if (heiress != null) { - ItemStack princess = BeeManager.beeRoot.getMemberStack(heiress, EnumBeeType.PRINCESS.ordinal()); - breedingTracker.registerPrincess(heiress); - offspring.push(princess); - } - } - - // Drones - IBee[] drones = queen.spawnDrones(beeHousing); - for (IBee drone : drones) { - ItemStack droneStack = BeeManager.beeRoot.getMemberStack(drone, EnumBeeType.DRONE.ordinal()); - breedingTracker.registerDrone(drone); - offspring.push(droneStack); - } - - IBeeHousingInventory beeInventory = beeHousing.getBeeInventory(); - - Collection spawn = new ArrayList<>(); - - while (!offspring.isEmpty()) { - ItemStack spawned = offspring.pop(); - if (!beeInventory.addProduct(spawned, true)) { - spawn.add(spawned); - } - } - - return spawn; - } - - /* CLIENT */ - - @Override - public void syncToClient() { - World world = housing.getWorld(); - if (world != null && !world.isRemote) { - if (housing instanceof Entity) { - Proxies.net.sendNetworkPacket(new PacketBeeLogicActiveEntity(housing, (Entity) housing), world); - } else { - Proxies.net.sendNetworkPacket(new PacketBeeLogicActive(housing), world); - } - } - } - - @Override - public void syncToClient(EntityPlayerMP player) { - World world = housing.getWorld(); - if (world != null && !world.isRemote) { - if (housing instanceof TileEntity) { - Proxies.net.sendToPlayer(new PacketBeeLogicActive(housing), player); - } else if (housing instanceof Entity) { - Proxies.net.sendToPlayer(new PacketBeeLogicActiveEntity(housing, (Entity) housing), player); - } - } - } - - @Override - public int getBeeProgressPercent() { - if (beeProgressMax == 0) { - return 0; - } - - return Math.round(beeProgress * 100f / beeProgressMax); - } - - @Override - public boolean canDoBeeFX() { - return active; - } - - @Override - public void doBeeFX() { - if (queen != null) { - queen.doFX(effectData, housing); - } - } - - private static class QueenCanWorkCache { - private static final int ticksPerCheckQueenCanWork = 10; - - private Set queenCanWorkCached = Collections.emptySet(); - private int queenCanWorkCooldown = 0; - - public Set queenCanWork(IBee queen, IBeeHousing beeHousing) { - if (queenCanWorkCooldown <= 0) { - queenCanWorkCached = queen.getCanWork(beeHousing); - queenCanWorkCooldown = ticksPerCheckQueenCanWork; - } else { - queenCanWorkCooldown--; - } - - return queenCanWorkCached; - } - } - - private static class PollenHandler { - private static final int MAX_POLLINATION_ATTEMPTS = 20; - - private IIndividual pollen; - private int attemptedPollinations = 0; - - public void doPollination(IBee queen, IBeeHousing beeHousing, IBeeListener beeListener) { - // Get pollen if none available yet - if (pollen == null) { - attemptedPollinations = 0; - pollen = queen.retrievePollen(beeHousing); - if (pollen != null) { - if (beeListener.onPollenRetrieved(pollen)) { - pollen = null; - } - } - } - - if (pollen != null) { - attemptedPollinations++; - if (queen.pollinateRandom(beeHousing, pollen) || attemptedPollinations >= MAX_POLLINATION_ATTEMPTS) { - pollen = null; - } - } - } - } - + private static final int totalBreedingTime = Constants.APIARY_BREEDING_TIME; + + private final IBeeHousing housing; + private final IBeeModifier beeModifier; + private final IBeeListener beeListener; + + private int beeProgress; + private int beeProgressMax; + + private int queenWorkCycleThrottle; + private IEffectData effectData[] = new IEffectData[2]; + + private final Stack spawn = new Stack<>(); + + private final HasFlowersCache hasFlowersCache = new HasFlowersCache(); + private final QueenCanWorkCache queenCanWorkCache = new QueenCanWorkCache(); + private final PollenHandler pollenHandler = new PollenHandler(); + + // Client + private boolean active; + private IBee queen; + private ItemStack queenStack; // used to detect server changes and sync clientQueen + + public BeekeepingLogic(IBeeHousing housing) { + this.housing = housing; + this.beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); + this.beeListener = BeeManager.beeRoot.createBeeHousingListener(housing); + } + + // / SAVING & LOADING + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + beeProgress = nbttagcompound.getInteger("BreedingTime"); + queenWorkCycleThrottle = nbttagcompound.getInteger("Throttle"); + + NBTTagCompound queenNBT = nbttagcompound.getCompoundTag("queen"); + queenStack = ItemStack.loadItemStackFromNBT(queenNBT); + queen = BeeManager.beeRoot.getMember(queenStack); + + setActive(nbttagcompound.getBoolean("Active")); + + hasFlowersCache.readFromNBT(nbttagcompound); + + NBTTagList nbttaglist = nbttagcompound.getTagList("Offspring", 10); + for (int i = 0; i < nbttaglist.tagCount(); i++) { + spawn.add(ItemStack.loadItemStackFromNBT(nbttaglist.getCompoundTagAt(i))); + } + } + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setInteger("BreedingTime", beeProgress); + nbttagcompound.setInteger("Throttle", queenWorkCycleThrottle); + + if (queenStack != null) { + NBTTagCompound queenNBT = new NBTTagCompound(); + queenStack.writeToNBT(queenNBT); + nbttagcompound.setTag("queen", queenNBT); + } + + nbttagcompound.setBoolean("Active", active); + + hasFlowersCache.writeToNBT(nbttagcompound); + + Stack spawnCopy = new Stack<>(); + if (spawn.size() < 128) spawnCopy.addAll(spawn); + else for (byte b = 0; b < 128; ++b) spawnCopy.add(spawn.get(b)); + NBTTagList nbttaglist = new NBTTagList(); + while (!spawnCopy.isEmpty() && spawnCopy.size() <= 128) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + spawnCopy.pop().writeToNBT(nbttagcompound1); + nbttaglist.appendTag(nbttagcompound1); + } + nbttagcompound.setTag("Offspring", nbttaglist); + } + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeBoolean(active); + if (active) { + data.writeItemStack(queenStack); + } + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + boolean active = data.readBoolean(); + setActive(active); + if (active) { + queenStack = data.readItemStack(); + queen = BeeManager.beeRoot.getMember(queenStack); + } + } + + /* Activatable */ + private void setActive(boolean active) { + if (this.active == active) { + return; + } + this.active = active; + + syncToClient(); + } + + /* UPDATING */ + + @Override + public boolean canWork() { + + IErrorLogic errorLogic = housing.getErrorLogic(); + errorLogic.clearErrors(); + + IBeeHousingInventory beeInventory = housing.getBeeInventory(); + + boolean hasSpace = addPendingProducts(beeInventory, spawn); + errorLogic.setCondition(!hasSpace, EnumErrorCode.NO_SPACE_INVENTORY); + + ItemStack queenStack = beeInventory.getQueen(); + EnumBeeType beeType = BeeManager.beeRoot.getType(queenStack); + // check if we're breeding + if (beeType == EnumBeeType.PRINCESS) { + boolean hasDrone = BeeManager.beeRoot.isDrone(beeInventory.getDrone()); + errorLogic.setCondition(!hasDrone, EnumErrorCode.NO_DRONE); + + setActive(false); // not active (no bee FX) when we are breeding + return !errorLogic.hasErrors(); + } + + if (beeType == EnumBeeType.QUEEN) { + if (!isQueenAlive(queenStack)) { + IBee dyingQueen = BeeManager.beeRoot.getMember(queenStack); + Collection spawned = killQueen(dyingQueen, housing, beeListener); + spawn.addAll(spawned); + queenStack = null; + } + } else { + queenStack = null; + } + + if (!ItemStack.areItemStacksEqual(this.queenStack, queenStack)) { + this.queen = BeeManager.beeRoot.getMember(queenStack); + this.queenStack = queenStack; + } + + if (errorLogic.setCondition(queen == null, EnumErrorCode.NO_QUEEN)) { + setActive(false); + beeProgress = 0; + return false; + } + + Set queenErrors = queenCanWorkCache.queenCanWork(queen, housing); + for (IErrorState errorState : queenErrors) { + errorLogic.setCondition(true, errorState); + } + + boolean hasFlowers = hasFlowersCache.hasFlowers(queen, housing); + errorLogic.setCondition(!hasFlowers, EnumErrorCode.NO_FLOWER); + + boolean canWork = !errorLogic.hasErrors(); + setActive(canWork); + return canWork; + } + + @Override + public void doWork() { + IBeeHousingInventory beeInventory = housing.getBeeInventory(); + ItemStack queenStack = beeInventory.getQueen(); + EnumBeeType beeType = BeeManager.beeRoot.getType(queenStack); + if (beeType == EnumBeeType.PRINCESS) { + tickBreed(); + } else { + queenWorkTick(queen); + } + } + + private void queenWorkTick(IBee queen) { + if (queen == null) { + return; + } + + // Effects only fire when queen can work. + effectData = queen.doEffect(effectData, housing); + + // Work cycles are throttled, rather than occurring every game tick. + queenWorkCycleThrottle++; + if (queenWorkCycleThrottle >= PluginApiculture.ticksPerBeeWorkCycle) { + queenWorkCycleThrottle = 0; + + doProduction(queen, housing, beeListener); + queen.plantFlowerRandom(housing); + pollenHandler.doPollination(queen, housing, beeListener); + + // Age the queen + float lifespanModifier = beeModifier.getLifespanModifier(queen.getGenome(), queen.getMate(), 1.0f); + queen.age(housing.getWorld(), lifespanModifier); + + // Write the changed queen back into the item stack. + NBTTagCompound nbttagcompound = new NBTTagCompound(); + queen.writeToNBT(nbttagcompound); + housing.getBeeInventory().getQueen().setTagCompound(nbttagcompound); + } + + beeProgress = queen.getHealth(); + beeProgressMax = queen.getMaxHealth(); + } + + private static void doProduction(IBee queen, IBeeHousing beeHousing, IBeeListener beeListener) { + // Produce and add stacks + ItemStack[] products = queen.produceStacks(beeHousing); + if (products == null) { + return; + } + beeListener.wearOutEquipment(1); + + IBeeHousingInventory beeInventory = beeHousing.getBeeInventory(); + + for (ItemStack stack : products) { + beeInventory.addProduct(stack, false); + } + } + + private static boolean addPendingProducts(IBeeHousingInventory beeInventory, Stack spawn) { + boolean housingHasSpace = true; + + while (!spawn.isEmpty()) { + ItemStack next = spawn.peek(); + if (beeInventory.addProduct(next, true)) { + spawn.pop(); + } else { + housingHasSpace = false; + break; + } + } + + return housingHasSpace; + } + + /** Checks if a queen is alive. Much faster than reading the whole bee nbt */ + private static boolean isQueenAlive(ItemStack queenStack) { + if (queenStack == null) { + return false; + } + NBTTagCompound nbtTagCompound = queenStack.getTagCompound(); + if (nbtTagCompound == null) { + return false; + } + int health = nbtTagCompound.getInteger("Health"); + return health > 0; + } + + // / BREEDING + private void tickBreed() { + beeProgressMax = totalBreedingTime; + + IBeeHousingInventory beeInventory = housing.getBeeInventory(); + + ItemStack droneStack = beeInventory.getDrone(); + ItemStack princessStack = beeInventory.getQueen(); + + EnumBeeType droneType = BeeManager.beeRoot.getType(droneStack); + EnumBeeType princessType = BeeManager.beeRoot.getType(princessStack); + if (droneType != EnumBeeType.DRONE || princessType != EnumBeeType.PRINCESS) { + beeProgress = 0; + return; + } + + if (beeProgress < totalBreedingTime) { + beeProgress++; + } + if (beeProgress < totalBreedingTime) { + return; + } + + // Mate and replace princess with queen + IBee princess = BeeManager.beeRoot.getMember(princessStack); + IBee drone = BeeManager.beeRoot.getMember(droneStack); + princess.mate(drone); + + NBTTagCompound nbttagcompound = new NBTTagCompound(); + princess.writeToNBT(nbttagcompound); + queenStack = new ItemStack(PluginApiculture.items.beeQueenGE); + queenStack.setTagCompound(nbttagcompound); + + beeInventory.setQueen(queenStack); + + // Register the new queen with the breeding tracker + BeeManager.beeRoot + .getBreedingTracker(housing.getWorld(), housing.getOwner()) + .registerQueen(princess); + + // Remove drone + beeInventory.getDrone().stackSize--; + if (beeInventory.getDrone().stackSize <= 0) { + beeInventory.setDrone(null); + } + + // Reset breeding time + queen = princess; + beeProgress = princess.getHealth(); + beeProgressMax = princess.getMaxHealth(); + } + + private static Collection killQueen(IBee queen, IBeeHousing beeHousing, IBeeListener beeListener) { + if (queen == null) { + return Collections.emptySet(); + } + + IBeeHousingInventory beeInventory = beeHousing.getBeeInventory(); + + Collection spawn; + + if (queen.canSpawn()) { + spawn = spawnOffspring(queen, beeHousing); + beeListener.onQueenDeath(); + beeInventory.getQueen().stackSize = 0; + beeInventory.setQueen(null); + } else { + Log.warning("Tried to spawn offspring off an unmated queen. Devolving her to a princess."); + + ItemStack convert = new ItemStack(PluginApiculture.items.beePrincessGE); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + queen.writeToNBT(nbttagcompound); + convert.setTagCompound(nbttagcompound); + + spawn = Collections.singleton(convert); + beeInventory.setQueen(null); + } + + return spawn; + } + + /** + * Creates the succeeding princess and between one and three drones. + */ + private static Collection spawnOffspring(IBee queen, IBeeHousing beeHousing) { + + World world = beeHousing.getWorld(); + + Stack offspring = new Stack<>(); + IApiaristTracker breedingTracker = BeeManager.beeRoot.getBreedingTracker(world, beeHousing.getOwner()); + + // Princess + boolean secondPrincess = world.rand.nextInt(10000) < PluginApiculture.getSecondPrincessChance() * 100; + int count = secondPrincess ? 2 : 1; + while (count > 0) { + count--; + IBee heiress = queen.spawnPrincess(beeHousing); + if (heiress != null) { + ItemStack princess = BeeManager.beeRoot.getMemberStack(heiress, EnumBeeType.PRINCESS.ordinal()); + breedingTracker.registerPrincess(heiress); + offspring.push(princess); + } + } + + // Drones + IBee[] drones = queen.spawnDrones(beeHousing); + for (IBee drone : drones) { + ItemStack droneStack = BeeManager.beeRoot.getMemberStack(drone, EnumBeeType.DRONE.ordinal()); + breedingTracker.registerDrone(drone); + offspring.push(droneStack); + } + + IBeeHousingInventory beeInventory = beeHousing.getBeeInventory(); + + Collection spawn = new ArrayList<>(); + + while (!offspring.isEmpty()) { + ItemStack spawned = offspring.pop(); + if (!beeInventory.addProduct(spawned, true)) { + spawn.add(spawned); + } + } + + return spawn; + } + + /* CLIENT */ + + @Override + public void syncToClient() { + World world = housing.getWorld(); + if (world != null && !world.isRemote) { + if (housing instanceof Entity) { + Proxies.net.sendNetworkPacket(new PacketBeeLogicActiveEntity(housing, (Entity) housing), world); + } else { + Proxies.net.sendNetworkPacket(new PacketBeeLogicActive(housing), world); + } + } + } + + @Override + public void syncToClient(EntityPlayerMP player) { + World world = housing.getWorld(); + if (world != null && !world.isRemote) { + if (housing instanceof TileEntity) { + Proxies.net.sendToPlayer(new PacketBeeLogicActive(housing), player); + } else if (housing instanceof Entity) { + Proxies.net.sendToPlayer(new PacketBeeLogicActiveEntity(housing, (Entity) housing), player); + } + } + } + + @Override + public int getBeeProgressPercent() { + if (beeProgressMax == 0) { + return 0; + } + + return Math.round(beeProgress * 100f / beeProgressMax); + } + + @Override + public boolean canDoBeeFX() { + return active; + } + + @Override + public void doBeeFX() { + if (queen != null) { + queen.doFX(effectData, housing); + } + } + + private static class QueenCanWorkCache { + private static final int ticksPerCheckQueenCanWork = 10; + + private Set queenCanWorkCached = Collections.emptySet(); + private int queenCanWorkCooldown = 0; + + public Set queenCanWork(IBee queen, IBeeHousing beeHousing) { + if (queenCanWorkCooldown <= 0) { + queenCanWorkCached = queen.getCanWork(beeHousing); + queenCanWorkCooldown = ticksPerCheckQueenCanWork; + } else { + queenCanWorkCooldown--; + } + + return queenCanWorkCached; + } + } + + private static class PollenHandler { + private static final int MAX_POLLINATION_ATTEMPTS = 20; + + private IIndividual pollen; + private int attemptedPollinations = 0; + + public void doPollination(IBee queen, IBeeHousing beeHousing, IBeeListener beeListener) { + // Get pollen if none available yet + if (pollen == null) { + attemptedPollinations = 0; + pollen = queen.retrievePollen(beeHousing); + if (pollen != null) { + if (beeListener.onPollenRetrieved(pollen)) { + pollen = null; + } + } + } + + if (pollen != null) { + attemptedPollinations++; + if (queen.pollinateRandom(beeHousing, pollen) || attemptedPollinations >= MAX_POLLINATION_ATTEMPTS) { + pollen = null; + } + } + } + } } diff --git a/src/main/java/forestry/apiculture/FakeBeekeepingLogic.java b/src/main/java/forestry/apiculture/FakeBeekeepingLogic.java index 9f0ca1c6d..807777824 100644 --- a/src/main/java/forestry/apiculture/FakeBeekeepingLogic.java +++ b/src/main/java/forestry/apiculture/FakeBeekeepingLogic.java @@ -1,69 +1,54 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.nbt.NBTTagCompound; - -import forestry.api.apiculture.IBeekeepingLogic; - -public class FakeBeekeepingLogic implements IBeekeepingLogic { - public static final FakeBeekeepingLogic instance = new FakeBeekeepingLogic(); - - private FakeBeekeepingLogic() { - - } - - @Override - public boolean canWork() { - return false; - } - - @Override - public void doWork() { - - } - - @Override - public void syncToClient() { - - } - - @Override - public void syncToClient(EntityPlayerMP player) { - - } - - @Override - public int getBeeProgressPercent() { - return 0; - } - - @Override - public boolean canDoBeeFX() { - return false; - } - - @Override - public void doBeeFX() { - - } - - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture; + +import forestry.api.apiculture.IBeekeepingLogic; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; + +public class FakeBeekeepingLogic implements IBeekeepingLogic { + public static final FakeBeekeepingLogic instance = new FakeBeekeepingLogic(); + + private FakeBeekeepingLogic() {} + + @Override + public boolean canWork() { + return false; + } + + @Override + public void doWork() {} + + @Override + public void syncToClient() {} + + @Override + public void syncToClient(EntityPlayerMP player) {} + + @Override + public int getBeeProgressPercent() { + return 0; + } + + @Override + public boolean canDoBeeFX() { + return false; + } + + @Override + public void doBeeFX() {} + + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) {} + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) {} +} diff --git a/src/main/java/forestry/apiculture/HasFlowersCache.java b/src/main/java/forestry/apiculture/HasFlowersCache.java index 6b4a1ae44..8f621f1f1 100644 --- a/src/main/java/forestry/apiculture/HasFlowersCache.java +++ b/src/main/java/forestry/apiculture/HasFlowersCache.java @@ -1,115 +1,119 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture; - -import java.util.Random; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; - -import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.FlowerManager; -import forestry.api.apiculture.IBee; -import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeeModifier; -import forestry.api.core.INBTTagable; -import forestry.api.genetics.IFlowerProvider; -import forestry.core.utils.vect.Vect; -import forestry.plugins.PluginApiculture; - -public class HasFlowersCache implements INBTTagable { - private static final String nbtKey = "hasFlowerCache"; - private static final Random random = new Random(); - private static final int flowerCheckInterval = 128; - - private final int flowerCheckTime = random.nextInt(flowerCheckInterval); - private ChunkCoordinates flowerCoords = null; - private int cooldown = 0; - - public boolean hasFlowers(IBee queen, IBeeHousing beeHousing) { - IFlowerProvider flowerProvider = queen.getGenome().getFlowerProvider(); - String flowerType = flowerProvider.getFlowerType(); - World world = beeHousing.getWorld(); - - if (flowerCoords != null) { - if (world.getTotalWorldTime() % flowerCheckInterval != flowerCheckTime) { - return true; - } - - IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(beeHousing); - ChunkCoordinates housingCoords = beeHousing.getCoordinates(); - - int[] genomeTerritory = queen.getGenome().getTerritory(); - float housingModifier = beeModifier.getTerritoryModifier(queen.getGenome(), 1f); - Vect area = new Vect(genomeTerritory).multiply(housingModifier * 3.0f); - Vect min = new Vect(area).multiply(-0.5f).add(housingCoords); - Vect max = new Vect(area).multiply(0.5f).add(housingCoords); - - if (isFlowerValid(world, flowerType, min, max)) { - return true; - } else { - flowerCoords = null; - cooldown = 0; - } - } - - if (cooldown <= 0) { - flowerCoords = FlowerManager.flowerRegistry.getAcceptedFlowerCoordinates(beeHousing, queen, flowerType); - cooldown = PluginApiculture.ticksPerBeeWorkCycle; - } else { - cooldown--; - } - - return flowerCoords != null; - } - - private boolean isFlowerValid(World world, String flowerType, Vect min, Vect max) { - if (!isFlowerCoordInRange(flowerCoords, min, max)) { - return false; - } - return FlowerManager.flowerRegistry.isAcceptedFlower(flowerType, world, flowerCoords.posX, flowerCoords.posY, flowerCoords.posZ); - } - - private static boolean isFlowerCoordInRange(ChunkCoordinates flowerCoords, Vect min, Vect max) { - return flowerCoords.posX >= min.x && flowerCoords.posX <= max.x && flowerCoords.posY >= min.y && flowerCoords.posY <= max.y && flowerCoords.posZ >= min.z && flowerCoords.posZ <= max.z; - } - - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - if (!nbttagcompound.hasKey(nbtKey)) { - return; - } - - NBTTagCompound hasFlowerCacheNBT = nbttagcompound.getCompoundTag(nbtKey); - if (hasFlowerCacheNBT.hasKey("flowerX")) { - int x = hasFlowerCacheNBT.getInteger("flowerX"); - int y = hasFlowerCacheNBT.getInteger("flowerY"); - int z = hasFlowerCacheNBT.getInteger("flowerZ"); - flowerCoords = new ChunkCoordinates(x, y, z); - } - - cooldown = hasFlowerCacheNBT.getInteger("cooldown"); - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - NBTTagCompound hasFlowerCacheNBT = new NBTTagCompound(); - if (flowerCoords != null) { - hasFlowerCacheNBT.setInteger("flowerX", flowerCoords.posX); - hasFlowerCacheNBT.setInteger("flowerY", flowerCoords.posY); - hasFlowerCacheNBT.setInteger("flowerZ", flowerCoords.posZ); - } - hasFlowerCacheNBT.setInteger("cooldown", cooldown); - - nbttagcompound.setTag(nbtKey, hasFlowerCacheNBT); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture; + +import forestry.api.apiculture.BeeManager; +import forestry.api.apiculture.FlowerManager; +import forestry.api.apiculture.IBee; +import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeeModifier; +import forestry.api.core.INBTTagable; +import forestry.api.genetics.IFlowerProvider; +import forestry.core.utils.vect.Vect; +import forestry.plugins.PluginApiculture; +import java.util.Random; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; + +public class HasFlowersCache implements INBTTagable { + private static final String nbtKey = "hasFlowerCache"; + private static final Random random = new Random(); + private static final int flowerCheckInterval = 128; + + private final int flowerCheckTime = random.nextInt(flowerCheckInterval); + private ChunkCoordinates flowerCoords = null; + private int cooldown = 0; + + public boolean hasFlowers(IBee queen, IBeeHousing beeHousing) { + IFlowerProvider flowerProvider = queen.getGenome().getFlowerProvider(); + String flowerType = flowerProvider.getFlowerType(); + World world = beeHousing.getWorld(); + + if (flowerCoords != null) { + if (world.getTotalWorldTime() % flowerCheckInterval != flowerCheckTime) { + return true; + } + + IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(beeHousing); + ChunkCoordinates housingCoords = beeHousing.getCoordinates(); + + int[] genomeTerritory = queen.getGenome().getTerritory(); + float housingModifier = beeModifier.getTerritoryModifier(queen.getGenome(), 1f); + Vect area = new Vect(genomeTerritory).multiply(housingModifier * 3.0f); + Vect min = new Vect(area).multiply(-0.5f).add(housingCoords); + Vect max = new Vect(area).multiply(0.5f).add(housingCoords); + + if (isFlowerValid(world, flowerType, min, max)) { + return true; + } else { + flowerCoords = null; + cooldown = 0; + } + } + + if (cooldown <= 0) { + flowerCoords = FlowerManager.flowerRegistry.getAcceptedFlowerCoordinates(beeHousing, queen, flowerType); + cooldown = PluginApiculture.ticksPerBeeWorkCycle; + } else { + cooldown--; + } + + return flowerCoords != null; + } + + private boolean isFlowerValid(World world, String flowerType, Vect min, Vect max) { + if (!isFlowerCoordInRange(flowerCoords, min, max)) { + return false; + } + return FlowerManager.flowerRegistry.isAcceptedFlower( + flowerType, world, flowerCoords.posX, flowerCoords.posY, flowerCoords.posZ); + } + + private static boolean isFlowerCoordInRange(ChunkCoordinates flowerCoords, Vect min, Vect max) { + return flowerCoords.posX >= min.x + && flowerCoords.posX <= max.x + && flowerCoords.posY >= min.y + && flowerCoords.posY <= max.y + && flowerCoords.posZ >= min.z + && flowerCoords.posZ <= max.z; + } + + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + if (!nbttagcompound.hasKey(nbtKey)) { + return; + } + + NBTTagCompound hasFlowerCacheNBT = nbttagcompound.getCompoundTag(nbtKey); + if (hasFlowerCacheNBT.hasKey("flowerX")) { + int x = hasFlowerCacheNBT.getInteger("flowerX"); + int y = hasFlowerCacheNBT.getInteger("flowerY"); + int z = hasFlowerCacheNBT.getInteger("flowerZ"); + flowerCoords = new ChunkCoordinates(x, y, z); + } + + cooldown = hasFlowerCacheNBT.getInteger("cooldown"); + } + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + NBTTagCompound hasFlowerCacheNBT = new NBTTagCompound(); + if (flowerCoords != null) { + hasFlowerCacheNBT.setInteger("flowerX", flowerCoords.posX); + hasFlowerCacheNBT.setInteger("flowerY", flowerCoords.posY); + hasFlowerCacheNBT.setInteger("flowerZ", flowerCoords.posZ); + } + hasFlowerCacheNBT.setInteger("cooldown", cooldown); + + nbttagcompound.setTag(nbtKey, hasFlowerCacheNBT); + } +} diff --git a/src/main/java/forestry/apiculture/IApiary.java b/src/main/java/forestry/apiculture/IApiary.java index a4a4b83df..f55eeed9e 100644 --- a/src/main/java/forestry/apiculture/IApiary.java +++ b/src/main/java/forestry/apiculture/IApiary.java @@ -1,18 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture; - -import forestry.api.apiculture.IBeeHousing; -import forestry.apiculture.inventory.IApiaryInventory; - -public interface IApiary extends IBeeHousing { - IApiaryInventory getApiaryInventory(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture; + +import forestry.api.apiculture.IBeeHousing; +import forestry.apiculture.inventory.IApiaryInventory; + +public interface IApiary extends IBeeHousing { + IApiaryInventory getApiaryInventory(); +} diff --git a/src/main/java/forestry/apiculture/InventoryBeeHousing.java b/src/main/java/forestry/apiculture/InventoryBeeHousing.java index b4230a34b..24401f399 100644 --- a/src/main/java/forestry/apiculture/InventoryBeeHousing.java +++ b/src/main/java/forestry/apiculture/InventoryBeeHousing.java @@ -1,78 +1,76 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture; - -import net.minecraft.item.ItemStack; - -import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.EnumBeeType; -import forestry.api.apiculture.IBeeHousingInventory; -import forestry.core.access.IAccessHandler; -import forestry.core.inventory.InventoryAdapterRestricted; -import forestry.core.utils.InventoryUtil; -import forestry.core.utils.SlotUtil; - -public class InventoryBeeHousing extends InventoryAdapterRestricted implements IBeeHousingInventory { - public static final int SLOT_QUEEN = 0; - public static final int SLOT_DRONE = 1; - public static final int SLOT_PRODUCT_1 = 2; - public static final int SLOT_PRODUCT_COUNT = 7; - - public InventoryBeeHousing(int size, IAccessHandler accessHandler) { - super(size, "Items", accessHandler); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - EnumBeeType beeType = BeeManager.beeRoot.getType(itemStack); - - if (slotIndex == SLOT_QUEEN) { - return beeType == EnumBeeType.QUEEN || beeType == EnumBeeType.PRINCESS; - } else if (slotIndex == SLOT_DRONE) { - return beeType == EnumBeeType.DRONE; - } - return false; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { - if (!super.canExtractItem(slotIndex, itemstack, side)) { - return false; - } - return SlotUtil.isSlotInRange(slotIndex, SLOT_PRODUCT_1, SLOT_PRODUCT_COUNT); - } - - @Override - public final ItemStack getQueen() { - return getStackInSlot(SLOT_QUEEN); - } - - @Override - public final ItemStack getDrone() { - return getStackInSlot(SLOT_DRONE); - } - - @Override - public final void setQueen(ItemStack itemstack) { - setInventorySlotContents(SLOT_QUEEN, itemstack); - } - - @Override - public final void setDrone(ItemStack itemstack) { - setInventorySlotContents(SLOT_DRONE, itemstack); - } - - @Override - public final boolean addProduct(ItemStack product, boolean all) { - return InventoryUtil.tryAddStack(this, product, SLOT_PRODUCT_1, SLOT_PRODUCT_COUNT, all, true); - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture; + +import forestry.api.apiculture.BeeManager; +import forestry.api.apiculture.EnumBeeType; +import forestry.api.apiculture.IBeeHousingInventory; +import forestry.core.access.IAccessHandler; +import forestry.core.inventory.InventoryAdapterRestricted; +import forestry.core.utils.InventoryUtil; +import forestry.core.utils.SlotUtil; +import net.minecraft.item.ItemStack; + +public class InventoryBeeHousing extends InventoryAdapterRestricted implements IBeeHousingInventory { + public static final int SLOT_QUEEN = 0; + public static final int SLOT_DRONE = 1; + public static final int SLOT_PRODUCT_1 = 2; + public static final int SLOT_PRODUCT_COUNT = 7; + + public InventoryBeeHousing(int size, IAccessHandler accessHandler) { + super(size, "Items", accessHandler); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + EnumBeeType beeType = BeeManager.beeRoot.getType(itemStack); + + if (slotIndex == SLOT_QUEEN) { + return beeType == EnumBeeType.QUEEN || beeType == EnumBeeType.PRINCESS; + } else if (slotIndex == SLOT_DRONE) { + return beeType == EnumBeeType.DRONE; + } + return false; + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { + if (!super.canExtractItem(slotIndex, itemstack, side)) { + return false; + } + return SlotUtil.isSlotInRange(slotIndex, SLOT_PRODUCT_1, SLOT_PRODUCT_COUNT); + } + + @Override + public final ItemStack getQueen() { + return getStackInSlot(SLOT_QUEEN); + } + + @Override + public final ItemStack getDrone() { + return getStackInSlot(SLOT_DRONE); + } + + @Override + public final void setQueen(ItemStack itemstack) { + setInventorySlotContents(SLOT_QUEEN, itemstack); + } + + @Override + public final void setDrone(ItemStack itemstack) { + setInventorySlotContents(SLOT_DRONE, itemstack); + } + + @Override + public final boolean addProduct(ItemStack product, boolean all) { + return InventoryUtil.tryAddStack(this, product, SLOT_PRODUCT_1, SLOT_PRODUCT_COUNT, all, true); + } +} diff --git a/src/main/java/forestry/apiculture/MaterialBeehive.java b/src/main/java/forestry/apiculture/MaterialBeehive.java index 4db15559b..50bf7e9d9 100755 --- a/src/main/java/forestry/apiculture/MaterialBeehive.java +++ b/src/main/java/forestry/apiculture/MaterialBeehive.java @@ -15,12 +15,11 @@ import net.minecraft.block.material.Material; public class MaterialBeehive extends Material { - public MaterialBeehive(boolean noHarvest) { - super(MapColor.stoneColor); - if (noHarvest) { - this.setRequiresTool(); - } - setImmovableMobility(); - } - + public MaterialBeehive(boolean noHarvest) { + super(MapColor.stoneColor); + if (noHarvest) { + this.setRequiresTool(); + } + setImmovableMobility(); + } } diff --git a/src/main/java/forestry/apiculture/SaveEventHandlerApiculture.java b/src/main/java/forestry/apiculture/SaveEventHandlerApiculture.java index f5a9a06dd..16baaa84c 100755 --- a/src/main/java/forestry/apiculture/SaveEventHandlerApiculture.java +++ b/src/main/java/forestry/apiculture/SaveEventHandlerApiculture.java @@ -10,24 +10,20 @@ ******************************************************************************/ package forestry.apiculture; -import net.minecraft.world.World; - import forestry.api.apiculture.BeeManager; import forestry.core.ISaveEventHandler; +import net.minecraft.world.World; public class SaveEventHandlerApiculture implements ISaveEventHandler { - @Override - public void onWorldLoad(World world) { - BeeManager.beeRoot.resetBeekeepingMode(); - } + @Override + public void onWorldLoad(World world) { + BeeManager.beeRoot.resetBeekeepingMode(); + } - @Override - public void onWorldSave(World world) { - } - - @Override - public void onWorldUnload(World world) { - } + @Override + public void onWorldSave(World world) {} + @Override + public void onWorldUnload(World world) {} } diff --git a/src/main/java/forestry/apiculture/VillageHandlerApiculture.java b/src/main/java/forestry/apiculture/VillageHandlerApiculture.java index 0aeef7733..29931bb85 100755 --- a/src/main/java/forestry/apiculture/VillageHandlerApiculture.java +++ b/src/main/java/forestry/apiculture/VillageHandlerApiculture.java @@ -10,9 +10,16 @@ ******************************************************************************/ package forestry.apiculture; +import cpw.mods.fml.common.registry.VillagerRegistry.IVillageCreationHandler; +import cpw.mods.fml.common.registry.VillagerRegistry.IVillageTradeHandler; +import forestry.api.apiculture.EnumBeeType; +import forestry.apiculture.blocks.BlockApicultureType; +import forestry.apiculture.genetics.BeeDefinition; +import forestry.apiculture.worldgen.ComponentVillageBeeHouse; +import forestry.core.utils.Log; +import forestry.plugins.PluginApiculture; import java.util.List; import java.util.Random; - import net.minecraft.entity.passive.EntityVillager; import net.minecraft.init.Blocks; import net.minecraft.init.Items; @@ -22,80 +29,79 @@ import net.minecraft.village.MerchantRecipe; import net.minecraft.village.MerchantRecipeList; import net.minecraft.world.gen.structure.MapGenStructureIO; import net.minecraft.world.gen.structure.StructureVillagePieces; - import net.minecraftforge.oredict.OreDictionary; -import cpw.mods.fml.common.registry.VillagerRegistry.IVillageCreationHandler; -import cpw.mods.fml.common.registry.VillagerRegistry.IVillageTradeHandler; - -import forestry.api.apiculture.EnumBeeType; -import forestry.apiculture.blocks.BlockApicultureType; -import forestry.apiculture.genetics.BeeDefinition; -import forestry.apiculture.worldgen.ComponentVillageBeeHouse; -import forestry.core.utils.Log; -import forestry.plugins.PluginApiculture; - public class VillageHandlerApiculture implements IVillageCreationHandler, IVillageTradeHandler { - public static void registerVillageComponents() { - try { - MapGenStructureIO.func_143031_a(ComponentVillageBeeHouse.class, "Forestry:BeeHouse"); - } catch (Throwable e) { - Log.severe("Failed to register village beehouse."); - } - } + public static void registerVillageComponents() { + try { + MapGenStructureIO.func_143031_a(ComponentVillageBeeHouse.class, "Forestry:BeeHouse"); + } catch (Throwable e) { + Log.severe("Failed to register village beehouse."); + } + } - @SuppressWarnings("unchecked") - @Override - public void manipulateTradesForVillager(EntityVillager villager, MerchantRecipeList recipeList, Random random) { - ItemStack wildcardPrincess = new ItemStack(PluginApiculture.items.beePrincessGE, 1, OreDictionary.WILDCARD_VALUE); - ItemStack wildcardDrone = new ItemStack(PluginApiculture.items.beeDroneGE, 4, OreDictionary.WILDCARD_VALUE); - recipeList.add(new MerchantRecipe(wildcardPrincess, new ItemStack(Items.emerald, 1))); + @SuppressWarnings("unchecked") + @Override + public void manipulateTradesForVillager(EntityVillager villager, MerchantRecipeList recipeList, Random random) { + ItemStack wildcardPrincess = + new ItemStack(PluginApiculture.items.beePrincessGE, 1, OreDictionary.WILDCARD_VALUE); + ItemStack wildcardDrone = new ItemStack(PluginApiculture.items.beeDroneGE, 4, OreDictionary.WILDCARD_VALUE); + recipeList.add(new MerchantRecipe(wildcardPrincess, new ItemStack(Items.emerald, 1))); - ItemStack randomComb = PluginApiculture.items.beeComb.getRandomComb(1, random, false); - recipeList.add(new MerchantRecipe(new ItemStack(Items.wheat, 2), randomComb)); + ItemStack randomComb = PluginApiculture.items.beeComb.getRandomComb(1, random, false); + recipeList.add(new MerchantRecipe(new ItemStack(Items.wheat, 2), randomComb)); - ItemStack apiary = PluginApiculture.blocks.apiculture.get(BlockApicultureType.APIARY); - recipeList.add(new MerchantRecipe(new ItemStack(Blocks.log, 24, OreDictionary.WILDCARD_VALUE), apiary)); + ItemStack apiary = PluginApiculture.blocks.apiculture.get(BlockApicultureType.APIARY); + recipeList.add(new MerchantRecipe(new ItemStack(Blocks.log, 24, OreDictionary.WILDCARD_VALUE), apiary)); - ItemStack provenFrames = PluginApiculture.items.frameProven.getItemStack(6); - recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 1), provenFrames)); + ItemStack provenFrames = PluginApiculture.items.frameProven.getItemStack(6); + recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 1), provenFrames)); - ItemStack monasticDrone = BeeDefinition.MONASTIC.getMemberStack(EnumBeeType.DRONE); - recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 12), wildcardPrincess, monasticDrone)); + ItemStack monasticDrone = BeeDefinition.MONASTIC.getMemberStack(EnumBeeType.DRONE); + recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 12), wildcardPrincess, monasticDrone)); - ItemStack endDrone = BeeDefinition.ENDED.getMemberStack(EnumBeeType.DRONE); - recipeList.add(new MerchantRecipe(new ItemStack(Items.ender_eye, 16), wildcardPrincess, endDrone)); + ItemStack endDrone = BeeDefinition.ENDED.getMemberStack(EnumBeeType.DRONE); + recipeList.add(new MerchantRecipe(new ItemStack(Items.ender_eye, 16), wildcardPrincess, endDrone)); - ItemStack propolis = new ItemStack(PluginApiculture.items.propolis,1); - ItemStack forestDrone = BeeDefinition.FOREST.getMemberStack(EnumBeeType.DRONE); - ItemStack meadowsDrone = BeeDefinition.MEADOWS.getMemberStack(EnumBeeType.DRONE); - ItemStack modestDrone = BeeDefinition.MODEST.getMemberStack(EnumBeeType.DRONE); - ItemStack tropicalDrone = BeeDefinition.TROPICAL.getMemberStack(EnumBeeType.DRONE); - ItemStack wintryDrone = BeeDefinition.WINTRY.getMemberStack(EnumBeeType.DRONE); - ItemStack marshyDrone = BeeDefinition.MARSHY.getMemberStack(EnumBeeType.DRONE); - recipeList.add(new MerchantRecipe(propolis, wildcardDrone, forestDrone)); - recipeList.add(new MerchantRecipe(propolis, wildcardDrone, meadowsDrone)); - recipeList.add(new MerchantRecipe(propolis, wildcardDrone, modestDrone)); - recipeList.add(new MerchantRecipe(propolis, wildcardDrone, tropicalDrone)); - recipeList.add(new MerchantRecipe(propolis, wildcardDrone, wintryDrone)); - recipeList.add(new MerchantRecipe(propolis, wildcardDrone, marshyDrone)); - } + ItemStack propolis = new ItemStack(PluginApiculture.items.propolis, 1); + ItemStack forestDrone = BeeDefinition.FOREST.getMemberStack(EnumBeeType.DRONE); + ItemStack meadowsDrone = BeeDefinition.MEADOWS.getMemberStack(EnumBeeType.DRONE); + ItemStack modestDrone = BeeDefinition.MODEST.getMemberStack(EnumBeeType.DRONE); + ItemStack tropicalDrone = BeeDefinition.TROPICAL.getMemberStack(EnumBeeType.DRONE); + ItemStack wintryDrone = BeeDefinition.WINTRY.getMemberStack(EnumBeeType.DRONE); + ItemStack marshyDrone = BeeDefinition.MARSHY.getMemberStack(EnumBeeType.DRONE); + recipeList.add(new MerchantRecipe(propolis, wildcardDrone, forestDrone)); + recipeList.add(new MerchantRecipe(propolis, wildcardDrone, meadowsDrone)); + recipeList.add(new MerchantRecipe(propolis, wildcardDrone, modestDrone)); + recipeList.add(new MerchantRecipe(propolis, wildcardDrone, tropicalDrone)); + recipeList.add(new MerchantRecipe(propolis, wildcardDrone, wintryDrone)); + recipeList.add(new MerchantRecipe(propolis, wildcardDrone, marshyDrone)); + } - @Override - public StructureVillagePieces.PieceWeight getVillagePieceWeight(Random random, int size) { - return new StructureVillagePieces.PieceWeight(ComponentVillageBeeHouse.class, 15, MathHelper.getRandomIntegerInRange(random, size, 1 + size)); - } + @Override + public StructureVillagePieces.PieceWeight getVillagePieceWeight(Random random, int size) { + return new StructureVillagePieces.PieceWeight( + ComponentVillageBeeHouse.class, 15, MathHelper.getRandomIntegerInRange(random, size, 1 + size)); + } - @Override - public Class getComponentClass() { - return ComponentVillageBeeHouse.class; - } + @Override + public Class getComponentClass() { + return ComponentVillageBeeHouse.class; + } - @SuppressWarnings("rawtypes") - @Override - public Object buildComponent(StructureVillagePieces.PieceWeight villagePiece, StructureVillagePieces.Start startPiece, List pieces, Random random, int p1, int p2, - int p3, int p4, int p5) { - return ComponentVillageBeeHouse.buildComponent(startPiece, pieces, random, p1, p2, p3, p4, p5); - } + @SuppressWarnings("rawtypes") + @Override + public Object buildComponent( + StructureVillagePieces.PieceWeight villagePiece, + StructureVillagePieces.Start startPiece, + List pieces, + Random random, + int p1, + int p2, + int p3, + int p4, + int p5) { + return ComponentVillageBeeHouse.buildComponent(startPiece, pieces, random, p1, p2, p3, p4, p5); + } } diff --git a/src/main/java/forestry/apiculture/blocks/BlockAlveary.java b/src/main/java/forestry/apiculture/blocks/BlockAlveary.java index d37777cc0..6c2515da5 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockAlveary.java +++ b/src/main/java/forestry/apiculture/blocks/BlockAlveary.java @@ -10,22 +10,8 @@ ******************************************************************************/ package forestry.apiculture.blocks; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.IIcon; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.core.Tabs; import forestry.apiculture.MaterialBeehive; import forestry.apiculture.multiblock.TileAlveary; @@ -38,254 +24,265 @@ import forestry.apiculture.multiblock.TileAlvearyStabiliser; import forestry.apiculture.multiblock.TileAlvearySwarmer; import forestry.core.blocks.BlockStructure; import forestry.core.render.TextureManager; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; public class BlockAlveary extends BlockStructure { - public enum Type { - PLAIN, - ENTRANCE, - SWARMER, - FAN, - HEATER, - HYGRO, - STABILIZER, - SIEVE; + public enum Type { + PLAIN, + ENTRANCE, + SWARMER, + FAN, + HEATER, + HYGRO, + STABILIZER, + SIEVE; - public static final Type[] VALUES = values(); - } + public static final Type[] VALUES = values(); + } - public BlockAlveary() { - super(new MaterialBeehive(false)); - setHardness(1.0f); - setCreativeTab(Tabs.tabApiculture); - setHarvestLevel("axe", 0); - } + public BlockAlveary() { + super(new MaterialBeehive(false)); + setHardness(1.0f); + setCreativeTab(Tabs.tabApiculture); + setHarvestLevel("axe", 0); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - @SideOnly(Side.CLIENT) - public void getSubBlocks(Item item, CreativeTabs tab, List list) { - for (int i = 0; i < 8; i++) { - if (i == 1) { - continue; - } - list.add(new ItemStack(item, 1, i)); - } - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + @SideOnly(Side.CLIENT) + public void getSubBlocks(Item item, CreativeTabs tab, List list) { + for (int i = 0; i < 8; i++) { + if (i == 1) { + continue; + } + list.add(new ItemStack(item, 1, i)); + } + } - @Override - public int getRenderType() { - return 0; - } + @Override + public int getRenderType() { + return 0; + } - @Override - public boolean renderAsNormalBlock() { - return true; - } + @Override + public boolean renderAsNormalBlock() { + return true; + } - @Override - public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - ArrayList drop = new ArrayList<>(); - drop.add(new ItemStack(this, 1, metadata != 1 ? metadata : 0)); - return drop; - } + @Override + public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + ArrayList drop = new ArrayList<>(); + drop.add(new ItemStack(this, 1, metadata != 1 ? metadata : 0)); + return drop; + } - @Override - public int getDamageValue(World world, int x, int y, int z) { - int meta = world.getBlockMetadata(x, y, z); - return meta != 1 ? meta : 0; - } + @Override + public int getDamageValue(World world, int x, int y, int z) { + int meta = world.getBlockMetadata(x, y, z); + return meta != 1 ? meta : 0; + } - /* TILE ENTITY CREATION */ - @Override - public TileEntity createTileEntity(World world, int metadata) { - if (metadata < 0 || metadata > Type.VALUES.length) { - return null; - } + /* TILE ENTITY CREATION */ + @Override + public TileEntity createTileEntity(World world, int metadata) { + if (metadata < 0 || metadata > Type.VALUES.length) { + return null; + } - Type type = Type.VALUES[metadata]; - switch (type) { - case SWARMER: - return new TileAlvearySwarmer(); - case FAN: - return new TileAlvearyFan(); - case HEATER: - return new TileAlvearyHeater(); - case HYGRO: - return new TileAlvearyHygroregulator(); - case STABILIZER: - return new TileAlvearyStabiliser(); - case SIEVE: - return new TileAlvearySieve(); - case PLAIN: - default: - return new TileAlvearyPlain(); - } - } + Type type = Type.VALUES[metadata]; + switch (type) { + case SWARMER: + return new TileAlvearySwarmer(); + case FAN: + return new TileAlvearyFan(); + case HEATER: + return new TileAlvearyHeater(); + case HYGRO: + return new TileAlvearyHygroregulator(); + case STABILIZER: + return new TileAlvearyStabiliser(); + case SIEVE: + return new TileAlvearySieve(); + case PLAIN: + default: + return new TileAlvearyPlain(); + } + } - @Override - public TileEntity createNewTileEntity(World world, int meta) { - return createTileEntity(world, meta); - } + @Override + public TileEntity createNewTileEntity(World world, int meta) { + return createTileEntity(world, meta); + } - /* ICONS */ - public static final int PLAIN = 0; - public static final int ENTRANCE = 1; - public static final int BOTTOM = 2; - public static final int LEFT = 3; - public static final int RIGHT = 4; - public static final int ALVEARY_SWARMER_OFF = 5; - public static final int ALVEARY_SWARMER_ON = 6; - public static final int ALVEARY_HEATER_OFF = 7; - public static final int ALVEARY_HEATER_ON = 8; - public static final int ALVEARY_FAN_OFF = 9; - public static final int ALVEARY_FAN_ON = 10; - public static final int ALVEARY_HYGRO = 11; - public static final int STABILISER = 12; - public static final int SIEVE = 13; + /* ICONS */ + public static final int PLAIN = 0; + public static final int ENTRANCE = 1; + public static final int BOTTOM = 2; + public static final int LEFT = 3; + public static final int RIGHT = 4; + public static final int ALVEARY_SWARMER_OFF = 5; + public static final int ALVEARY_SWARMER_ON = 6; + public static final int ALVEARY_HEATER_OFF = 7; + public static final int ALVEARY_HEATER_ON = 8; + public static final int ALVEARY_FAN_OFF = 9; + public static final int ALVEARY_FAN_ON = 10; + public static final int ALVEARY_HYGRO = 11; + public static final int STABILISER = 12; + public static final int SIEVE = 13; - @SideOnly(Side.CLIENT) - private IIcon[] icons; + @SideOnly(Side.CLIENT) + private IIcon[] icons; - @SideOnly(Side.CLIENT) - @Override - public void registerBlockIcons(IIconRegister register) { - icons = new IIcon[14]; - icons[0] = TextureManager.registerTex(register, "apiculture/alveary.plain"); - icons[1] = TextureManager.registerTex(register, "apiculture/alveary.entrance"); - icons[2] = TextureManager.registerTex(register, "apiculture/alveary.bottom"); - icons[3] = TextureManager.registerTex(register, "apiculture/alveary.left"); - icons[4] = TextureManager.registerTex(register, "apiculture/alveary.right"); - icons[5] = TextureManager.registerTex(register, "apiculture/alveary.swarmer.off"); - icons[6] = TextureManager.registerTex(register, "apiculture/alveary.swarmer.on"); - icons[7] = TextureManager.registerTex(register, "apiculture/alveary.heater.off"); - icons[8] = TextureManager.registerTex(register, "apiculture/alveary.heater.on"); - icons[9] = TextureManager.registerTex(register, "apiculture/alveary.fan.off"); - icons[10] = TextureManager.registerTex(register, "apiculture/alveary.fan.on"); - icons[11] = TextureManager.registerTex(register, "apiculture/alveary.valve"); - icons[12] = TextureManager.registerTex(register, "apiculture/alveary.stabiliser"); - icons[13] = TextureManager.registerTex(register, "apiculture/alveary.sieve"); - } + @SideOnly(Side.CLIENT) + @Override + public void registerBlockIcons(IIconRegister register) { + icons = new IIcon[14]; + icons[0] = TextureManager.registerTex(register, "apiculture/alveary.plain"); + icons[1] = TextureManager.registerTex(register, "apiculture/alveary.entrance"); + icons[2] = TextureManager.registerTex(register, "apiculture/alveary.bottom"); + icons[3] = TextureManager.registerTex(register, "apiculture/alveary.left"); + icons[4] = TextureManager.registerTex(register, "apiculture/alveary.right"); + icons[5] = TextureManager.registerTex(register, "apiculture/alveary.swarmer.off"); + icons[6] = TextureManager.registerTex(register, "apiculture/alveary.swarmer.on"); + icons[7] = TextureManager.registerTex(register, "apiculture/alveary.heater.off"); + icons[8] = TextureManager.registerTex(register, "apiculture/alveary.heater.on"); + icons[9] = TextureManager.registerTex(register, "apiculture/alveary.fan.off"); + icons[10] = TextureManager.registerTex(register, "apiculture/alveary.fan.on"); + icons[11] = TextureManager.registerTex(register, "apiculture/alveary.valve"); + icons[12] = TextureManager.registerTex(register, "apiculture/alveary.stabiliser"); + icons[13] = TextureManager.registerTex(register, "apiculture/alveary.sieve"); + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(int side, int metadata) { - if ((metadata <= 1 - || metadata == Type.SIEVE.ordinal() || metadata == Type.SWARMER.ordinal() || metadata == Type.STABILIZER.ordinal()) - && (side == 1 || side == 0)) { - return icons[BOTTOM]; - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(int side, int metadata) { + if ((metadata <= 1 + || metadata == Type.SIEVE.ordinal() + || metadata == Type.SWARMER.ordinal() + || metadata == Type.STABILIZER.ordinal()) + && (side == 1 || side == 0)) { + return icons[BOTTOM]; + } - Type type = Type.VALUES[metadata]; + Type type = Type.VALUES[metadata]; - switch (type) { - case PLAIN: - return icons[PLAIN]; - case ENTRANCE: - return icons[ENTRANCE]; - case SWARMER: - return icons[ALVEARY_SWARMER_OFF]; - case FAN: - return icons[ALVEARY_FAN_OFF]; - case HEATER: - return icons[ALVEARY_HEATER_OFF]; - case HYGRO: - return icons[ALVEARY_HYGRO]; - case STABILIZER: - return icons[STABILISER]; - case SIEVE: - return icons[SIEVE]; - default: - return null; - } + switch (type) { + case PLAIN: + return icons[PLAIN]; + case ENTRANCE: + return icons[ENTRANCE]; + case SWARMER: + return icons[ALVEARY_SWARMER_OFF]; + case FAN: + return icons[ALVEARY_FAN_OFF]; + case HEATER: + return icons[ALVEARY_HEATER_OFF]; + case HYGRO: + return icons[ALVEARY_HYGRO]; + case STABILIZER: + return icons[STABILISER]; + case SIEVE: + return icons[SIEVE]; + default: + return null; + } + } - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { + int meta = world.getBlockMetadata(x, y, z); - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { - int meta = world.getBlockMetadata(x, y, z); + if (meta == 1) { + return this.getIcon(side, meta); + } else if (meta > 1) { + return getBlockTextureFromSideAndTile(world, x, y, z, side); + } - if (meta == 1) { - return this.getIcon(side, meta); - } else if (meta > 1) { - return getBlockTextureFromSideAndTile(world, x, y, z, side); - } + Block blockXP = world.getBlock(x + 1, y, z); + Block blockXM = world.getBlock(x - 1, y, z); - Block blockXP = world.getBlock(x + 1, y, z); - Block blockXM = world.getBlock(x - 1, y, z); + if (blockXP == this && blockXM != this) { - if (blockXP == this && blockXM != this) { + if (world.getBlockMetadata(x + 1, y, z) == 1) { - if (world.getBlockMetadata(x + 1, y, z) == 1) { + if (world.getBlock(x, y, z + 1) != this) { + return switchForSide(42, side); + } else { + return switchForSide(41, side); + } - if (world.getBlock(x, y, z + 1) != this) { - return switchForSide(42, side); - } else { - return switchForSide(41, side); - } + } else { + return this.getIcon(side, meta); + } - } else { - return this.getIcon(side, meta); - } + } else if (blockXP != this && blockXM == this) { + if (world.getBlockMetadata(x - 1, y, z) == 1) { - } else if (blockXP != this && blockXM == this) { - if (world.getBlockMetadata(x - 1, y, z) == 1) { + if (world.getBlock(x, y, z + 1) != this) { + return switchForSide(41, side); + } else { + return switchForSide(42, side); + } - if (world.getBlock(x, y, z + 1) != this) { - return switchForSide(41, side); - } else { - return switchForSide(42, side); - } + } else { + return this.getIcon(side, meta); + } + } - } else { - return this.getIcon(side, meta); - } - } + return this.getIcon(side, meta); + } - return this.getIcon(side, meta); - } + @SideOnly(Side.CLIENT) + private IIcon getBlockTextureFromSideAndTile(IBlockAccess world, int x, int y, int z, int side) { + TileEntity tile = world.getTileEntity(x, y, z); + if (!(tile instanceof TileAlveary)) { + return getIcon(side, 0); + } - @SideOnly(Side.CLIENT) - private IIcon getBlockTextureFromSideAndTile(IBlockAccess world, int x, int y, int z, int side) { - TileEntity tile = world.getTileEntity(x, y, z); - if (!(tile instanceof TileAlveary)) { - return getIcon(side, 0); - } + return icons[((TileAlveary) tile).getIcon(side)]; + } - return icons[((TileAlveary) tile).getIcon(side)]; - } + @SideOnly(Side.CLIENT) + private IIcon switchForSide(int textureId, int side) { - @SideOnly(Side.CLIENT) - private IIcon switchForSide(int textureId, int side) { + if (side == 4 || side == 5) { + if (textureId == 41) { + return icons[LEFT]; + } else { + return icons[RIGHT]; + } + } else if (textureId == 41) { + return icons[RIGHT]; + } else { + return icons[LEFT]; + } + } - if (side == 4 || side == 5) { - if (textureId == 41) { - return icons[LEFT]; - } else { - return icons[RIGHT]; - } - } else if (textureId == 41) { - return icons[RIGHT]; - } else { - return icons[LEFT]; - } + @Override + public void onNeighborBlockChange(World world, int x, int y, int z, Block block) { + super.onNeighborBlockChange(world, x, y, z, block); - } + TileEntity tileEntity = world.getTileEntity(x, y, z); + if (tileEntity instanceof TileAlveary) { + TileAlveary tileAlveary = (TileAlveary) tileEntity; - @Override - public void onNeighborBlockChange(World world, int x, int y, int z, Block block) { - super.onNeighborBlockChange(world, x, y, z, block); + // We must check that the slabs on top were not removed + tileAlveary.getMultiblockLogic().getController().reassemble(); + } + } - TileEntity tileEntity = world.getTileEntity(x, y, z); - if (tileEntity instanceof TileAlveary) { - TileAlveary tileAlveary = (TileAlveary) tileEntity; - - // We must check that the slabs on top were not removed - tileAlveary.getMultiblockLogic().getController().reassemble(); - } - } - - public ItemStack get(Type type) { - return new ItemStack(this, 1, type.ordinal()); - } + public ItemStack get(Type type) { + return new ItemStack(this, 1, type.ordinal()); + } } diff --git a/src/main/java/forestry/apiculture/blocks/BlockApiculture.java b/src/main/java/forestry/apiculture/blocks/BlockApiculture.java index c77ed4c77..b243e97a6 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockApiculture.java +++ b/src/main/java/forestry/apiculture/blocks/BlockApiculture.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.blocks; - -import forestry.api.core.Tabs; -import forestry.core.blocks.BlockBase; - -public class BlockApiculture extends BlockBase { - public BlockApiculture() { - super(); - setCreativeTab(Tabs.tabApiculture); - setHarvestLevel("axe", 0); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.blocks; + +import forestry.api.core.Tabs; +import forestry.core.blocks.BlockBase; + +public class BlockApiculture extends BlockBase { + public BlockApiculture() { + super(); + setCreativeTab(Tabs.tabApiculture); + setHarvestLevel("axe", 0); + } +} diff --git a/src/main/java/forestry/apiculture/blocks/BlockApicultureType.java b/src/main/java/forestry/apiculture/blocks/BlockApicultureType.java index 69de30b0a..8311659e4 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockApicultureType.java +++ b/src/main/java/forestry/apiculture/blocks/BlockApicultureType.java @@ -1,58 +1,56 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.blocks; - -import java.util.Locale; - -import org.apache.commons.lang3.text.WordUtils; - -import forestry.apiculture.tiles.TileApiaristChest; -import forestry.apiculture.tiles.TileApiary; -import forestry.apiculture.tiles.TileBeehouse; -import forestry.core.blocks.IMachineProperties; -import forestry.core.tiles.TileForestry; - -public enum BlockApicultureType implements IMachineProperties { - APIARY(TileApiary.class), - APIARIST_CHEST_LEGACY(TileApiaristChest.class, "ApiaristChest"), - BEEHOUSE(TileBeehouse.class); - - public static final BlockApicultureType[] VALUES = values(); - - private final String teIdent; - private final Class teClass; - - BlockApicultureType(Class teClass) { - String name = toString().toLowerCase(Locale.ENGLISH); - this.teIdent = "forestry." + WordUtils.capitalize(name); - this.teClass = teClass; - } - - BlockApicultureType(Class teClass, String name) { - this.teIdent = "forestry." + name; - this.teClass = teClass; - } - - @Override - public int getMeta() { - return ordinal(); - } - - @Override - public String getTeIdent() { - return teIdent; - } - - @Override - public Class getTeClass() { - return teClass; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.blocks; + +import forestry.apiculture.tiles.TileApiaristChest; +import forestry.apiculture.tiles.TileApiary; +import forestry.apiculture.tiles.TileBeehouse; +import forestry.core.blocks.IMachineProperties; +import forestry.core.tiles.TileForestry; +import java.util.Locale; +import org.apache.commons.lang3.text.WordUtils; + +public enum BlockApicultureType implements IMachineProperties { + APIARY(TileApiary.class), + APIARIST_CHEST_LEGACY(TileApiaristChest.class, "ApiaristChest"), + BEEHOUSE(TileBeehouse.class); + + public static final BlockApicultureType[] VALUES = values(); + + private final String teIdent; + private final Class teClass; + + BlockApicultureType(Class teClass) { + String name = toString().toLowerCase(Locale.ENGLISH); + this.teIdent = "forestry." + WordUtils.capitalize(name); + this.teClass = teClass; + } + + BlockApicultureType(Class teClass, String name) { + this.teIdent = "forestry." + name; + this.teClass = teClass; + } + + @Override + public int getMeta() { + return ordinal(); + } + + @Override + public String getTeIdent() { + return teIdent; + } + + @Override + public Class getTeClass() { + return teClass; + } +} diff --git a/src/main/java/forestry/apiculture/blocks/BlockBeehives.java b/src/main/java/forestry/apiculture/blocks/BlockBeehives.java index e8237e914..4c9166daa 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockBeehives.java +++ b/src/main/java/forestry/apiculture/blocks/BlockBeehives.java @@ -10,10 +10,21 @@ ******************************************************************************/ package forestry.apiculture.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.apiculture.IHiveDrop; +import forestry.api.core.Tabs; +import forestry.apiculture.MaterialBeehive; +import forestry.apiculture.tiles.TileSwarm; +import forestry.apiculture.worldgen.HiveRegistry; +import forestry.core.config.Config; +import forestry.core.render.TextureManager; +import forestry.core.utils.InventoryUtil; +import forestry.core.utils.ItemStackUtil; +import forestry.plugins.PluginApiculture; import java.util.ArrayList; import java.util.Collections; import java.util.List; - import net.minecraft.block.BlockContainer; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; @@ -26,194 +37,179 @@ import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.apiculture.IHiveDrop; -import forestry.api.core.Tabs; -import forestry.apiculture.MaterialBeehive; -import forestry.apiculture.tiles.TileSwarm; -import forestry.apiculture.worldgen.HiveRegistry; -import forestry.core.config.Config; -import forestry.core.render.TextureManager; -import forestry.core.utils.InventoryUtil; -import forestry.core.utils.ItemStackUtil; -import forestry.plugins.PluginApiculture; - public class BlockBeehives extends BlockContainer { - public enum Type { - LEGACY, - FOREST, - MEADOWS; - } + public enum Type { + LEGACY, + FOREST, + MEADOWS; + } - public BlockBeehives() { - super(new MaterialBeehive(true)); - setLightLevel(0.8f); - setHardness(1.0f); - setCreativeTab(Tabs.tabApiculture); - setHarvestLevel("scoop", 0); - } + public BlockBeehives() { + super(new MaterialBeehive(true)); + setLightLevel(0.8f); + setHardness(1.0f); + setCreativeTab(Tabs.tabApiculture); + setHarvestLevel("scoop", 0); + } - @Override - public TileEntity createNewTileEntity(World world, int meta) { - return new TileSwarm(); - } + @Override + public TileEntity createNewTileEntity(World world, int meta) { + return new TileSwarm(); + } - @Override - public boolean canEntityDestroy(IBlockAccess world, int x, int y, int z, Entity entity) { - return false; - } + @Override + public boolean canEntityDestroy(IBlockAccess world, int x, int y, int z, Entity entity) { + return false; + } - @Override - public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) { - if (canHarvestBlock(player, world.getBlockMetadata(x, y, z))) { - // Handle TE'd beehives - TileEntity tile = world.getTileEntity(x, y, z); + @Override + public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) { + if (canHarvestBlock(player, world.getBlockMetadata(x, y, z))) { + // Handle TE'd beehives + TileEntity tile = world.getTileEntity(x, y, z); - if (tile instanceof TileSwarm) { - TileSwarm swarm = (TileSwarm) tile; - if (swarm.containsBees()) { - for (ItemStack beeStack : InventoryUtil.getStacks(swarm.contained)) { - if (beeStack != null) { - ItemStackUtil.dropItemStackAsEntity(beeStack, world, x, y, z); - } - } - } - } - } + if (tile instanceof TileSwarm) { + TileSwarm swarm = (TileSwarm) tile; + if (swarm.containsBees()) { + for (ItemStack beeStack : InventoryUtil.getStacks(swarm.contained)) { + if (beeStack != null) { + ItemStackUtil.dropItemStackAsEntity(beeStack, world, x, y, z); + } + } + } + } + } - return world.setBlockToAir(x, y, z); - } + return world.setBlockToAir(x, y, z); + } - @Override - public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - ArrayList ret = new ArrayList<>(); + @Override + public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + ArrayList ret = new ArrayList<>(); - // Handle legacy block - if (metadata == 0) { - ret.add(new ItemStack(this)); - return ret; - } + // Handle legacy block + if (metadata == 0) { + ret.add(new ItemStack(this)); + return ret; + } - List dropList = getDropsForHive(metadata); + List dropList = getDropsForHive(metadata); - Collections.shuffle(dropList); - // Grab a princess - int tries = 0; - boolean hasPrincess = false; - while (tries <= 10 && !hasPrincess) { - tries++; + Collections.shuffle(dropList); + // Grab a princess + int tries = 0; + boolean hasPrincess = false; + while (tries <= 10 && !hasPrincess) { + tries++; - for (IHiveDrop drop : dropList) { - if (world.rand.nextInt(100) < drop.getChance(world, x, y, z)) { - ret.add(drop.getPrincess(world, x, y, z, fortune)); - hasPrincess = true; - break; - } - } - } + for (IHiveDrop drop : dropList) { + if (world.rand.nextInt(100) < drop.getChance(world, x, y, z)) { + ret.add(drop.getPrincess(world, x, y, z, fortune)); + hasPrincess = true; + break; + } + } + } - // Grab drones - for (IHiveDrop drop : dropList) { - if (world.rand.nextInt(100) < drop.getChance(world, x, y, z)) { - ret.addAll(drop.getDrones(world, x, y, z, fortune)); - break; - } - } - // Grab anything else on offer - for (IHiveDrop drop : dropList) { - if (world.rand.nextInt(100) < drop.getChance(world, x, y, z)) { - ret.addAll(drop.getAdditional(world, x, y, z, fortune)); - break; - } - } + // Grab drones + for (IHiveDrop drop : dropList) { + if (world.rand.nextInt(100) < drop.getChance(world, x, y, z)) { + ret.addAll(drop.getDrones(world, x, y, z, fortune)); + break; + } + } + // Grab anything else on offer + for (IHiveDrop drop : dropList) { + if (world.rand.nextInt(100) < drop.getChance(world, x, y, z)) { + ret.addAll(drop.getAdditional(world, x, y, z, fortune)); + break; + } + } - return ret; - } + return ret; + } - // / CREATIVE INVENTORY - @Override - public int damageDropped(int meta) { - return meta; - } + // / CREATIVE INVENTORY + @Override + public int damageDropped(int meta) { + return meta; + } - private static List getDropsForHive(int meta) { - String hiveName = getHiveNameForMeta(meta); - if (hiveName == null) { - return Collections.emptyList(); - } - return PluginApiculture.hiveRegistry.getDrops(hiveName); - } + private static List getDropsForHive(int meta) { + String hiveName = getHiveNameForMeta(meta); + if (hiveName == null) { + return Collections.emptyList(); + } + return PluginApiculture.hiveRegistry.getDrops(hiveName); + } - private static String getHiveNameForMeta(int meta) { - switch (meta) { - case 1: - return HiveRegistry.forest; - case 2: - return HiveRegistry.meadows; - case 3: - return HiveRegistry.desert; - case 4: - return HiveRegistry.jungle; - case 5: - return HiveRegistry.end; - case 6: - return HiveRegistry.snow; - case 7: - return HiveRegistry.swamp; - } - return null; - } + private static String getHiveNameForMeta(int meta) { + switch (meta) { + case 1: + return HiveRegistry.forest; + case 2: + return HiveRegistry.meadows; + case 3: + return HiveRegistry.desert; + case 4: + return HiveRegistry.jungle; + case 5: + return HiveRegistry.end; + case 6: + return HiveRegistry.snow; + case 7: + return HiveRegistry.swamp; + } + return null; + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { - itemList.add(new ItemStack(this, 1, 1)); - itemList.add(new ItemStack(this, 1, 2)); - itemList.add(new ItemStack(this, 1, 3)); - itemList.add(new ItemStack(this, 1, 4)); - if (Config.isDebug) { - itemList.add(new ItemStack(this, 1, 5)); - } - itemList.add(new ItemStack(this, 1, 6)); - itemList.add(new ItemStack(this, 1, 7)); - // Swarm hive not added - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { + itemList.add(new ItemStack(this, 1, 1)); + itemList.add(new ItemStack(this, 1, 2)); + itemList.add(new ItemStack(this, 1, 3)); + itemList.add(new ItemStack(this, 1, 4)); + if (Config.isDebug) { + itemList.add(new ItemStack(this, 1, 5)); + } + itemList.add(new ItemStack(this, 1, 6)); + itemList.add(new ItemStack(this, 1, 7)); + // Swarm hive not added + } - /* ICONS */ - @SideOnly(Side.CLIENT) - private IIcon[] icons; + /* ICONS */ + @SideOnly(Side.CLIENT) + private IIcon[] icons; - @Override - @SideOnly(Side.CLIENT) - public void registerBlockIcons(IIconRegister register) { - icons = new IIcon[18]; - for (int i = 1; i < 9; i++) { - icons[i * 2] = TextureManager.registerTex(register, "beehives/beehive." + i + ".top"); - icons[(i * 2) + 1] = TextureManager.registerTex(register, "beehives/beehive." + i + ".side"); - } - } + @Override + @SideOnly(Side.CLIENT) + public void registerBlockIcons(IIconRegister register) { + icons = new IIcon[18]; + for (int i = 1; i < 9; i++) { + icons[i * 2] = TextureManager.registerTex(register, "beehives/beehive." + i + ".top"); + icons[(i * 2) + 1] = TextureManager.registerTex(register, "beehives/beehive." + i + ".side"); + } + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(int i, int j) { - if (j == 0 || j > 8) { - // placeholder for not causing NPE - return icons[3]; - } - - if (i == 0 || i == 1) { - if (j * 2 < icons.length && icons[j * 2] != null) { - return icons[j * 2]; - } else { - return icons[2]; - } - } else if (j * 2 + 1 < icons.length && icons[j * 2 + 1] != null) { - return icons[j * 2 + 1]; - } else { - return icons[3]; - } - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(int i, int j) { + if (j == 0 || j > 8) { + // placeholder for not causing NPE + return icons[3]; + } + if (i == 0 || i == 1) { + if (j * 2 < icons.length && icons[j * 2] != null) { + return icons[j * 2]; + } else { + return icons[2]; + } + } else if (j * 2 + 1 < icons.length && icons[j * 2 + 1] != null) { + return icons[j * 2 + 1]; + } else { + return icons[3]; + } + } } diff --git a/src/main/java/forestry/apiculture/blocks/BlockCandle.java b/src/main/java/forestry/apiculture/blocks/BlockCandle.java index 5d8cf0317..dc7d72f5b 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockCandle.java +++ b/src/main/java/forestry/apiculture/blocks/BlockCandle.java @@ -11,7 +11,14 @@ package forestry.apiculture.blocks; import com.google.common.collect.ImmutableMap; - +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.core.Tabs; +import forestry.apiculture.tiles.TileCandle; +import forestry.core.proxy.Proxies; +import forestry.core.render.TextureManager; +import forestry.core.utils.ItemStackUtil; +import forestry.core.utils.StringUtil; import java.awt.Color; import java.util.ArrayList; import java.util.Arrays; @@ -20,7 +27,6 @@ import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; - import net.minecraft.block.BlockTorch; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; @@ -36,301 +42,300 @@ import net.minecraft.util.IIcon; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.oredict.OreDictionary; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.core.Tabs; -import forestry.apiculture.tiles.TileCandle; -import forestry.core.proxy.Proxies; -import forestry.core.render.TextureManager; -import forestry.core.utils.ItemStackUtil; -import forestry.core.utils.StringUtil; - public class BlockCandle extends BlockTorch { - private static final ImmutableMap colours; - private static final Set lightingItems; - public static final String colourTagName = "colour"; + private static final ImmutableMap colours; + private static final Set lightingItems; + public static final String colourTagName = "colour"; - static { - colours = ImmutableMap.builder() - .put("dyeWhite", new Color(255, 255, 255).getRGB()) - .put("dyeOrange", new Color(219, 125, 62).getRGB()) - .put("dyeMagenta", new Color(255, 20, 255).getRGB()) - .put("dyeLightBlue", new Color(107, 138, 201).getRGB()) - .put("dyeYellow", new Color(255, 255, 20).getRGB()) - .put("dyeLime", new Color(20, 255, 20).getRGB()) - .put("dyePink", new Color(208, 132, 153).getRGB()) - .put("dyeGray", new Color(74, 74, 74).getRGB()) - .put("dyeLightGray", new Color(154, 161, 161).getRGB()) - .put("dyeCyan", new Color(20, 255, 255).getRGB()) - .put("dyePurple", new Color(126, 61, 181).getRGB()) - .put("dyeBlue", new Color(20, 20, 255).getRGB()) - .put("dyeBrown", new Color(79, 50, 31).getRGB()) - .put("dyeGreen", new Color(53, 70, 27).getRGB()) - .put("dyeRed", new Color(150, 52, 48).getRGB()) - .put("dyeBlack", new Color(20, 20, 20).getRGB()) - .build(); + static { + colours = ImmutableMap.builder() + .put("dyeWhite", new Color(255, 255, 255).getRGB()) + .put("dyeOrange", new Color(219, 125, 62).getRGB()) + .put("dyeMagenta", new Color(255, 20, 255).getRGB()) + .put("dyeLightBlue", new Color(107, 138, 201).getRGB()) + .put("dyeYellow", new Color(255, 255, 20).getRGB()) + .put("dyeLime", new Color(20, 255, 20).getRGB()) + .put("dyePink", new Color(208, 132, 153).getRGB()) + .put("dyeGray", new Color(74, 74, 74).getRGB()) + .put("dyeLightGray", new Color(154, 161, 161).getRGB()) + .put("dyeCyan", new Color(20, 255, 255).getRGB()) + .put("dyePurple", new Color(126, 61, 181).getRGB()) + .put("dyeBlue", new Color(20, 20, 255).getRGB()) + .put("dyeBrown", new Color(79, 50, 31).getRGB()) + .put("dyeGreen", new Color(53, 70, 27).getRGB()) + .put("dyeRed", new Color(150, 52, 48).getRGB()) + .put("dyeBlack", new Color(20, 20, 20).getRGB()) + .build(); - lightingItems = new HashSet<>(Arrays.asList( - Items.flint_and_steel, - Items.flint, - Item.getItemFromBlock(Blocks.torch) - )); - } + lightingItems = + new HashSet<>(Arrays.asList(Items.flint_and_steel, Items.flint, Item.getItemFromBlock(Blocks.torch))); + } - @SideOnly(Side.CLIENT) - private IIcon litStump; - @SideOnly(Side.CLIENT) - private IIcon litTip; - @SideOnly(Side.CLIENT) - private IIcon unlitStump; - @SideOnly(Side.CLIENT) - private IIcon unlitTip; + @SideOnly(Side.CLIENT) + private IIcon litStump; - public BlockCandle() { - super(); - this.setHardness(0.0F); - this.setStepSound(soundTypeWood); - setCreativeTab(Tabs.tabApiculture); - } + @SideOnly(Side.CLIENT) + private IIcon litTip; - @Override - public boolean hasTileEntity(int metadata) { - return true; - } + @SideOnly(Side.CLIENT) + private IIcon unlitStump; - @Override - public TileEntity createTileEntity(World world, int metadata) { - return new TileCandle(); - } + @SideOnly(Side.CLIENT) + private IIcon unlitTip; - @Override - public int getRenderType() { - return Proxies.render.getCandleRenderId(); - } + public BlockCandle() { + super(); + this.setHardness(0.0F); + this.setStepSound(soundTypeWood); + setCreativeTab(Tabs.tabApiculture); + } - @SideOnly(Side.CLIENT) - @Override - public void registerBlockIcons(IIconRegister register) { - String fileBase = StringUtil.cleanBlockName(this); - this.blockIcon = TextureManager.registerTex(register, "stump"); - this.litStump = TextureManager.registerTex(register, fileBase + "StumpLit"); - this.litTip = TextureManager.registerTex(register, fileBase + "TipLit"); - this.unlitStump = TextureManager.registerTex(register, fileBase + "StumpUnlit"); - this.unlitTip = TextureManager.registerTex(register, fileBase + "TipUnlit"); - } + @Override + public boolean hasTileEntity(int metadata) { + return true; + } - @Override - public int getLightValue(IBlockAccess world, int x, int y, int z) { - TileEntity tileEntity = world.getTileEntity(x, y, z); - if (tileEntity instanceof TileCandle && ((TileCandle) tileEntity).isLit()) { - return 14; - } - return 0; - } + @Override + public TileEntity createTileEntity(World world, int metadata) { + return new TileCandle(); + } - @SideOnly(Side.CLIENT) - public IIcon getTextureFromPassAndLit(int pass, boolean isLit) { - IIcon i; - if (pass == 0) { - if (isLit) { - i = this.litTip; - } else { - i = this.unlitTip; - } - } else { - if (isLit) { - i = this.litStump; - } else { - i = this.unlitStump; - } - } - return i; - } + @Override + public int getRenderType() { + return Proxies.render.getCandleRenderId(); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { - itemList.add(new ItemStack(this, 1, 0)); - } + @SideOnly(Side.CLIENT) + @Override + public void registerBlockIcons(IIconRegister register) { + String fileBase = StringUtil.cleanBlockName(this); + this.blockIcon = TextureManager.registerTex(register, "stump"); + this.litStump = TextureManager.registerTex(register, fileBase + "StumpLit"); + this.litTip = TextureManager.registerTex(register, fileBase + "TipLit"); + this.unlitStump = TextureManager.registerTex(register, fileBase + "StumpUnlit"); + this.unlitTip = TextureManager.registerTex(register, fileBase + "TipUnlit"); + } - @Override - public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int facing, float facingX, float facingY, float facingZ) { - TileEntity tileEntity = world.getTileEntity(x, y, z); - if (!(tileEntity instanceof TileCandle)) { - return false; - } + @Override + public int getLightValue(IBlockAccess world, int x, int y, int z) { + TileEntity tileEntity = world.getTileEntity(x, y, z); + if (tileEntity instanceof TileCandle && ((TileCandle) tileEntity).isLit()) { + return 14; + } + return 0; + } - TileCandle tileCandle = (TileCandle) tileEntity; - final boolean isLit = tileCandle.isLit(); + @SideOnly(Side.CLIENT) + public IIcon getTextureFromPassAndLit(int pass, boolean isLit) { + IIcon i; + if (pass == 0) { + if (isLit) { + i = this.litTip; + } else { + i = this.unlitTip; + } + } else { + if (isLit) { + i = this.litStump; + } else { + i = this.unlitStump; + } + } + return i; + } - boolean flag = false; - boolean toggleLitState = true; - ItemStack heldItem = player.getCurrentEquippedItem(); + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { + itemList.add(new ItemStack(this, 1, 0)); + } - if (!isLit) { - if (heldItem == null || !lightingItems.contains(heldItem.getItem())) { - toggleLitState = false; - } else if (ItemStackUtil.equals(this, heldItem) && isLit(heldItem)) { - toggleLitState = true; - } - } + @Override + public boolean onBlockActivated( + World world, + int x, + int y, + int z, + EntityPlayer player, + int facing, + float facingX, + float facingY, + float facingZ) { + TileEntity tileEntity = world.getTileEntity(x, y, z); + if (!(tileEntity instanceof TileCandle)) { + return false; + } - if (heldItem != null) { - if (ItemStackUtil.equals(this, heldItem)) { - if (!isLit(heldItem)) { - // Copy the colour of an unlit, coloured candle. - if (heldItem.hasTagCompound() && heldItem.getTagCompound().hasKey(colourTagName)) { - tileCandle.setColour(heldItem.getTagCompound().getInteger(colourTagName)); - } else { - // Reset to white if item has no - tileCandle.setColour(0xffffff); - } - } else { - toggleLitState = true; - } - flag = true; - } else { - boolean dyed = tryDye(heldItem, isLit, tileCandle); - if (dyed) { - world.markBlockForUpdate(x, y, z); - toggleLitState = false; - flag = true; - } - } - } + TileCandle tileCandle = (TileCandle) tileEntity; + final boolean isLit = tileCandle.isLit(); - if (toggleLitState) { - tileCandle.setLit(!isLit); - world.markBlockForUpdate(x, y, z); - flag = true; - } - return flag; - } + boolean flag = false; + boolean toggleLitState = true; + ItemStack heldItem = player.getCurrentEquippedItem(); - private static boolean tryDye(ItemStack held, boolean isLit, TileCandle tileCandle) { - // Check for dye-able ness. - for (Map.Entry colour : colours.entrySet()) { - String colourName = colour.getKey(); - for (ItemStack stack : OreDictionary.getOres(colourName)) { - if (OreDictionary.itemMatches(stack, held, true)) { - if (isLit) { - tileCandle.setColour(colour.getValue()); - } else { - tileCandle.addColour(colour.getValue()); - } - return true; - } - } - } - return false; - } + if (!isLit) { + if (heldItem == null || !lightingItems.contains(heldItem.getItem())) { + toggleLitState = false; + } else if (ItemStackUtil.equals(this, heldItem) && isLit(heldItem)) { + toggleLitState = true; + } + } - /* DROP HANDLING */ - // Hack: When harvesting we need to get the drops in onBlockHarvested, - // because Mojang destroys the block and tile before calling getDrops. - private final ThreadLocal drop = new ThreadLocal<>(); + if (heldItem != null) { + if (ItemStackUtil.equals(this, heldItem)) { + if (!isLit(heldItem)) { + // Copy the colour of an unlit, coloured candle. + if (heldItem.hasTagCompound() && heldItem.getTagCompound().hasKey(colourTagName)) { + tileCandle.setColour(heldItem.getTagCompound().getInteger(colourTagName)); + } else { + // Reset to white if item has no + tileCandle.setColour(0xffffff); + } + } else { + toggleLitState = true; + } + flag = true; + } else { + boolean dyed = tryDye(heldItem, isLit, tileCandle); + if (dyed) { + world.markBlockForUpdate(x, y, z); + toggleLitState = false; + flag = true; + } + } + } - @Override - public void onBlockHarvested(World world, int x, int y, int z, int metadata, EntityPlayer player) { - if (!world.isRemote) { - ItemStack itemStack = getCandleDrop(world, x, y, z); - drop.set(itemStack); - } - } + if (toggleLitState) { + tileCandle.setLit(!isLit); + world.markBlockForUpdate(x, y, z); + flag = true; + } + return flag; + } - @Override - public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - ItemStack dropStack = drop.get(); - drop.remove(); + private static boolean tryDye(ItemStack held, boolean isLit, TileCandle tileCandle) { + // Check for dye-able ness. + for (Map.Entry colour : colours.entrySet()) { + String colourName = colour.getKey(); + for (ItemStack stack : OreDictionary.getOres(colourName)) { + if (OreDictionary.itemMatches(stack, held, true)) { + if (isLit) { + tileCandle.setColour(colour.getValue()); + } else { + tileCandle.addColour(colour.getValue()); + } + return true; + } + } + } + return false; + } - // not harvested, get drops normally - if (dropStack == null) { - dropStack = getCandleDrop(world, x, y, z); - } + /* DROP HANDLING */ + // Hack: When harvesting we need to get the drops in onBlockHarvested, + // because Mojang destroys the block and tile before calling getDrops. + private final ThreadLocal drop = new ThreadLocal<>(); - ArrayList drops = new ArrayList<>(1); - drops.add(dropStack); + @Override + public void onBlockHarvested(World world, int x, int y, int z, int metadata, EntityPlayer player) { + if (!world.isRemote) { + ItemStack itemStack = getCandleDrop(world, x, y, z); + drop.set(itemStack); + } + } - return drops; - } + @Override + public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + ItemStack dropStack = drop.get(); + drop.remove(); - @Override - public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { - return getCandleDrop(world, x, y, z); - } + // not harvested, get drops normally + if (dropStack == null) { + dropStack = getCandleDrop(world, x, y, z); + } - private ItemStack getCandleDrop(World world, int x, int y, int z) { - TileEntity tileEntity = world.getTileEntity(x, y, z); - if (!(tileEntity instanceof TileCandle)) { - return null; - } - TileCandle tileCandle = (TileCandle) tileEntity; - int colour = tileCandle.getColour(); + ArrayList drops = new ArrayList<>(1); + drops.add(dropStack); - int newMeta = tileCandle.isLit() ? 1 : 0; - ItemStack itemStack = new ItemStack(this, 1, newMeta); - if (colour != 0xffffff) { - // When dropped, tag new item stack with colour. Unless it's white, then do no such thing for maximum stacking. - NBTTagCompound tag = new NBTTagCompound(); - tag.setInteger(colourTagName, colour); - itemStack.setTagCompound(tag); - } - return itemStack; - } + return drops; + } - @Override - public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack itemStack) { - TileCandle tileCandle = (TileCandle) (world.getTileEntity(x, y, z)); - int colour = getColourValueFromItemStack(itemStack); - boolean isLit = isLit(itemStack); - tileCandle.setColour(colour); - tileCandle.setLit(isLit); - } + @Override + public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { + return getCandleDrop(world, x, y, z); + } - @Override - @SideOnly(Side.CLIENT) - public void randomDisplayTick(World world, int x, int y, int z, Random random) { - TileEntity tileEntity = world.getTileEntity(x, y, z); - if (tileEntity instanceof TileCandle && ((TileCandle) tileEntity).isLit()) { - super.randomDisplayTick(world, x, y, z, random); - } - } + private ItemStack getCandleDrop(World world, int x, int y, int z) { + TileEntity tileEntity = world.getTileEntity(x, y, z); + if (!(tileEntity instanceof TileCandle)) { + return null; + } + TileCandle tileCandle = (TileCandle) tileEntity; + int colour = tileCandle.getColour(); - private static int getColourValueFromItemStack(ItemStack itemStack) { - int value = 0xffffff; // default to white. - if (itemStack.hasTagCompound()) { - NBTTagCompound tag = itemStack.getTagCompound(); - if (tag.hasKey(colourTagName)) { - value = tag.getInteger(colourTagName); - } - } - return value; - } + int newMeta = tileCandle.isLit() ? 1 : 0; + ItemStack itemStack = new ItemStack(this, 1, newMeta); + if (colour != 0xffffff) { + // When dropped, tag new item stack with colour. Unless it's white, then do no such thing for maximum + // stacking. + NBTTagCompound tag = new NBTTagCompound(); + tag.setInteger(colourTagName, colour); + itemStack.setTagCompound(tag); + } + return itemStack; + } - public static boolean isLit(ItemStack itemStack) { - return itemStack.getItemDamage() > 0; - } + @Override + public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack itemStack) { + TileCandle tileCandle = (TileCandle) (world.getTileEntity(x, y, z)); + int colour = getColourValueFromItemStack(itemStack); + boolean isLit = isLit(itemStack); + tileCandle.setColour(colour); + tileCandle.setLit(isLit); + } - public static void addItemToLightingList(Item item) { - if (item == null) { - throw new NullPointerException(); - } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(World world, int x, int y, int z, Random random) { + TileEntity tileEntity = world.getTileEntity(x, y, z); + if (tileEntity instanceof TileCandle && ((TileCandle) tileEntity).isLit()) { + super.randomDisplayTick(world, x, y, z, random); + } + } - if (!lightingItems.contains(item)) { - lightingItems.add(item); - } - } + private static int getColourValueFromItemStack(ItemStack itemStack) { + int value = 0xffffff; // default to white. + if (itemStack.hasTagCompound()) { + NBTTagCompound tag = itemStack.getTagCompound(); + if (tag.hasKey(colourTagName)) { + value = tag.getInteger(colourTagName); + } + } + return value; + } - public ItemStack getUnlitCandle(int amount) { - return new ItemStack(this, amount, 0); - } + public static boolean isLit(ItemStack itemStack) { + return itemStack.getItemDamage() > 0; + } - public ItemStack getLitCandle(int amount) { - return new ItemStack(this, amount, 1); - } + public static void addItemToLightingList(Item item) { + if (item == null) { + throw new NullPointerException(); + } + + if (!lightingItems.contains(item)) { + lightingItems.add(item); + } + } + + public ItemStack getUnlitCandle(int amount) { + return new ItemStack(this, amount, 0); + } + + public ItemStack getLitCandle(int amount) { + return new ItemStack(this, amount, 1); + } } diff --git a/src/main/java/forestry/apiculture/blocks/BlockRegistryApiculture.java b/src/main/java/forestry/apiculture/blocks/BlockRegistryApiculture.java index bfac863c9..a211c606d 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockRegistryApiculture.java +++ b/src/main/java/forestry/apiculture/blocks/BlockRegistryApiculture.java @@ -1,41 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.blocks; - -import forestry.api.core.Tabs; -import forestry.apiculture.items.ItemBlockCandle; -import forestry.core.blocks.BlockBase; -import forestry.core.blocks.BlockRegistry; -import forestry.core.items.ItemBlockForestry; - -public class BlockRegistryApiculture extends BlockRegistry { - public final BlockApiculture apiculture; - public final BlockBase apicultureChest; - public final BlockBeehives beehives; - public final BlockCandle candle; - public final BlockStump stump; - public final BlockAlveary alveary; - - public BlockRegistryApiculture() { - apiculture = registerBlock(new BlockApiculture(), ItemBlockForestry.class, "apiculture"); - - apicultureChest = registerBlock(new BlockBase(true), ItemBlockForestry.class, "apicultureChest"); - apicultureChest.setCreativeTab(Tabs.tabApiculture); - apicultureChest.setHarvestLevel("axe", 0); - - beehives = registerBlock(new BlockBeehives(), ItemBlockForestry.class, "beehives"); - - candle = registerBlock(new BlockCandle(), ItemBlockCandle.class, "candle"); - stump = registerBlock(new BlockStump(), ItemBlockForestry.class, "stump"); - - alveary = registerBlock(new BlockAlveary(), ItemBlockForestry.class, "alveary"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.blocks; + +import forestry.api.core.Tabs; +import forestry.apiculture.items.ItemBlockCandle; +import forestry.core.blocks.BlockBase; +import forestry.core.blocks.BlockRegistry; +import forestry.core.items.ItemBlockForestry; + +public class BlockRegistryApiculture extends BlockRegistry { + public final BlockApiculture apiculture; + public final BlockBase apicultureChest; + public final BlockBeehives beehives; + public final BlockCandle candle; + public final BlockStump stump; + public final BlockAlveary alveary; + + public BlockRegistryApiculture() { + apiculture = registerBlock(new BlockApiculture(), ItemBlockForestry.class, "apiculture"); + + apicultureChest = registerBlock(new BlockBase(true), ItemBlockForestry.class, "apicultureChest"); + apicultureChest.setCreativeTab(Tabs.tabApiculture); + apicultureChest.setHarvestLevel("axe", 0); + + beehives = registerBlock(new BlockBeehives(), ItemBlockForestry.class, "beehives"); + + candle = registerBlock(new BlockCandle(), ItemBlockCandle.class, "candle"); + stump = registerBlock(new BlockStump(), ItemBlockForestry.class, "stump"); + + alveary = registerBlock(new BlockAlveary(), ItemBlockForestry.class, "alveary"); + } +} diff --git a/src/main/java/forestry/apiculture/blocks/BlockStump.java b/src/main/java/forestry/apiculture/blocks/BlockStump.java index c552f3617..edf10bac9 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockStump.java +++ b/src/main/java/forestry/apiculture/blocks/BlockStump.java @@ -10,9 +10,17 @@ ******************************************************************************/ package forestry.apiculture.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.core.Tabs; +import forestry.apiculture.tiles.TileCandle; +import forestry.core.config.Constants; +import forestry.core.render.TextureManager; +import forestry.core.utils.ItemStackUtil; +import forestry.core.utils.StringUtil; +import forestry.plugins.PluginApiculture; import java.util.List; import java.util.Random; - import net.minecraft.block.BlockTorch; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; @@ -23,63 +31,66 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.core.Tabs; -import forestry.apiculture.tiles.TileCandle; -import forestry.core.config.Constants; -import forestry.core.render.TextureManager; -import forestry.core.utils.ItemStackUtil; -import forestry.core.utils.StringUtil; -import forestry.plugins.PluginApiculture; - public class BlockStump extends BlockTorch { - public BlockStump() { - super(); - this.setHardness(0.0F); - this.setStepSound(soundTypeWood); - setCreativeTab(Tabs.tabApiculture); - } + public BlockStump() { + super(); + this.setHardness(0.0F); + this.setStepSound(soundTypeWood); + setCreativeTab(Tabs.tabApiculture); + } - @SideOnly(Side.CLIENT) - @Override - public void registerBlockIcons(IIconRegister register) { - this.blockIcon = TextureManager.registerTex(register, StringUtil.cleanBlockName(this)); - } + @SideOnly(Side.CLIENT) + @Override + public void registerBlockIcons(IIconRegister register) { + this.blockIcon = TextureManager.registerTex(register, StringUtil.cleanBlockName(this)); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { - itemList.add(new ItemStack(this, 1, 0)); - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { + itemList.add(new ItemStack(this, 1, 0)); + } - @Override - public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int facing, float facingX, float facingY, float facingZ) { + @Override + public boolean onBlockActivated( + World world, + int x, + int y, + int z, + EntityPlayer player, + int facing, + float facingX, + float facingY, + float facingZ) { - ItemStack held = player.getCurrentEquippedItem(); - if (held != null && - (held.getItem() == Items.flint_and_steel || - held.getItem() == Items.flint || - ItemStackUtil.equals(Blocks.torch, held))) { - world.setBlock(x, y, z, PluginApiculture.blocks.candle, world.getBlockMetadata(x, y, z) | 0x08, Constants.FLAG_BLOCK_SYNCH); - TileCandle tc = new TileCandle(); - tc.setColour(0); // default to white - world.setTileEntity(x, y, z, tc); - return true; - } + ItemStack held = player.getCurrentEquippedItem(); + if (held != null + && (held.getItem() == Items.flint_and_steel + || held.getItem() == Items.flint + || ItemStackUtil.equals(Blocks.torch, held))) { + world.setBlock( + x, + y, + z, + PluginApiculture.blocks.candle, + world.getBlockMetadata(x, y, z) | 0x08, + Constants.FLAG_BLOCK_SYNCH); + TileCandle tc = new TileCandle(); + tc.setColour(0); // default to white + world.setTileEntity(x, y, z, tc); + return true; + } - return false; - } + return false; + } - @Override - @SideOnly(Side.CLIENT) - public int getRenderColor(int par1) { - return 0xee0000; - } + @Override + @SideOnly(Side.CLIENT) + public int getRenderColor(int par1) { + return 0xee0000; + } - @Override - public void randomDisplayTick(World par1World, int par2, int par3, int par4, Random par5Random) { - } + @Override + public void randomDisplayTick(World par1World, int par2, int par3, int par4, Random par5Random) {} } diff --git a/src/main/java/forestry/apiculture/commands/BeeModeHelper.java b/src/main/java/forestry/apiculture/commands/BeeModeHelper.java index e54fe20e9..c85c05bc8 100644 --- a/src/main/java/forestry/apiculture/commands/BeeModeHelper.java +++ b/src/main/java/forestry/apiculture/commands/BeeModeHelper.java @@ -10,52 +10,49 @@ ******************************************************************************/ package forestry.apiculture.commands; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.world.World; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeekeepingMode; import forestry.core.commands.ICommandModeHelper; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.world.World; public class BeeModeHelper implements ICommandModeHelper { - @Override - public String[] getModeNames() { - ArrayList beekeepingModes = BeeManager.beeRoot.getBeekeepingModes(); - int modeStringCount = beekeepingModes.size(); - List modeStrings = new ArrayList<>(modeStringCount); - for (IBeekeepingMode mode : beekeepingModes) { - modeStrings.add(mode.getName()); - } + @Override + public String[] getModeNames() { + ArrayList beekeepingModes = BeeManager.beeRoot.getBeekeepingModes(); + int modeStringCount = beekeepingModes.size(); + List modeStrings = new ArrayList<>(modeStringCount); + for (IBeekeepingMode mode : beekeepingModes) { + modeStrings.add(mode.getName()); + } - return modeStrings.toArray(new String[modeStringCount]); - } + return modeStrings.toArray(new String[modeStringCount]); + } - @Override - public String getModeNameMatching(String desired) { - IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(desired); - if (mode == null) { - return null; - } - return mode.getName(); - } + @Override + public String getModeNameMatching(String desired) { + IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(desired); + if (mode == null) { + return null; + } + return mode.getName(); + } - @Override - public String getModeName(World world) { - return BeeManager.beeRoot.getBeekeepingMode(world).getName(); - } + @Override + public String getModeName(World world) { + return BeeManager.beeRoot.getBeekeepingMode(world).getName(); + } - @Override - public void setMode(World world, String modeName) { - BeeManager.beeRoot.setBeekeepingMode(world, modeName); - } - - @Override - public Iterable getDescription(String modeName) { - IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(modeName); - return mode.getDescription(); - } + @Override + public void setMode(World world, String modeName) { + BeeManager.beeRoot.setBeekeepingMode(world, modeName); + } + @Override + public Iterable getDescription(String modeName) { + IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(modeName); + return mode.getDescription(); + } } diff --git a/src/main/java/forestry/apiculture/commands/BeeStatsSaveHelper.java b/src/main/java/forestry/apiculture/commands/BeeStatsSaveHelper.java index 75a35e6d3..9ffcd1260 100644 --- a/src/main/java/forestry/apiculture/commands/BeeStatsSaveHelper.java +++ b/src/main/java/forestry/apiculture/commands/BeeStatsSaveHelper.java @@ -10,14 +10,7 @@ ******************************************************************************/ package forestry.apiculture.commands; -import java.util.ArrayList; -import java.util.Collection; - -import net.minecraft.util.StatCollector; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.api.apiculture.IApiaristTracker; @@ -27,49 +20,54 @@ import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IBreedingTracker; import forestry.core.commands.IStatsSaveHelper; import forestry.core.utils.StringUtil; +import java.util.ArrayList; +import java.util.Collection; +import net.minecraft.util.StatCollector; +import net.minecraft.world.World; public class BeeStatsSaveHelper implements IStatsSaveHelper { - @Override - public String getUnlocalizedSaveStatsString() { - return "for.chat.command.forestry.bee.save.stats"; - } + @Override + public String getUnlocalizedSaveStatsString() { + return "for.chat.command.forestry.bee.save.stats"; + } - @Override - public void addExtraInfo(Collection statistics, IBreedingTracker breedingTracker) { - IApiaristTracker tracker = (IApiaristTracker) breedingTracker; - String discoveredLine = StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.discovered") + ":"; - statistics.add(discoveredLine); - statistics.add(StringUtil.line(discoveredLine.length())); + @Override + public void addExtraInfo(Collection statistics, IBreedingTracker breedingTracker) { + IApiaristTracker tracker = (IApiaristTracker) breedingTracker; + String discoveredLine = + StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.discovered") + ":"; + statistics.add(discoveredLine); + statistics.add(StringUtil.line(discoveredLine.length())); - String queen = StatCollector.translateToLocal("for.bees.grammar.queen.type"); - String princess = StatCollector.translateToLocal("for.bees.grammar.princess.type"); - String drone = StatCollector.translateToLocal("for.bees.grammar.drone.type"); - statistics.add(queen + ":\t\t" + tracker.getQueenCount()); - statistics.add(princess + ":\t" + tracker.getPrincessCount()); - statistics.add(drone + ":\t\t" + tracker.getDroneCount()); - statistics.add(""); - } + String queen = StatCollector.translateToLocal("for.bees.grammar.queen.type"); + String princess = StatCollector.translateToLocal("for.bees.grammar.princess.type"); + String drone = StatCollector.translateToLocal("for.bees.grammar.drone.type"); + statistics.add(queen + ":\t\t" + tracker.getQueenCount()); + statistics.add(princess + ":\t" + tracker.getPrincessCount()); + statistics.add(drone + ":\t\t" + tracker.getDroneCount()); + statistics.add(""); + } - @Override - public Collection getSpecies() { - Collection species = new ArrayList<>(); - for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { - if (allele instanceof IAlleleBeeSpecies) { - species.add((IAlleleBeeSpecies) allele); - } - } - return species; - } + @Override + public Collection getSpecies() { + Collection species = new ArrayList<>(); + for (IAllele allele : + AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleBeeSpecies) { + species.add((IAlleleBeeSpecies) allele); + } + } + return species; + } - @Override - public String getFileSuffix() { - return "bees"; - } - - @Override - public IBreedingTracker getBreedingTracker(World world, GameProfile gameProfile) { - return BeeManager.beeRoot.getBreedingTracker(world, gameProfile); - } + @Override + public String getFileSuffix() { + return "bees"; + } + @Override + public IBreedingTracker getBreedingTracker(World world, GameProfile gameProfile) { + return BeeManager.beeRoot.getBreedingTracker(world, gameProfile); + } } diff --git a/src/main/java/forestry/apiculture/commands/CommandBee.java b/src/main/java/forestry/apiculture/commands/CommandBee.java index 9cf050973..19266346a 100644 --- a/src/main/java/forestry/apiculture/commands/CommandBee.java +++ b/src/main/java/forestry/apiculture/commands/CommandBee.java @@ -18,15 +18,15 @@ import forestry.core.commands.SubCommand; public class CommandBee extends SubCommand { - public CommandBee() { - super("bee"); - addAlias("beekeeping"); + public CommandBee() { + super("bee"); + addAlias("beekeeping"); - IStatsSaveHelper saveHelper = new BeeStatsSaveHelper(); - ICommandModeHelper modeHelper = new BeeModeHelper(); + IStatsSaveHelper saveHelper = new BeeStatsSaveHelper(); + ICommandModeHelper modeHelper = new BeeModeHelper(); - addChildCommand(new CommandMode(modeHelper)); - addChildCommand(new CommandSaveStats(saveHelper, modeHelper)); - addChildCommand(new CommandBeeGive()); - } + addChildCommand(new CommandMode(modeHelper)); + addChildCommand(new CommandSaveStats(saveHelper, modeHelper)); + addChildCommand(new CommandBeeGive()); + } } diff --git a/src/main/java/forestry/apiculture/commands/CommandBeeGive.java b/src/main/java/forestry/apiculture/commands/CommandBeeGive.java index 0e113dca2..4e6f33ea1 100644 --- a/src/main/java/forestry/apiculture/commands/CommandBeeGive.java +++ b/src/main/java/forestry/apiculture/commands/CommandBeeGive.java @@ -10,14 +10,6 @@ ******************************************************************************/ package forestry.apiculture.commands; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.IAlleleBeeSpecies; @@ -29,151 +21,165 @@ import forestry.core.commands.CommandHelpers; import forestry.core.commands.SpeciesNotFoundException; import forestry.core.commands.SubCommand; import forestry.core.commands.TemplateNotFoundException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; public class CommandBeeGive extends SubCommand { - private final String beeTypeHelpString; - private final String[] beeTypeArr; + private final String beeTypeHelpString; + private final String[] beeTypeArr; - public CommandBeeGive() { - super("give"); - setPermLevel(PermLevel.ADMIN); + public CommandBeeGive() { + super("give"); + setPermLevel(PermLevel.ADMIN); - List beeTypeStrings = new ArrayList<>(); - for (EnumBeeType type : EnumBeeType.values()) { - if (type == EnumBeeType.NONE) { - continue; - } - beeTypeStrings.add(type.getName()); - } + List beeTypeStrings = new ArrayList<>(); + for (EnumBeeType type : EnumBeeType.values()) { + if (type == EnumBeeType.NONE) { + continue; + } + beeTypeStrings.add(type.getName()); + } - beeTypeArr = beeTypeStrings.toArray(new String[beeTypeStrings.size()]); + beeTypeArr = beeTypeStrings.toArray(new String[beeTypeStrings.size()]); - StringBuilder beeTypeHelp = new StringBuilder(); - String separator = ", "; + StringBuilder beeTypeHelp = new StringBuilder(); + String separator = ", "; - Iterator iter = beeTypeStrings.iterator(); - while (iter.hasNext()) { - beeTypeHelp.append(iter.next()); - if (iter.hasNext()) { - beeTypeHelp.append(separator); - } - } - beeTypeHelpString = beeTypeHelp.toString(); - } + Iterator iter = beeTypeStrings.iterator(); + while (iter.hasNext()) { + beeTypeHelp.append(iter.next()); + if (iter.hasNext()) { + beeTypeHelp.append(separator); + } + } + beeTypeHelpString = beeTypeHelp.toString(); + } - @Override - public void processSubCommand(ICommandSender sender, String[] arguments) { - if (arguments.length < 2) { - printHelp(sender); - return; - } + @Override + public void processSubCommand(ICommandSender sender, String[] arguments) { + if (arguments.length < 2) { + printHelp(sender); + return; + } - IBeeGenome beeGenome = getBeeGenome(arguments[0]); - EnumBeeType beeType = getBeeType(arguments[1]); - if (beeType == EnumBeeType.NONE) { - printHelp(sender); - return; - } + IBeeGenome beeGenome = getBeeGenome(arguments[0]); + EnumBeeType beeType = getBeeType(arguments[1]); + if (beeType == EnumBeeType.NONE) { + printHelp(sender); + return; + } - EntityPlayer player; - if (arguments.length == 3) { - player = CommandHelpers.getPlayer(sender, arguments[2]); - } else { - player = CommandHelpers.getPlayer(sender, sender.getCommandSenderName()); - } - if (player == null) { - printHelp(sender); - return; - } + EntityPlayer player; + if (arguments.length == 3) { + player = CommandHelpers.getPlayer(sender, arguments[2]); + } else { + player = CommandHelpers.getPlayer(sender, sender.getCommandSenderName()); + } + if (player == null) { + printHelp(sender); + return; + } - IBee bee = BeeManager.beeRoot.getBee(player.worldObj, beeGenome); + IBee bee = BeeManager.beeRoot.getBee(player.worldObj, beeGenome); - if (beeType == EnumBeeType.QUEEN) { - bee.mate(bee); - } + if (beeType == EnumBeeType.QUEEN) { + bee.mate(bee); + } - ItemStack beeStack = BeeManager.beeRoot.getMemberStack(bee, beeType.ordinal()); - player.dropPlayerItemWithRandomChoice(beeStack, true); + ItemStack beeStack = BeeManager.beeRoot.getMemberStack(bee, beeType.ordinal()); + player.dropPlayerItemWithRandomChoice(beeStack, true); - CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.bee.give.given", player.getCommandSenderName(), bee.getGenome().getPrimary().getName(), beeType.getName()); - } + CommandHelpers.sendLocalizedChatMessage( + sender, + "for.chat.command.forestry.bee.give.given", + player.getCommandSenderName(), + bee.getGenome().getPrimary().getName(), + beeType.getName()); + } - private static IBeeGenome getBeeGenome(String speciesName) { - IAlleleBeeSpecies species = null; + private static IBeeGenome getBeeGenome(String speciesName) { + IAlleleBeeSpecies species = null; - for (String uid : AlleleManager.alleleRegistry.getRegisteredAlleles().keySet()) { + for (String uid : AlleleManager.alleleRegistry.getRegisteredAlleles().keySet()) { - if (!uid.equals(speciesName)) { - continue; - } + if (!uid.equals(speciesName)) { + continue; + } - if (AlleleManager.alleleRegistry.getAllele(uid) instanceof IAlleleBeeSpecies) { - species = (IAlleleBeeSpecies) AlleleManager.alleleRegistry.getAllele(uid); - break; - } - } + if (AlleleManager.alleleRegistry.getAllele(uid) instanceof IAlleleBeeSpecies) { + species = (IAlleleBeeSpecies) AlleleManager.alleleRegistry.getAllele(uid); + break; + } + } - if (species == null) { - for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { - if (allele instanceof IAlleleBeeSpecies && allele.getName().equals(speciesName)) { - species = (IAlleleBeeSpecies) allele; - break; - } - } - } + if (species == null) { + for (IAllele allele : + AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleBeeSpecies && allele.getName().equals(speciesName)) { + species = (IAlleleBeeSpecies) allele; + break; + } + } + } - if (species == null) { - throw new SpeciesNotFoundException(speciesName); - } + if (species == null) { + throw new SpeciesNotFoundException(speciesName); + } - IAllele[] template = BeeManager.beeRoot.getTemplate(species.getUID()); + IAllele[] template = BeeManager.beeRoot.getTemplate(species.getUID()); - if (template == null) { - throw new TemplateNotFoundException(species); - } + if (template == null) { + throw new TemplateNotFoundException(species); + } - return BeeManager.beeRoot.templateAsGenome(template); - } + return BeeManager.beeRoot.templateAsGenome(template); + } - @Override - public List addTabCompletionOptions(ICommandSender sender, String[] parameters) { - if (parameters.length == 1) { - List tabCompletion = CommandHelpers.getListOfStringsMatchingLastWord(parameters, getSpecies()); - tabCompletion.add("help"); - return tabCompletion; - } else if (parameters.length == 2) { - return CommandHelpers.getListOfStringsMatchingLastWord(parameters, beeTypeArr); - } else if (parameters.length == 3) { - return CommandHelpers.getListOfStringsMatchingLastWord(parameters, CommandHelpers.getPlayers()); - } - return null; - } + @Override + public List addTabCompletionOptions(ICommandSender sender, String[] parameters) { + if (parameters.length == 1) { + List tabCompletion = CommandHelpers.getListOfStringsMatchingLastWord(parameters, getSpecies()); + tabCompletion.add("help"); + return tabCompletion; + } else if (parameters.length == 2) { + return CommandHelpers.getListOfStringsMatchingLastWord(parameters, beeTypeArr); + } else if (parameters.length == 3) { + return CommandHelpers.getListOfStringsMatchingLastWord(parameters, CommandHelpers.getPlayers()); + } + return null; + } - private static String[] getSpecies() { - List species = new ArrayList<>(); + private static String[] getSpecies() { + List species = new ArrayList<>(); - for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { - if (allele instanceof IAlleleBeeSpecies) { - species.add(allele.getName()); - } - } + for (IAllele allele : + AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleBeeSpecies) { + species.add(allele.getName()); + } + } - return species.toArray(new String[species.size()]); - } + return species.toArray(new String[species.size()]); + } - private static EnumBeeType getBeeType(String beeTypeName) { - for (EnumBeeType beeType : EnumBeeType.values()) { - if (beeType.getName().equalsIgnoreCase(beeTypeName)) { - return beeType; - } - } - return EnumBeeType.NONE; - } + private static EnumBeeType getBeeType(String beeTypeName) { + for (EnumBeeType beeType : EnumBeeType.values()) { + if (beeType.getName().equalsIgnoreCase(beeTypeName)) { + return beeType; + } + } + return EnumBeeType.NONE; + } - @Override - public void printHelp(ICommandSender sender) { - super.printHelp(sender); - CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.beekeeping.give.available", beeTypeHelpString); - } + @Override + public void printHelp(ICommandSender sender) { + super.printHelp(sender); + CommandHelpers.sendLocalizedChatMessage( + sender, "for.chat.command.forestry.beekeeping.give.available", beeTypeHelpString); + } } diff --git a/src/main/java/forestry/apiculture/entities/AIAvoidPlayers.java b/src/main/java/forestry/apiculture/entities/AIAvoidPlayers.java index 4b4472546..8f5aa5a20 100644 --- a/src/main/java/forestry/apiculture/entities/AIAvoidPlayers.java +++ b/src/main/java/forestry/apiculture/entities/AIAvoidPlayers.java @@ -20,76 +20,77 @@ import net.minecraft.util.Vec3; public class AIAvoidPlayers extends EntityAIBase { - private final EntityCreature mob; + private final EntityCreature mob; - private final float farSpeed; - private final float nearSpeed; - private final float minDistance; + private final float farSpeed; + private final float nearSpeed; + private final float minDistance; - private PathEntity pathing; + private PathEntity pathing; - private final PathNavigate pathNavigator; + private final PathNavigate pathNavigator; - private EntityPlayer player; + private EntityPlayer player; - public AIAvoidPlayers(EntityCreature mob, float minDistance, float farSpeed, float nearSpeed) { - this.mob = mob; - this.minDistance = minDistance; - this.farSpeed = farSpeed; - this.nearSpeed = nearSpeed; - this.pathNavigator = mob.getNavigator(); - this.setMutexBits(1); - } + public AIAvoidPlayers(EntityCreature mob, float minDistance, float farSpeed, float nearSpeed) { + this.mob = mob; + this.minDistance = minDistance; + this.farSpeed = farSpeed; + this.nearSpeed = nearSpeed; + this.pathNavigator = mob.getNavigator(); + this.setMutexBits(1); + } - @Override - public boolean shouldExecute() { + @Override + public boolean shouldExecute() { - player = mob.worldObj.getClosestPlayerToEntity(mob, minDistance); + player = mob.worldObj.getClosestPlayerToEntity(mob, minDistance); - if (player == null) { - return false; - } + if (player == null) { + return false; + } - if (!mob.getEntitySenses().canSee(player)) { - return false; - } + if (!mob.getEntitySenses().canSee(player)) { + return false; + } - Vec3 randomTarget = RandomPositionGenerator.findRandomTargetBlockAwayFrom(mob, 16, 7, - Vec3.createVectorHelper(player.posX, player.posY, player.posZ)); + Vec3 randomTarget = RandomPositionGenerator.findRandomTargetBlockAwayFrom( + mob, 16, 7, Vec3.createVectorHelper(player.posX, player.posY, player.posZ)); - if (randomTarget == null) { - return false; - } + if (randomTarget == null) { + return false; + } - if (player.getDistanceSq(randomTarget.xCoord, randomTarget.yCoord, randomTarget.zCoord) < player.getDistanceSqToEntity(mob)) { - return false; - } + if (player.getDistanceSq(randomTarget.xCoord, randomTarget.yCoord, randomTarget.zCoord) + < player.getDistanceSqToEntity(mob)) { + return false; + } - pathing = pathNavigator.getPathToXYZ(randomTarget.xCoord, randomTarget.yCoord, randomTarget.zCoord); - return pathing != null && pathing.isDestinationSame(randomTarget); - } + pathing = pathNavigator.getPathToXYZ(randomTarget.xCoord, randomTarget.yCoord, randomTarget.zCoord); + return pathing != null && pathing.isDestinationSame(randomTarget); + } - @Override - public boolean continueExecuting() { - return !this.pathNavigator.noPath(); - } + @Override + public boolean continueExecuting() { + return !this.pathNavigator.noPath(); + } - @Override - public void startExecuting() { - this.pathNavigator.setPath(pathing, farSpeed); - } + @Override + public void startExecuting() { + this.pathNavigator.setPath(pathing, farSpeed); + } - @Override - public void resetTask() { - player = null; - } + @Override + public void resetTask() { + player = null; + } - @Override - public void updateTask() { - if (mob.getDistanceSqToEntity(player) < 49.0D) { - mob.getNavigator().setSpeed(nearSpeed); - } else { - mob.getNavigator().setSpeed(farSpeed); - } - } + @Override + public void updateTask() { + if (mob.getDistanceSqToEntity(player) < 49.0D) { + mob.getNavigator().setSpeed(nearSpeed); + } else { + mob.getNavigator().setSpeed(farSpeed); + } + } } diff --git a/src/main/java/forestry/apiculture/entities/EntityBee.java b/src/main/java/forestry/apiculture/entities/EntityBee.java index 2dd72a915..6001a25f2 100755 --- a/src/main/java/forestry/apiculture/entities/EntityBee.java +++ b/src/main/java/forestry/apiculture/entities/EntityBee.java @@ -10,85 +10,83 @@ ******************************************************************************/ package forestry.apiculture.entities; -import net.minecraft.entity.EntityCreature; -import net.minecraft.entity.passive.IAnimals; -import net.minecraft.util.ResourceLocation; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.api.apiculture.IBee; import forestry.core.config.Constants; import forestry.core.render.ForestryResource; +import net.minecraft.entity.EntityCreature; +import net.minecraft.entity.passive.IAnimals; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.World; public class EntityBee extends EntityCreature implements IAnimals { - private static final String DEFAULT_TEXTURE = Constants.TEXTURE_PATH_ENTITIES + "/bees/honeyBee.png"; + private static final String DEFAULT_TEXTURE = Constants.TEXTURE_PATH_ENTITIES + "/bees/honeyBee.png"; - private IBee contained; - private IAlleleBeeSpecies species; - private EnumBeeType type = EnumBeeType.DRONE; + private IBee contained; + private IAlleleBeeSpecies species; + private EnumBeeType type = EnumBeeType.DRONE; - private String beeTexture = DEFAULT_TEXTURE; - private long lastUpdate; + private String beeTexture = DEFAULT_TEXTURE; + private long lastUpdate; - public EntityBee(World world) { - super(world); - } + public EntityBee(World world) { + super(world); + } - private void resetAppearance() { - beeTexture = species.getEntityTexture(); - } + private void resetAppearance() { + beeTexture = species.getEntityTexture(); + } - public EntityBee setIndividual(IBee bee) { - if (bee != null) { - contained = bee; - } else { - contained = BeeManager.beeRoot.templateAsIndividual(BeeManager.beeRoot.getDefaultTemplate()); - } + public EntityBee setIndividual(IBee bee) { + if (bee != null) { + contained = bee; + } else { + contained = BeeManager.beeRoot.templateAsIndividual(BeeManager.beeRoot.getDefaultTemplate()); + } - //isImmuneToFire = contained.getGenome().getFireResist(); - setSpecies(contained.getGenome().getPrimary()); - //dataWatcher.updateObject(DATAWATCHER_ID_SPECIES, species.getUID()); - //dataWatcher.updateObject(DATAWATCHER_ID_SCALE, (int)(contained.getSize() * 100)); - return this; - } + // isImmuneToFire = contained.getGenome().getFireResist(); + setSpecies(contained.getGenome().getPrimary()); + // dataWatcher.updateObject(DATAWATCHER_ID_SPECIES, species.getUID()); + // dataWatcher.updateObject(DATAWATCHER_ID_SCALE, (int)(contained.getSize() * 100)); + return this; + } - public IBee getBee() { - return contained; - } + public IBee getBee() { + return contained; + } - public EntityBee setType(EnumBeeType type) { - this.type = type; - return this; - } + public EntityBee setType(EnumBeeType type) { + this.type = type; + return this; + } - public EnumBeeType getType() { - return type; - } + public EnumBeeType getType() { + return type; + } - public EntityBee setSpecies(IAlleleBeeSpecies species) { - this.species = species; - resetAppearance(); - lastUpdate = worldObj.getTotalWorldTime(); - return this; - } + public EntityBee setSpecies(IAlleleBeeSpecies species) { + this.species = species; + resetAppearance(); + lastUpdate = worldObj.getTotalWorldTime(); + return this; + } - @SideOnly(Side.CLIENT) - private ResourceLocation textureResource; - private long lastTextureUpdate; + @SideOnly(Side.CLIENT) + private ResourceLocation textureResource; - @SideOnly(Side.CLIENT) - public ResourceLocation getTexture() { - if (textureResource == null || lastTextureUpdate != lastUpdate) { - textureResource = new ForestryResource(beeTexture); - } + private long lastTextureUpdate; - return textureResource; - } + @SideOnly(Side.CLIENT) + public ResourceLocation getTexture() { + if (textureResource == null || lastTextureUpdate != lastUpdate) { + textureResource = new ForestryResource(beeTexture); + } + return textureResource; + } } diff --git a/src/main/java/forestry/apiculture/entities/EntityFXBee.java b/src/main/java/forestry/apiculture/entities/EntityFXBee.java index 5f6ef45ef..52e3ebead 100644 --- a/src/main/java/forestry/apiculture/entities/EntityFXBee.java +++ b/src/main/java/forestry/apiculture/entities/EntityFXBee.java @@ -15,74 +15,76 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.world.World; public class EntityFXBee extends EntityFX { - public EntityFXBee(World world, double x, double y, double z, int color) { - super(world, x, y, z, 0.0D, 0.0D, 0.0D); + public EntityFXBee(World world, double x, double y, double z, int color) { + super(world, x, y, z, 0.0D, 0.0D, 0.0D); - particleRed = (color >> 16 & 255) / 255.0F; - particleGreen = (color >> 8 & 255) / 255.0F; - particleBlue = (color & 255) / 255.0F; + particleRed = (color >> 16 & 255) / 255.0F; + particleGreen = (color >> 8 & 255) / 255.0F; + particleBlue = (color & 255) / 255.0F; - this.setSize(0.1F, 0.1F); - this.particleScale *= 0.2F; - this.particleMaxAge = (int) (20.0D / (Math.random() * 0.8D + 0.2D)); - this.noClip = true; + this.setSize(0.1F, 0.1F); + this.particleScale *= 0.2F; + this.particleMaxAge = (int) (20.0D / (Math.random() * 0.8D + 0.2D)); + this.noClip = true; - this.motionX *= 0.1D; - this.motionY *= 0.015D; - this.motionZ *= 0.1D; - } + this.motionX *= 0.1D; + this.motionY *= 0.015D; + this.motionZ *= 0.1D; + } - /** - * Called to update the entity's position/logic. - */ - @Override - public void onUpdate() { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - this.moveEntity(this.motionX, this.motionY, this.motionZ); - this.motionX *= (1 + 0.2D * rand.nextFloat()); - this.motionY = (this.motionY + 0.2 * (-0.5 + rand.nextFloat())) / 2; - this.motionZ *= (1 + 0.2D * rand.nextFloat()); + /** + * Called to update the entity's position/logic. + */ + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.motionX *= (1 + 0.2D * rand.nextFloat()); + this.motionY = (this.motionY + 0.2 * (-0.5 + rand.nextFloat())) / 2; + this.motionZ *= (1 + 0.2D * rand.nextFloat()); - if (this.particleAge++ >= this.particleMaxAge) { - this.setDead(); - } - } + if (this.particleAge++ >= this.particleMaxAge) { + this.setDead(); + } + } - @Override - public void renderParticle(Tessellator tessellator, float f, float f1, float f2, float f3, float f4, float f5) { - float minU = 0; - float maxU = 1; - float minV = 0; - float maxV = 1; + @Override + public void renderParticle(Tessellator tessellator, float f, float f1, float f2, float f3, float f4, float f5) { + float minU = 0; + float maxU = 1; + float minV = 0; + float maxV = 1; - if (this.particleIcon != null) { - minU = particleIcon.getMinU(); - maxU = particleIcon.getMaxU(); - minV = particleIcon.getMinV(); - maxV = particleIcon.getMaxV(); - } + if (this.particleIcon != null) { + minU = particleIcon.getMinU(); + maxU = particleIcon.getMaxU(); + minV = particleIcon.getMinV(); + maxV = particleIcon.getMaxV(); + } - float f10 = 0.1F * particleScale; - float f11 = (float) ((prevPosX + (posX - prevPosX) * f) - interpPosX); - float f12 = (float) ((prevPosY + (posY - prevPosY) * f) - interpPosY); - float f13 = (float) ((prevPosZ + (posZ - prevPosZ) * f) - interpPosZ); + float f10 = 0.1F * particleScale; + float f11 = (float) ((prevPosX + (posX - prevPosX) * f) - interpPosX); + float f12 = (float) ((prevPosY + (posY - prevPosY) * f) - interpPosY); + float f13 = (float) ((prevPosZ + (posZ - prevPosZ) * f) - interpPosZ); - tessellator.setColorRGBA_F(particleRed, particleGreen, particleBlue, 1.0F); - tessellator.addVertexWithUV(f11 - f1 * f10 - f4 * f10, f12 - f2 * f10, f13 - f3 * f10 - f5 * f10, maxU, maxV); - tessellator.addVertexWithUV((f11 - f1 * f10) + f4 * f10, f12 + f2 * f10, (f13 - f3 * f10) + f5 * f10, maxU, minV); - tessellator.addVertexWithUV(f11 + f1 * f10 + f4 * f10, f12 + f2 * f10, f13 + f3 * f10 + f5 * f10, minU, minV); - tessellator.addVertexWithUV((f11 + f1 * f10) - f4 * f10, f12 - f2 * f10, (f13 + f3 * f10) - f5 * f10, minU, maxV); - } + tessellator.setColorRGBA_F(particleRed, particleGreen, particleBlue, 1.0F); + tessellator.addVertexWithUV(f11 - f1 * f10 - f4 * f10, f12 - f2 * f10, f13 - f3 * f10 - f5 * f10, maxU, maxV); + tessellator.addVertexWithUV( + (f11 - f1 * f10) + f4 * f10, f12 + f2 * f10, (f13 - f3 * f10) + f5 * f10, maxU, minV); + tessellator.addVertexWithUV(f11 + f1 * f10 + f4 * f10, f12 + f2 * f10, f13 + f3 * f10 + f5 * f10, minU, minV); + tessellator.addVertexWithUV( + (f11 + f1 * f10) - f4 * f10, f12 - f2 * f10, (f13 + f3 * f10) - f5 * f10, minU, maxV); + } - @Override - public int getBrightnessForRender(float partialTicks) { - return 0x0000f0; - } + @Override + public int getBrightnessForRender(float partialTicks) { + return 0x0000f0; + } - @Override - public int getFXLayer() { - return 2; - } + @Override + public int getFXLayer() { + return 2; + } } diff --git a/src/main/java/forestry/apiculture/entities/EntityMinecartApiary.java b/src/main/java/forestry/apiculture/entities/EntityMinecartApiary.java index 1a831b7c7..307126f6f 100644 --- a/src/main/java/forestry/apiculture/entities/EntityMinecartApiary.java +++ b/src/main/java/forestry/apiculture/entities/EntityMinecartApiary.java @@ -1,121 +1,119 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.entities; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -import forestry.api.apiculture.IBeeHousingInventory; -import forestry.api.apiculture.IBeeListener; -import forestry.api.apiculture.IBeeModifier; -import forestry.api.apiculture.IHiveFrame; -import forestry.apiculture.ApiaryBeeListener; -import forestry.apiculture.ApiaryBeeModifier; -import forestry.apiculture.IApiary; -import forestry.apiculture.blocks.BlockApicultureType; -import forestry.apiculture.gui.ContainerMinecartBeehouse; -import forestry.apiculture.gui.GuiBeeHousing; -import forestry.apiculture.inventory.IApiaryInventory; -import forestry.apiculture.inventory.InventoryApiary; -import forestry.core.config.Config; -import forestry.core.inventory.IInventoryAdapter; -import forestry.plugins.PluginApiculture; - -public class EntityMinecartApiary extends EntityMinecartBeeHousingBase implements IApiary { - private static final IBeeModifier beeModifier = new ApiaryBeeModifier(); - private final IBeeListener beeListener = new ApiaryBeeListener(this); - private final InventoryApiary inventory = new InventoryApiary(getAccessHandler()); - - @SuppressWarnings("unused") - public EntityMinecartApiary(World world) { - super(world); - } - - public EntityMinecartApiary(World world, double posX, double posY, double posZ) { - super(world, posX, posY, posZ); - } - - @Override - public List getHints() { - return Config.hints.get("apiary"); - } - - @Override - protected IInventoryAdapter getInternalInventory() { - return inventory; - } - - @Override - public IApiaryInventory getApiaryInventory() { - return inventory; - } - - @Override - public IBeeHousingInventory getBeeInventory() { - return inventory; - } - - @Override - public Block func_145820_n() { - return PluginApiculture.blocks.apiculture; - } - - @Override - public int getDisplayTileData() { - return BlockApicultureType.APIARY.ordinal(); - } - - @Override - public ItemStack getCartItem() { - return PluginApiculture.items.minecartBeehouse.getApiaryMinecart(); - } - - @Override - public Collection getBeeModifiers() { - List beeModifiers = new ArrayList<>(); - - beeModifiers.add(beeModifier); - - for (IHiveFrame frame : inventory.getFrames()) { - beeModifiers.add(frame.getBeeModifier()); - } - - return beeModifiers; - } - - @Override - public Iterable getBeeListeners() { - return Collections.singleton(beeListener); - } - - @Override - public Object getGui(EntityPlayer player, int data) { - ContainerMinecartBeehouse container = new ContainerMinecartBeehouse(player.inventory, this, true); - return new GuiBeeHousing<>(this, container, GuiBeeHousing.Icon.APIARY); - } - - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerMinecartBeehouse(player.inventory, this, true); - } - - @Override - public int getIdOfEntity() { - return getEntityId(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.entities; + +import forestry.api.apiculture.IBeeHousingInventory; +import forestry.api.apiculture.IBeeListener; +import forestry.api.apiculture.IBeeModifier; +import forestry.api.apiculture.IHiveFrame; +import forestry.apiculture.ApiaryBeeListener; +import forestry.apiculture.ApiaryBeeModifier; +import forestry.apiculture.IApiary; +import forestry.apiculture.blocks.BlockApicultureType; +import forestry.apiculture.gui.ContainerMinecartBeehouse; +import forestry.apiculture.gui.GuiBeeHousing; +import forestry.apiculture.inventory.IApiaryInventory; +import forestry.apiculture.inventory.InventoryApiary; +import forestry.core.config.Config; +import forestry.core.inventory.IInventoryAdapter; +import forestry.plugins.PluginApiculture; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; + +public class EntityMinecartApiary extends EntityMinecartBeeHousingBase implements IApiary { + private static final IBeeModifier beeModifier = new ApiaryBeeModifier(); + private final IBeeListener beeListener = new ApiaryBeeListener(this); + private final InventoryApiary inventory = new InventoryApiary(getAccessHandler()); + + @SuppressWarnings("unused") + public EntityMinecartApiary(World world) { + super(world); + } + + public EntityMinecartApiary(World world, double posX, double posY, double posZ) { + super(world, posX, posY, posZ); + } + + @Override + public List getHints() { + return Config.hints.get("apiary"); + } + + @Override + protected IInventoryAdapter getInternalInventory() { + return inventory; + } + + @Override + public IApiaryInventory getApiaryInventory() { + return inventory; + } + + @Override + public IBeeHousingInventory getBeeInventory() { + return inventory; + } + + @Override + public Block func_145820_n() { + return PluginApiculture.blocks.apiculture; + } + + @Override + public int getDisplayTileData() { + return BlockApicultureType.APIARY.ordinal(); + } + + @Override + public ItemStack getCartItem() { + return PluginApiculture.items.minecartBeehouse.getApiaryMinecart(); + } + + @Override + public Collection getBeeModifiers() { + List beeModifiers = new ArrayList<>(); + + beeModifiers.add(beeModifier); + + for (IHiveFrame frame : inventory.getFrames()) { + beeModifiers.add(frame.getBeeModifier()); + } + + return beeModifiers; + } + + @Override + public Iterable getBeeListeners() { + return Collections.singleton(beeListener); + } + + @Override + public Object getGui(EntityPlayer player, int data) { + ContainerMinecartBeehouse container = new ContainerMinecartBeehouse(player.inventory, this, true); + return new GuiBeeHousing<>(this, container, GuiBeeHousing.Icon.APIARY); + } + + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerMinecartBeehouse(player.inventory, this, true); + } + + @Override + public int getIdOfEntity() { + return getEntityId(); + } +} diff --git a/src/main/java/forestry/apiculture/entities/EntityMinecartBeeHousingBase.java b/src/main/java/forestry/apiculture/entities/EntityMinecartBeeHousingBase.java index ee1da4304..c2126b44e 100644 --- a/src/main/java/forestry/apiculture/entities/EntityMinecartBeeHousingBase.java +++ b/src/main/java/forestry/apiculture/entities/EntityMinecartBeeHousingBase.java @@ -1,184 +1,182 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.entities; - -import java.io.IOException; -import java.util.Random; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - -import com.mojang.authlib.GameProfile; - -import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeekeepingLogic; -import forestry.api.core.EnumHumidity; -import forestry.api.core.EnumTemperature; -import forestry.api.core.ForestryAPI; -import forestry.api.core.IErrorLogic; -import forestry.apiculture.gui.IGuiBeeHousingInventory; -import forestry.apiculture.network.packets.PacketBeeLogicEntityRequest; -import forestry.apiculture.tiles.TileBeeHousingBase; -import forestry.core.entities.EntityMinecartContainerForestry; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.IStreamableGui; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.IClimatised; - -public abstract class EntityMinecartBeeHousingBase extends EntityMinecartContainerForestry implements IBeeHousing, IGuiBeeHousingInventory, IClimatised, IStreamableGui { - private static final Random random = new Random(); - private static final int beeFXInterval = 4; - private static final int pollenFXInterval = 50; - - private final int beeFXTime = random.nextInt(beeFXInterval); - private final int pollenFXTime = random.nextInt(pollenFXInterval); - - private final IBeekeepingLogic beeLogic = BeeManager.beeRoot.createBeekeepingLogic(this); - private final IErrorLogic errorLogic = ForestryAPI.errorStateRegistry.createErrorLogic(); - - // CLIENT - private int breedingProgressPercent = 0; - private boolean needsActiveUpdate = true; - - @SuppressWarnings("unused") - public EntityMinecartBeeHousingBase(World world) { - super(world); - } - - public EntityMinecartBeeHousingBase(World world, double posX, double posY, double posZ) { - super(world, posX, posY, posZ); - } - - /* IBeeHousing */ - @Override - public IBeekeepingLogic getBeekeepingLogic() { - return beeLogic; - } - - @Override - public EnumTemperature getTemperature() { - return EnumTemperature.getFromBiome(getBiome(), (int) posX, (int) posY, (int) posZ); - } - - @Override - public EnumHumidity getHumidity() { - return EnumHumidity.getFromValue(getBiome().rainfall); - } - - @Override - public float getExactTemperature() { - return getBiome().temperature; - } - - @Override - public float getExactHumidity() { - return getBiome().rainfall; - } - - @Override - public int getBlockLightValue() { - return worldObj.getBlockLightValue((int) posX, (int) posY + 1, (int) posZ); - } - - @Override - public boolean canBlockSeeTheSky() { - return worldObj.canBlockSeeTheSky((int) posX, (int) posY + 1, (int) posZ); - } - - @Override - public World getWorld() { - return worldObj; - } - - @Override - public BiomeGenBase getBiome() { - return worldObj.getBiomeGenForCoords((int) posX, (int) posZ); - } - - @Override - public GameProfile getOwner() { - return getAccessHandler().getOwner(); - } - - @Override - public IErrorLogic getErrorLogic() { - return errorLogic; - } - - @Override - public ChunkCoordinates getCoordinates() { - return new ChunkCoordinates((int) posX, (int) posY, (int) posZ); - } - - @Override - public Vec3 getBeeFXCoordinates() { - return Vec3.createVectorHelper(posX, posY + 0.25, posZ); - } - - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - data.writeVarInt(beeLogic.getBeeProgressPercent()); - } - - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - breedingProgressPercent = data.readVarInt(); - } - - @Override - public int getHealthScaled(int i) { - return (breedingProgressPercent * i) / 100; - } - - @Override - public void onUpdate() { - super.onUpdate(); - if (!worldObj.isRemote) { - if (beeLogic.canWork()) { - beeLogic.doWork(); - } - } else { - if (needsActiveUpdate) { - IForestryPacketServer packet = new PacketBeeLogicEntityRequest(this); - Proxies.net.sendToServer(packet); - needsActiveUpdate = false; - } - - if (beeLogic.canDoBeeFX()) { - if (worldObj.getTotalWorldTime() % beeFXInterval == beeFXTime) { - beeLogic.doBeeFX(); - } - - if (worldObj.getTotalWorldTime() % pollenFXInterval == pollenFXTime) { - TileBeeHousingBase.doPollenFX(worldObj, posX - 0.5, posY - 0.1, posZ - 0.5); - } - } - } - } - - @Override - protected void readEntityFromNBT(NBTTagCompound nbtTagCompound) { - super.readEntityFromNBT(nbtTagCompound); - beeLogic.readFromNBT(nbtTagCompound); - } - - @Override - protected void writeEntityToNBT(NBTTagCompound nbtTagCompound) { - super.writeEntityToNBT(nbtTagCompound); - beeLogic.writeToNBT(nbtTagCompound); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.entities; + +import com.mojang.authlib.GameProfile; +import forestry.api.apiculture.BeeManager; +import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeekeepingLogic; +import forestry.api.core.EnumHumidity; +import forestry.api.core.EnumTemperature; +import forestry.api.core.ForestryAPI; +import forestry.api.core.IErrorLogic; +import forestry.apiculture.gui.IGuiBeeHousingInventory; +import forestry.apiculture.network.packets.PacketBeeLogicEntityRequest; +import forestry.apiculture.tiles.TileBeeHousingBase; +import forestry.core.entities.EntityMinecartContainerForestry; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.IStreamableGui; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.IClimatised; +import java.io.IOException; +import java.util.Random; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; + +public abstract class EntityMinecartBeeHousingBase extends EntityMinecartContainerForestry + implements IBeeHousing, IGuiBeeHousingInventory, IClimatised, IStreamableGui { + private static final Random random = new Random(); + private static final int beeFXInterval = 4; + private static final int pollenFXInterval = 50; + + private final int beeFXTime = random.nextInt(beeFXInterval); + private final int pollenFXTime = random.nextInt(pollenFXInterval); + + private final IBeekeepingLogic beeLogic = BeeManager.beeRoot.createBeekeepingLogic(this); + private final IErrorLogic errorLogic = ForestryAPI.errorStateRegistry.createErrorLogic(); + + // CLIENT + private int breedingProgressPercent = 0; + private boolean needsActiveUpdate = true; + + @SuppressWarnings("unused") + public EntityMinecartBeeHousingBase(World world) { + super(world); + } + + public EntityMinecartBeeHousingBase(World world, double posX, double posY, double posZ) { + super(world, posX, posY, posZ); + } + + /* IBeeHousing */ + @Override + public IBeekeepingLogic getBeekeepingLogic() { + return beeLogic; + } + + @Override + public EnumTemperature getTemperature() { + return EnumTemperature.getFromBiome(getBiome(), (int) posX, (int) posY, (int) posZ); + } + + @Override + public EnumHumidity getHumidity() { + return EnumHumidity.getFromValue(getBiome().rainfall); + } + + @Override + public float getExactTemperature() { + return getBiome().temperature; + } + + @Override + public float getExactHumidity() { + return getBiome().rainfall; + } + + @Override + public int getBlockLightValue() { + return worldObj.getBlockLightValue((int) posX, (int) posY + 1, (int) posZ); + } + + @Override + public boolean canBlockSeeTheSky() { + return worldObj.canBlockSeeTheSky((int) posX, (int) posY + 1, (int) posZ); + } + + @Override + public World getWorld() { + return worldObj; + } + + @Override + public BiomeGenBase getBiome() { + return worldObj.getBiomeGenForCoords((int) posX, (int) posZ); + } + + @Override + public GameProfile getOwner() { + return getAccessHandler().getOwner(); + } + + @Override + public IErrorLogic getErrorLogic() { + return errorLogic; + } + + @Override + public ChunkCoordinates getCoordinates() { + return new ChunkCoordinates((int) posX, (int) posY, (int) posZ); + } + + @Override + public Vec3 getBeeFXCoordinates() { + return Vec3.createVectorHelper(posX, posY + 0.25, posZ); + } + + @Override + public void writeGuiData(DataOutputStreamForestry data) throws IOException { + data.writeVarInt(beeLogic.getBeeProgressPercent()); + } + + @Override + public void readGuiData(DataInputStreamForestry data) throws IOException { + breedingProgressPercent = data.readVarInt(); + } + + @Override + public int getHealthScaled(int i) { + return (breedingProgressPercent * i) / 100; + } + + @Override + public void onUpdate() { + super.onUpdate(); + if (!worldObj.isRemote) { + if (beeLogic.canWork()) { + beeLogic.doWork(); + } + } else { + if (needsActiveUpdate) { + IForestryPacketServer packet = new PacketBeeLogicEntityRequest(this); + Proxies.net.sendToServer(packet); + needsActiveUpdate = false; + } + + if (beeLogic.canDoBeeFX()) { + if (worldObj.getTotalWorldTime() % beeFXInterval == beeFXTime) { + beeLogic.doBeeFX(); + } + + if (worldObj.getTotalWorldTime() % pollenFXInterval == pollenFXTime) { + TileBeeHousingBase.doPollenFX(worldObj, posX - 0.5, posY - 0.1, posZ - 0.5); + } + } + } + } + + @Override + protected void readEntityFromNBT(NBTTagCompound nbtTagCompound) { + super.readEntityFromNBT(nbtTagCompound); + beeLogic.readFromNBT(nbtTagCompound); + } + + @Override + protected void writeEntityToNBT(NBTTagCompound nbtTagCompound) { + super.writeEntityToNBT(nbtTagCompound); + beeLogic.writeToNBT(nbtTagCompound); + } +} diff --git a/src/main/java/forestry/apiculture/entities/EntityMinecartBeehouse.java b/src/main/java/forestry/apiculture/entities/EntityMinecartBeehouse.java index 813e2fb2e..b935f57df 100644 --- a/src/main/java/forestry/apiculture/entities/EntityMinecartBeehouse.java +++ b/src/main/java/forestry/apiculture/entities/EntityMinecartBeehouse.java @@ -1,106 +1,104 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.entities; - -import java.util.Collections; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -import forestry.api.apiculture.DefaultBeeListener; -import forestry.api.apiculture.IBeeHousingInventory; -import forestry.api.apiculture.IBeeListener; -import forestry.api.apiculture.IBeeModifier; -import forestry.apiculture.BeehouseBeeModifier; -import forestry.apiculture.InventoryBeeHousing; -import forestry.apiculture.blocks.BlockApicultureType; -import forestry.apiculture.gui.ContainerMinecartBeehouse; -import forestry.apiculture.gui.GuiBeeHousing; -import forestry.core.config.Config; -import forestry.core.inventory.IInventoryAdapter; -import forestry.plugins.PluginApiculture; - -public class EntityMinecartBeehouse extends EntityMinecartBeeHousingBase { - private static final IBeeModifier beeModifier = new BeehouseBeeModifier(); - private static final IBeeListener beeListener = new DefaultBeeListener(); - private final InventoryBeeHousing beeInventory = new InventoryBeeHousing(9, getAccessHandler()); - - @SuppressWarnings("unused") - public EntityMinecartBeehouse(World world) { - super(world); - beeInventory.disableAutomation(); - } - - public EntityMinecartBeehouse(World world, double posX, double posY, double posZ) { - super(world, posX, posY, posZ); - beeInventory.disableAutomation(); - } - - @Override - public List getHints() { - return Config.hints.get("bee.house"); - } - - @Override - public Block func_145820_n() { - return PluginApiculture.blocks.apiculture; - } - - @Override - public int getDisplayTileData() { - return BlockApicultureType.BEEHOUSE.ordinal(); - } - - @Override - public ItemStack getCartItem() { - return PluginApiculture.items.minecartBeehouse.getBeeHouseMinecart(); - } - - /* IBeeHousing */ - @Override - public Iterable getBeeModifiers() { - return Collections.singleton(beeModifier); - } - - @Override - public Iterable getBeeListeners() { - return Collections.singleton(beeListener); - } - - @Override - public IBeeHousingInventory getBeeInventory() { - return beeInventory; - } - - @Override - protected IInventoryAdapter getInternalInventory() { - return beeInventory; - } - - @Override - public Object getGui(EntityPlayer player, int data) { - ContainerMinecartBeehouse container = new ContainerMinecartBeehouse(player.inventory, this, false); - return new GuiBeeHousing<>(this, container, GuiBeeHousing.Icon.BEE_HOUSE); - } - - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerMinecartBeehouse(player.inventory, this, false); - } - - @Override - public int getIdOfEntity() { - return getEntityId(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.entities; + +import forestry.api.apiculture.DefaultBeeListener; +import forestry.api.apiculture.IBeeHousingInventory; +import forestry.api.apiculture.IBeeListener; +import forestry.api.apiculture.IBeeModifier; +import forestry.apiculture.BeehouseBeeModifier; +import forestry.apiculture.InventoryBeeHousing; +import forestry.apiculture.blocks.BlockApicultureType; +import forestry.apiculture.gui.ContainerMinecartBeehouse; +import forestry.apiculture.gui.GuiBeeHousing; +import forestry.core.config.Config; +import forestry.core.inventory.IInventoryAdapter; +import forestry.plugins.PluginApiculture; +import java.util.Collections; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; + +public class EntityMinecartBeehouse extends EntityMinecartBeeHousingBase { + private static final IBeeModifier beeModifier = new BeehouseBeeModifier(); + private static final IBeeListener beeListener = new DefaultBeeListener(); + private final InventoryBeeHousing beeInventory = new InventoryBeeHousing(9, getAccessHandler()); + + @SuppressWarnings("unused") + public EntityMinecartBeehouse(World world) { + super(world); + beeInventory.disableAutomation(); + } + + public EntityMinecartBeehouse(World world, double posX, double posY, double posZ) { + super(world, posX, posY, posZ); + beeInventory.disableAutomation(); + } + + @Override + public List getHints() { + return Config.hints.get("bee.house"); + } + + @Override + public Block func_145820_n() { + return PluginApiculture.blocks.apiculture; + } + + @Override + public int getDisplayTileData() { + return BlockApicultureType.BEEHOUSE.ordinal(); + } + + @Override + public ItemStack getCartItem() { + return PluginApiculture.items.minecartBeehouse.getBeeHouseMinecart(); + } + + /* IBeeHousing */ + @Override + public Iterable getBeeModifiers() { + return Collections.singleton(beeModifier); + } + + @Override + public Iterable getBeeListeners() { + return Collections.singleton(beeListener); + } + + @Override + public IBeeHousingInventory getBeeInventory() { + return beeInventory; + } + + @Override + protected IInventoryAdapter getInternalInventory() { + return beeInventory; + } + + @Override + public Object getGui(EntityPlayer player, int data) { + ContainerMinecartBeehouse container = new ContainerMinecartBeehouse(player.inventory, this, false); + return new GuiBeeHousing<>(this, container, GuiBeeHousing.Icon.BEE_HOUSE); + } + + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerMinecartBeehouse(player.inventory, this, false); + } + + @Override + public int getIdOfEntity() { + return getEntityId(); + } +} diff --git a/src/main/java/forestry/apiculture/flowers/Flower.java b/src/main/java/forestry/apiculture/flowers/Flower.java index e93e39689..a848cf861 100644 --- a/src/main/java/forestry/apiculture/flowers/Flower.java +++ b/src/main/java/forestry/apiculture/flowers/Flower.java @@ -11,75 +11,77 @@ package forestry.apiculture.flowers; import com.google.common.base.Objects; - -import javax.annotation.Nonnull; - -import net.minecraft.block.Block; - -import net.minecraftforge.oredict.OreDictionary; - import forestry.api.genetics.IFlower; +import javax.annotation.Nonnull; +import net.minecraft.block.Block; +import net.minecraftforge.oredict.OreDictionary; final class Flower implements IFlower { - private final Block block; - private final int meta; - private Double weight; + private final Block block; + private final int meta; + private Double weight; - public Flower(Block block, int meta, double weight) { - this.block = block; - this.meta = meta; - this.weight = weight; - } + public Flower(Block block, int meta, double weight) { + this.block = block; + this.meta = meta; + this.weight = weight; + } - public boolean isPlantable() { - return this.weight != 0.0; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof IFlower)) { - return false; - } + public boolean isPlantable() { + return this.weight != 0.0; + } - IFlower flower = (IFlower) obj; + @Override + public boolean equals(Object obj) { + if (!(obj instanceof IFlower)) { + return false; + } - return Block.isEqualTo(this.block, flower.getBlock()) && (this.meta == OreDictionary.WILDCARD_VALUE || flower.getMeta() == OreDictionary.WILDCARD_VALUE || this.meta == flower.getMeta()); - } + IFlower flower = (IFlower) obj; - @Override - public int compareTo(@Nonnull IFlower other) { - return this.weight.compareTo(other.getWeight()); - } + return Block.isEqualTo(this.block, flower.getBlock()) + && (this.meta == OreDictionary.WILDCARD_VALUE + || flower.getMeta() == OreDictionary.WILDCARD_VALUE + || this.meta == flower.getMeta()); + } - @Override - public int hashCode() { - return Objects.hashCode(block); - } + @Override + public int compareTo(@Nonnull IFlower other) { + return this.weight.compareTo(other.getWeight()); + } - @Override - public Block getBlock() { - return block; - } + @Override + public int hashCode() { + return Objects.hashCode(block); + } - @Override - public int getMeta() { - return meta; - } + @Override + public Block getBlock() { + return block; + } - @Override - public double getWeight() { - return weight; - } + @Override + public int getMeta() { + return meta; + } - @Override - public void setWeight(double weight) { - this.weight = weight; - } + @Override + public double getWeight() { + return weight; + } - @Override - public String toString() { - return Objects.toStringHelper(this).add("block", block).add("meta", meta).add("weight", weight).toString(); - } + @Override + public void setWeight(double weight) { + this.weight = weight; + } + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("block", block) + .add("meta", meta) + .add("weight", weight) + .toString(); + } } diff --git a/src/main/java/forestry/apiculture/flowers/FlowerProvider.java b/src/main/java/forestry/apiculture/flowers/FlowerProvider.java index b89505274..1d0a333fa 100644 --- a/src/main/java/forestry/apiculture/flowers/FlowerProvider.java +++ b/src/main/java/forestry/apiculture/flowers/FlowerProvider.java @@ -10,69 +10,65 @@ ******************************************************************************/ package forestry.apiculture.flowers; -import java.util.EnumSet; -import java.util.Set; - -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -import net.minecraftforge.common.EnumPlantType; - import forestry.api.apiculture.FlowerManager; import forestry.api.genetics.IFlower; import forestry.api.genetics.IFlowerProvider; import forestry.api.genetics.IIndividual; import forestry.api.genetics.IPollinatable; import forestry.core.utils.StringUtil; +import java.util.EnumSet; +import java.util.Set; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraftforge.common.EnumPlantType; public class FlowerProvider implements IFlowerProvider { - private final String flowerType; - private final String description; + private final String flowerType; + private final String description; - public FlowerProvider(String flowerType, String description) { - this.flowerType = flowerType; - this.description = description; - } + public FlowerProvider(String flowerType, String description) { + this.flowerType = flowerType; + this.description = description; + } - @Override - public String getFlowerType() { - return flowerType; - } + @Override + public String getFlowerType() { + return flowerType; + } - @Override - public boolean isAcceptedPollinatable(World world, IPollinatable pollinatable) { + @Override + public boolean isAcceptedPollinatable(World world, IPollinatable pollinatable) { - EnumSet plantTypes = pollinatable.getPlantType(); + EnumSet plantTypes = pollinatable.getPlantType(); - switch (flowerType) { - case FlowerManager.FlowerTypeNether: - return plantTypes.contains(EnumPlantType.Nether); - case FlowerManager.FlowerTypeCacti: - return plantTypes.contains(EnumPlantType.Desert); - default: - return plantTypes.size() > 1 || !plantTypes.contains(EnumPlantType.Nether); - } - } + switch (flowerType) { + case FlowerManager.FlowerTypeNether: + return plantTypes.contains(EnumPlantType.Nether); + case FlowerManager.FlowerTypeCacti: + return plantTypes.contains(EnumPlantType.Desert); + default: + return plantTypes.size() > 1 || !plantTypes.contains(EnumPlantType.Nether); + } + } - @Override - public boolean growFlower(World world, IIndividual individual, int x, int y, int z) { - return FlowerManager.flowerRegistry.growFlower(this.flowerType, world, individual, x, y, z); - } + @Override + public boolean growFlower(World world, IIndividual individual, int x, int y, int z) { + return FlowerManager.flowerRegistry.growFlower(this.flowerType, world, individual, x, y, z); + } - @Override - public String getDescription() { - return StringUtil.localize(this.description); - } + @Override + public String getDescription() { + return StringUtil.localize(this.description); + } - @Override - public ItemStack[] affectProducts(World world, IIndividual individual, int x, int y, int z, ItemStack[] products) { - return products; - } - - @Override - public Set getFlowers() { - return FlowerManager.flowerRegistry.getAcceptableFlowers(this.flowerType); - } + @Override + public ItemStack[] affectProducts(World world, IIndividual individual, int x, int y, int z, ItemStack[] products) { + return products; + } + @Override + public Set getFlowers() { + return FlowerManager.flowerRegistry.getAcceptableFlowers(this.flowerType); + } } diff --git a/src/main/java/forestry/apiculture/flowers/FlowerRegistry.java b/src/main/java/forestry/apiculture/flowers/FlowerRegistry.java index 0410e06aa..73fca4665 100644 --- a/src/main/java/forestry/apiculture/flowers/FlowerRegistry.java +++ b/src/main/java/forestry/apiculture/flowers/FlowerRegistry.java @@ -14,31 +14,7 @@ import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.TreeMap; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockFlowerPot; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.tileentity.TileEntityFlowerPot; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; - -import net.minecraftforge.common.IPlantable; -import net.minecraftforge.oredict.OreDictionary; - import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.FlowerManager; import forestry.api.apiculture.IBee; @@ -56,278 +32,312 @@ import forestry.core.utils.Log; import forestry.core.utils.vect.MutableVect; import forestry.core.utils.vect.Vect; import forestry.plugins.PluginManager; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.TreeMap; +import net.minecraft.block.Block; +import net.minecraft.block.BlockFlowerPot; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.tileentity.TileEntityFlowerPot; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; +import net.minecraftforge.common.IPlantable; +import net.minecraftforge.oredict.OreDictionary; public final class FlowerRegistry implements IFlowerRegistry, IFlowerGrowthHelper { - private final Set defaultFlowerTypes = ImmutableSet.of( - FlowerManager.FlowerTypeVanilla, - FlowerManager.FlowerTypeNether, - FlowerManager.FlowerTypeCacti, - FlowerManager.FlowerTypeMushrooms, - FlowerManager.FlowerTypeEnd, - FlowerManager.FlowerTypeJungle, - FlowerManager.FlowerTypeSnow, - FlowerManager.FlowerTypeWheat, - FlowerManager.FlowerTypeGourd - ); + private final Set defaultFlowerTypes = ImmutableSet.of( + FlowerManager.FlowerTypeVanilla, + FlowerManager.FlowerTypeNether, + FlowerManager.FlowerTypeCacti, + FlowerManager.FlowerTypeMushrooms, + FlowerManager.FlowerTypeEnd, + FlowerManager.FlowerTypeJungle, + FlowerManager.FlowerTypeSnow, + FlowerManager.FlowerTypeWheat, + FlowerManager.FlowerTypeGourd); - private final HashMultimap registeredRules; // custom check - private final HashMultimap registeredBlocks; // quick first check - private final HashMultimap registeredFlowers; // full check + private final HashMultimap registeredRules; // custom check + private final HashMultimap registeredBlocks; // quick first check + private final HashMultimap registeredFlowers; // full check - private final ArrayListMultimap growthRules; - private final Map> chances; + private final ArrayListMultimap growthRules; + private final Map> chances; - public FlowerRegistry() { - this.registeredRules = HashMultimap.create(); - this.registeredBlocks = HashMultimap.create(); - this.registeredFlowers = HashMultimap.create(); - this.growthRules = ArrayListMultimap.create(); - this.chances = new HashMap<>(); + public FlowerRegistry() { + this.registeredRules = HashMultimap.create(); + this.registeredBlocks = HashMultimap.create(); + this.registeredFlowers = HashMultimap.create(); + this.growthRules = ArrayListMultimap.create(); + this.chances = new HashMap<>(); - registerVanillaGrowthRules(); - } + registerVanillaGrowthRules(); + } - @Override - public void registerAcceptableFlower(Block block, String... flowerTypes) { - registerFlower(block, OreDictionary.WILDCARD_VALUE, 0.0, flowerTypes); - } + @Override + public void registerAcceptableFlower(Block block, String... flowerTypes) { + registerFlower(block, OreDictionary.WILDCARD_VALUE, 0.0, flowerTypes); + } - @Override - public void registerAcceptableFlower(Block block, int meta, String... flowerTypes) { - registerFlower(block, meta, 0.0, flowerTypes); - } + @Override + public void registerAcceptableFlower(Block block, int meta, String... flowerTypes) { + registerFlower(block, meta, 0.0, flowerTypes); + } - @Override - public void registerAcceptableFlowerRule(IFlowerAcceptableRule acceptableFlower, String... flowerTypes) { - for (String flowerType : flowerTypes) { - if (defaultFlowerTypes.contains(flowerType)) { - Log.severe("IFlowerAcceptableRules are too slow to be applied to Forestry's built-in flower type: " + flowerType + "."); - } else { - registeredRules.put(flowerType, acceptableFlower); - } - } - } + @Override + public void registerAcceptableFlowerRule(IFlowerAcceptableRule acceptableFlower, String... flowerTypes) { + for (String flowerType : flowerTypes) { + if (defaultFlowerTypes.contains(flowerType)) { + Log.severe("IFlowerAcceptableRules are too slow to be applied to Forestry's built-in flower type: " + + flowerType + "."); + } else { + registeredRules.put(flowerType, acceptableFlower); + } + } + } - @Override - public void registerPlantableFlower(Block block, int meta, double weight, String... flowerTypes) { - registerFlower(block, meta, weight, flowerTypes); - } + @Override + public void registerPlantableFlower(Block block, int meta, double weight, String... flowerTypes) { + registerFlower(block, meta, weight, flowerTypes); + } - private void registerFlower(Block block, int meta, double weight, String... flowerTypes) { - if (block == null) { - return; - } - if (weight <= 0.0) { - weight = 0.0; - } - if (weight >= 1.0) { - weight = 1.0; - } + private void registerFlower(Block block, int meta, double weight, String... flowerTypes) { + if (block == null) { + return; + } + if (weight <= 0.0) { + weight = 0.0; + } + if (weight >= 1.0) { + weight = 1.0; + } - Flower newFlower = new Flower(block, meta, weight); + Flower newFlower = new Flower(block, meta, weight); - for (String flowerType : flowerTypes) { - if (flowerType == null) { - throw new NullPointerException("Tried to register flower with null type. " + block); - } + for (String flowerType : flowerTypes) { + if (flowerType == null) { + throw new NullPointerException("Tried to register flower with null type. " + block); + } - Set flowers = this.registeredFlowers.get(flowerType); - flowers.add(newFlower); + Set flowers = this.registeredFlowers.get(flowerType); + flowers.add(newFlower); - Set blocks = this.registeredBlocks.get(flowerType); - blocks.add(block); + Set blocks = this.registeredBlocks.get(flowerType); + blocks.add(block); - if (this.chances.containsKey(flowerType)) { - this.chances.remove(flowerType); - } - } - } + if (this.chances.containsKey(flowerType)) { + this.chances.remove(flowerType); + } + } + } - private static Vect getArea(IBeeGenome genome, IBeeModifier beeModifier) { - int[] genomeTerritory = genome.getTerritory(); - float housingModifier = beeModifier.getTerritoryModifier(genome, 1f); - return new Vect(genomeTerritory).multiply(housingModifier * 3.0f); - } + private static Vect getArea(IBeeGenome genome, IBeeModifier beeModifier) { + int[] genomeTerritory = genome.getTerritory(); + float housingModifier = beeModifier.getTerritoryModifier(genome, 1f); + return new Vect(genomeTerritory).multiply(housingModifier * 3.0f); + } - @Override - public ChunkCoordinates getAcceptedFlowerCoordinates(IBeeHousing beeHousing, IBee bee, String flowerType) { - if (!this.registeredFlowers.containsKey(flowerType)) { - return null; - } + @Override + public ChunkCoordinates getAcceptedFlowerCoordinates(IBeeHousing beeHousing, IBee bee, String flowerType) { + if (!this.registeredFlowers.containsKey(flowerType)) { + return null; + } - Set acceptableRules = this.registeredRules.get(flowerType); - Set acceptedBlocks = this.registeredBlocks.get(flowerType); - Set acceptedFlowers = this.registeredFlowers.get(flowerType); - World world = beeHousing.getWorld(); + Set acceptableRules = this.registeredRules.get(flowerType); + Set acceptedBlocks = this.registeredBlocks.get(flowerType); + Set acceptedFlowers = this.registeredFlowers.get(flowerType); + World world = beeHousing.getWorld(); - IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(beeHousing); + IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(beeHousing); - Vect area = getArea(bee.getGenome(), beeModifier); - Vect housingPos = new Vect(beeHousing.getCoordinates()).add(-area.x / 2, -area.y / 2, -area.z / 2); + Vect area = getArea(bee.getGenome(), beeModifier); + Vect housingPos = new Vect(beeHousing.getCoordinates()).add(-area.x / 2, -area.y / 2, -area.z / 2); - MutableVect posCurrent = new MutableVect(0, 0, 0); - while (posCurrent.advancePositionInArea(area)) { + MutableVect posCurrent = new MutableVect(0, 0, 0); + while (posCurrent.advancePositionInArea(area)) { - Vect posBlock = Vect.add(housingPos, posCurrent); + Vect posBlock = Vect.add(housingPos, posCurrent); - for (IFlowerAcceptableRule acceptableRule : acceptableRules) { - if (acceptableRule.isAcceptableFlower(flowerType, world, posBlock.x, posBlock.y, posBlock.z)) { - return new ChunkCoordinates(posBlock.x, posBlock.y, posBlock.z); - } - } + for (IFlowerAcceptableRule acceptableRule : acceptableRules) { + if (acceptableRule.isAcceptableFlower(flowerType, world, posBlock.x, posBlock.y, posBlock.z)) { + return new ChunkCoordinates(posBlock.x, posBlock.y, posBlock.z); + } + } - if (isAcceptedFlower(flowerType, acceptedBlocks, acceptedFlowers, world, posBlock.x, posBlock.y, posBlock.z)) { - return new ChunkCoordinates(posBlock.x, posBlock.y, posBlock.z); - } - } + if (isAcceptedFlower( + flowerType, acceptedBlocks, acceptedFlowers, world, posBlock.x, posBlock.y, posBlock.z)) { + return new ChunkCoordinates(posBlock.x, posBlock.y, posBlock.z); + } + } - return null; - } + return null; + } - @Override - public boolean isAcceptedFlower(String flowerType, World world, int x, int y, int z) { - if (!this.registeredFlowers.containsKey(flowerType)) { - return false; - } + @Override + public boolean isAcceptedFlower(String flowerType, World world, int x, int y, int z) { + if (!this.registeredFlowers.containsKey(flowerType)) { + return false; + } - if (!world.blockExists(x, y, z)) - return false; + if (!world.blockExists(x, y, z)) return false; - Set acceptedCustom = this.registeredRules.get(flowerType); - for (IFlowerAcceptableRule acceptableFlower : acceptedCustom) { - if (acceptableFlower.isAcceptableFlower(flowerType, world, x, y, z)) { - return true; - } - } + Set acceptedCustom = this.registeredRules.get(flowerType); + for (IFlowerAcceptableRule acceptableFlower : acceptedCustom) { + if (acceptableFlower.isAcceptableFlower(flowerType, world, x, y, z)) { + return true; + } + } - Set acceptedBlocks = this.registeredBlocks.get(flowerType); - Set acceptedFlowers = this.registeredFlowers.get(flowerType); + Set acceptedBlocks = this.registeredBlocks.get(flowerType); + Set acceptedFlowers = this.registeredFlowers.get(flowerType); - return isAcceptedFlower(flowerType, acceptedBlocks, acceptedFlowers, world, x, y, z); - } + return isAcceptedFlower(flowerType, acceptedBlocks, acceptedFlowers, world, x, y, z); + } - private static boolean isAcceptedFlower(String flowerType, Set acceptedBlocks, Set acceptedFlowers, World world, int x, int y, int z) { - Block block = world.getBlock(x, y, z); + private static boolean isAcceptedFlower( + String flowerType, + Set acceptedBlocks, + Set acceptedFlowers, + World world, + int x, + int y, + int z) { + Block block = world.getBlock(x, y, z); - final int meta; + final int meta; - if (block instanceof BlockFlowerPot) { - TileEntity tile = world.getTileEntity(x, y, z); - TileEntityFlowerPot tileFlowerPot = (TileEntityFlowerPot) tile; - Item item = tileFlowerPot.getFlowerPotItem(); - block = Block.getBlockFromItem(item); - meta = tileFlowerPot.getFlowerPotData(); - } else { - if (!acceptedBlocks.contains(block)) { - return false; - } - meta = world.getBlockMetadata(x, y, z); - } + if (block instanceof BlockFlowerPot) { + TileEntity tile = world.getTileEntity(x, y, z); + TileEntityFlowerPot tileFlowerPot = (TileEntityFlowerPot) tile; + Item item = tileFlowerPot.getFlowerPotItem(); + block = Block.getBlockFromItem(item); + meta = tileFlowerPot.getFlowerPotData(); + } else { + if (!acceptedBlocks.contains(block)) { + return false; + } + meta = world.getBlockMetadata(x, y, z); + } - if (PluginManager.Module.AGRICRAFT.isEnabled()) { - Block cropBlock = GameRegistry.findBlock("AgriCraft", "crops"); - if (block == cropBlock) { - if (block instanceof IPlantable) { - //For agricraft versions which implement IPlantable in the BlockCrop class - block = ((IPlantable) block).getPlant(world, x, y, z); - } else { - //For earlier versions of AgriCraft - ArrayList drops = block.getDrops(world, x, y, z, 7, 0); - if (drops.get(1).getItem() == Items.wheat_seeds && flowerType.equals(FlowerManager.FlowerTypeWheat)) { - return true; - } - if (drops.get(1).getItem() == Items.nether_wart && flowerType.equals(FlowerManager.FlowerTypeNether)) { - return true; - } - } - } - } + if (PluginManager.Module.AGRICRAFT.isEnabled()) { + Block cropBlock = GameRegistry.findBlock("AgriCraft", "crops"); + if (block == cropBlock) { + if (block instanceof IPlantable) { + // For agricraft versions which implement IPlantable in the BlockCrop class + block = ((IPlantable) block).getPlant(world, x, y, z); + } else { + // For earlier versions of AgriCraft + ArrayList drops = block.getDrops(world, x, y, z, 7, 0); + if (drops.get(1).getItem() == Items.wheat_seeds + && flowerType.equals(FlowerManager.FlowerTypeWheat)) { + return true; + } + if (drops.get(1).getItem() == Items.nether_wart + && flowerType.equals(FlowerManager.FlowerTypeNether)) { + return true; + } + } + } + } - Flower flower = new Flower(block, meta, 0); - return acceptedFlowers.contains(flower); - } + Flower flower = new Flower(block, meta, 0); + return acceptedFlowers.contains(flower); + } - @Override - public boolean growFlower(String flowerType, World world, IIndividual individual, int x, int y, int z) { - if (!this.growthRules.containsKey(flowerType)) { - return false; - } + @Override + public boolean growFlower(String flowerType, World world, IIndividual individual, int x, int y, int z) { + if (!this.growthRules.containsKey(flowerType)) { + return false; + } - for (IFlowerGrowthRule rule : this.growthRules.get(flowerType)) { - boolean success; - try { - success = rule.growFlower(this, flowerType, world, x, y, z); - } catch (Throwable ignored) { - // legacy method - success = rule.growFlower(this, flowerType, world, individual, x, y, z); - } + for (IFlowerGrowthRule rule : this.growthRules.get(flowerType)) { + boolean success; + try { + success = rule.growFlower(this, flowerType, world, x, y, z); + } catch (Throwable ignored) { + // legacy method + success = rule.growFlower(this, flowerType, world, individual, x, y, z); + } - if (success) { - return true; - } - } + if (success) { + return true; + } + } - return false; - } + return false; + } - @Override - public Set getAcceptableFlowers(String flowerType) { - return ImmutableSet.copyOf(this.registeredFlowers.get(flowerType)); - } + @Override + public Set getAcceptableFlowers(String flowerType) { + return ImmutableSet.copyOf(this.registeredFlowers.get(flowerType)); + } - @Override - public void registerGrowthRule(IFlowerGrowthRule rule, String... flowerTypes) { - if (rule == null) { - return; - } + @Override + public void registerGrowthRule(IFlowerGrowthRule rule, String... flowerTypes) { + if (rule == null) { + return; + } - for (String flowerType : flowerTypes) { - this.growthRules.get(flowerType).add(rule); - } - } + for (String flowerType : flowerTypes) { + this.growthRules.get(flowerType).add(rule); + } + } - @Override - public IFlower getRandomPlantableFlower(String flowerType, Random rand) { - TreeMap chancesMap = getChancesMap(flowerType); - double maxKey = chancesMap.lastKey() + 1.0; - return chancesMap.get(chancesMap.lowerKey(rand.nextDouble() * maxKey)); - } + @Override + public IFlower getRandomPlantableFlower(String flowerType, Random rand) { + TreeMap chancesMap = getChancesMap(flowerType); + double maxKey = chancesMap.lastKey() + 1.0; + return chancesMap.get(chancesMap.lowerKey(rand.nextDouble() * maxKey)); + } - @Override - public Collection getFlowerTypes() { - return new ArrayList<>(Sets.union(defaultFlowerTypes, registeredFlowers.keySet())); - } + @Override + public Collection getFlowerTypes() { + return new ArrayList<>(Sets.union(defaultFlowerTypes, registeredFlowers.keySet())); + } - private TreeMap getChancesMap(String flowerType) { - if (!this.chances.containsKey(flowerType)) { - TreeMap flowerChances = new TreeMap<>(); - double count = 0.0; - for (Flower flower : this.registeredFlowers.get(flowerType)) { - if (flower.isPlantable()) { - flowerChances.put(count, flower); - count += flower.getWeight(); - } - } - this.chances.put(flowerType, flowerChances); - } - return this.chances.get(flowerType); - } + private TreeMap getChancesMap(String flowerType) { + if (!this.chances.containsKey(flowerType)) { + TreeMap flowerChances = new TreeMap<>(); + double count = 0.0; + for (Flower flower : this.registeredFlowers.get(flowerType)) { + if (flower.isPlantable()) { + flowerChances.put(count, flower); + count += flower.getWeight(); + } + } + this.chances.put(flowerType, flowerChances); + } + return this.chances.get(flowerType); + } - private void registerVanillaGrowthRules() { - registerGrowthRule(new GrowthRuleDirtGrass(), FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); - registerGrowthRule(new GrowthRuleSnow(), FlowerManager.FlowerTypeSnow); - registerGrowthRule(new GrowthRuleFlowerPot(), FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow, FlowerManager.FlowerTypeMushrooms, FlowerManager.FlowerTypeCacti, - FlowerManager.FlowerTypeJungle); - registerGrowthRule(new GrowthRuleMycelium(), FlowerManager.FlowerTypeMushrooms); - registerGrowthRule(new GrowthRuleNone(), FlowerManager.FlowerTypeEnd); - registerGrowthRule(new GrowthRuleFertilize(Blocks.melon_stem, Blocks.pumpkin_stem), FlowerManager.FlowerTypeGourd); - registerGrowthRule(new GrowthRuleFertilize(Blocks.wheat), FlowerManager.FlowerTypeWheat); - } + private void registerVanillaGrowthRules() { + registerGrowthRule(new GrowthRuleDirtGrass(), FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); + registerGrowthRule(new GrowthRuleSnow(), FlowerManager.FlowerTypeSnow); + registerGrowthRule( + new GrowthRuleFlowerPot(), + FlowerManager.FlowerTypeVanilla, + FlowerManager.FlowerTypeSnow, + FlowerManager.FlowerTypeMushrooms, + FlowerManager.FlowerTypeCacti, + FlowerManager.FlowerTypeJungle); + registerGrowthRule(new GrowthRuleMycelium(), FlowerManager.FlowerTypeMushrooms); + registerGrowthRule(new GrowthRuleNone(), FlowerManager.FlowerTypeEnd); + registerGrowthRule( + new GrowthRuleFertilize(Blocks.melon_stem, Blocks.pumpkin_stem), FlowerManager.FlowerTypeGourd); + registerGrowthRule(new GrowthRuleFertilize(Blocks.wheat), FlowerManager.FlowerTypeWheat); + } - @Override - public boolean plantRandomFlower(String flowerType, World world, int x, int y, int z) { - IFlower flower = getRandomPlantableFlower(flowerType, world.rand); - return world.setBlock(x, y, z, flower.getBlock(), flower.getMeta(), Constants.FLAG_BLOCK_SYNCH); - } + @Override + public boolean plantRandomFlower(String flowerType, World world, int x, int y, int z) { + IFlower flower = getRandomPlantableFlower(flowerType, world.rand); + return world.setBlock(x, y, z, flower.getBlock(), flower.getMeta(), Constants.FLAG_BLOCK_SYNCH); + } } diff --git a/src/main/java/forestry/apiculture/flowers/GrowthRuleDirtGrass.java b/src/main/java/forestry/apiculture/flowers/GrowthRuleDirtGrass.java index 079a9c6af..3d3bb9936 100644 --- a/src/main/java/forestry/apiculture/flowers/GrowthRuleDirtGrass.java +++ b/src/main/java/forestry/apiculture/flowers/GrowthRuleDirtGrass.java @@ -10,46 +10,51 @@ ******************************************************************************/ package forestry.apiculture.flowers; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.world.World; - import forestry.api.genetics.IFlower; import forestry.api.genetics.IFlowerGrowthHelper; import forestry.api.genetics.IFlowerGrowthRule; import forestry.api.genetics.IFlowerRegistry; import forestry.api.genetics.IIndividual; import forestry.core.config.Constants; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.world.World; public class GrowthRuleDirtGrass implements IFlowerGrowthRule { - @Override - public boolean growFlower(IFlowerRegistry flowerRegistry, String flowerType, World world, IIndividual individual, int x, int y, int z) { - if (!world.isAirBlock(x, y, z)) { - return false; - } + @Override + public boolean growFlower( + IFlowerRegistry flowerRegistry, + String flowerType, + World world, + IIndividual individual, + int x, + int y, + int z) { + if (!world.isAirBlock(x, y, z)) { + return false; + } - Block ground = world.getBlock(x, y - 1, z); - if (ground != Blocks.dirt && ground != Blocks.grass) { - return false; - } + Block ground = world.getBlock(x, y - 1, z); + if (ground != Blocks.dirt && ground != Blocks.grass) { + return false; + } - IFlower flower = flowerRegistry.getRandomPlantableFlower(flowerType, world.rand); - return world.setBlock(x, y, z, flower.getBlock(), flower.getMeta(), Constants.FLAG_BLOCK_SYNCH); - } + IFlower flower = flowerRegistry.getRandomPlantableFlower(flowerType, world.rand); + return world.setBlock(x, y, z, flower.getBlock(), flower.getMeta(), Constants.FLAG_BLOCK_SYNCH); + } - @Override - public boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z) { - if (!world.isAirBlock(x, y, z)) { - return false; - } + @Override + public boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z) { + if (!world.isAirBlock(x, y, z)) { + return false; + } - Block ground = world.getBlock(x, y - 1, z); - if (ground != Blocks.dirt && ground != Blocks.grass) { - return false; - } - - return helper.plantRandomFlower(flowerType, world, x, y, z); - } + Block ground = world.getBlock(x, y - 1, z); + if (ground != Blocks.dirt && ground != Blocks.grass) { + return false; + } + return helper.plantRandomFlower(flowerType, world, x, y, z); + } } diff --git a/src/main/java/forestry/apiculture/flowers/GrowthRuleFertilize.java b/src/main/java/forestry/apiculture/flowers/GrowthRuleFertilize.java index 9df48fab8..de6907427 100644 --- a/src/main/java/forestry/apiculture/flowers/GrowthRuleFertilize.java +++ b/src/main/java/forestry/apiculture/flowers/GrowthRuleFertilize.java @@ -10,55 +10,53 @@ ******************************************************************************/ package forestry.apiculture.flowers; -import java.util.Arrays; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.world.World; - import forestry.api.genetics.IFlowerGrowthHelper; import forestry.api.genetics.IFlowerGrowthRule; import forestry.api.genetics.IFlowerRegistry; import forestry.api.genetics.IIndividual; +import java.util.Arrays; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.world.World; public class GrowthRuleFertilize implements IFlowerGrowthRule { - private final List allowedItems; + private final List allowedItems; - public GrowthRuleFertilize(Block... allowedItems) { - this.allowedItems = Arrays.asList(allowedItems); - } + public GrowthRuleFertilize(Block... allowedItems) { + this.allowedItems = Arrays.asList(allowedItems); + } - @Override - public boolean growFlower(IFlowerRegistry fr, String flowerType, World world, IIndividual individual, int x, int y, int z) { - return growFlower(world, x, y, z); - } + @Override + public boolean growFlower( + IFlowerRegistry fr, String flowerType, World world, IIndividual individual, int x, int y, int z) { + return growFlower(world, x, y, z); + } - @Override - public boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z) { - return growFlower(world, x, y, z); - } + @Override + public boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z) { + return growFlower(world, x, y, z); + } - private boolean growFlower(World world, int x, int y, int z) { - Block ground = world.getBlock(x, y, z); - int groundMeta; - for (Block b : this.allowedItems) { - if (b == ground) { - groundMeta = world.getBlockMetadata(x, y, z); - if (groundMeta > 6) { - return false; - } - if (groundMeta < 6) { - groundMeta += world.rand.nextInt(2) + 1; - } else { - groundMeta = 7; - } + private boolean growFlower(World world, int x, int y, int z) { + Block ground = world.getBlock(x, y, z); + int groundMeta; + for (Block b : this.allowedItems) { + if (b == ground) { + groundMeta = world.getBlockMetadata(x, y, z); + if (groundMeta > 6) { + return false; + } + if (groundMeta < 6) { + groundMeta += world.rand.nextInt(2) + 1; + } else { + groundMeta = 7; + } - return world.setBlockMetadataWithNotify(x, y, z, groundMeta, 2); - } - } - - return false; - } + return world.setBlockMetadataWithNotify(x, y, z, groundMeta, 2); + } + } + return false; + } } diff --git a/src/main/java/forestry/apiculture/flowers/GrowthRuleFlowerPot.java b/src/main/java/forestry/apiculture/flowers/GrowthRuleFlowerPot.java index 5344a2ae7..8113c0687 100644 --- a/src/main/java/forestry/apiculture/flowers/GrowthRuleFlowerPot.java +++ b/src/main/java/forestry/apiculture/flowers/GrowthRuleFlowerPot.java @@ -10,76 +10,76 @@ ******************************************************************************/ package forestry.apiculture.flowers; +import forestry.api.apiculture.FlowerManager; +import forestry.api.genetics.IFlowerGrowthHelper; +import forestry.api.genetics.IFlowerGrowthRule; +import forestry.api.genetics.IFlowerRegistry; +import forestry.api.genetics.IIndividual; import net.minecraft.block.Block; import net.minecraft.block.BlockFlowerPot; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityFlowerPot; import net.minecraft.world.World; -import forestry.api.apiculture.FlowerManager; -import forestry.api.genetics.IFlowerGrowthHelper; -import forestry.api.genetics.IFlowerGrowthRule; -import forestry.api.genetics.IFlowerRegistry; -import forestry.api.genetics.IIndividual; - public class GrowthRuleFlowerPot implements IFlowerGrowthRule { - @Override - public boolean growFlower(IFlowerRegistry fr, String flowerType, World world, IIndividual individual, int x, int y, int z) { - return growFlower(flowerType, world, x, y, z); - } + @Override + public boolean growFlower( + IFlowerRegistry fr, String flowerType, World world, IIndividual individual, int x, int y, int z) { + return growFlower(flowerType, world, x, y, z); + } - @Override - public boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z) { - return growFlower(flowerType, world, x, y, z); - } + @Override + public boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z) { + return growFlower(flowerType, world, x, y, z); + } - private static boolean growFlower(String flowerType, World world, int x, int y, int z) { - TileEntity tile = world.getTileEntity(x, y, z); - if (!(tile instanceof TileEntityFlowerPot)) { - return false; - } + private static boolean growFlower(String flowerType, World world, int x, int y, int z) { + TileEntity tile = world.getTileEntity(x, y, z); + if (!(tile instanceof TileEntityFlowerPot)) { + return false; + } - TileEntityFlowerPot flowerPotTile = (TileEntityFlowerPot) tile; - if (flowerPotTile.getFlowerPotItem() != null) { - return false; - } + TileEntityFlowerPot flowerPotTile = (TileEntityFlowerPot) tile; + if (flowerPotTile.getFlowerPotItem() != null) { + return false; + } - Block block = world.getBlock(x, y, z); - if (!(block instanceof BlockFlowerPot)) { - return false; - } + Block block = world.getBlock(x, y, z); + if (!(block instanceof BlockFlowerPot)) { + return false; + } - BlockFlowerPot flowerPot = (BlockFlowerPot) block; + BlockFlowerPot flowerPot = (BlockFlowerPot) block; - int flower; - switch (flowerType) { - case FlowerManager.FlowerTypeVanilla: - case FlowerManager.FlowerTypeSnow: - flower = world.rand.nextInt(2) + 1; - break; - case FlowerManager.FlowerTypeJungle: - flower = 6; - break; - case FlowerManager.FlowerTypeCacti: - flower = world.rand.nextInt(2) + 9; - break; - case FlowerManager.FlowerTypeMushrooms: - flower = world.rand.nextInt(2) + 7; - break; - default: - return false; - } + int flower; + switch (flowerType) { + case FlowerManager.FlowerTypeVanilla: + case FlowerManager.FlowerTypeSnow: + flower = world.rand.nextInt(2) + 1; + break; + case FlowerManager.FlowerTypeJungle: + flower = 6; + break; + case FlowerManager.FlowerTypeCacti: + flower = world.rand.nextInt(2) + 9; + break; + case FlowerManager.FlowerTypeMushrooms: + flower = world.rand.nextInt(2) + 7; + break; + default: + return false; + } - TileEntityFlowerPot newTile = (TileEntityFlowerPot) flowerPot.createNewTileEntity(world, flower); + TileEntityFlowerPot newTile = (TileEntityFlowerPot) flowerPot.createNewTileEntity(world, flower); - flowerPotTile.func_145964_a(newTile.getFlowerPotItem(), newTile.getFlowerPotData()); - flowerPotTile.markDirty(); + flowerPotTile.func_145964_a(newTile.getFlowerPotItem(), newTile.getFlowerPotData()); + flowerPotTile.markDirty(); - if (!world.setBlockMetadataWithNotify(x, y, z, 1, 2)) { - world.markBlockForUpdate(x, y, z); - } + if (!world.setBlockMetadataWithNotify(x, y, z, 1, 2)) { + world.markBlockForUpdate(x, y, z); + } - return true; - } + return true; + } } diff --git a/src/main/java/forestry/apiculture/flowers/GrowthRuleMycelium.java b/src/main/java/forestry/apiculture/flowers/GrowthRuleMycelium.java index 31e5466a5..8e5b8b63a 100644 --- a/src/main/java/forestry/apiculture/flowers/GrowthRuleMycelium.java +++ b/src/main/java/forestry/apiculture/flowers/GrowthRuleMycelium.java @@ -10,46 +10,45 @@ ******************************************************************************/ package forestry.apiculture.flowers; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.world.World; - import forestry.api.genetics.IFlower; import forestry.api.genetics.IFlowerGrowthHelper; import forestry.api.genetics.IFlowerGrowthRule; import forestry.api.genetics.IFlowerRegistry; import forestry.api.genetics.IIndividual; import forestry.core.config.Constants; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.world.World; public class GrowthRuleMycelium implements IFlowerGrowthRule { - @Override - public boolean growFlower(IFlowerRegistry fr, String flowerType, World world, IIndividual individual, int x, int y, int z) { - if (!world.isAirBlock(x, y, z)) { - return false; - } + @Override + public boolean growFlower( + IFlowerRegistry fr, String flowerType, World world, IIndividual individual, int x, int y, int z) { + if (!world.isAirBlock(x, y, z)) { + return false; + } - Block ground = world.getBlock(x, y - 1, z); - if (ground != Blocks.mycelium) { - return false; - } + Block ground = world.getBlock(x, y - 1, z); + if (ground != Blocks.mycelium) { + return false; + } - IFlower flower = fr.getRandomPlantableFlower(flowerType, world.rand); - return world.setBlock(x, y, z, flower.getBlock(), flower.getMeta(), Constants.FLAG_BLOCK_SYNCH); - } + IFlower flower = fr.getRandomPlantableFlower(flowerType, world.rand); + return world.setBlock(x, y, z, flower.getBlock(), flower.getMeta(), Constants.FLAG_BLOCK_SYNCH); + } - @Override - public boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z) { - if (!world.isAirBlock(x, y, z)) { - return false; - } + @Override + public boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z) { + if (!world.isAirBlock(x, y, z)) { + return false; + } - Block ground = world.getBlock(x, y - 1, z); - if (ground != Blocks.mycelium) { - return false; - } - - return helper.plantRandomFlower(flowerType, world, x, y, z); - } + Block ground = world.getBlock(x, y - 1, z); + if (ground != Blocks.mycelium) { + return false; + } + return helper.plantRandomFlower(flowerType, world, x, y, z); + } } diff --git a/src/main/java/forestry/apiculture/flowers/GrowthRuleNone.java b/src/main/java/forestry/apiculture/flowers/GrowthRuleNone.java index e04297cbe..5c00d615b 100644 --- a/src/main/java/forestry/apiculture/flowers/GrowthRuleNone.java +++ b/src/main/java/forestry/apiculture/flowers/GrowthRuleNone.java @@ -10,23 +10,22 @@ ******************************************************************************/ package forestry.apiculture.flowers; -import net.minecraft.world.World; - import forestry.api.genetics.IFlowerGrowthHelper; import forestry.api.genetics.IFlowerGrowthRule; import forestry.api.genetics.IFlowerRegistry; import forestry.api.genetics.IIndividual; +import net.minecraft.world.World; public class GrowthRuleNone implements IFlowerGrowthRule { - @Override - public boolean growFlower(IFlowerRegistry fr, String flowerType, World world, IIndividual individual, int x, int y, int z) { - return true; - } - - @Override - public boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z) { - return true; - } + @Override + public boolean growFlower( + IFlowerRegistry fr, String flowerType, World world, IIndividual individual, int x, int y, int z) { + return true; + } + @Override + public boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z) { + return true; + } } diff --git a/src/main/java/forestry/apiculture/flowers/GrowthRuleSnow.java b/src/main/java/forestry/apiculture/flowers/GrowthRuleSnow.java index b35e973e9..847ede867 100644 --- a/src/main/java/forestry/apiculture/flowers/GrowthRuleSnow.java +++ b/src/main/java/forestry/apiculture/flowers/GrowthRuleSnow.java @@ -10,46 +10,45 @@ ******************************************************************************/ package forestry.apiculture.flowers; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.world.World; - import forestry.api.genetics.IFlower; import forestry.api.genetics.IFlowerGrowthHelper; import forestry.api.genetics.IFlowerGrowthRule; import forestry.api.genetics.IFlowerRegistry; import forestry.api.genetics.IIndividual; import forestry.core.config.Constants; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.world.World; public class GrowthRuleSnow implements IFlowerGrowthRule { - @Override - public boolean growFlower(IFlowerRegistry fr, String flowerType, World world, IIndividual individual, int x, int y, int z) { - if (world.getBlock(x, y, z) != Blocks.snow) { - return false; - } + @Override + public boolean growFlower( + IFlowerRegistry fr, String flowerType, World world, IIndividual individual, int x, int y, int z) { + if (world.getBlock(x, y, z) != Blocks.snow) { + return false; + } - Block ground = world.getBlock(x, y - 1, z); - if (ground != Blocks.dirt && ground != Blocks.grass) { - return false; - } + Block ground = world.getBlock(x, y - 1, z); + if (ground != Blocks.dirt && ground != Blocks.grass) { + return false; + } - IFlower flower = fr.getRandomPlantableFlower(flowerType, world.rand); - return world.setBlock(x, y, z, flower.getBlock(), flower.getMeta(), Constants.FLAG_BLOCK_SYNCH); - } + IFlower flower = fr.getRandomPlantableFlower(flowerType, world.rand); + return world.setBlock(x, y, z, flower.getBlock(), flower.getMeta(), Constants.FLAG_BLOCK_SYNCH); + } - @Override - public boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z) { - if (world.getBlock(x, y, z) != Blocks.snow) { - return false; - } + @Override + public boolean growFlower(IFlowerGrowthHelper helper, String flowerType, World world, int x, int y, int z) { + if (world.getBlock(x, y, z) != Blocks.snow) { + return false; + } - Block ground = world.getBlock(x, y - 1, z); - if (ground != Blocks.dirt && ground != Blocks.grass) { - return false; - } - - return helper.plantRandomFlower(flowerType, world, x, y, z); - } + Block ground = world.getBlock(x, y - 1, z); + if (ground != Blocks.dirt && ground != Blocks.grass) { + return false; + } + return helper.plantRandomFlower(flowerType, world, x, y, z); + } } diff --git a/src/main/java/forestry/apiculture/genetics/ApiaristTracker.java b/src/main/java/forestry/apiculture/genetics/ApiaristTracker.java index d971f6df2..6b8e0e602 100755 --- a/src/main/java/forestry/apiculture/genetics/ApiaristTracker.java +++ b/src/main/java/forestry/apiculture/genetics/ApiaristTracker.java @@ -10,9 +10,6 @@ ******************************************************************************/ package forestry.apiculture.genetics; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.IApiaristTracker; @@ -20,99 +17,98 @@ import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.IIndividual; import forestry.api.genetics.ISpeciesRoot; import forestry.core.genetics.BreedingTracker; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; public class ApiaristTracker extends BreedingTracker implements IApiaristTracker { - /** Required for creation from map storage */ - public ApiaristTracker(String s) { - super(s); - } + /** Required for creation from map storage */ + public ApiaristTracker(String s) { + super(s); + } - private int queensTotal = 0; - private int dronesTotal = 0; - private int princessesTotal = 0; + private int queensTotal = 0; + private int dronesTotal = 0; + private int princessesTotal = 0; - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { - queensTotal = nbttagcompound.getInteger("QueensTotal"); - princessesTotal = nbttagcompound.getInteger("PrincessesTotal"); - dronesTotal = nbttagcompound.getInteger("DronesTotal"); + queensTotal = nbttagcompound.getInteger("QueensTotal"); + princessesTotal = nbttagcompound.getInteger("PrincessesTotal"); + dronesTotal = nbttagcompound.getInteger("DronesTotal"); - super.readFromNBT(nbttagcompound); + super.readFromNBT(nbttagcompound); + } - } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setInteger("QueensTotal", queensTotal); + nbttagcompound.setInteger("PrincessesTotal", princessesTotal); + nbttagcompound.setInteger("DronesTotal", dronesTotal); - nbttagcompound.setInteger("QueensTotal", queensTotal); - nbttagcompound.setInteger("PrincessesTotal", princessesTotal); - nbttagcompound.setInteger("DronesTotal", dronesTotal); + super.writeToNBT(nbttagcompound); + } - super.writeToNBT(nbttagcompound); + @Override + public void registerPickup(IIndividual individual) { + ISpeciesRoot speciesRoot = individual.getGenome().getPrimary().getRoot(); + if (!speciesRoot.getUID().equals(speciesRootUID())) { + return; + } - } + if (!individual.isPureBred(EnumBeeChromosome.SPECIES)) { + return; + } - @Override - public void registerPickup(IIndividual individual) { - ISpeciesRoot speciesRoot = individual.getGenome().getPrimary().getRoot(); - if (!speciesRoot.getUID().equals(speciesRootUID())) { - return; - } + if (speciesRoot.getCombinations(individual.getGenome().getPrimary()).size() > 0) { + return; + } - if (!individual.isPureBred(EnumBeeChromosome.SPECIES)) { - return; - } + registerSpecies(individual.getGenome().getPrimary()); + } - if (speciesRoot.getCombinations(individual.getGenome().getPrimary()).size() > 0) { - return; - } + @Override + public void registerQueen(IIndividual bee) { + queensTotal++; + } - registerSpecies(individual.getGenome().getPrimary()); - } + @Override + public int getQueenCount() { + return queensTotal; + } - @Override - public void registerQueen(IIndividual bee) { - queensTotal++; - } + @Override + public void registerPrincess(IIndividual bee) { - @Override - public int getQueenCount() { - return queensTotal; - } + princessesTotal++; + registerBirth(bee); + } - @Override - public void registerPrincess(IIndividual bee) { + @Override + public int getPrincessCount() { + return princessesTotal; + } - princessesTotal++; - registerBirth(bee); - } + @Override + public void registerDrone(IIndividual bee) { + dronesTotal++; + registerBirth(bee); + } - @Override - public int getPrincessCount() { - return princessesTotal; - } + @Override + public int getDroneCount() { + return dronesTotal; + } - @Override - public void registerDrone(IIndividual bee) { - dronesTotal++; - registerBirth(bee); - } - - @Override - public int getDroneCount() { - return dronesTotal; - } - - @Override - protected IBreedingTracker getBreedingTracker(EntityPlayer player) { - return BeeManager.beeRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); - } - - @Override - protected String speciesRootUID() { - return BeeHelper.UID; - } + @Override + protected IBreedingTracker getBreedingTracker(EntityPlayer player) { + return BeeManager.beeRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); + } + @Override + protected String speciesRootUID() { + return BeeHelper.UID; + } } diff --git a/src/main/java/forestry/apiculture/genetics/Bee.java b/src/main/java/forestry/apiculture/genetics/Bee.java index 749f0f91f..cc4b3a9e1 100644 --- a/src/main/java/forestry/apiculture/genetics/Bee.java +++ b/src/main/java/forestry/apiculture/genetics/Bee.java @@ -10,24 +10,7 @@ ******************************************************************************/ package forestry.apiculture.genetics; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; - -import net.minecraft.item.EnumRarity; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - import com.mojang.authlib.GameProfile; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.FlowerManager; @@ -66,731 +49,776 @@ import forestry.core.utils.GeneticsUtil; import forestry.core.utils.Log; import forestry.core.utils.StringUtil; import forestry.core.utils.vect.Vect; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import net.minecraft.item.EnumRarity; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; public class Bee extends IndividualLiving implements IBee { - private int generation; - private boolean isNatural = true; + private int generation; + private boolean isNatural = true; + + private IBeeGenome genome; + private IBeeGenome mate; + + /* CONSTRUCTOR */ + public Bee(NBTTagCompound nbttagcompound) { + readFromNBT(nbttagcompound); + } + + public Bee(IBeeGenome genome, IBee mate) { + this(genome); + this.mate = mate.getGenome(); + } + + public Bee(IBeeGenome genome) { + this(genome, true, 0); + } + + private Bee(IBeeGenome genome, boolean isNatural, int generation) { + super(genome.getLifespan()); + this.genome = genome; + this.isNatural = isNatural; + this.generation = generation; + } + + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + + if (nbttagcompound == null) { + genome = BeeDefinition.FOREST.getGenome(); + return; + } + + super.readFromNBT(nbttagcompound); + + if (nbttagcompound.hasKey("NA")) { + isNatural = nbttagcompound.getBoolean("NA"); + } + + if (nbttagcompound.hasKey("GEN")) { + generation = nbttagcompound.getInteger("GEN"); + } - private IBeeGenome genome; - private IBeeGenome mate; + if (nbttagcompound.hasKey("Genome")) { + genome = BeeGenome.fromNBT(nbttagcompound.getCompoundTag("Genome")); + } else { + genome = BeeDefinition.FOREST.getGenome(); + } + + if (nbttagcompound.hasKey("Mate")) { + mate = BeeGenome.fromNBT(nbttagcompound.getCompoundTag("Mate")); + } + } + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + + super.writeToNBT(nbttagcompound); + + if (!isNatural) { + nbttagcompound.setBoolean("NA", false); + } + + if (generation > 0) { + nbttagcompound.setInteger("GEN", generation); + } + } + + public void setIsNatural(boolean flag) { + this.isNatural = flag; + } + + public boolean isNatural() { + return this.isNatural; + } + + public int getGeneration() { + return generation; + } + + @Override + public void mate(IIndividual individual) { + if (!(individual instanceof IBee)) { + return; + } + + IBee drone = (IBee) individual; + mate = drone.getGenome(); + } + + /* EFFECTS */ + @Override + public IEffectData[] doEffect(IEffectData[] storedData, IBeeHousing housing) { + IAlleleBeeEffect effect = genome.getEffect(); + + if (effect == null) { + return null; + } + + storedData[0] = doEffect(effect, storedData[0], housing); + + // Return here if the primary can already not be combined + if (!effect.isCombinable()) { + return storedData; + } + + IAlleleBeeEffect secondary = (IAlleleBeeEffect) genome.getInactiveAllele(EnumBeeChromosome.EFFECT); + if (!secondary.isCombinable()) { + return storedData; + } + + storedData[1] = doEffect(secondary, storedData[1], housing); + + return storedData; + } + + private IEffectData doEffect(IAlleleBeeEffect effect, IEffectData storedData, IBeeHousing housing) { + storedData = effect.validateStorage(storedData); + return effect.doEffect(genome, storedData, housing); + } + + @Override + public IEffectData[] doFX(IEffectData[] storedData, IBeeHousing housing) { + IAlleleBeeEffect effect = genome.getEffect(); + + if (effect == null) { + return null; + } + + storedData[0] = doFX(effect, storedData[0], housing); + + // Return here if the primary can already not be combined + if (!effect.isCombinable()) { + return storedData; + } + + IAlleleBeeEffect secondary = (IAlleleBeeEffect) genome.getInactiveAllele(EnumBeeChromosome.EFFECT); + if (!secondary.isCombinable()) { + return storedData; + } + + storedData[1] = doFX(secondary, storedData[1], housing); + + return storedData; + } + + private IEffectData doFX(IAlleleBeeEffect effect, IEffectData storedData, IBeeHousing housing) { + return effect.doFX(genome, storedData, housing); + } + + // / INFORMATION + @Override + public IBeeGenome getGenome() { + return genome; + } + + @Override + public IBeeGenome getMate() { + return mate; + } + + @Override + public IBee copy() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + this.writeToNBT(nbttagcompound); + return new Bee(nbttagcompound); + } + + @Override + public boolean canSpawn() { + return mate != null; + } + + @Override + public Set getCanWork(IBeeHousing housing) { + World world = housing.getWorld(); + BiomeGenBase biome = housing.getBiome(); + + Set errorStates = new HashSet<>(); + + IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); + + // / Rain needs tolerant flyers + if (world.isRaining() && BiomeHelper.canRainOrSnow(biome) && !canFlyInRain(beeModifier)) { + errorStates.add(EnumErrorCode.IS_RAINING); + } + + // / Night or darkness requires nocturnal species + if (world.isDaytime()) { + if (!canWorkDuringDay()) { + errorStates.add(EnumErrorCode.NOT_NIGHT); + } + } else { + if (!canWorkAtNight(beeModifier)) { + errorStates.add(EnumErrorCode.NOT_DAY); + } + } + + if (housing.getBlockLightValue() > Constants.APIARY_MIN_LEVEL_LIGHT) { + if (!canWorkDuringDay()) { + errorStates.add(EnumErrorCode.NOT_GLOOMY); + } + } else { + if (!canWorkAtNight(beeModifier)) { + errorStates.add(EnumErrorCode.NOT_BRIGHT); + } + } + + // / Check for the sky, except if in hell + if (!world.provider.hasNoSky) { + if (!housing.canBlockSeeTheSky() && !canWorkUnderground(beeModifier)) { + errorStates.add(EnumErrorCode.NO_SKY); + } + } + + // / And finally climate check + IAlleleBeeSpecies species = genome.getPrimary(); + { + EnumTemperature actualTemperature = housing.getTemperature(); + EnumTemperature beeBaseTemperature = species.getTemperature(); + EnumTolerance beeToleranceTemperature = genome.getToleranceTemp(); + + if (!AlleleManager.climateHelper.isWithinLimits( + actualTemperature, beeBaseTemperature, beeToleranceTemperature)) { + if (beeBaseTemperature.ordinal() > actualTemperature.ordinal()) { + errorStates.add(EnumErrorCode.TOO_COLD); + } else { + errorStates.add(EnumErrorCode.TOO_HOT); + } + } + } + + { + EnumHumidity actualHumidity = housing.getHumidity(); + EnumHumidity beeBaseHumidity = species.getHumidity(); + EnumTolerance beeToleranceHumidity = genome.getToleranceHumid(); + + if (!AlleleManager.climateHelper.isWithinLimits(actualHumidity, beeBaseHumidity, beeToleranceHumidity)) { + if (beeBaseHumidity.ordinal() > actualHumidity.ordinal()) { + errorStates.add(EnumErrorCode.TOO_ARID); + } else { + errorStates.add(EnumErrorCode.TOO_HUMID); + } + } + } + + return errorStates; + } + + private boolean canWorkAtNight(IBeeModifier beeModifier) { + return genome.getPrimary().isNocturnal() || genome.getNocturnal() || beeModifier.isSelfLighted(); + } + + private boolean canWorkDuringDay() { + return !genome.getPrimary().isNocturnal() || genome.getNocturnal(); + } + + private boolean canWorkUnderground(IBeeModifier beeModifier) { + return genome.getCaveDwelling() || beeModifier.isSunlightSimulated(); + } + + private boolean canFlyInRain(IBeeModifier beeModifier) { + return genome.getTolerantFlyer() || beeModifier.isSealed(); + } + + private boolean isSuitableBiome(BiomeGenBase biome) { + if (biome == null) { + return false; + } + + EnumTemperature temperature = EnumTemperature.getFromBiome(biome); + EnumHumidity humidity = EnumHumidity.getFromValue(biome.rainfall); + return isSuitableClimate(temperature, humidity); + } + + private boolean isSuitableClimate(EnumTemperature temperature, EnumHumidity humidity) { + return AlleleManager.climateHelper.isWithinLimits( + temperature, + humidity, + genome.getPrimary().getTemperature(), + genome.getToleranceTemp(), + genome.getPrimary().getHumidity(), + genome.getToleranceHumid()); + } + + @Override + public ArrayList getSuitableBiomes() { + ArrayList suitableBiomes = new ArrayList<>(); + for (BiomeGenBase biome : BiomeGenBase.getBiomeGenArray()) { + if (isSuitableBiome(biome)) { + suitableBiomes.add(biome); + } + } + + return suitableBiomes; + } + + @Override + public void addTooltip(List list) { + + // No info 4 u! + if (!isAnalyzed) { + list.add("<" + StringUtil.localize("gui.unknown") + ">"); + return; + } + + // You analyzed it? Juicy tooltip coming up! + IAlleleBeeSpecies primary = genome.getPrimary(); + IAlleleBeeSpecies secondary = genome.getSecondary(); + if (!isPureBred(EnumBeeChromosome.SPECIES)) { + list.add(EnumChatFormatting.BLUE + + StringUtil.localize("bees.hybrid") + .replaceAll("%PRIMARY", primary.getName()) + .replaceAll("%SECONDARY", secondary.getName())); + } + + if (generation > 0) { + EnumRarity rarity; + if (generation >= 1000) { + rarity = EnumRarity.epic; + } else if (generation >= 100) { + rarity = EnumRarity.rare; + } else if (generation >= 10) { + rarity = EnumRarity.uncommon; + } else { + rarity = EnumRarity.common; + } + + String generationString = + rarity.rarityColor + StringUtil.localizeAndFormat("gui.beealyzer.generations", generation); + list.add(generationString); + } + + IAllele speedAllele = genome.getActiveAllele(EnumBeeChromosome.SPEED); + IAlleleTolerance tempToleranceAllele = + (IAlleleTolerance) getGenome().getActiveAllele(EnumBeeChromosome.TEMPERATURE_TOLERANCE); + IAlleleTolerance humidToleranceAllele = + (IAlleleTolerance) getGenome().getActiveAllele(EnumBeeChromosome.HUMIDITY_TOLERANCE); + + String unlocalizedCustomSpeed = + "tooltip.worker." + speedAllele.getUnlocalizedName().replaceAll("(.*)\\.", ""); + String speed; + if (StringUtil.canTranslate(unlocalizedCustomSpeed)) { + speed = StringUtil.localize(unlocalizedCustomSpeed); + } else { + speed = speedAllele.getName() + ' ' + StringUtil.localize("gui.worker"); + } + + String lifespan = + genome.getActiveAllele(EnumBeeChromosome.LIFESPAN).getName() + ' ' + StringUtil.localize("gui.life"); + String tempTolerance = EnumChatFormatting.GREEN + "T: " + + AlleleManager.climateHelper.toDisplay(genome.getPrimary().getTemperature()) + " / " + + tempToleranceAllele.getName(); + String humidTolerance = EnumChatFormatting.GREEN + "H: " + + AlleleManager.climateHelper.toDisplay(genome.getPrimary().getHumidity()) + " / " + + humidToleranceAllele.getName(); + String flowers = genome.getFlowerProvider().getDescription(); + + list.add(lifespan); + list.add(speed); + list.add(tempTolerance); + list.add(humidTolerance); + list.add(flowers); + + if (genome.getNocturnal()) { + list.add(EnumChatFormatting.RED + GenericRatings.rateActivityTime(genome.getNocturnal(), false)); + } + + if (genome.getTolerantFlyer()) { + list.add(EnumChatFormatting.WHITE + StringUtil.localize("gui.flyer.tooltip")); + } + } + + @Override + public void age(World world, float housingLifespanModifier) { + IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(world); + IBeeModifier beeModifier = mode.getBeeModifier(); + float finalModifier = + housingLifespanModifier * beeModifier.getLifespanModifier(genome, mate, housingLifespanModifier); + + super.age(world, finalModifier); + } + + // / PRODUCTION + @Override + public ItemStack[] getProduceList() { + ArrayList products = new ArrayList<>(); + + IAlleleBeeSpecies primary = genome.getPrimary(); + IAlleleBeeSpecies secondary = genome.getSecondary(); + + products.addAll(primary.getProductChances().keySet()); + + Set secondaryProducts = secondary.getProductChances().keySet(); + // Remove duplicates + for (ItemStack second : secondaryProducts) { + boolean skip = false; + + for (ItemStack compare : products) { + if (second.isItemEqual(compare)) { + skip = true; + break; + } + } + + if (!skip) { + products.add(second); + } + } + + return products.toArray(new ItemStack[products.size()]); + } + + @Override + public ItemStack[] getSpecialtyList() { + Set specialties = genome.getPrimary().getSpecialtyChances().keySet(); + return specialties.toArray(new ItemStack[specialties.size()]); + } + + @Override + public ItemStack[] produceStacks(IBeeHousing housing) { + if (housing == null) { + Log.warning("Failed to produce in an apiary because the beehousing was null."); + return null; + } + IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(housing.getWorld()); + if (mode == null) { + Log.warning("Failed to produce in an apiary because the beekeeping mode was null."); + return null; + } + + List products = new ArrayList<>(); + + IAlleleBeeSpecies primary = genome.getPrimary(); + IAlleleBeeSpecies secondary = genome.getSecondary(); + + // All work and no play makes queen a dull girl. + if (mode.isOverworked(this, housing)) { + setIsNatural(false); + } + + IBeeModifier beeHousingModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); + IBeeModifier beeModeModifier = mode.getBeeModifier(); + + // Bee genetic speed * beehousing * beekeeping mode + float speed = genome.getSpeed() + * beeHousingModifier.getProductionModifier(genome, 1f) + * beeModeModifier.getProductionModifier(genome, 1f); + + // / Primary Products + for (Map.Entry entry : primary.getProductChances().entrySet()) { + if (housing.getWorld().rand.nextFloat() < entry.getValue() * speed) { + products.add(entry.getKey().copy()); + } + } + // / Secondary Products + for (Map.Entry entry : secondary.getProductChances().entrySet()) { + if (housing.getWorld().rand.nextFloat() < Math.round(entry.getValue() / 2) * speed) { + products.add(entry.getKey().copy()); + } + } + + // / Specialty products + if (primary.isJubilant(genome, housing) && secondary.isJubilant(genome, housing)) { + for (Map.Entry entry : + primary.getSpecialtyChances().entrySet()) { + if (housing.getWorld().rand.nextFloat() < entry.getValue() * speed) { + products.add(entry.getKey().copy()); + } + } + } + + ItemStack[] productsArray = products.toArray(new ItemStack[products.size()]); + ChunkCoordinates housingCoordinates = housing.getCoordinates(); + return genome.getFlowerProvider() + .affectProducts( + housing.getWorld(), + this, + housingCoordinates.posX, + housingCoordinates.posY, + housingCoordinates.posZ, + productsArray); + } + + /* REPRODUCTION */ + @Override + public IBee spawnPrincess(IBeeHousing housing) { + + // We need a mated queen to produce offspring. + if (mate == null) { + return null; + } + + // Fatigued queens do not produce princesses. + if (BeeManager.beeRoot.getBeekeepingMode(housing.getWorld()).isFatigued(this, housing)) { + return null; + } + + return createOffspring(housing, getGeneration() + 1); + } + + @Override + public IBee[] spawnDrones(IBeeHousing housing) { + + World world = housing.getWorld(); + + // We need a mated queen to produce offspring. + if (mate == null) { + return null; + } + + List bees = new ArrayList<>(); + + ChunkCoordinates housingCoordinates = housing.getCoordinates(); + int toCreate = BeeManager.beeRoot + .getBeekeepingMode(world) + .getFinalFertility( + this, world, housingCoordinates.posX, housingCoordinates.posY, housingCoordinates.posZ); + + if (toCreate <= 0) { + toCreate = 1; + } + + for (int i = 0; i < toCreate; i++) { + IBee offspring = createOffspring(housing, 0); + if (offspring != null) { + offspring.setIsNatural(true); + bees.add(offspring); + } + } + + if (bees.size() > 0) { + return bees.toArray(new IBee[bees.size()]); + } else { + return null; + } + } + + private IBee createOffspring(IBeeHousing housing, int generation) { + + World world = housing.getWorld(); + + IChromosome[] chromosomes = new IChromosome[genome.getChromosomes().length]; + IChromosome[] parent1 = genome.getChromosomes(); + IChromosome[] parent2 = mate.getChromosomes(); + + // Check for mutation. Replace one of the parents with the mutation + // template if mutation occured. + IChromosome[] mutated1 = mutateSpecies(housing, genome, mate); + if (mutated1 != null) { + parent1 = mutated1; + } + IChromosome[] mutated2 = mutateSpecies(housing, mate, genome); + if (mutated2 != null) { + parent2 = mutated2; + } + + for (int i = 0; i < parent1.length; i++) { + if (parent1[i] != null && parent2[i] != null) { + chromosomes[i] = Chromosome.inheritChromosome(world.rand, parent1[i], parent2[i]); + } + } + + IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(world); + return new Bee(new BeeGenome(chromosomes), mode.isNaturalOffspring(this), generation); + } + + private static IChromosome[] mutateSpecies(IBeeHousing housing, IBeeGenome genomeOne, IBeeGenome genomeTwo) { + + World world = housing.getWorld(); + + IChromosome[] parent1 = genomeOne.getChromosomes(); + IChromosome[] parent2 = genomeTwo.getChromosomes(); + + IBeeGenome genome0; + IBeeGenome genome1; + + IAlleleBeeSpecies allele0; + IAlleleBeeSpecies allele1; + + if (world.rand.nextBoolean()) { + allele0 = (IAlleleBeeSpecies) parent1[EnumBeeChromosome.SPECIES.ordinal()].getPrimaryAllele(); + allele1 = (IAlleleBeeSpecies) parent2[EnumBeeChromosome.SPECIES.ordinal()].getSecondaryAllele(); + + genome0 = genomeOne; + genome1 = genomeTwo; + } else { + allele0 = (IAlleleBeeSpecies) parent2[EnumBeeChromosome.SPECIES.ordinal()].getPrimaryAllele(); + allele1 = (IAlleleBeeSpecies) parent1[EnumBeeChromosome.SPECIES.ordinal()].getSecondaryAllele(); - /* CONSTRUCTOR */ - public Bee(NBTTagCompound nbttagcompound) { - readFromNBT(nbttagcompound); - } + genome0 = genomeTwo; + genome1 = genomeOne; + } + + GameProfile playerProfile = housing.getOwner(); + IApiaristTracker breedingTracker = BeeManager.beeRoot.getBreedingTracker(world, playerProfile); - public Bee(IBeeGenome genome, IBee mate) { - this(genome); - this.mate = mate.getGenome(); - } - - public Bee(IBeeGenome genome) { - this(genome, true, 0); - } + List combinations = BeeManager.beeRoot.getCombinations(allele0, allele1, true); + for (IMutation mutation : combinations) { + IBeeMutation beeMutation = (IBeeMutation) mutation; + + float chance = beeMutation.getChance(housing, allele0, allele1, genome0, genome1); + if (chance <= 0) { + continue; + } + + // boost chance for researched mutations + if (breedingTracker.isResearched(beeMutation)) { + float mutationBoost = chance * (Config.researchMutationBoostMultiplier - 1.0f); + mutationBoost = Math.min(Config.maxResearchMutationBoostPercent, mutationBoost); + chance += mutationBoost; + } + + if (chance > world.rand.nextFloat() * 100) { + breedingTracker.registerMutation(mutation); + return BeeManager.beeRoot.templateAsChromosomes(mutation.getTemplate()); + } + } + + return null; + } - private Bee(IBeeGenome genome, boolean isNatural, int generation) { - super(genome.getLifespan()); - this.genome = genome; - this.isNatural = isNatural; - this.generation = generation; - } + /* FLOWERS */ + @Override + public IIndividual retrievePollen(IBeeHousing housing) { - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { + IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - if (nbttagcompound == null) { - genome = BeeDefinition.FOREST.getGenome(); - return; - } + int chance = Math.round(genome.getFlowering() * beeModifier.getFloweringModifier(getGenome(), 1f)); - super.readFromNBT(nbttagcompound); + World world = housing.getWorld(); + Random random = world.rand; - if (nbttagcompound.hasKey("NA")) { - isNatural = nbttagcompound.getBoolean("NA"); - } + // Correct speed + if (random.nextInt(100) >= chance) { + return null; + } - if (nbttagcompound.hasKey("GEN")) { - generation = nbttagcompound.getInteger("GEN"); - } + Vect area = getArea(genome, beeModifier); + Vect offset = new Vect(-area.x / 2, -area.y / 4, -area.z / 2); + Vect housingPos = new Vect(housing.getCoordinates()); - if (nbttagcompound.hasKey("Genome")) { - genome = BeeGenome.fromNBT(nbttagcompound.getCompoundTag("Genome")); - } else { - genome = BeeDefinition.FOREST.getGenome(); - } + IIndividual pollen = null; + + for (int i = 0; i < 20; i++) { + Vect randomPos = Vect.getRandomPositionInArea(random, area); + Vect blockPos = Vect.add(housingPos, randomPos, offset); + TileEntity tile = world.getTileEntity(blockPos.x, blockPos.y, blockPos.z); + + if (tile instanceof IPollinatable) { + IPollinatable pitcher = (IPollinatable) tile; + if (genome.getFlowerProvider().isAcceptedPollinatable(world, pitcher)) { + pollen = pitcher.getPollen(); + } + } else { + pollen = GeneticsUtil.getErsatzPollen(world, blockPos.x, blockPos.y, blockPos.z); + } - if (nbttagcompound.hasKey("Mate")) { - mate = BeeGenome.fromNBT(nbttagcompound.getCompoundTag("Mate")); - } + if (pollen != null) { + return pollen; + } + } - } + return null; + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { + @Override + public boolean pollinateRandom(IBeeHousing housing, IIndividual pollen) { - super.writeToNBT(nbttagcompound); + IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - if (!isNatural) { - nbttagcompound.setBoolean("NA", false); - } + int chance = (int) (genome.getFlowering() * beeModifier.getFloweringModifier(getGenome(), 1f)); + + World world = housing.getWorld(); + Random random = world.rand; + + // Correct speed + if (random.nextInt(100) >= chance) { + return false; + } + + Vect area = getArea(genome, beeModifier); + Vect offset = new Vect(-area.x / 2, -area.y / 4, -area.z / 2); + Vect housingPos = new Vect(housing.getCoordinates()); + + for (int i = 0; i < 30; i++) { + + Vect randomPos = Vect.getRandomPositionInArea(random, area); + Vect posBlock = Vect.add(housingPos, randomPos, offset); - if (generation > 0) { - nbttagcompound.setInteger("GEN", generation); - } - } - - public void setIsNatural(boolean flag) { - this.isNatural = flag; - } - - public boolean isNatural() { - return this.isNatural; - } - - public int getGeneration() { - return generation; - } - - @Override - public void mate(IIndividual individual) { - if (!(individual instanceof IBee)) { - return; - } + ICheckPollinatable checkPollinatable = + GeneticsUtil.getCheckPollinatable(world, posBlock.x, posBlock.y, posBlock.z); + if (checkPollinatable == null) { + continue; + } + + if (!genome.getFlowerProvider().isAcceptedPollinatable(world, new FakePollinatable(checkPollinatable))) { + continue; + } + if (!checkPollinatable.canMateWith(pollen)) { + continue; + } + + IPollinatable realPollinatable = + GeneticsUtil.getOrCreatePollinatable(housing.getOwner(), world, posBlock.x, posBlock.y, posBlock.z); - IBee drone = (IBee) individual; - mate = drone.getGenome(); - } + if (realPollinatable != null) { + realPollinatable.mateWith(pollen); + return true; + } + } - /* EFFECTS */ - @Override - public IEffectData[] doEffect(IEffectData[] storedData, IBeeHousing housing) { - IAlleleBeeEffect effect = genome.getEffect(); - - if (effect == null) { - return null; - } - - storedData[0] = doEffect(effect, storedData[0], housing); - - // Return here if the primary can already not be combined - if (!effect.isCombinable()) { - return storedData; - } - - IAlleleBeeEffect secondary = (IAlleleBeeEffect) genome.getInactiveAllele(EnumBeeChromosome.EFFECT); - if (!secondary.isCombinable()) { - return storedData; - } - - storedData[1] = doEffect(secondary, storedData[1], housing); - - return storedData; - } - - private IEffectData doEffect(IAlleleBeeEffect effect, IEffectData storedData, IBeeHousing housing) { - storedData = effect.validateStorage(storedData); - return effect.doEffect(genome, storedData, housing); - } - - @Override - public IEffectData[] doFX(IEffectData[] storedData, IBeeHousing housing) { - IAlleleBeeEffect effect = genome.getEffect(); - - if (effect == null) { - return null; - } - - storedData[0] = doFX(effect, storedData[0], housing); - - // Return here if the primary can already not be combined - if (!effect.isCombinable()) { - return storedData; - } - - IAlleleBeeEffect secondary = (IAlleleBeeEffect) genome.getInactiveAllele(EnumBeeChromosome.EFFECT); - if (!secondary.isCombinable()) { - return storedData; - } - - storedData[1] = doFX(secondary, storedData[1], housing); - - return storedData; - } - - private IEffectData doFX(IAlleleBeeEffect effect, IEffectData storedData, IBeeHousing housing) { - return effect.doFX(genome, storedData, housing); - } - - // / INFORMATION - @Override - public IBeeGenome getGenome() { - return genome; - } - - @Override - public IBeeGenome getMate() { - return mate; - } - - @Override - public IBee copy() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - this.writeToNBT(nbttagcompound); - return new Bee(nbttagcompound); - - } - - @Override - public boolean canSpawn() { - return mate != null; - } - - @Override - public Set getCanWork(IBeeHousing housing) { - World world = housing.getWorld(); - BiomeGenBase biome = housing.getBiome(); - - Set errorStates = new HashSet<>(); - - IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - - // / Rain needs tolerant flyers - if (world.isRaining() && BiomeHelper.canRainOrSnow(biome) && !canFlyInRain(beeModifier)) { - errorStates.add(EnumErrorCode.IS_RAINING); - } - - // / Night or darkness requires nocturnal species - if (world.isDaytime()) { - if (!canWorkDuringDay()) { - errorStates.add(EnumErrorCode.NOT_NIGHT); - } - } else { - if (!canWorkAtNight(beeModifier)) { - errorStates.add(EnumErrorCode.NOT_DAY); - } - } - - if (housing.getBlockLightValue() > Constants.APIARY_MIN_LEVEL_LIGHT) { - if (!canWorkDuringDay()) { - errorStates.add(EnumErrorCode.NOT_GLOOMY); - } - } else { - if (!canWorkAtNight(beeModifier)) { - errorStates.add(EnumErrorCode.NOT_BRIGHT); - } - } - - // / Check for the sky, except if in hell - if (!world.provider.hasNoSky) { - if (!housing.canBlockSeeTheSky() && !canWorkUnderground(beeModifier)) { - errorStates.add(EnumErrorCode.NO_SKY); - } - } - - // / And finally climate check - IAlleleBeeSpecies species = genome.getPrimary(); - { - EnumTemperature actualTemperature = housing.getTemperature(); - EnumTemperature beeBaseTemperature = species.getTemperature(); - EnumTolerance beeToleranceTemperature = genome.getToleranceTemp(); - - if (!AlleleManager.climateHelper.isWithinLimits(actualTemperature, beeBaseTemperature, beeToleranceTemperature)) { - if (beeBaseTemperature.ordinal() > actualTemperature.ordinal()) { - errorStates.add(EnumErrorCode.TOO_COLD); - } else { - errorStates.add(EnumErrorCode.TOO_HOT); - } - } - } - - { - EnumHumidity actualHumidity = housing.getHumidity(); - EnumHumidity beeBaseHumidity = species.getHumidity(); - EnumTolerance beeToleranceHumidity = genome.getToleranceHumid(); - - if (!AlleleManager.climateHelper.isWithinLimits(actualHumidity, beeBaseHumidity, beeToleranceHumidity)) { - if (beeBaseHumidity.ordinal() > actualHumidity.ordinal()) { - errorStates.add(EnumErrorCode.TOO_ARID); - } else { - errorStates.add(EnumErrorCode.TOO_HUMID); - } - } - } - - return errorStates; - } - - private boolean canWorkAtNight(IBeeModifier beeModifier) { - return genome.getPrimary().isNocturnal() || genome.getNocturnal() || beeModifier.isSelfLighted(); - } - - private boolean canWorkDuringDay() { - return !genome.getPrimary().isNocturnal() || genome.getNocturnal(); - } - - private boolean canWorkUnderground(IBeeModifier beeModifier) { - return genome.getCaveDwelling() || beeModifier.isSunlightSimulated(); - } - - private boolean canFlyInRain(IBeeModifier beeModifier) { - return genome.getTolerantFlyer() || beeModifier.isSealed(); - } - - private boolean isSuitableBiome(BiomeGenBase biome) { - if (biome == null) { - return false; - } - - EnumTemperature temperature = EnumTemperature.getFromBiome(biome); - EnumHumidity humidity = EnumHumidity.getFromValue(biome.rainfall); - return isSuitableClimate(temperature, humidity); - } - - private boolean isSuitableClimate(EnumTemperature temperature, EnumHumidity humidity) { - return AlleleManager.climateHelper.isWithinLimits(temperature, humidity, - genome.getPrimary().getTemperature(), genome.getToleranceTemp(), - genome.getPrimary().getHumidity(), genome.getToleranceHumid()); - } - - @Override - public ArrayList getSuitableBiomes() { - ArrayList suitableBiomes = new ArrayList<>(); - for (BiomeGenBase biome : BiomeGenBase.getBiomeGenArray()) { - if (isSuitableBiome(biome)) { - suitableBiomes.add(biome); - } - } - - return suitableBiomes; - } - - @Override - public void addTooltip(List list) { - - // No info 4 u! - if (!isAnalyzed) { - list.add("<" + StringUtil.localize("gui.unknown") + ">"); - return; - } - - // You analyzed it? Juicy tooltip coming up! - IAlleleBeeSpecies primary = genome.getPrimary(); - IAlleleBeeSpecies secondary = genome.getSecondary(); - if (!isPureBred(EnumBeeChromosome.SPECIES)) { - list.add(EnumChatFormatting.BLUE + StringUtil.localize("bees.hybrid").replaceAll("%PRIMARY", primary.getName()).replaceAll("%SECONDARY", secondary.getName())); - } - - if (generation > 0) { - EnumRarity rarity; - if (generation >= 1000) { - rarity = EnumRarity.epic; - } else if (generation >= 100) { - rarity = EnumRarity.rare; - } else if (generation >= 10) { - rarity = EnumRarity.uncommon; - } else { - rarity = EnumRarity.common; - } - - String generationString = rarity.rarityColor + StringUtil.localizeAndFormat("gui.beealyzer.generations", generation); - list.add(generationString); - } - - IAllele speedAllele = genome.getActiveAllele(EnumBeeChromosome.SPEED); - IAlleleTolerance tempToleranceAllele = (IAlleleTolerance) getGenome().getActiveAllele(EnumBeeChromosome.TEMPERATURE_TOLERANCE); - IAlleleTolerance humidToleranceAllele = (IAlleleTolerance) getGenome().getActiveAllele(EnumBeeChromosome.HUMIDITY_TOLERANCE); - - String unlocalizedCustomSpeed = "tooltip.worker." + speedAllele.getUnlocalizedName().replaceAll("(.*)\\.", ""); - String speed; - if (StringUtil.canTranslate(unlocalizedCustomSpeed)) { - speed = StringUtil.localize(unlocalizedCustomSpeed); - } else { - speed = speedAllele.getName() + ' ' + StringUtil.localize("gui.worker"); - } - - String lifespan = genome.getActiveAllele(EnumBeeChromosome.LIFESPAN).getName() + ' ' + StringUtil.localize("gui.life"); - String tempTolerance = EnumChatFormatting.GREEN + "T: " + AlleleManager.climateHelper.toDisplay(genome.getPrimary().getTemperature()) + " / " + tempToleranceAllele.getName(); - String humidTolerance = EnumChatFormatting.GREEN + "H: " + AlleleManager.climateHelper.toDisplay(genome.getPrimary().getHumidity()) + " / " + humidToleranceAllele.getName(); - String flowers = genome.getFlowerProvider().getDescription(); - - list.add(lifespan); - list.add(speed); - list.add(tempTolerance); - list.add(humidTolerance); - list.add(flowers); - - if (genome.getNocturnal()) { - list.add(EnumChatFormatting.RED + GenericRatings.rateActivityTime(genome.getNocturnal(), false)); - } - - if (genome.getTolerantFlyer()) { - list.add(EnumChatFormatting.WHITE + StringUtil.localize("gui.flyer.tooltip")); - } - } - - @Override - public void age(World world, float housingLifespanModifier) { - IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(world); - IBeeModifier beeModifier = mode.getBeeModifier(); - float finalModifier = housingLifespanModifier * beeModifier.getLifespanModifier(genome, mate, housingLifespanModifier); - - super.age(world, finalModifier); - } - - // / PRODUCTION - @Override - public ItemStack[] getProduceList() { - ArrayList products = new ArrayList<>(); - - IAlleleBeeSpecies primary = genome.getPrimary(); - IAlleleBeeSpecies secondary = genome.getSecondary(); - - products.addAll(primary.getProductChances().keySet()); - - Set secondaryProducts = secondary.getProductChances().keySet(); - // Remove duplicates - for (ItemStack second : secondaryProducts) { - boolean skip = false; - - for (ItemStack compare : products) { - if (second.isItemEqual(compare)) { - skip = true; - break; - } - } - - if (!skip) { - products.add(second); - } - - } - - return products.toArray(new ItemStack[products.size()]); - } - - @Override - public ItemStack[] getSpecialtyList() { - Set specialties = genome.getPrimary().getSpecialtyChances().keySet(); - return specialties.toArray(new ItemStack[specialties.size()]); - } - - @Override - public ItemStack[] produceStacks(IBeeHousing housing) { - if (housing == null) { - Log.warning("Failed to produce in an apiary because the beehousing was null."); - return null; - } - IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(housing.getWorld()); - if (mode == null) { - Log.warning("Failed to produce in an apiary because the beekeeping mode was null."); - return null; - } - - List products = new ArrayList<>(); - - IAlleleBeeSpecies primary = genome.getPrimary(); - IAlleleBeeSpecies secondary = genome.getSecondary(); - - // All work and no play makes queen a dull girl. - if (mode.isOverworked(this, housing)) { - setIsNatural(false); - } - - IBeeModifier beeHousingModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - IBeeModifier beeModeModifier = mode.getBeeModifier(); - - // Bee genetic speed * beehousing * beekeeping mode - float speed = genome.getSpeed() * beeHousingModifier.getProductionModifier(genome, 1f) * beeModeModifier.getProductionModifier(genome, 1f); - - // / Primary Products - for (Map.Entry entry : primary.getProductChances().entrySet()) { - if (housing.getWorld().rand.nextFloat() < entry.getValue() * speed) { - products.add(entry.getKey().copy()); - } - } - // / Secondary Products - for (Map.Entry entry : secondary.getProductChances().entrySet()) { - if (housing.getWorld().rand.nextFloat() < Math.round(entry.getValue() / 2) * speed) { - products.add(entry.getKey().copy()); - } - } - - // / Specialty products - if (primary.isJubilant(genome, housing) && secondary.isJubilant(genome, housing)) { - for (Map.Entry entry : primary.getSpecialtyChances().entrySet()) { - if (housing.getWorld().rand.nextFloat() < entry.getValue() * speed) { - products.add(entry.getKey().copy()); - } - } - } - - ItemStack[] productsArray = products.toArray(new ItemStack[products.size()]); - ChunkCoordinates housingCoordinates = housing.getCoordinates(); - return genome.getFlowerProvider().affectProducts(housing.getWorld(), this, housingCoordinates.posX, housingCoordinates.posY, housingCoordinates.posZ, productsArray); - } - - /* REPRODUCTION */ - @Override - public IBee spawnPrincess(IBeeHousing housing) { - - // We need a mated queen to produce offspring. - if (mate == null) { - return null; - } - - // Fatigued queens do not produce princesses. - if (BeeManager.beeRoot.getBeekeepingMode(housing.getWorld()).isFatigued(this, housing)) { - return null; - } - - return createOffspring(housing, getGeneration() + 1); - } - - @Override - public IBee[] spawnDrones(IBeeHousing housing) { - - World world = housing.getWorld(); - - // We need a mated queen to produce offspring. - if (mate == null) { - return null; - } - - List bees = new ArrayList<>(); - - ChunkCoordinates housingCoordinates = housing.getCoordinates(); - int toCreate = BeeManager.beeRoot.getBeekeepingMode(world).getFinalFertility(this, world, housingCoordinates.posX, housingCoordinates.posY, housingCoordinates.posZ); - - if (toCreate <= 0) { - toCreate = 1; - } - - for (int i = 0; i < toCreate; i++) { - IBee offspring = createOffspring(housing, 0); - if (offspring != null) { - offspring.setIsNatural(true); - bees.add(offspring); - } - } - - if (bees.size() > 0) { - return bees.toArray(new IBee[bees.size()]); - } else { - return null; - } - } - - private IBee createOffspring(IBeeHousing housing, int generation) { - - World world = housing.getWorld(); - - IChromosome[] chromosomes = new IChromosome[genome.getChromosomes().length]; - IChromosome[] parent1 = genome.getChromosomes(); - IChromosome[] parent2 = mate.getChromosomes(); - - // Check for mutation. Replace one of the parents with the mutation - // template if mutation occured. - IChromosome[] mutated1 = mutateSpecies(housing, genome, mate); - if (mutated1 != null) { - parent1 = mutated1; - } - IChromosome[] mutated2 = mutateSpecies(housing, mate, genome); - if (mutated2 != null) { - parent2 = mutated2; - } - - for (int i = 0; i < parent1.length; i++) { - if (parent1[i] != null && parent2[i] != null) { - chromosomes[i] = Chromosome.inheritChromosome(world.rand, parent1[i], parent2[i]); - } - } - - IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(world); - return new Bee(new BeeGenome(chromosomes), mode.isNaturalOffspring(this), generation); - } - - private static IChromosome[] mutateSpecies(IBeeHousing housing, IBeeGenome genomeOne, IBeeGenome genomeTwo) { - - World world = housing.getWorld(); - - IChromosome[] parent1 = genomeOne.getChromosomes(); - IChromosome[] parent2 = genomeTwo.getChromosomes(); - - IBeeGenome genome0; - IBeeGenome genome1; - - IAlleleBeeSpecies allele0; - IAlleleBeeSpecies allele1; - - if (world.rand.nextBoolean()) { - allele0 = (IAlleleBeeSpecies) parent1[EnumBeeChromosome.SPECIES.ordinal()].getPrimaryAllele(); - allele1 = (IAlleleBeeSpecies) parent2[EnumBeeChromosome.SPECIES.ordinal()].getSecondaryAllele(); - - genome0 = genomeOne; - genome1 = genomeTwo; - } else { - allele0 = (IAlleleBeeSpecies) parent2[EnumBeeChromosome.SPECIES.ordinal()].getPrimaryAllele(); - allele1 = (IAlleleBeeSpecies) parent1[EnumBeeChromosome.SPECIES.ordinal()].getSecondaryAllele(); + return false; + } - genome0 = genomeTwo; - genome1 = genomeOne; - } + @Override + public void plantFlowerRandom(IBeeHousing housing) { - GameProfile playerProfile = housing.getOwner(); - IApiaristTracker breedingTracker = BeeManager.beeRoot.getBreedingTracker(world, playerProfile); + IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - List combinations = BeeManager.beeRoot.getCombinations(allele0, allele1, true); - for (IMutation mutation : combinations) { - IBeeMutation beeMutation = (IBeeMutation) mutation; + int chance = Math.round(genome.getFlowering() * beeModifier.getFloweringModifier(getGenome(), 1f)); - float chance = beeMutation.getChance(housing, allele0, allele1, genome0, genome1); - if (chance <= 0) { - continue; - } + World world = housing.getWorld(); + Random random = world.rand; - // boost chance for researched mutations - if (breedingTracker.isResearched(beeMutation)) { - float mutationBoost = chance * (Config.researchMutationBoostMultiplier - 1.0f); - mutationBoost = Math.min(Config.maxResearchMutationBoostPercent, mutationBoost); - chance += mutationBoost; - } + // Correct speed + if (random.nextInt(100) >= chance) { + return; + } - if (chance > world.rand.nextFloat() * 100) { - breedingTracker.registerMutation(mutation); - return BeeManager.beeRoot.templateAsChromosomes(mutation.getTemplate()); - } - } - - return null; - } - - /* FLOWERS */ - @Override - public IIndividual retrievePollen(IBeeHousing housing) { - - IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - - int chance = Math.round(genome.getFlowering() * beeModifier.getFloweringModifier(getGenome(), 1f)); - - World world = housing.getWorld(); - Random random = world.rand; - - // Correct speed - if (random.nextInt(100) >= chance) { - return null; - } - - Vect area = getArea(genome, beeModifier); - Vect offset = new Vect(-area.x / 2, -area.y / 4, -area.z / 2); - Vect housingPos = new Vect(housing.getCoordinates()); - - IIndividual pollen = null; - - for (int i = 0; i < 20; i++) { - Vect randomPos = Vect.getRandomPositionInArea(random, area); - Vect blockPos = Vect.add(housingPos, randomPos, offset); - TileEntity tile = world.getTileEntity(blockPos.x, blockPos.y, blockPos.z); - - if (tile instanceof IPollinatable) { - IPollinatable pitcher = (IPollinatable) tile; - if (genome.getFlowerProvider().isAcceptedPollinatable(world, pitcher)) { - pollen = pitcher.getPollen(); - } - } else { - pollen = GeneticsUtil.getErsatzPollen(world, blockPos.x, blockPos.y, blockPos.z); - } - - if (pollen != null) { - return pollen; - } - } - - return null; - } - - @Override - public boolean pollinateRandom(IBeeHousing housing, IIndividual pollen) { - - IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - - int chance = (int) (genome.getFlowering() * beeModifier.getFloweringModifier(getGenome(), 1f)); - - World world = housing.getWorld(); - Random random = world.rand; - - // Correct speed - if (random.nextInt(100) >= chance) { - return false; - } - - Vect area = getArea(genome, beeModifier); - Vect offset = new Vect(-area.x / 2, -area.y / 4, -area.z / 2); - Vect housingPos = new Vect(housing.getCoordinates()); - - for (int i = 0; i < 30; i++) { - - Vect randomPos = Vect.getRandomPositionInArea(random, area); - Vect posBlock = Vect.add(housingPos, randomPos, offset); - - ICheckPollinatable checkPollinatable = GeneticsUtil.getCheckPollinatable(world, posBlock.x, posBlock.y, posBlock.z); - if (checkPollinatable == null) { - continue; - } - - if (!genome.getFlowerProvider().isAcceptedPollinatable(world, new FakePollinatable(checkPollinatable))) { - continue; - } - if (!checkPollinatable.canMateWith(pollen)) { - continue; - } - - IPollinatable realPollinatable = GeneticsUtil.getOrCreatePollinatable(housing.getOwner(), world, posBlock.x, posBlock.y, posBlock.z); - - if (realPollinatable != null) { - realPollinatable.mateWith(pollen); - return true; - } - } - - return false; - } - - @Override - public void plantFlowerRandom(IBeeHousing housing) { - - IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - - int chance = Math.round(genome.getFlowering() * beeModifier.getFloweringModifier(getGenome(), 1f)); - - World world = housing.getWorld(); - Random random = world.rand; - - // Correct speed - if (random.nextInt(100) >= chance) { - return; - } - - // Gather required info - IFlowerProvider provider = genome.getFlowerProvider(); - Vect area = getArea(genome, beeModifier); - Vect offset = new Vect(-area.x / 2, -area.y / 4, -area.z / 2); - Vect housingPos = new Vect(housing.getCoordinates()); - - for (int i = 0; i < 10; i++) { - Vect randomPos = Vect.getRandomPositionInArea(random, area); - Vect posBlock = Vect.add(housingPos, randomPos, offset); - - if (FlowerManager.flowerRegistry.growFlower(provider.getFlowerType(), world, this, posBlock.x, posBlock.y, posBlock.z)) { - break; - } - } - } - - private static Vect getArea(IBeeGenome genome, IBeeModifier beeModifier) { - int[] genomeTerritory = genome.getTerritory(); - float housingModifier = beeModifier.getTerritoryModifier(genome, 1f); - return new Vect(genomeTerritory).multiply(housingModifier * 3.0f); - } + // Gather required info + IFlowerProvider provider = genome.getFlowerProvider(); + Vect area = getArea(genome, beeModifier); + Vect offset = new Vect(-area.x / 2, -area.y / 4, -area.z / 2); + Vect housingPos = new Vect(housing.getCoordinates()); + + for (int i = 0; i < 10; i++) { + Vect randomPos = Vect.getRandomPositionInArea(random, area); + Vect posBlock = Vect.add(housingPos, randomPos, offset); + + if (FlowerManager.flowerRegistry.growFlower( + provider.getFlowerType(), world, this, posBlock.x, posBlock.y, posBlock.z)) { + break; + } + } + } + + private static Vect getArea(IBeeGenome genome, IBeeModifier beeModifier) { + int[] genomeTerritory = genome.getTerritory(); + float housingModifier = beeModifier.getTerritoryModifier(genome, 1f); + return new Vect(genomeTerritory).multiply(housingModifier * 3.0f); + } } diff --git a/src/main/java/forestry/apiculture/genetics/BeeBranchDefinition.java b/src/main/java/forestry/apiculture/genetics/BeeBranchDefinition.java index d5bda0eb7..759cf3af1 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeBranchDefinition.java +++ b/src/main/java/forestry/apiculture/genetics/BeeBranchDefinition.java @@ -1,159 +1,157 @@ -package forestry.apiculture.genetics; - -import java.util.Arrays; -import java.util.Locale; - -import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.EnumBeeChromosome; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IClassification; -import forestry.apiculture.genetics.alleles.AlleleEffect; -import forestry.core.genetics.IBranchDefinition; -import forestry.core.genetics.alleles.AlleleHelper; -import forestry.core.genetics.alleles.EnumAllele; - -public enum BeeBranchDefinition implements IBranchDefinition { - HONEY("Apis"), - NOBLE("Probapis"), - INDUSTRIOUS("Industrapis"), - HEROIC("Herapis"), - INFERNAL("Diapis") { - @Override - protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_2); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.NOCTURNAL, true); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.NETHER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.AVERAGE); - } - }, - AUSTERE("Modapis") { - @Override - protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.NOCTURNAL, true); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.CACTI); - } - }, - TROPICAL("Caldapis") { - @Override - protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.UP_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.JUNGLE); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.EFFECT, AlleleEffect.effectMiasmic); - } - }, - END("Finapis") { - @Override - protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.LOW); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGE); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.END); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.NOCTURNAL, true); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.EFFECT, AlleleEffect.effectMisanthrope); - } - }, - FROZEN("Coagapis") { - @Override - protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.SNOW); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.EFFECT, AlleleEffect.effectGlacial); - } - }, - VENGEFUL("Punapis") { - @Override - protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGEST); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.EFFECT, AlleleEffect.effectRadioactive); - } - }, - FESTIVE("Festapis") { - @Override - protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_2); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); - } - }, - AGRARIAN("Rustapis") { - @Override - protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.WHEAT); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTER); - } - }, - BOGGY("Paludapis") { - @Override - protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.MUSHROOMS); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); - } - }, - MONASTIC("Monapis") { - @Override - protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.LOW); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.CAVE_DWELLING, true); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.WHEAT); - } - }; - - private final IClassification branch; - - BeeBranchDefinition(String scientific) { - branch = BeeManager.beeFactory.createBranch(this.name().toLowerCase(Locale.ENGLISH), scientific); - } - - protected void setBranchProperties(IAllele[] template) { - - } - - @Override - public final IAllele[] getTemplate() { - IAllele[] template = getDefaultTemplate(); - setBranchProperties(template); - return template; - } - - @Override - public final IClassification getBranch() { - return branch; - } - - private static IAllele[] defaultTemplate; - - private static IAllele[] getDefaultTemplate() { - if (defaultTemplate == null) { - defaultTemplate = new IAllele[EnumBeeChromosome.values().length]; - - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.NORMAL); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.NONE); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.NOCTURNAL, false); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.NONE); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.TOLERANT_FLYER, false); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.CAVE_DWELLING, false); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.VANILLA); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWEST); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.AVERAGE); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.EFFECT, AlleleEffect.effectNone); - } - return Arrays.copyOf(defaultTemplate, defaultTemplate.length); - } -} +package forestry.apiculture.genetics; + +import forestry.api.apiculture.BeeManager; +import forestry.api.apiculture.EnumBeeChromosome; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IClassification; +import forestry.apiculture.genetics.alleles.AlleleEffect; +import forestry.core.genetics.IBranchDefinition; +import forestry.core.genetics.alleles.AlleleHelper; +import forestry.core.genetics.alleles.EnumAllele; +import java.util.Arrays; +import java.util.Locale; + +public enum BeeBranchDefinition implements IBranchDefinition { + HONEY("Apis"), + NOBLE("Probapis"), + INDUSTRIOUS("Industrapis"), + HEROIC("Herapis"), + INFERNAL("Diapis") { + @Override + protected void setBranchProperties(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_2); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.NOCTURNAL, true); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.NETHER); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.AVERAGE); + } + }, + AUSTERE("Modapis") { + @Override + protected void setBranchProperties(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.NOCTURNAL, true); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.CACTI); + } + }, + TROPICAL("Caldapis") { + @Override + protected void setBranchProperties(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.UP_1); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.JUNGLE); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.EFFECT, AlleleEffect.effectMiasmic); + } + }, + END("Finapis") { + @Override + protected void setBranchProperties(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.LOW); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGE); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.END); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.NOCTURNAL, true); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.EFFECT, AlleleEffect.effectMisanthrope); + } + }, + FROZEN("Coagapis") { + @Override + protected void setBranchProperties(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.SNOW); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.EFFECT, AlleleEffect.effectGlacial); + } + }, + VENGEFUL("Punapis") { + @Override + protected void setBranchProperties(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGEST); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.EFFECT, AlleleEffect.effectRadioactive); + } + }, + FESTIVE("Festapis") { + @Override + protected void setBranchProperties(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_2); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + } + }, + AGRARIAN("Rustapis") { + @Override + protected void setBranchProperties(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.WHEAT); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTER); + } + }, + BOGGY("Paludapis") { + @Override + protected void setBranchProperties(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.MUSHROOMS); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWER); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + } + }, + MONASTIC("Monapis") { + @Override + protected void setBranchProperties(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.LOW); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTER); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.CAVE_DWELLING, true); + AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.WHEAT); + } + }; + + private final IClassification branch; + + BeeBranchDefinition(String scientific) { + branch = BeeManager.beeFactory.createBranch(this.name().toLowerCase(Locale.ENGLISH), scientific); + } + + protected void setBranchProperties(IAllele[] template) {} + + @Override + public final IAllele[] getTemplate() { + IAllele[] template = getDefaultTemplate(); + setBranchProperties(template); + return template; + } + + @Override + public final IClassification getBranch() { + return branch; + } + + private static IAllele[] defaultTemplate; + + private static IAllele[] getDefaultTemplate() { + if (defaultTemplate == null) { + defaultTemplate = new IAllele[EnumBeeChromosome.values().length]; + + AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); + AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); + AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.NORMAL); + AlleleHelper.instance.set( + defaultTemplate, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.NONE); + AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.NOCTURNAL, false); + AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.NONE); + AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.TOLERANT_FLYER, false); + AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.CAVE_DWELLING, false); + AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.VANILLA); + AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWEST); + AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.AVERAGE); + AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.EFFECT, AlleleEffect.effectNone); + } + return Arrays.copyOf(defaultTemplate, defaultTemplate.length); + } +} diff --git a/src/main/java/forestry/apiculture/genetics/BeeDefinition.java b/src/main/java/forestry/apiculture/genetics/BeeDefinition.java index b009395b6..7e05f1eca 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeDefinition.java +++ b/src/main/java/forestry/apiculture/genetics/BeeDefinition.java @@ -1,1036 +1,1059 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.genetics; - -import java.awt.Color; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.Locale; - -import org.apache.commons.lang3.text.WordUtils; - -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.common.BiomeDictionary; - -import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.EnumBeeChromosome; -import forestry.api.apiculture.EnumBeeType; -import forestry.api.apiculture.IAlleleBeeSpeciesCustom; -import forestry.api.apiculture.IBee; -import forestry.api.apiculture.IBeeGenome; -import forestry.api.apiculture.IBeeMutationCustom; -import forestry.api.core.EnumHumidity; -import forestry.api.core.EnumTemperature; -import forestry.api.genetics.IAllele; -import forestry.apiculture.genetics.alleles.AlleleEffect; -import forestry.apiculture.items.EnumHoneyComb; -import forestry.apiculture.items.EnumPollenCluster; -import forestry.core.genetics.alleles.AlleleHelper; -import forestry.core.genetics.alleles.EnumAllele; -import forestry.plugins.PluginApiculture; -import forestry.plugins.PluginCore; - -public enum BeeDefinition implements IBeeDefinition { - /* HONEY BRANCH */ - FOREST(BeeBranchDefinition.HONEY, "nigrocincta", true, new Color(0x19d0ec), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.HONEY, 1), 0.30f); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.HIGH); - } - - @Override - protected void registerMutations() { - // found in hives - } - }, - MEADOWS(BeeBranchDefinition.HONEY, "florea", true, new Color(0xef131e), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.HONEY, 1), 0.30f); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWER); - } - - @Override - protected void registerMutations() { - // found in hives - } - }, - COMMON(BeeBranchDefinition.HONEY, "cerana", true, new Color(0xb2b2b2), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.HONEY, 1), 0.35f); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - } - - @Override - protected void registerMutations() { - for (BeeDefinition hiveBee0 : overworldHiveBees) { - for (BeeDefinition hiveBee1 : overworldHiveBees) { - if (hiveBee0.ordinal() < hiveBee1.ordinal()) { - registerMutation(hiveBee0, hiveBee1, 15); - } - } - } - } - }, - CULTIVATED(BeeBranchDefinition.HONEY, "mellifera", true, new Color(0x5734ec), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.HONEY, 1), 0.40f); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.FAST); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); - } - - @Override - protected void registerMutations() { - for (BeeDefinition hiveBee : overworldHiveBees) { - registerMutation(COMMON, hiveBee, 12); - } - } - }, - - /* NOBLE BRANCH */ - NOBLE(BeeBranchDefinition.NOBLE, "nobilis", false, new Color(0xec9a19), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.DRIPPING, 1), 0.20f); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOW); - } - - @Override - protected void registerMutations() { - registerMutation(COMMON, CULTIVATED, 10); - } - }, - MAJESTIC(BeeBranchDefinition.NOBLE, "regalis", true, new Color(0x7f0000), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.DRIPPING, 1), 0.30f); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTENED); - AlleleHelper.instance.set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.MAXIMUM); - } - - @Override - protected void registerMutations() { - registerMutation(NOBLE, CULTIVATED, 8); - } - }, - IMPERIAL(BeeBranchDefinition.NOBLE, "imperatorius", false, new Color(0xa3e02f), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.DRIPPING, 1), 0.20f) - .addProduct(PluginApiculture.items.royalJelly.getItemStack(), 0.15f) - .setHasEffect(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectBeatific); - } - - @Override - protected void registerMutations() { - registerMutation(NOBLE, MAJESTIC, 8); - } - }, - - /* INDUSTRIOUS BRANCH */ - DILIGENT(BeeBranchDefinition.INDUSTRIOUS, "sedulus", false, new Color(0xc219ec), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.STRINGY, 1), 0.20f); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOW); - } - - @Override - protected void registerMutations() { - registerMutation(COMMON, CULTIVATED, 10); - } - }, - UNWEARY(BeeBranchDefinition.INDUSTRIOUS, "assiduus", true, new Color(0x19ec5a), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.STRINGY, 1), 0.30f); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTENED); - } - - @Override - protected void registerMutations() { - registerMutation(DILIGENT, CULTIVATED, 8); - } - }, - INDUSTRIOUS(BeeBranchDefinition.INDUSTRIOUS, "industria", false, new Color(0xffffff), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.STRINGY, 1), 0.20f) - .addProduct(PluginApiculture.items.pollenCluster.get(EnumPollenCluster.NORMAL, 1), 0.15f) - .setHasEffect(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FAST); - } - - @Override - protected void registerMutations() { - registerMutation(DILIGENT, UNWEARY, 8); - } - }, - - /* HEROIC BRANCH */ - STEADFAST(BeeBranchDefinition.HEROIC, "legio", false, new Color(0x4d2b15), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.COCOA, 1), 0.20f) - .setHasEffect(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.CAVE_DWELLING, true); - } - - @Override - protected void registerMutations() { - // only found in dungeons chests - } - }, - VALIANT(BeeBranchDefinition.HEROIC, "centurio", true, new Color(0x626bdd), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.COCOA, 1), 0.30f) - .addSpecialty(new ItemStack(Items.sugar), 0.15f); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); - AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.CAVE_DWELLING, true); - } - - @Override - protected void registerMutations() { - // found rarely at random in other bee's hives - } - }, - HEROIC(BeeBranchDefinition.HEROIC, "kraphti", false, new Color(0xb3d5e4), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.COCOA, 1), 0.40f) - .setHasEffect(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); - AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.CAVE_DWELLING, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectHeroic); - } - - @Override - protected void registerMutations() { - registerMutation(STEADFAST, VALIANT, 6) - .restrictBiomeType(BiomeDictionary.Type.FOREST); - } - }, - - /* INFERNAL BRANCH */ - SINISTER(BeeBranchDefinition.INFERNAL, "caecus", false, new Color(0xb3d5e4), new Color(0x9a2323)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SIMMERING, 1), 0.45f) - .setTemperature(EnumTemperature.HELLISH) - .setHumidity(EnumHumidity.ARID); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectAggressive); - } - - @Override - protected void registerMutations() { - for (BeeDefinition parent2 : EnumSet.of(MODEST, TROPICAL)) { - registerMutation(CULTIVATED, parent2, 60) - .restrictBiomeType(BiomeDictionary.Type.NETHER); - } - } - }, - FIENDISH(BeeBranchDefinition.INFERNAL, "diabolus", true, new Color(0xd7bee5), new Color(0x9a2323)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SIMMERING, 1), 0.55f) - .addProduct(PluginCore.items.ash.getItemStack(), 0.15f) - .setTemperature(EnumTemperature.HELLISH) - .setHumidity(EnumHumidity.ARID); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectAggressive); - } - - @Override - protected void registerMutations() { - for (BeeDefinition parent2 : EnumSet.of(CULTIVATED, MODEST, TROPICAL)) { - registerMutation(SINISTER, parent2, 40) - .restrictBiomeType(BiomeDictionary.Type.NETHER); - } - } - }, - DEMONIC(BeeBranchDefinition.INFERNAL, "draco", false, new Color(0xf4e400), new Color(0x9a2323)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SIMMERING, 1), 0.45f) - .addProduct(new ItemStack(Items.glowstone_dust), 0.15f) - .setHasEffect() - .setTemperature(EnumTemperature.HELLISH) - .setHumidity(EnumHumidity.ARID); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectIgnition); - } - - @Override - protected void registerMutations() { - registerMutation(SINISTER, FIENDISH, 25) - .restrictBiomeType(BiomeDictionary.Type.NETHER); - } - }, - - /* AUSTERE BRANCH */ - MODEST(BeeBranchDefinition.AUSTERE, "modicus", false, new Color(0xc5be86), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.PARCHED, 1), 0.20f) - .setTemperature(EnumTemperature.HOT) - .setHumidity(EnumHumidity.ARID); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - } - - @Override - protected void registerMutations() { - // found in hives - } - }, - FRUGAL(BeeBranchDefinition.AUSTERE, "permodestus", true, new Color(0xe8dcb1), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.PARCHED, 1), 0.30f) - .setTemperature(EnumTemperature.HOT) - .setHumidity(EnumHumidity.ARID); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); - } - - @Override - protected void registerMutations() { - registerMutation(MODEST, SINISTER, 16) - .restrictTemperature(EnumTemperature.HOT, EnumTemperature.HELLISH) - .restrictHumidity(EnumHumidity.ARID); - registerMutation(MODEST, FIENDISH, 10) - .restrictTemperature(EnumTemperature.HOT, EnumTemperature.HELLISH) - .restrictHumidity(EnumHumidity.ARID); - } - }, - AUSTERE(BeeBranchDefinition.AUSTERE, "correpere", false, new Color(0xfffac2), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.PARCHED, 1), 0.20f) - .addSpecialty(PluginApiculture.items.beeComb.get(EnumHoneyComb.POWDERY, 1), 0.50f) - .setHasEffect() - .setTemperature(EnumTemperature.HOT) - .setHumidity(EnumHumidity.ARID); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); - AlleleHelper.instance.set(template, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_2); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectCreeper); - } - - @Override - protected void registerMutations() { - registerMutation(MODEST, FRUGAL, 8) - .restrictTemperature(EnumTemperature.HOT, EnumTemperature.HELLISH) - .restrictHumidity(EnumHumidity.ARID); - } - }, - - /* TROPICAL BRANCH */ - TROPICAL(BeeBranchDefinition.TROPICAL, "mendelia", false, new Color(0x378020), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SILKY, 1), 0.20f) - .setTemperature(EnumTemperature.WARM) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - } - - @Override - protected void registerMutations() { - // found in hives - } - }, - EXOTIC(BeeBranchDefinition.TROPICAL, "darwini", true, new Color(0x304903), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SILKY, 1), 0.30f) - .setTemperature(EnumTemperature.WARM) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); - } - - @Override - protected void registerMutations() { - registerMutation(AUSTERE, TROPICAL, 12); - } - }, - EDENIC(BeeBranchDefinition.TROPICAL, "humboldti", false, new Color(0x393d0d), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SILKY, 1), 0.20f) - .setHasEffect() - .setTemperature(EnumTemperature.WARM) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); - AlleleHelper.instance.set(template, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_2); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectExploration); - } - - @Override - protected void registerMutations() { - registerMutation(EXOTIC, TROPICAL, 8); - } - }, - - /* END BRANCH */ - ENDED(BeeBranchDefinition.END, "notchi", false, new Color(0xe079fa), new Color(0xd9de9e)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.MYSTERIOUS, 1), 0.30f) - .setTemperature(EnumTemperature.COLD); - } - - @Override - protected void setAlleles(IAllele[] template) { - - } - - @Override - protected void registerMutations() { - // found in hives - } - }, - SPECTRAL(BeeBranchDefinition.END, "idolum", true, new Color(0xa98bed), new Color(0xd9de9e)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.MYSTERIOUS, 1), 0.50f) - .setTemperature(EnumTemperature.COLD); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectReanimation); - } - - @Override - protected void registerMutations() { - registerMutation(HERMITIC, ENDED, 4); - } - }, - PHANTASMAL(BeeBranchDefinition.END, "lemur", false, new Color(0xcc00fa), new Color(0xd9de9e)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.MYSTERIOUS, 1), 0.40f) - .setHasEffect() - .setTemperature(EnumTemperature.COLD); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGEST); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectResurrection); - } - - @Override - protected void registerMutations() { - registerMutation(SPECTRAL, ENDED, 2); - } - }, - - /* FROZEN BRANCH */ - WINTRY(BeeBranchDefinition.FROZEN, "brumalis", false, new Color(0xa0ffc8), new Color(0xdaf5f3)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.FROZEN, 1), 0.30f) - .setTemperature(EnumTemperature.ICY); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - AlleleHelper.instance.set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.MAXIMUM); - } - - @Override - protected void registerMutations() { - // found in hives - } - }, - ICY(BeeBranchDefinition.FROZEN, "coagulis", true, new Color(0xa0ffff), new Color(0xdaf5f3)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.FROZEN, 1), 0.20f) - .addProduct(PluginCore.items.craftingMaterial.getIceShard(1), 0.20f) - .setTemperature(EnumTemperature.ICY); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - } - - @Override - protected void registerMutations() { - registerMutation(INDUSTRIOUS, WINTRY, 12) - .restrictTemperature(EnumTemperature.ICY, EnumTemperature.COLD); - } - }, - GLACIAL(BeeBranchDefinition.FROZEN, "glacialis", false, new Color(0xefffff), new Color(0xdaf5f3)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.FROZEN, 1), 0.20f) - .addProduct(PluginCore.items.craftingMaterial.getIceShard(1), 0.40f) - .setTemperature(EnumTemperature.ICY) - .setHasEffect(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - } - - @Override - protected void registerMutations() { - registerMutation(ICY, WINTRY, 8) - .restrictTemperature(EnumTemperature.ICY, EnumTemperature.COLD); - } - }, - - /* VENGEFUL BRANCH */ - VINDICTIVE(BeeBranchDefinition.VENGEFUL, "ultio", false, new Color(0xeafff3), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.IRRADIATED, 1), 0.25f) - .setIsNotCounted(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); - } - - @Override - protected void registerMutations() { - registerMutation(MONASTIC, DEMONIC, 4).setIsSecret(); - } - }, - VENGEFUL(BeeBranchDefinition.VENGEFUL, "punire", false, new Color(0xc2de00), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.IRRADIATED, 1), 0.40f) - .setIsNotCounted(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); - } - - @Override - protected void registerMutations() { - registerMutation(DEMONIC, VINDICTIVE, 8).setIsSecret(); - registerMutation(MONASTIC, VINDICTIVE, 8).setIsSecret(); - } - }, - AVENGING(BeeBranchDefinition.VENGEFUL, "hostimentum", false, new Color(0xddff00), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.IRRADIATED, 1), 0.40f) - .setHasEffect() - .setIsNotCounted(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGEST); - } - - @Override - protected void registerMutations() { - registerMutation(VENGEFUL, VINDICTIVE, 4); - } - }, - - /* FESTIVE BRANCH */ - // Easter - LEPORINE(BeeBranchDefinition.FESTIVE, "lepus", false, new Color(0xfeff8f), new Color(0x3cd757)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SILKY, 1), 0.30f) - .addProduct(new ItemStack(Items.egg), 0.10f) - .setHasEffect() - .setIsNotCounted(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectFestiveEaster); - } - - @Override - protected void registerMutations() { - registerMutation(MEADOWS, FOREST, 10) - .restrictDateRange(3, 29, 4, 15) - .setIsSecret(); - } - }, - // Christmas - MERRY(BeeBranchDefinition.FESTIVE, "feliciter", false, new Color(0xffffff), new Color(0xd40000)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.FROZEN, 1), 0.30f) - .addProduct(PluginCore.items.craftingMaterial.getIceShard(1), 0.20f) - .setTemperature(EnumTemperature.ICY) - .setHasEffect() - .setIsNotCounted(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectSnowing); - } - - @Override - protected void registerMutations() { - registerMutation(WINTRY, FOREST, 10) - .restrictDateRange(12, 21, 12, 27) - .setIsSecret(); - } - }, - // New Year - TIPSY(BeeBranchDefinition.FESTIVE, "ebrius", false, new Color(0xffffff), new Color(0xc219ec)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.FROZEN, 1), 0.30f) - .addProduct(PluginCore.items.craftingMaterial.getIceShard(1), 0.20f) - .setTemperature(EnumTemperature.ICY) - .setHasEffect() - .setIsNotCounted(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectDrunkard); - } - - @Override - protected void registerMutations() { - registerMutation(WINTRY, MEADOWS, 10) - .restrictDateRange(12, 27, 1, 2) - .setIsSecret(); - } - }, - // (missing) Solstice - // Halloween - TRICKY(BeeBranchDefinition.FESTIVE, "libita", false, new Color(0x49413B), new Color(0xFF6A00)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.HONEY, 1), 0.40f) - .addProduct(new ItemStack(Items.cookie), 0.15f) - .addSpecialty(new ItemStack(Items.skull, 1, 0), 0.02f) - .addSpecialty(new ItemStack(Items.skull, 1, 2), 0.02f) - .addSpecialty(new ItemStack(Items.skull, 1, 3), 0.02f) - .addSpecialty(new ItemStack(Items.skull, 1, 4), 0.02f) - .setHasEffect() - .setIsNotCounted(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.TOLERANT_FLYER, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.GOURD); - } - - @Override - protected void registerMutations() { - registerMutation(SINISTER, COMMON, 10) - .restrictDateRange(10, 15, 11, 3) - .setIsSecret(); - } - }, - // (missing) Thanksgiving - - /* AGRARIAN BRANCH */ - RURAL(BeeBranchDefinition.AGRARIAN, "rustico", false, new Color(0xfeff8f), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.WHEATEN, 1), 0.20f); - } - - @Override - protected void setAlleles(IAllele[] template) { - - } - - @Override - protected void registerMutations() { - registerMutation(MEADOWS, DILIGENT, 12) - .restrictBiomeType(BiomeDictionary.Type.PLAINS); - } - }, - FARMERLY(BeeBranchDefinition.AGRARIAN, "arator", true, new Color(0xD39728), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.WHEATEN, 1), 0.27f); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); - AlleleHelper.instance.set(template, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGE); - } - - @Override - protected void registerMutations() { - registerMutation(RURAL, UNWEARY, 10) - .restrictBiomeType(BiomeDictionary.Type.PLAINS); - } - }, - AGRARIAN(BeeBranchDefinition.AGRARIAN, "arator", true, new Color(0xFFCA75), new Color(0xFFE047)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.WHEATEN, 1), 0.35f) - .setHasEffect(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); - AlleleHelper.instance.set(template, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_2); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectFertile); - AlleleHelper.instance.set(template, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGE); - } - - @Override - protected void registerMutations() { - registerMutation(FARMERLY, INDUSTRIOUS, 6) - .restrictBiomeType(BiomeDictionary.Type.PLAINS); - } - }, - - /* BOGGY BRANCH */ - MARSHY(BeeBranchDefinition.BOGGY, "adorasti", true, new Color(0x546626), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.MOSSY, 1), 0.30f) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] template) { - - } - - @Override - protected void registerMutations() { - // found in hives - } - }, - MIRY(BeeBranchDefinition.BOGGY, "humidium", true, new Color(0x92AF42), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.MOSSY, 1), 0.36f) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.MAXIMUM); - AlleleHelper.instance.set(template, EnumBeeChromosome.TOLERANT_FLYER, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); - } - - @Override - protected void registerMutations() { - registerMutation(MARSHY, NOBLE, 15) - .restrictTemperature(EnumTemperature.WARM) - .restrictHumidity(EnumHumidity.DAMP); - } - }, - BOGGY(BeeBranchDefinition.BOGGY, "paluster", true, new Color(0x698948), new Color(0xffdc16)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.MOSSY, 1), 0.39f) - .addSpecialty(PluginCore.items.peat.getItemStack(), 0.08f) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.TOLERANT_FLYER, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectMycophilic); - AlleleHelper.instance.set(template, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGER); - } - - @Override - protected void registerMutations() { - registerMutation(MARSHY, MIRY, 9) - .restrictTemperature(EnumTemperature.WARM) - .restrictHumidity(EnumHumidity.DAMP); - } - }, - - /* MONASTIC BRANCH */ - MONASTIC(BeeBranchDefinition.MONASTIC, "monachus", false, new Color(0x42371c), new Color(0xfff7b6)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.WHEATEN, 1), 0.30f) - .addSpecialty(PluginApiculture.items.beeComb.get(EnumHoneyComb.MELLOW, 1), 0.10f) - .setJubilanceProvider(new JubilanceProviderHermit()); - } - - @Override - protected void setAlleles(IAllele[] template) { - - } - - @Override - protected void registerMutations() { - // can only be bought from Apiarist Villagers - } - }, - SECLUDED(BeeBranchDefinition.MONASTIC, "contractus", true, new Color(0x7b6634), new Color(0xfff7b6)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addSpecialty(PluginApiculture.items.beeComb.get(EnumHoneyComb.MELLOW, 1), 0.20f) - .setJubilanceProvider(new JubilanceProviderHermit()); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTEST); - } - - @Override - protected void registerMutations() { - registerMutation(MONASTIC, AUSTERE, 12); - } - }, - HERMITIC(BeeBranchDefinition.MONASTIC, "anachoreta", false, new Color(0xffd46c), new Color(0xfff7b6)) { - @Override - protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { - beeSpecies.addSpecialty(PluginApiculture.items.beeComb.get(EnumHoneyComb.MELLOW, 1), 0.20f) - .setJubilanceProvider(new JubilanceProviderHermit()) - .setHasEffect(); - } - - @Override - protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTEST); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectRepulsion); - } - - @Override - protected void registerMutations() { - registerMutation(MONASTIC, SECLUDED, 8); - } - }; - - private static final EnumSet overworldHiveBees = EnumSet.of(FOREST, MARSHY, MEADOWS, MODEST, TROPICAL, WINTRY); - - private final BeeBranchDefinition branch; - private final IAlleleBeeSpeciesCustom species; - - private IAllele[] template; - private IBeeGenome genome; - - BeeDefinition(BeeBranchDefinition branch, String binomial, boolean dominant, Color primary, Color secondary) { - String lowercaseName = this.toString().toLowerCase(Locale.ENGLISH); - String species = "species" + WordUtils.capitalize(lowercaseName); - - String uid = "forestry." + species; - String description = "for.description." + species; - String name = "for.bees.species." + lowercaseName; - - this.branch = branch; - this.species = BeeManager.beeFactory.createSpecies(uid, dominant, "Sengir", name, description, branch.getBranch(), binomial, primary.getRGB(), secondary.getRGB()); - } - - protected abstract void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies); - - protected abstract void setAlleles(IAllele[] template); - - protected abstract void registerMutations(); - - public static void initBees() { - for (BeeDefinition bee : values()) { - bee.init(); - } - for (BeeDefinition bee : values()) { - bee.registerMutations(); - } - } - - private void init() { - if (!overworldHiveBees.contains(this)) { - species.setIsSecret(); - } - setSpeciesProperties(species); - - template = branch.getTemplate(); - AlleleHelper.instance.set(template, EnumBeeChromosome.SPECIES, species); - setAlleles(template); - - genome = BeeManager.beeRoot.templateAsGenome(template); - - BeeManager.beeRoot.registerTemplate(template); - } - - protected final IBeeMutationCustom registerMutation(BeeDefinition parent1, BeeDefinition parent2, int chance) { - return BeeManager.beeMutationFactory.createMutation(parent1.species, parent2.species, getTemplate(), chance); - } - - @Override - public final IAllele[] getTemplate() { - return Arrays.copyOf(template, template.length); - } - - @Override - public final IBeeGenome getGenome() { - return genome; - } - - @Override - public final IBee getIndividual() { - return new Bee(genome); - } - - @Override - public final ItemStack getMemberStack(EnumBeeType beeType) { - IBee bee = getIndividual(); - return BeeManager.beeRoot.getMemberStack(bee, beeType.ordinal()); - } - - public final IBeeDefinition getRainResist() { - return new BeeVariation.RainResist(this); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.genetics; + +import forestry.api.apiculture.BeeManager; +import forestry.api.apiculture.EnumBeeChromosome; +import forestry.api.apiculture.EnumBeeType; +import forestry.api.apiculture.IAlleleBeeSpeciesCustom; +import forestry.api.apiculture.IBee; +import forestry.api.apiculture.IBeeGenome; +import forestry.api.apiculture.IBeeMutationCustom; +import forestry.api.core.EnumHumidity; +import forestry.api.core.EnumTemperature; +import forestry.api.genetics.IAllele; +import forestry.apiculture.genetics.alleles.AlleleEffect; +import forestry.apiculture.items.EnumHoneyComb; +import forestry.apiculture.items.EnumPollenCluster; +import forestry.core.genetics.alleles.AlleleHelper; +import forestry.core.genetics.alleles.EnumAllele; +import forestry.plugins.PluginApiculture; +import forestry.plugins.PluginCore; +import java.awt.Color; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.Locale; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.BiomeDictionary; +import org.apache.commons.lang3.text.WordUtils; + +public enum BeeDefinition implements IBeeDefinition { + /* HONEY BRANCH */ + FOREST(BeeBranchDefinition.HONEY, "nigrocincta", true, new Color(0x19d0ec), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.HONEY, 1), 0.30f); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWER); + AlleleHelper.instance.set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.HIGH); + } + + @Override + protected void registerMutations() { + // found in hives + } + }, + MEADOWS(BeeBranchDefinition.HONEY, "florea", true, new Color(0xef131e), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.HONEY, 1), 0.30f); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWER); + } + + @Override + protected void registerMutations() { + // found in hives + } + }, + COMMON(BeeBranchDefinition.HONEY, "cerana", true, new Color(0xb2b2b2), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.HONEY, 1), 0.35f); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + } + + @Override + protected void registerMutations() { + for (BeeDefinition hiveBee0 : overworldHiveBees) { + for (BeeDefinition hiveBee1 : overworldHiveBees) { + if (hiveBee0.ordinal() < hiveBee1.ordinal()) { + registerMutation(hiveBee0, hiveBee1, 15); + } + } + } + } + }, + CULTIVATED(BeeBranchDefinition.HONEY, "mellifera", true, new Color(0x5734ec), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.HONEY, 1), 0.40f); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.FAST); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); + } + + @Override + protected void registerMutations() { + for (BeeDefinition hiveBee : overworldHiveBees) { + registerMutation(COMMON, hiveBee, 12); + } + } + }, + + /* NOBLE BRANCH */ + NOBLE(BeeBranchDefinition.NOBLE, "nobilis", false, new Color(0xec9a19), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.DRIPPING, 1), 0.20f); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOW); + } + + @Override + protected void registerMutations() { + registerMutation(COMMON, CULTIVATED, 10); + } + }, + MAJESTIC(BeeBranchDefinition.NOBLE, "regalis", true, new Color(0x7f0000), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.DRIPPING, 1), 0.30f); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTENED); + AlleleHelper.instance.set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.MAXIMUM); + } + + @Override + protected void registerMutations() { + registerMutation(NOBLE, CULTIVATED, 8); + } + }, + IMPERIAL(BeeBranchDefinition.NOBLE, "imperatorius", false, new Color(0xa3e02f), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.DRIPPING, 1), 0.20f) + .addProduct(PluginApiculture.items.royalJelly.getItemStack(), 0.15f) + .setHasEffect(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectBeatific); + } + + @Override + protected void registerMutations() { + registerMutation(NOBLE, MAJESTIC, 8); + } + }, + + /* INDUSTRIOUS BRANCH */ + DILIGENT(BeeBranchDefinition.INDUSTRIOUS, "sedulus", false, new Color(0xc219ec), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.STRINGY, 1), 0.20f); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOW); + } + + @Override + protected void registerMutations() { + registerMutation(COMMON, CULTIVATED, 10); + } + }, + UNWEARY(BeeBranchDefinition.INDUSTRIOUS, "assiduus", true, new Color(0x19ec5a), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.STRINGY, 1), 0.30f); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTENED); + } + + @Override + protected void registerMutations() { + registerMutation(DILIGENT, CULTIVATED, 8); + } + }, + INDUSTRIOUS(BeeBranchDefinition.INDUSTRIOUS, "industria", false, new Color(0xffffff), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.STRINGY, 1), 0.20f) + .addProduct(PluginApiculture.items.pollenCluster.get(EnumPollenCluster.NORMAL, 1), 0.15f) + .setHasEffect(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FAST); + } + + @Override + protected void registerMutations() { + registerMutation(DILIGENT, UNWEARY, 8); + } + }, + + /* HEROIC BRANCH */ + STEADFAST(BeeBranchDefinition.HEROIC, "legio", false, new Color(0x4d2b15), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.COCOA, 1), 0.20f) + .setHasEffect(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); + AlleleHelper.instance.set(template, EnumBeeChromosome.CAVE_DWELLING, true); + } + + @Override + protected void registerMutations() { + // only found in dungeons chests + } + }, + VALIANT(BeeBranchDefinition.HEROIC, "centurio", true, new Color(0x626bdd), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.COCOA, 1), 0.30f) + .addSpecialty(new ItemStack(Items.sugar), 0.15f); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); + AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); + AlleleHelper.instance.set(template, EnumBeeChromosome.CAVE_DWELLING, true); + } + + @Override + protected void registerMutations() { + // found rarely at random in other bee's hives + } + }, + HEROIC(BeeBranchDefinition.HEROIC, "kraphti", false, new Color(0xb3d5e4), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.COCOA, 1), 0.40f) + .setHasEffect(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); + AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); + AlleleHelper.instance.set(template, EnumBeeChromosome.CAVE_DWELLING, true); + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectHeroic); + } + + @Override + protected void registerMutations() { + registerMutation(STEADFAST, VALIANT, 6).restrictBiomeType(BiomeDictionary.Type.FOREST); + } + }, + + /* INFERNAL BRANCH */ + SINISTER(BeeBranchDefinition.INFERNAL, "caecus", false, new Color(0xb3d5e4), new Color(0x9a2323)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SIMMERING, 1), 0.45f) + .setTemperature(EnumTemperature.HELLISH) + .setHumidity(EnumHumidity.ARID); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectAggressive); + } + + @Override + protected void registerMutations() { + for (BeeDefinition parent2 : EnumSet.of(MODEST, TROPICAL)) { + registerMutation(CULTIVATED, parent2, 60).restrictBiomeType(BiomeDictionary.Type.NETHER); + } + } + }, + FIENDISH(BeeBranchDefinition.INFERNAL, "diabolus", true, new Color(0xd7bee5), new Color(0x9a2323)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SIMMERING, 1), 0.55f) + .addProduct(PluginCore.items.ash.getItemStack(), 0.15f) + .setTemperature(EnumTemperature.HELLISH) + .setHumidity(EnumHumidity.ARID); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectAggressive); + } + + @Override + protected void registerMutations() { + for (BeeDefinition parent2 : EnumSet.of(CULTIVATED, MODEST, TROPICAL)) { + registerMutation(SINISTER, parent2, 40).restrictBiomeType(BiomeDictionary.Type.NETHER); + } + } + }, + DEMONIC(BeeBranchDefinition.INFERNAL, "draco", false, new Color(0xf4e400), new Color(0x9a2323)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SIMMERING, 1), 0.45f) + .addProduct(new ItemStack(Items.glowstone_dust), 0.15f) + .setHasEffect() + .setTemperature(EnumTemperature.HELLISH) + .setHumidity(EnumHumidity.ARID); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectIgnition); + } + + @Override + protected void registerMutations() { + registerMutation(SINISTER, FIENDISH, 25).restrictBiomeType(BiomeDictionary.Type.NETHER); + } + }, + + /* AUSTERE BRANCH */ + MODEST(BeeBranchDefinition.AUSTERE, "modicus", false, new Color(0xc5be86), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.PARCHED, 1), 0.20f) + .setTemperature(EnumTemperature.HOT) + .setHumidity(EnumHumidity.ARID); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + } + + @Override + protected void registerMutations() { + // found in hives + } + }, + FRUGAL(BeeBranchDefinition.AUSTERE, "permodestus", true, new Color(0xe8dcb1), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.PARCHED, 1), 0.30f) + .setTemperature(EnumTemperature.HOT) + .setHumidity(EnumHumidity.ARID); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); + } + + @Override + protected void registerMutations() { + registerMutation(MODEST, SINISTER, 16) + .restrictTemperature(EnumTemperature.HOT, EnumTemperature.HELLISH) + .restrictHumidity(EnumHumidity.ARID); + registerMutation(MODEST, FIENDISH, 10) + .restrictTemperature(EnumTemperature.HOT, EnumTemperature.HELLISH) + .restrictHumidity(EnumHumidity.ARID); + } + }, + AUSTERE(BeeBranchDefinition.AUSTERE, "correpere", false, new Color(0xfffac2), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.PARCHED, 1), 0.20f) + .addSpecialty(PluginApiculture.items.beeComb.get(EnumHoneyComb.POWDERY, 1), 0.50f) + .setHasEffect() + .setTemperature(EnumTemperature.HOT) + .setHumidity(EnumHumidity.ARID); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); + AlleleHelper.instance.set(template, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_2); + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectCreeper); + } + + @Override + protected void registerMutations() { + registerMutation(MODEST, FRUGAL, 8) + .restrictTemperature(EnumTemperature.HOT, EnumTemperature.HELLISH) + .restrictHumidity(EnumHumidity.ARID); + } + }, + + /* TROPICAL BRANCH */ + TROPICAL(BeeBranchDefinition.TROPICAL, "mendelia", false, new Color(0x378020), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SILKY, 1), 0.20f) + .setTemperature(EnumTemperature.WARM) + .setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + } + + @Override + protected void registerMutations() { + // found in hives + } + }, + EXOTIC(BeeBranchDefinition.TROPICAL, "darwini", true, new Color(0x304903), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SILKY, 1), 0.30f) + .setTemperature(EnumTemperature.WARM) + .setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); + } + + @Override + protected void registerMutations() { + registerMutation(AUSTERE, TROPICAL, 12); + } + }, + EDENIC(BeeBranchDefinition.TROPICAL, "humboldti", false, new Color(0x393d0d), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SILKY, 1), 0.20f) + .setHasEffect() + .setTemperature(EnumTemperature.WARM) + .setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); + AlleleHelper.instance.set(template, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_2); + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectExploration); + } + + @Override + protected void registerMutations() { + registerMutation(EXOTIC, TROPICAL, 8); + } + }, + + /* END BRANCH */ + ENDED(BeeBranchDefinition.END, "notchi", false, new Color(0xe079fa), new Color(0xd9de9e)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.MYSTERIOUS, 1), 0.30f) + .setTemperature(EnumTemperature.COLD); + } + + @Override + protected void setAlleles(IAllele[] template) {} + + @Override + protected void registerMutations() { + // found in hives + } + }, + SPECTRAL(BeeBranchDefinition.END, "idolum", true, new Color(0xa98bed), new Color(0xd9de9e)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.MYSTERIOUS, 1), 0.50f) + .setTemperature(EnumTemperature.COLD); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectReanimation); + } + + @Override + protected void registerMutations() { + registerMutation(HERMITIC, ENDED, 4); + } + }, + PHANTASMAL(BeeBranchDefinition.END, "lemur", false, new Color(0xcc00fa), new Color(0xd9de9e)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.MYSTERIOUS, 1), 0.40f) + .setHasEffect() + .setTemperature(EnumTemperature.COLD); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGEST); + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectResurrection); + } + + @Override + protected void registerMutations() { + registerMutation(SPECTRAL, ENDED, 2); + } + }, + + /* FROZEN BRANCH */ + WINTRY(BeeBranchDefinition.FROZEN, "brumalis", false, new Color(0xa0ffc8), new Color(0xdaf5f3)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.FROZEN, 1), 0.30f) + .setTemperature(EnumTemperature.ICY); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.instance.set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.MAXIMUM); + } + + @Override + protected void registerMutations() { + // found in hives + } + }, + ICY(BeeBranchDefinition.FROZEN, "coagulis", true, new Color(0xa0ffff), new Color(0xdaf5f3)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.FROZEN, 1), 0.20f) + .addProduct(PluginCore.items.craftingMaterial.getIceShard(1), 0.20f) + .setTemperature(EnumTemperature.ICY); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + } + + @Override + protected void registerMutations() { + registerMutation(INDUSTRIOUS, WINTRY, 12).restrictTemperature(EnumTemperature.ICY, EnumTemperature.COLD); + } + }, + GLACIAL(BeeBranchDefinition.FROZEN, "glacialis", false, new Color(0xefffff), new Color(0xdaf5f3)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.FROZEN, 1), 0.20f) + .addProduct(PluginCore.items.craftingMaterial.getIceShard(1), 0.40f) + .setTemperature(EnumTemperature.ICY) + .setHasEffect(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + } + + @Override + protected void registerMutations() { + registerMutation(ICY, WINTRY, 8).restrictTemperature(EnumTemperature.ICY, EnumTemperature.COLD); + } + }, + + /* VENGEFUL BRANCH */ + VINDICTIVE(BeeBranchDefinition.VENGEFUL, "ultio", false, new Color(0xeafff3), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.IRRADIATED, 1), 0.25f) + .setIsNotCounted(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + } + + @Override + protected void registerMutations() { + registerMutation(MONASTIC, DEMONIC, 4).setIsSecret(); + } + }, + VENGEFUL(BeeBranchDefinition.VENGEFUL, "punire", false, new Color(0xc2de00), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.IRRADIATED, 1), 0.40f) + .setIsNotCounted(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); + } + + @Override + protected void registerMutations() { + registerMutation(DEMONIC, VINDICTIVE, 8).setIsSecret(); + registerMutation(MONASTIC, VINDICTIVE, 8).setIsSecret(); + } + }, + AVENGING(BeeBranchDefinition.VENGEFUL, "hostimentum", false, new Color(0xddff00), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.IRRADIATED, 1), 0.40f) + .setHasEffect() + .setIsNotCounted(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); + AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGEST); + } + + @Override + protected void registerMutations() { + registerMutation(VENGEFUL, VINDICTIVE, 4); + } + }, + + /* FESTIVE BRANCH */ + // Easter + LEPORINE(BeeBranchDefinition.FESTIVE, "lepus", false, new Color(0xfeff8f), new Color(0x3cd757)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.SILKY, 1), 0.30f) + .addProduct(new ItemStack(Items.egg), 0.10f) + .setHasEffect() + .setIsNotCounted(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectFestiveEaster); + } + + @Override + protected void registerMutations() { + registerMutation(MEADOWS, FOREST, 10) + .restrictDateRange(3, 29, 4, 15) + .setIsSecret(); + } + }, + // Christmas + MERRY(BeeBranchDefinition.FESTIVE, "feliciter", false, new Color(0xffffff), new Color(0xd40000)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.FROZEN, 1), 0.30f) + .addProduct(PluginCore.items.craftingMaterial.getIceShard(1), 0.20f) + .setTemperature(EnumTemperature.ICY) + .setHasEffect() + .setIsNotCounted(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectSnowing); + } + + @Override + protected void registerMutations() { + registerMutation(WINTRY, FOREST, 10) + .restrictDateRange(12, 21, 12, 27) + .setIsSecret(); + } + }, + // New Year + TIPSY(BeeBranchDefinition.FESTIVE, "ebrius", false, new Color(0xffffff), new Color(0xc219ec)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.FROZEN, 1), 0.30f) + .addProduct(PluginCore.items.craftingMaterial.getIceShard(1), 0.20f) + .setTemperature(EnumTemperature.ICY) + .setHasEffect() + .setIsNotCounted(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectDrunkard); + } + + @Override + protected void registerMutations() { + registerMutation(WINTRY, MEADOWS, 10) + .restrictDateRange(12, 27, 1, 2) + .setIsSecret(); + } + }, + // (missing) Solstice + // Halloween + TRICKY(BeeBranchDefinition.FESTIVE, "libita", false, new Color(0x49413B), new Color(0xFF6A00)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.HONEY, 1), 0.40f) + .addProduct(new ItemStack(Items.cookie), 0.15f) + .addSpecialty(new ItemStack(Items.skull, 1, 0), 0.02f) + .addSpecialty(new ItemStack(Items.skull, 1, 2), 0.02f) + .addSpecialty(new ItemStack(Items.skull, 1, 3), 0.02f) + .addSpecialty(new ItemStack(Items.skull, 1, 4), 0.02f) + .setHasEffect() + .setIsNotCounted(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); + AlleleHelper.instance.set(template, EnumBeeChromosome.TOLERANT_FLYER, true); + AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.GOURD); + } + + @Override + protected void registerMutations() { + registerMutation(SINISTER, COMMON, 10) + .restrictDateRange(10, 15, 11, 3) + .setIsSecret(); + } + }, + // (missing) Thanksgiving + + /* AGRARIAN BRANCH */ + RURAL(BeeBranchDefinition.AGRARIAN, "rustico", false, new Color(0xfeff8f), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.WHEATEN, 1), 0.20f); + } + + @Override + protected void setAlleles(IAllele[] template) {} + + @Override + protected void registerMutations() { + registerMutation(MEADOWS, DILIGENT, 12).restrictBiomeType(BiomeDictionary.Type.PLAINS); + } + }, + FARMERLY(BeeBranchDefinition.AGRARIAN, "arator", true, new Color(0xD39728), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies.addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.WHEATEN, 1), 0.27f); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); + AlleleHelper.instance.set(template, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGE); + } + + @Override + protected void registerMutations() { + registerMutation(RURAL, UNWEARY, 10).restrictBiomeType(BiomeDictionary.Type.PLAINS); + } + }, + AGRARIAN(BeeBranchDefinition.AGRARIAN, "arator", true, new Color(0xFFCA75), new Color(0xFFE047)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.WHEATEN, 1), 0.35f) + .setHasEffect(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); + AlleleHelper.instance.set(template, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_2); + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectFertile); + AlleleHelper.instance.set(template, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGE); + } + + @Override + protected void registerMutations() { + registerMutation(FARMERLY, INDUSTRIOUS, 6).restrictBiomeType(BiomeDictionary.Type.PLAINS); + } + }, + + /* BOGGY BRANCH */ + MARSHY(BeeBranchDefinition.BOGGY, "adorasti", true, new Color(0x546626), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.MOSSY, 1), 0.30f) + .setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] template) {} + + @Override + protected void registerMutations() { + // found in hives + } + }, + MIRY(BeeBranchDefinition.BOGGY, "humidium", true, new Color(0x92AF42), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.MOSSY, 1), 0.36f) + .setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.MAXIMUM); + AlleleHelper.instance.set(template, EnumBeeChromosome.TOLERANT_FLYER, true); + AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); + } + + @Override + protected void registerMutations() { + registerMutation(MARSHY, NOBLE, 15) + .restrictTemperature(EnumTemperature.WARM) + .restrictHumidity(EnumHumidity.DAMP); + } + }, + BOGGY(BeeBranchDefinition.BOGGY, "paluster", true, new Color(0x698948), new Color(0xffdc16)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.MOSSY, 1), 0.39f) + .addSpecialty(PluginCore.items.peat.getItemStack(), 0.08f) + .setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.TOLERANT_FLYER, true); + AlleleHelper.instance.set(template, EnumBeeChromosome.NOCTURNAL, true); + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectMycophilic); + AlleleHelper.instance.set(template, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGER); + } + + @Override + protected void registerMutations() { + registerMutation(MARSHY, MIRY, 9) + .restrictTemperature(EnumTemperature.WARM) + .restrictHumidity(EnumHumidity.DAMP); + } + }, + + /* MONASTIC BRANCH */ + MONASTIC(BeeBranchDefinition.MONASTIC, "monachus", false, new Color(0x42371c), new Color(0xfff7b6)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addProduct(PluginApiculture.items.beeComb.get(EnumHoneyComb.WHEATEN, 1), 0.30f) + .addSpecialty(PluginApiculture.items.beeComb.get(EnumHoneyComb.MELLOW, 1), 0.10f) + .setJubilanceProvider(new JubilanceProviderHermit()); + } + + @Override + protected void setAlleles(IAllele[] template) {} + + @Override + protected void registerMutations() { + // can only be bought from Apiarist Villagers + } + }, + SECLUDED(BeeBranchDefinition.MONASTIC, "contractus", true, new Color(0x7b6634), new Color(0xfff7b6)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addSpecialty(PluginApiculture.items.beeComb.get(EnumHoneyComb.MELLOW, 1), 0.20f) + .setJubilanceProvider(new JubilanceProviderHermit()); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTEST); + } + + @Override + protected void registerMutations() { + registerMutation(MONASTIC, AUSTERE, 12); + } + }, + HERMITIC(BeeBranchDefinition.MONASTIC, "anachoreta", false, new Color(0xffd46c), new Color(0xfff7b6)) { + @Override + protected void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies) { + beeSpecies + .addSpecialty(PluginApiculture.items.beeComb.get(EnumHoneyComb.MELLOW, 1), 0.20f) + .setJubilanceProvider(new JubilanceProviderHermit()) + .setHasEffect(); + } + + @Override + protected void setAlleles(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTEST); + AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectRepulsion); + } + + @Override + protected void registerMutations() { + registerMutation(MONASTIC, SECLUDED, 8); + } + }; + + private static final EnumSet overworldHiveBees = + EnumSet.of(FOREST, MARSHY, MEADOWS, MODEST, TROPICAL, WINTRY); + + private final BeeBranchDefinition branch; + private final IAlleleBeeSpeciesCustom species; + + private IAllele[] template; + private IBeeGenome genome; + + BeeDefinition(BeeBranchDefinition branch, String binomial, boolean dominant, Color primary, Color secondary) { + String lowercaseName = this.toString().toLowerCase(Locale.ENGLISH); + String species = "species" + WordUtils.capitalize(lowercaseName); + + String uid = "forestry." + species; + String description = "for.description." + species; + String name = "for.bees.species." + lowercaseName; + + this.branch = branch; + this.species = BeeManager.beeFactory.createSpecies( + uid, + dominant, + "Sengir", + name, + description, + branch.getBranch(), + binomial, + primary.getRGB(), + secondary.getRGB()); + } + + protected abstract void setSpeciesProperties(IAlleleBeeSpeciesCustom beeSpecies); + + protected abstract void setAlleles(IAllele[] template); + + protected abstract void registerMutations(); + + public static void initBees() { + for (BeeDefinition bee : values()) { + bee.init(); + } + for (BeeDefinition bee : values()) { + bee.registerMutations(); + } + } + + private void init() { + if (!overworldHiveBees.contains(this)) { + species.setIsSecret(); + } + setSpeciesProperties(species); + + template = branch.getTemplate(); + AlleleHelper.instance.set(template, EnumBeeChromosome.SPECIES, species); + setAlleles(template); + + genome = BeeManager.beeRoot.templateAsGenome(template); + + BeeManager.beeRoot.registerTemplate(template); + } + + protected final IBeeMutationCustom registerMutation(BeeDefinition parent1, BeeDefinition parent2, int chance) { + return BeeManager.beeMutationFactory.createMutation(parent1.species, parent2.species, getTemplate(), chance); + } + + @Override + public final IAllele[] getTemplate() { + return Arrays.copyOf(template, template.length); + } + + @Override + public final IBeeGenome getGenome() { + return genome; + } + + @Override + public final IBee getIndividual() { + return new Bee(genome); + } + + @Override + public final ItemStack getMemberStack(EnumBeeType beeType) { + IBee bee = getIndividual(); + return BeeManager.beeRoot.getMemberStack(bee, beeType.ordinal()); + } + + public final IBeeDefinition getRainResist() { + return new BeeVariation.RainResist(this); + } +} diff --git a/src/main/java/forestry/apiculture/genetics/BeeFactory.java b/src/main/java/forestry/apiculture/genetics/BeeFactory.java index 094813ff5..01d1ef2ad 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeFactory.java +++ b/src/main/java/forestry/apiculture/genetics/BeeFactory.java @@ -1,32 +1,50 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.genetics; - -import forestry.api.apiculture.EnumBeeChromosome; -import forestry.api.apiculture.IAlleleBeeSpeciesCustom; -import forestry.api.apiculture.IBeeFactory; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IClassification; -import forestry.apiculture.genetics.alleles.AlleleBeeSpecies; - -public class BeeFactory implements IBeeFactory { - @Override - public IAlleleBeeSpeciesCustom createSpecies(String uid, boolean dominant, String authority, String unlocalizedName, String unlocalizedDescription, IClassification branch, String binomial, int primaryColor, int secondaryColor) { - IAlleleBeeSpeciesCustom species = new AlleleBeeSpecies(uid, unlocalizedName, authority, unlocalizedDescription, dominant, branch, binomial, primaryColor, secondaryColor); - AlleleManager.alleleRegistry.registerAllele(species, EnumBeeChromosome.SPECIES); - return species; - } - - @Override - public IClassification createBranch(String uid, String scientific) { - return new BranchBees(uid, scientific); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.genetics; + +import forestry.api.apiculture.EnumBeeChromosome; +import forestry.api.apiculture.IAlleleBeeSpeciesCustom; +import forestry.api.apiculture.IBeeFactory; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IClassification; +import forestry.apiculture.genetics.alleles.AlleleBeeSpecies; + +public class BeeFactory implements IBeeFactory { + @Override + public IAlleleBeeSpeciesCustom createSpecies( + String uid, + boolean dominant, + String authority, + String unlocalizedName, + String unlocalizedDescription, + IClassification branch, + String binomial, + int primaryColor, + int secondaryColor) { + IAlleleBeeSpeciesCustom species = new AlleleBeeSpecies( + uid, + unlocalizedName, + authority, + unlocalizedDescription, + dominant, + branch, + binomial, + primaryColor, + secondaryColor); + AlleleManager.alleleRegistry.registerAllele(species, EnumBeeChromosome.SPECIES); + return species; + } + + @Override + public IClassification createBranch(String uid, String scientific) { + return new BranchBees(uid, scientific); + } +} diff --git a/src/main/java/forestry/apiculture/genetics/BeeGenome.java b/src/main/java/forestry/apiculture/genetics/BeeGenome.java index feb6c0dc2..d50bd7499 100755 --- a/src/main/java/forestry/apiculture/genetics/BeeGenome.java +++ b/src/main/java/forestry/apiculture/genetics/BeeGenome.java @@ -13,13 +13,6 @@ package forestry.apiculture.genetics; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; - -import javax.annotation.Nonnull; -import java.util.concurrent.TimeUnit; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.IAlleleBeeEffect; @@ -38,140 +31,143 @@ import forestry.core.genetics.alleles.AlleleArea; import forestry.core.genetics.alleles.AlleleBoolean; import forestry.core.genetics.alleles.AlleleTolerance; import forestry.core.utils.vect.Vect; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nonnull; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; public class BeeGenome extends Genome implements IBeeGenome { - /** - * 0 - Species (determines product) - * 1 - Speed - * 2 - Lifespan - * 3 - Fertility (Maximum number of offspring) - * 4 - Preferred temperature Icy: Snow biomes Cold: Tundra/Steppe, Extreme Mountains/Hills? Normal: Plains, Forests, Mountains Hot: Desert Hellish: Nether - * 5 - Temperature tolerance (Range +/-) - * 6 - Nocturnal - * 7 - Preferred humidity (Arid - Normal - Damp) - * 8 - Humidity tolerance (Range +/-) - * 9 - Flight interference tolerance (stuff falling from the sky/other hindrances -> tolerates dampness + flight interference tolerance => rain resistance) - * 10 - Cave dwelling - * 11 - Required flowers - * 12 - Flower plant chance - * 13 - Territory - */ + /** + * 0 - Species (determines product) + * 1 - Speed + * 2 - Lifespan + * 3 - Fertility (Maximum number of offspring) + * 4 - Preferred temperature Icy: Snow biomes Cold: Tundra/Steppe, Extreme Mountains/Hills? Normal: Plains, Forests, Mountains Hot: Desert Hellish: Nether + * 5 - Temperature tolerance (Range +/-) + * 6 - Nocturnal + * 7 - Preferred humidity (Arid - Normal - Damp) + * 8 - Humidity tolerance (Range +/-) + * 9 - Flight interference tolerance (stuff falling from the sky/other hindrances -> tolerates dampness + flight interference tolerance => rain resistance) + * 10 - Cave dwelling + * 11 - Required flowers + * 12 - Flower plant chance + * 13 - Territory + */ + private static final LoadingCache beeGenomeCache = CacheBuilder.newBuilder() + .maximumSize(128) + .expireAfterAccess(1, TimeUnit.MINUTES) + .build(new CacheLoader() { + @Override + public BeeGenome load(@Nonnull NBTTagCompound tagCompound) { + return new BeeGenome(tagCompound); + } + }); - private static final LoadingCache beeGenomeCache = CacheBuilder.newBuilder() - .maximumSize(128) - .expireAfterAccess(1, TimeUnit.MINUTES) - .build(new CacheLoader() { - @Override - public BeeGenome load(@Nonnull NBTTagCompound tagCompound) { - return new BeeGenome(tagCompound); - } - }); + public static BeeGenome fromNBT(NBTTagCompound nbtTagCompound) { + if (nbtTagCompound == null) { + return null; + } - public static BeeGenome fromNBT(NBTTagCompound nbtTagCompound) { - if (nbtTagCompound == null) { - return null; - } + return beeGenomeCache.getUnchecked(nbtTagCompound); + } - return beeGenomeCache.getUnchecked(nbtTagCompound); - } + /* CONSTRUCTOR */ + private BeeGenome(NBTTagCompound nbttagcompound) { + super(nbttagcompound); + } - /* CONSTRUCTOR */ - private BeeGenome(NBTTagCompound nbttagcompound) { - super(nbttagcompound); - } + public BeeGenome(IChromosome[] chromosomes) { + super(chromosomes); + } - public BeeGenome(IChromosome[] chromosomes) { - super(chromosomes); - } + // NBT RETRIEVAL + public static IAlleleBeeSpecies getSpecies(ItemStack itemStack) { + if (!BeeManager.beeRoot.isMember(itemStack)) { + return null; + } - // NBT RETRIEVAL - public static IAlleleBeeSpecies getSpecies(ItemStack itemStack) { - if (!BeeManager.beeRoot.isMember(itemStack)) { - return null; - } + IAlleleSpecies species = getSpeciesDirectly(itemStack); + if (species instanceof IAlleleBeeSpecies) { + return (IAlleleBeeSpecies) species; + } - IAlleleSpecies species = getSpeciesDirectly(itemStack); - if (species instanceof IAlleleBeeSpecies) { - return (IAlleleBeeSpecies) species; - } + return (IAlleleBeeSpecies) getActiveAllele(itemStack, EnumBeeChromosome.SPECIES, BeeManager.beeRoot); + } - return (IAlleleBeeSpecies) getActiveAllele(itemStack, EnumBeeChromosome.SPECIES, BeeManager.beeRoot); - } + // / INFORMATION RETRIEVAL + @Override + public IAlleleBeeSpecies getPrimary() { + return (IAlleleBeeSpecies) getActiveAllele(EnumBeeChromosome.SPECIES); + } - // / INFORMATION RETRIEVAL - @Override - public IAlleleBeeSpecies getPrimary() { - return (IAlleleBeeSpecies) getActiveAllele(EnumBeeChromosome.SPECIES); - } + @Override + public IAlleleBeeSpecies getSecondary() { + return (IAlleleBeeSpecies) getInactiveAllele(EnumBeeChromosome.SPECIES); + } - @Override - public IAlleleBeeSpecies getSecondary() { - return (IAlleleBeeSpecies) getInactiveAllele(EnumBeeChromosome.SPECIES); - } + @Override + public float getSpeed() { + return ((IAlleleFloat) getActiveAllele(EnumBeeChromosome.SPEED)).getValue(); + } - @Override - public float getSpeed() { - return ((IAlleleFloat) getActiveAllele(EnumBeeChromosome.SPEED)).getValue(); - } + @Override + public int getLifespan() { + return ((IAlleleInteger) getActiveAllele(EnumBeeChromosome.LIFESPAN)).getValue(); + } - @Override - public int getLifespan() { - return ((IAlleleInteger) getActiveAllele(EnumBeeChromosome.LIFESPAN)).getValue(); - } + @Override + public int getFertility() { + return ((IAlleleInteger) getActiveAllele(EnumBeeChromosome.FERTILITY)).getValue(); + } - @Override - public int getFertility() { - return ((IAlleleInteger) getActiveAllele(EnumBeeChromosome.FERTILITY)).getValue(); - } + @Override + public EnumTolerance getToleranceTemp() { + return ((AlleleTolerance) getActiveAllele(EnumBeeChromosome.TEMPERATURE_TOLERANCE)).getValue(); + } - @Override - public EnumTolerance getToleranceTemp() { - return ((AlleleTolerance) getActiveAllele(EnumBeeChromosome.TEMPERATURE_TOLERANCE)).getValue(); - } + @Override + public boolean getNocturnal() { + return ((AlleleBoolean) getActiveAllele(EnumBeeChromosome.NOCTURNAL)).getValue(); + } - @Override - public boolean getNocturnal() { - return ((AlleleBoolean) getActiveAllele(EnumBeeChromosome.NOCTURNAL)).getValue(); - } + @Override + public EnumTolerance getToleranceHumid() { + return ((AlleleTolerance) getActiveAllele(EnumBeeChromosome.HUMIDITY_TOLERANCE)).getValue(); + } - @Override - public EnumTolerance getToleranceHumid() { - return ((AlleleTolerance) getActiveAllele(EnumBeeChromosome.HUMIDITY_TOLERANCE)).getValue(); - } + @Override + public boolean getTolerantFlyer() { + return ((AlleleBoolean) getActiveAllele(EnumBeeChromosome.TOLERANT_FLYER)).getValue(); + } - @Override - public boolean getTolerantFlyer() { - return ((AlleleBoolean) getActiveAllele(EnumBeeChromosome.TOLERANT_FLYER)).getValue(); - } + @Override + public boolean getCaveDwelling() { + return ((AlleleBoolean) getActiveAllele(EnumBeeChromosome.CAVE_DWELLING)).getValue(); + } - @Override - public boolean getCaveDwelling() { - return ((AlleleBoolean) getActiveAllele(EnumBeeChromosome.CAVE_DWELLING)).getValue(); - } + @Override + public IFlowerProvider getFlowerProvider() { + return ((IAlleleFlowers) getActiveAllele(EnumBeeChromosome.FLOWER_PROVIDER)).getProvider(); + } - @Override - public IFlowerProvider getFlowerProvider() { - return ((IAlleleFlowers) getActiveAllele(EnumBeeChromosome.FLOWER_PROVIDER)).getProvider(); - } + @Override + public int getFlowering() { + return ((IAlleleInteger) getActiveAllele(EnumBeeChromosome.FLOWERING)).getValue(); + } - @Override - public int getFlowering() { - return ((IAlleleInteger) getActiveAllele(EnumBeeChromosome.FLOWERING)).getValue(); - } + @Override + public int[] getTerritory() { + Vect area = ((AlleleArea) getActiveAllele(EnumBeeChromosome.TERRITORY)).getArea(); + return new int[] {area.x, area.y, area.z}; + } - @Override - public int[] getTerritory() { - Vect area = ((AlleleArea) getActiveAllele(EnumBeeChromosome.TERRITORY)).getArea(); - return new int[]{area.x, area.y, area.z}; - } + @Override + public IAlleleBeeEffect getEffect() { + return (IAlleleBeeEffect) getActiveAllele(EnumBeeChromosome.EFFECT); + } - @Override - public IAlleleBeeEffect getEffect() { - return (IAlleleBeeEffect) getActiveAllele(EnumBeeChromosome.EFFECT); - } - - @Override - public ISpeciesRoot getSpeciesRoot() { - return BeeManager.beeRoot; - } + @Override + public ISpeciesRoot getSpeciesRoot() { + return BeeManager.beeRoot; + } } diff --git a/src/main/java/forestry/apiculture/genetics/BeeHelper.java b/src/main/java/forestry/apiculture/genetics/BeeHelper.java index 2e887acfb..628668988 100755 --- a/src/main/java/forestry/apiculture/genetics/BeeHelper.java +++ b/src/main/java/forestry/apiculture/genetics/BeeHelper.java @@ -10,21 +10,8 @@ ******************************************************************************/ package forestry.apiculture.genetics; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Locale; -import java.util.Map.Entry; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import cpw.mods.fml.common.FMLCommonHandler; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.EnumBeeType; @@ -50,316 +37,328 @@ import forestry.apiculture.BeeHousingModifier; import forestry.apiculture.BeekeepingLogic; import forestry.core.genetics.SpeciesRoot; import forestry.plugins.PluginApiculture; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Locale; +import java.util.Map.Entry; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; public class BeeHelper extends SpeciesRoot implements IBeeRoot { - private static int beeSpeciesCount = -1; - public static final String UID = "rootBees"; + private static int beeSpeciesCount = -1; + public static final String UID = "rootBees"; - @Override - public String getUID() { - return UID; - } + @Override + public String getUID() { + return UID; + } - @Override - public Class getMemberClass() { - return IBee.class; - } + @Override + public Class getMemberClass() { + return IBee.class; + } - @Override - public int getSpeciesCount() { - if (beeSpeciesCount < 0) { - beeSpeciesCount = 0; - for (Entry entry : AlleleManager.alleleRegistry.getRegisteredAlleles().entrySet()) { - if (entry.getValue() instanceof IAlleleBeeSpecies) { - if (((IAlleleBeeSpecies) entry.getValue()).isCounted()) { - beeSpeciesCount++; - } - } - } - } + @Override + public int getSpeciesCount() { + if (beeSpeciesCount < 0) { + beeSpeciesCount = 0; + for (Entry entry : + AlleleManager.alleleRegistry.getRegisteredAlleles().entrySet()) { + if (entry.getValue() instanceof IAlleleBeeSpecies) { + if (((IAlleleBeeSpecies) entry.getValue()).isCounted()) { + beeSpeciesCount++; + } + } + } + } - return beeSpeciesCount; - } + return beeSpeciesCount; + } - @Override - public boolean isMember(ItemStack stack) { - return getType(stack) != EnumBeeType.NONE; - } + @Override + public boolean isMember(ItemStack stack) { + return getType(stack) != EnumBeeType.NONE; + } - @Override - public boolean isMember(ItemStack stack, int type) { - return getType(stack).ordinal() == type; - } + @Override + public boolean isMember(ItemStack stack, int type) { + return getType(stack).ordinal() == type; + } - @Override - public boolean isMember(IIndividual individual) { - return individual instanceof IBee; - } + @Override + public boolean isMember(IIndividual individual) { + return individual instanceof IBee; + } - @Override - public ItemStack getMemberStack(IIndividual individual, int type) { - if (!isMember(individual)) { - return null; - } - IBee bee = (IBee) individual; + @Override + public ItemStack getMemberStack(IIndividual individual, int type) { + if (!isMember(individual)) { + return null; + } + IBee bee = (IBee) individual; - Item beeItem; - switch (EnumBeeType.VALUES[type]) { - case QUEEN: - beeItem = PluginApiculture.items.beeQueenGE; - // ensure a queen is always mated - if (bee.getMate() == null) { - bee.mate(bee); - } - break; - case PRINCESS: - beeItem = PluginApiculture.items.beePrincessGE; - break; - case DRONE: - beeItem = PluginApiculture.items.beeDroneGE; - break; - case LARVAE: - beeItem = PluginApiculture.items.beeLarvaeGE; - break; - default: - throw new RuntimeException("Cannot instantiate a bee of type " + type); - } + Item beeItem; + switch (EnumBeeType.VALUES[type]) { + case QUEEN: + beeItem = PluginApiculture.items.beeQueenGE; + // ensure a queen is always mated + if (bee.getMate() == null) { + bee.mate(bee); + } + break; + case PRINCESS: + beeItem = PluginApiculture.items.beePrincessGE; + break; + case DRONE: + beeItem = PluginApiculture.items.beeDroneGE; + break; + case LARVAE: + beeItem = PluginApiculture.items.beeLarvaeGE; + break; + default: + throw new RuntimeException("Cannot instantiate a bee of type " + type); + } - NBTTagCompound nbttagcompound = new NBTTagCompound(); - bee.writeToNBT(nbttagcompound); - ItemStack beeStack = new ItemStack(beeItem); - beeStack.setTagCompound(nbttagcompound); - return beeStack; - } + NBTTagCompound nbttagcompound = new NBTTagCompound(); + bee.writeToNBT(nbttagcompound); + ItemStack beeStack = new ItemStack(beeItem); + beeStack.setTagCompound(nbttagcompound); + return beeStack; + } - @Override - public EnumBeeType getType(ItemStack stack) { - if (stack == null) { - return EnumBeeType.NONE; - } + @Override + public EnumBeeType getType(ItemStack stack) { + if (stack == null) { + return EnumBeeType.NONE; + } - Item item = stack.getItem(); + Item item = stack.getItem(); - if (PluginApiculture.items.beeDroneGE == item) { - return EnumBeeType.DRONE; - } else if (PluginApiculture.items.beePrincessGE == item) { - return EnumBeeType.PRINCESS; - } else if (PluginApiculture.items.beeQueenGE == item) { - return EnumBeeType.QUEEN; - } else if (PluginApiculture.items.beeLarvaeGE == item) { - return EnumBeeType.LARVAE; - } + if (PluginApiculture.items.beeDroneGE == item) { + return EnumBeeType.DRONE; + } else if (PluginApiculture.items.beePrincessGE == item) { + return EnumBeeType.PRINCESS; + } else if (PluginApiculture.items.beeQueenGE == item) { + return EnumBeeType.QUEEN; + } else if (PluginApiculture.items.beeLarvaeGE == item) { + return EnumBeeType.LARVAE; + } - return EnumBeeType.NONE; - } + return EnumBeeType.NONE; + } - @Override - public boolean isDrone(ItemStack stack) { - return getType(stack) == EnumBeeType.DRONE; - } + @Override + public boolean isDrone(ItemStack stack) { + return getType(stack) == EnumBeeType.DRONE; + } - @Override - public boolean isMated(ItemStack stack) { - if (getType(stack) != EnumBeeType.QUEEN) { - return false; - } + @Override + public boolean isMated(ItemStack stack) { + if (getType(stack) != EnumBeeType.QUEEN) { + return false; + } - NBTTagCompound nbt = stack.getTagCompound(); - return nbt != null && nbt.hasKey("Mate"); - } + NBTTagCompound nbt = stack.getTagCompound(); + return nbt != null && nbt.hasKey("Mate"); + } - @Override - public IBee getMember(ItemStack stack) { - if (!isMember(stack)) { - return null; - } + @Override + public IBee getMember(ItemStack stack) { + if (!isMember(stack)) { + return null; + } - return new Bee(stack.getTagCompound()); - } + return new Bee(stack.getTagCompound()); + } - @Override - public IBee getMember(NBTTagCompound compound) { - return new Bee(compound); - } + @Override + public IBee getMember(NBTTagCompound compound) { + return new Bee(compound); + } - @Override - public IBee getBee(World world, IBeeGenome genome) { - return new Bee(genome); - } + @Override + public IBee getBee(World world, IBeeGenome genome) { + return new Bee(genome); + } - @Override - public IBee getBee(World world, IBeeGenome genome, IBee mate) { - return new Bee(genome, mate); - } + @Override + public IBee getBee(World world, IBeeGenome genome, IBee mate) { + return new Bee(genome, mate); + } - /* GENOME CONVERSIONS */ - @Override - public IBeeGenome templateAsGenome(IAllele[] template) { - IChromosome[] chromosomes = templateAsChromosomes(template); - return new BeeGenome(chromosomes); - } + /* GENOME CONVERSIONS */ + @Override + public IBeeGenome templateAsGenome(IAllele[] template) { + IChromosome[] chromosomes = templateAsChromosomes(template); + return new BeeGenome(chromosomes); + } - @Override - public IBeeGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive) { - return new BeeGenome(templateAsChromosomes(templateActive, templateInactive)); - } + @Override + public IBeeGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive) { + return new BeeGenome(templateAsChromosomes(templateActive, templateInactive)); + } - @Override - public IBee templateAsIndividual(IAllele[] template) { - return new Bee(templateAsGenome(template)); - } + @Override + public IBee templateAsIndividual(IAllele[] template) { + return new Bee(templateAsGenome(template)); + } - @Override - public IBee templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive) { - return new Bee(templateAsGenome(templateActive, templateInactive)); - } + @Override + public IBee templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive) { + return new Bee(templateAsGenome(templateActive, templateInactive)); + } - /* TEMPLATES */ - private static final ArrayList beeTemplates = new ArrayList<>(); + /* TEMPLATES */ + private static final ArrayList beeTemplates = new ArrayList<>(); - @Override - public ArrayList getIndividualTemplates() { - return beeTemplates; - } + @Override + public ArrayList getIndividualTemplates() { + return beeTemplates; + } - @Override - public void registerTemplate(String identifier, IAllele[] template) { - IBeeGenome beeGenome = BeeManager.beeRoot.templateAsGenome(template); - IBee bee = new Bee(beeGenome); - beeTemplates.add(bee); - speciesTemplates.put(identifier, template); - } + @Override + public void registerTemplate(String identifier, IAllele[] template) { + IBeeGenome beeGenome = BeeManager.beeRoot.templateAsGenome(template); + IBee bee = new Bee(beeGenome); + beeTemplates.add(bee); + speciesTemplates.put(identifier, template); + } - @Override - public IAllele[] getDefaultTemplate() { - return BeeDefinition.FOREST.getTemplate(); - } + @Override + public IAllele[] getDefaultTemplate() { + return BeeDefinition.FOREST.getTemplate(); + } - /* MUTATIONS */ - /** - * List of possible mutations on species alleles. - */ - private static final ArrayList beeMutations = new ArrayList<>(); + /* MUTATIONS */ + /** + * List of possible mutations on species alleles. + */ + private static final ArrayList beeMutations = new ArrayList<>(); - @Override - public Collection getMutations(boolean shuffle) { - if (shuffle) { - Collections.shuffle(beeMutations); - } - return beeMutations; - } + @Override + public Collection getMutations(boolean shuffle) { + if (shuffle) { + Collections.shuffle(beeMutations); + } + return beeMutations; + } - @Override - public void registerMutation(IMutation mutation) { - if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getTemplate()[0].getUID())) { - return; - } - if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getAllele0().getUID())) { - return; - } - if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getAllele1().getUID())) { - return; - } + @Override + public void registerMutation(IMutation mutation) { + if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getTemplate()[0].getUID())) { + return; + } + if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getAllele0().getUID())) { + return; + } + if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getAllele1().getUID())) { + return; + } - beeMutations.add((IBeeMutation) mutation); - } + beeMutations.add((IBeeMutation) mutation); + } - /* BREEDING MODES */ - private final ArrayList beekeepingModes = new ArrayList<>(); - private static IBeekeepingMode activeBeekeepingMode; + /* BREEDING MODES */ + private final ArrayList beekeepingModes = new ArrayList<>(); + private static IBeekeepingMode activeBeekeepingMode; - @Override - public void resetBeekeepingMode() { - activeBeekeepingMode = null; - } + @Override + public void resetBeekeepingMode() { + activeBeekeepingMode = null; + } - @Override - public ArrayList getBeekeepingModes() { - return this.beekeepingModes; - } + @Override + public ArrayList getBeekeepingModes() { + return this.beekeepingModes; + } - @Override - public IBeekeepingMode getBeekeepingMode(World world) { - if (activeBeekeepingMode != null) { - return activeBeekeepingMode; - } + @Override + public IBeekeepingMode getBeekeepingMode(World world) { + if (activeBeekeepingMode != null) { + return activeBeekeepingMode; + } - // No beekeeping mode yet, get it. - IApiaristTracker tracker = getBreedingTracker(world, null); - String mode = tracker.getModeName(); - if (mode == null || mode.isEmpty()) { - mode = PluginApiculture.beekeepingMode; - } + // No beekeeping mode yet, get it. + IApiaristTracker tracker = getBreedingTracker(world, null); + String mode = tracker.getModeName(); + if (mode == null || mode.isEmpty()) { + mode = PluginApiculture.beekeepingMode; + } - setBeekeepingMode(world, mode); - FMLCommonHandler.instance().getFMLLogger().debug("Set beekeeping mode for a world to " + mode); + setBeekeepingMode(world, mode); + FMLCommonHandler.instance().getFMLLogger().debug("Set beekeeping mode for a world to " + mode); - return activeBeekeepingMode; - } + return activeBeekeepingMode; + } - @Override - public void registerBeekeepingMode(IBeekeepingMode mode) { - beekeepingModes.add(mode); - } + @Override + public void registerBeekeepingMode(IBeekeepingMode mode) { + beekeepingModes.add(mode); + } - @Override - public void setBeekeepingMode(World world, String name) { - activeBeekeepingMode = getBeekeepingMode(name); - getBreedingTracker(world, null).setModeName(name); - } + @Override + public void setBeekeepingMode(World world, String name) { + activeBeekeepingMode = getBeekeepingMode(name); + getBreedingTracker(world, null).setModeName(name); + } - @Override - public IBeekeepingMode getBeekeepingMode(String name) { - for (IBeekeepingMode mode : beekeepingModes) { - if (mode.getName().equals(name) || mode.getName().equals(name.toLowerCase(Locale.ENGLISH))) { - return mode; - } - } + @Override + public IBeekeepingMode getBeekeepingMode(String name) { + for (IBeekeepingMode mode : beekeepingModes) { + if (mode.getName().equals(name) || mode.getName().equals(name.toLowerCase(Locale.ENGLISH))) { + return mode; + } + } - FMLCommonHandler.instance().getFMLLogger().debug("Failed to find a beekeeping mode called '%s', reverting to fallback."); - return beekeepingModes.get(0); - } + FMLCommonHandler.instance() + .getFMLLogger() + .debug("Failed to find a beekeeping mode called '%s', reverting to fallback."); + return beekeepingModes.get(0); + } - @Override - public IApiaristTracker getBreedingTracker(World world, GameProfile player) { - String filename = "ApiaristTracker." + (player == null ? "common" : player.getId()); - ApiaristTracker tracker = (ApiaristTracker) world.loadItemData(ApiaristTracker.class, filename); + @Override + public IApiaristTracker getBreedingTracker(World world, GameProfile player) { + String filename = "ApiaristTracker." + (player == null ? "common" : player.getId()); + ApiaristTracker tracker = (ApiaristTracker) world.loadItemData(ApiaristTracker.class, filename); - // Create a tracker if there is none yet. - if (tracker == null) { - tracker = new ApiaristTracker(filename); - world.setItemData(filename, tracker); - } + // Create a tracker if there is none yet. + if (tracker == null) { + tracker = new ApiaristTracker(filename); + world.setItemData(filename, tracker); + } - tracker.setUsername(player); - tracker.setWorld(world); + tracker.setUsername(player); + tracker.setWorld(world); - return tracker; - } + return tracker; + } - @Override - public IBeekeepingLogic createBeekeepingLogic(IBeeHousing housing) { - return new BeekeepingLogic(housing); - } + @Override + public IBeekeepingLogic createBeekeepingLogic(IBeeHousing housing) { + return new BeekeepingLogic(housing); + } - @Override - public IBeeModifier createBeeHousingModifier(IBeeHousing housing) { - return new BeeHousingModifier(housing); - } + @Override + public IBeeModifier createBeeHousingModifier(IBeeHousing housing) { + return new BeeHousingModifier(housing); + } - @Override - public IBeeListener createBeeHousingListener(IBeeHousing housing) { - return new BeeHousingListener(housing); - } + @Override + public IBeeListener createBeeHousingListener(IBeeHousing housing) { + return new BeeHousingListener(housing); + } - @Override - public IChromosomeType[] getKaryotype() { - return EnumBeeChromosome.values(); - } + @Override + public IChromosomeType[] getKaryotype() { + return EnumBeeChromosome.values(); + } - @Override - public IChromosomeType getKaryotypeKey() { - return EnumBeeChromosome.SPECIES; - } + @Override + public IChromosomeType getKaryotypeKey() { + return EnumBeeChromosome.SPECIES; + } } diff --git a/src/main/java/forestry/apiculture/genetics/BeeMutation.java b/src/main/java/forestry/apiculture/genetics/BeeMutation.java index 48d1bc348..054efb8dd 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeMutation.java +++ b/src/main/java/forestry/apiculture/genetics/BeeMutation.java @@ -10,9 +10,6 @@ ******************************************************************************/ package forestry.apiculture.genetics; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.api.apiculture.IBeeGenome; @@ -22,38 +19,45 @@ import forestry.api.apiculture.IBeeMutationCustom; import forestry.api.apiculture.IBeeRoot; import forestry.api.genetics.IAllele; import forestry.core.genetics.mutations.Mutation; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; public class BeeMutation extends Mutation implements IBeeMutationCustom { - public BeeMutation(IAlleleBeeSpecies bee0, IAlleleBeeSpecies bee1, IAllele[] result, int chance) { - super(bee0, bee1, result, chance); - } + public BeeMutation(IAlleleBeeSpecies bee0, IAlleleBeeSpecies bee1, IAllele[] result, int chance) { + super(bee0, bee1, result, chance); + } - @Override - public IBeeRoot getRoot() { - return BeeManager.beeRoot; - } + @Override + public IBeeRoot getRoot() { + return BeeManager.beeRoot; + } - @Override - public float getChance(IBeeHousing housing, IAlleleBeeSpecies allele0, IAlleleBeeSpecies allele1, IBeeGenome genome0, IBeeGenome genome1) { - World world = housing.getWorld(); - ChunkCoordinates housingCoordinates = housing.getCoordinates(); - int x = housingCoordinates.posX; - int y = housingCoordinates.posY; - int z = housingCoordinates.posZ; + @Override + public float getChance( + IBeeHousing housing, + IAlleleBeeSpecies allele0, + IAlleleBeeSpecies allele1, + IBeeGenome genome0, + IBeeGenome genome1) { + World world = housing.getWorld(); + ChunkCoordinates housingCoordinates = housing.getCoordinates(); + int x = housingCoordinates.posX; + int y = housingCoordinates.posY; + int z = housingCoordinates.posZ; - float processedChance = super.getChance(world, x, y, z, allele0, allele1, genome0, genome1, housing); - if (processedChance <= 0) { - return 0; - } + float processedChance = super.getChance(world, x, y, z, allele0, allele1, genome0, genome1, housing); + if (processedChance <= 0) { + return 0; + } - IBeeModifier beeHousingModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - IBeeModifier beeModeModifier = BeeManager.beeRoot.getBeekeepingMode(world).getBeeModifier(); + IBeeModifier beeHousingModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); + IBeeModifier beeModeModifier = + BeeManager.beeRoot.getBeekeepingMode(world).getBeeModifier(); - processedChance *= beeHousingModifier.getMutationModifier(genome0, genome1, processedChance); - processedChance *= beeModeModifier.getMutationModifier(genome0, genome1, processedChance); - - return processedChance; - } + processedChance *= beeHousingModifier.getMutationModifier(genome0, genome1, processedChance); + processedChance *= beeModeModifier.getMutationModifier(genome0, genome1, processedChance); + return processedChance; + } } diff --git a/src/main/java/forestry/apiculture/genetics/BeeMutationFactory.java b/src/main/java/forestry/apiculture/genetics/BeeMutationFactory.java index 2013e75d2..e5707d5ca 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeMutationFactory.java +++ b/src/main/java/forestry/apiculture/genetics/BeeMutationFactory.java @@ -1,27 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.genetics; - -import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.IAlleleBeeSpecies; -import forestry.api.apiculture.IBeeMutationCustom; -import forestry.api.apiculture.IBeeMutationFactory; -import forestry.api.genetics.IAllele; - -public class BeeMutationFactory implements IBeeMutationFactory { - - @Override - public IBeeMutationCustom createMutation(IAlleleBeeSpecies parentBee0, IAlleleBeeSpecies parentBee1, IAllele[] result, int chance) { - IBeeMutationCustom mutation = new BeeMutation(parentBee0, parentBee1, result, chance); - BeeManager.beeRoot.registerMutation(mutation); - return mutation; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.genetics; + +import forestry.api.apiculture.BeeManager; +import forestry.api.apiculture.IAlleleBeeSpecies; +import forestry.api.apiculture.IBeeMutationCustom; +import forestry.api.apiculture.IBeeMutationFactory; +import forestry.api.genetics.IAllele; + +public class BeeMutationFactory implements IBeeMutationFactory { + + @Override + public IBeeMutationCustom createMutation( + IAlleleBeeSpecies parentBee0, IAlleleBeeSpecies parentBee1, IAllele[] result, int chance) { + IBeeMutationCustom mutation = new BeeMutation(parentBee0, parentBee1, result, chance); + BeeManager.beeRoot.registerMutation(mutation); + return mutation; + } +} diff --git a/src/main/java/forestry/apiculture/genetics/BeeVariation.java b/src/main/java/forestry/apiculture/genetics/BeeVariation.java index af8395da6..31c63612c 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeVariation.java +++ b/src/main/java/forestry/apiculture/genetics/BeeVariation.java @@ -1,57 +1,56 @@ -package forestry.apiculture.genetics; - -import net.minecraft.item.ItemStack; - -import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.EnumBeeChromosome; -import forestry.api.apiculture.EnumBeeType; -import forestry.api.apiculture.IBee; -import forestry.api.apiculture.IBeeGenome; -import forestry.api.genetics.IAllele; -import forestry.core.genetics.alleles.AlleleHelper; - -public abstract class BeeVariation implements IBeeDefinition { - - private final IAllele[] template; - private final IBeeGenome genome; - - protected BeeVariation(IBeeDefinition bee) { - template = bee.getTemplate(); - initializeTemplate(template); - genome = BeeManager.beeRoot.templateAsGenome(template); - } - - protected abstract void initializeTemplate(IAllele[] template); - - @Override - public IAllele[] getTemplate() { - return template; - } - - @Override - public IBeeGenome getGenome() { - return genome; - } - - @Override - public IBee getIndividual() { - return new Bee(genome); - } - - @Override - public final ItemStack getMemberStack(EnumBeeType beeType) { - IBee bee = getIndividual(); - return BeeManager.beeRoot.getMemberStack(bee, beeType.ordinal()); - } - - public static class RainResist extends BeeVariation { - public RainResist(IBeeDefinition bee) { - super(bee); - } - - @Override - protected void initializeTemplate(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.TOLERANT_FLYER, true); - } - } -} +package forestry.apiculture.genetics; + +import forestry.api.apiculture.BeeManager; +import forestry.api.apiculture.EnumBeeChromosome; +import forestry.api.apiculture.EnumBeeType; +import forestry.api.apiculture.IBee; +import forestry.api.apiculture.IBeeGenome; +import forestry.api.genetics.IAllele; +import forestry.core.genetics.alleles.AlleleHelper; +import net.minecraft.item.ItemStack; + +public abstract class BeeVariation implements IBeeDefinition { + + private final IAllele[] template; + private final IBeeGenome genome; + + protected BeeVariation(IBeeDefinition bee) { + template = bee.getTemplate(); + initializeTemplate(template); + genome = BeeManager.beeRoot.templateAsGenome(template); + } + + protected abstract void initializeTemplate(IAllele[] template); + + @Override + public IAllele[] getTemplate() { + return template; + } + + @Override + public IBeeGenome getGenome() { + return genome; + } + + @Override + public IBee getIndividual() { + return new Bee(genome); + } + + @Override + public final ItemStack getMemberStack(EnumBeeType beeType) { + IBee bee = getIndividual(); + return BeeManager.beeRoot.getMemberStack(bee, beeType.ordinal()); + } + + public static class RainResist extends BeeVariation { + public RainResist(IBeeDefinition bee) { + super(bee); + } + + @Override + protected void initializeTemplate(IAllele[] template) { + AlleleHelper.instance.set(template, EnumBeeChromosome.TOLERANT_FLYER, true); + } + } +} diff --git a/src/main/java/forestry/apiculture/genetics/BeekeepingMode.java b/src/main/java/forestry/apiculture/genetics/BeekeepingMode.java index 0fedf7ca7..31adac378 100755 --- a/src/main/java/forestry/apiculture/genetics/BeekeepingMode.java +++ b/src/main/java/forestry/apiculture/genetics/BeekeepingMode.java @@ -10,12 +10,6 @@ ******************************************************************************/ package forestry.apiculture.genetics; -import java.util.ArrayList; -import java.util.Locale; -import java.util.Random; - -import net.minecraft.world.World; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.DefaultBeeModifier; import forestry.api.apiculture.IBee; @@ -23,140 +17,150 @@ import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeeModifier; import forestry.api.apiculture.IBeekeepingMode; +import java.util.ArrayList; +import java.util.Locale; +import java.util.Random; +import net.minecraft.world.World; public class BeekeepingMode implements IBeekeepingMode { - public static final IBeekeepingMode easy = new BeekeepingMode("EASY", 2.0f, 1.0f, 1.0f, false, false); - public static final IBeekeepingMode normal = new BeekeepingMode("NORMAL", 1.0f, 1.0f, 1.0f, false, true); - public static final IBeekeepingMode hard = new BeekeepingMode("HARD", 0.75f, 1.5f, 1.0f, false, true); - public static final IBeekeepingMode hardcore = new BeekeepingMode("HARDCORE", 0.5f, 5.0f, 0.8f, true, true); - public static final IBeekeepingMode insane = new BeekeepingMode("INSANE", 0.2f, 10.0f, 0.6f, true, true); + public static final IBeekeepingMode easy = new BeekeepingMode("EASY", 2.0f, 1.0f, 1.0f, false, false); + public static final IBeekeepingMode normal = new BeekeepingMode("NORMAL", 1.0f, 1.0f, 1.0f, false, true); + public static final IBeekeepingMode hard = new BeekeepingMode("HARD", 0.75f, 1.5f, 1.0f, false, true); + public static final IBeekeepingMode hardcore = new BeekeepingMode("HARDCORE", 0.5f, 5.0f, 0.8f, true, true); + public static final IBeekeepingMode insane = new BeekeepingMode("INSANE", 0.2f, 10.0f, 0.6f, true, true); - private final Random rand; - private final String name; - private final boolean reducesFertility; - private final boolean canFatigue; - private final IBeeModifier beeModifier; + private final Random rand; + private final String name; + private final boolean reducesFertility; + private final boolean canFatigue; + private final IBeeModifier beeModifier; - public BeekeepingMode(String name, float mutationModifier, float lifespanModifier, float speedModifier, boolean reducesFertility, boolean canFatigue) { - this.rand = new Random(); - this.name = name; - this.reducesFertility = reducesFertility; - this.canFatigue = canFatigue; - this.beeModifier = new BeekeepingModeBeeModifier(mutationModifier, lifespanModifier, speedModifier); - } + public BeekeepingMode( + String name, + float mutationModifier, + float lifespanModifier, + float speedModifier, + boolean reducesFertility, + boolean canFatigue) { + this.rand = new Random(); + this.name = name; + this.reducesFertility = reducesFertility; + this.canFatigue = canFatigue; + this.beeModifier = new BeekeepingModeBeeModifier(mutationModifier, lifespanModifier, speedModifier); + } - @Override - public String getName() { - return this.name; - } + @Override + public String getName() { + return this.name; + } - @Override - public ArrayList getDescription() { - ArrayList ret = new ArrayList<>(); - ret.add("beemode." + name.toLowerCase(Locale.ENGLISH) + ".desc"); - return ret; - } + @Override + public ArrayList getDescription() { + ArrayList ret = new ArrayList<>(); + ret.add("beemode." + name.toLowerCase(Locale.ENGLISH) + ".desc"); + return ret; + } - @Override - public float getWearModifier() { - return 1.0f; - } + @Override + public float getWearModifier() { + return 1.0f; + } - @Override - public int getFinalFertility(IBee queen, World world, int x, int y, int z) { - int toCreate = queen.getGenome().getFertility(); + @Override + public int getFinalFertility(IBee queen, World world, int x, int y, int z) { + int toCreate = queen.getGenome().getFertility(); - if (reducesFertility) { - toCreate = new Random().nextInt(toCreate); - } + if (reducesFertility) { + toCreate = new Random().nextInt(toCreate); + } - return toCreate; - } + return toCreate; + } - @Override - public boolean isFatigued(IBee queen, IBeeHousing housing) { - if (!canFatigue) { - return false; - } + @Override + public boolean isFatigued(IBee queen, IBeeHousing housing) { + if (!canFatigue) { + return false; + } - if (queen.isNatural()) { - return false; - } + if (queen.isNatural()) { + return false; + } - IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); + IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - return queen.getGeneration() > 96 + rand.nextInt(6) + rand.nextInt(6) && - rand.nextFloat() < 0.02f * beeModifier.getGeneticDecay(queen.getGenome(), 1f); - } + return queen.getGeneration() > 96 + rand.nextInt(6) + rand.nextInt(6) + && rand.nextFloat() < 0.02f * beeModifier.getGeneticDecay(queen.getGenome(), 1f); + } - @Override - public boolean isOverworked(IBee queen, IBeeHousing housing) { - IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); + @Override + public boolean isOverworked(IBee queen, IBeeHousing housing) { + IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - float productionModifier = beeModifier.getProductionModifier(queen.getGenome(), 1f); - if (productionModifier > 16) { - if (housing.getWorld().rand.nextFloat() * 100 < 0.01 * ((productionModifier * productionModifier) - 100)) { - return true; - } - } - - return false; - } - - @Override - public boolean isDegenerating(IBee queen, IBee offspring, IBeeHousing housing) { - IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); + float productionModifier = beeModifier.getProductionModifier(queen.getGenome(), 1f); + if (productionModifier > 16) { + if (housing.getWorld().rand.nextFloat() * 100 < 0.01 * ((productionModifier * productionModifier) - 100)) { + return true; + } + } - float mutationModifier = beeModifier.getMutationModifier(queen.getGenome(), queen.getMate(), 1.0f); - if (mutationModifier > 10) { - if (housing.getWorld().rand.nextFloat() * 100 < 0.4 * ((mutationModifier * mutationModifier) - 100)) { - return true; - } - } - - return false; - } - - @Override - public boolean isNaturalOffspring(IBee queen) { - return queen.isNatural(); - } + return false; + } - @Override - public boolean mayMultiplyPrincess(IBee queen) { - return true; - } + @Override + public boolean isDegenerating(IBee queen, IBee offspring, IBeeHousing housing) { + IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - @Override - public IBeeModifier getBeeModifier() { - return beeModifier; - } + float mutationModifier = beeModifier.getMutationModifier(queen.getGenome(), queen.getMate(), 1.0f); + if (mutationModifier > 10) { + if (housing.getWorld().rand.nextFloat() * 100 < 0.4 * ((mutationModifier * mutationModifier) - 100)) { + return true; + } + } - private static class BeekeepingModeBeeModifier extends DefaultBeeModifier { - private final float mutationModifier; - private final float lifespanModifier; - private final float speedModifier; + return false; + } - public BeekeepingModeBeeModifier(float mutationModifier, float lifespanModifier, float speedModifier) { - this.mutationModifier = mutationModifier; - this.lifespanModifier = lifespanModifier; - this.speedModifier = speedModifier; - } + @Override + public boolean isNaturalOffspring(IBee queen) { + return queen.isNatural(); + } - @Override - public float getMutationModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { - return this.mutationModifier; - } + @Override + public boolean mayMultiplyPrincess(IBee queen) { + return true; + } - @Override - public float getLifespanModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { - return this.lifespanModifier; - } + @Override + public IBeeModifier getBeeModifier() { + return beeModifier; + } - @Override - public float getProductionModifier(IBeeGenome genome, float currentModifier) { - return this.speedModifier; - } - } + private static class BeekeepingModeBeeModifier extends DefaultBeeModifier { + private final float mutationModifier; + private final float lifespanModifier; + private final float speedModifier; + + public BeekeepingModeBeeModifier(float mutationModifier, float lifespanModifier, float speedModifier) { + this.mutationModifier = mutationModifier; + this.lifespanModifier = lifespanModifier; + this.speedModifier = speedModifier; + } + + @Override + public float getMutationModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { + return this.mutationModifier; + } + + @Override + public float getLifespanModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { + return this.lifespanModifier; + } + + @Override + public float getProductionModifier(IBeeGenome genome, float currentModifier) { + return this.speedModifier; + } + } } diff --git a/src/main/java/forestry/apiculture/genetics/BranchBees.java b/src/main/java/forestry/apiculture/genetics/BranchBees.java index fc59c1e90..22fce5155 100755 --- a/src/main/java/forestry/apiculture/genetics/BranchBees.java +++ b/src/main/java/forestry/apiculture/genetics/BranchBees.java @@ -14,8 +14,7 @@ import forestry.core.genetics.Branch; public class BranchBees extends Branch { - public BranchBees(String uid, String scientific) { - super("bees." + uid, scientific); - } - + public BranchBees(String uid, String scientific) { + super("bees." + uid, scientific); + } } diff --git a/src/main/java/forestry/apiculture/genetics/DefaultBeeIconColourProvider.java b/src/main/java/forestry/apiculture/genetics/DefaultBeeIconColourProvider.java index 10cb49322..1d363a21a 100644 --- a/src/main/java/forestry/apiculture/genetics/DefaultBeeIconColourProvider.java +++ b/src/main/java/forestry/apiculture/genetics/DefaultBeeIconColourProvider.java @@ -1,34 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.genetics; - -import forestry.api.apiculture.IBeeIconColourProvider; - -public class DefaultBeeIconColourProvider implements IBeeIconColourProvider { - private final int primaryColour; - private final int secondaryColour; - - public DefaultBeeIconColourProvider(int primaryColour, int secondaryColour) { - this.primaryColour = primaryColour; - this.secondaryColour = secondaryColour; - } - - @Override - public int getIconColour(int renderPass) { - if (renderPass == 0) { - return primaryColour; - } - if (renderPass == 1) { - return secondaryColour; - } - return 0xffffff; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.genetics; + +import forestry.api.apiculture.IBeeIconColourProvider; + +public class DefaultBeeIconColourProvider implements IBeeIconColourProvider { + private final int primaryColour; + private final int secondaryColour; + + public DefaultBeeIconColourProvider(int primaryColour, int secondaryColour) { + this.primaryColour = primaryColour; + this.secondaryColour = secondaryColour; + } + + @Override + public int getIconColour(int renderPass) { + if (renderPass == 0) { + return primaryColour; + } + if (renderPass == 1) { + return secondaryColour; + } + return 0xffffff; + } +} diff --git a/src/main/java/forestry/apiculture/genetics/DefaultBeeIconProvider.java b/src/main/java/forestry/apiculture/genetics/DefaultBeeIconProvider.java index 37ea41367..8f52e6e57 100644 --- a/src/main/java/forestry/apiculture/genetics/DefaultBeeIconProvider.java +++ b/src/main/java/forestry/apiculture/genetics/DefaultBeeIconProvider.java @@ -1,64 +1,59 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.genetics; - -import java.util.Locale; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.util.IIcon; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.apiculture.EnumBeeType; -import forestry.api.apiculture.IBeeIconProvider; -import forestry.core.render.TextureManager; - -public class DefaultBeeIconProvider implements IBeeIconProvider { - - public static final DefaultBeeIconProvider instance = new DefaultBeeIconProvider(); - - private DefaultBeeIconProvider() { - - } - - private static final IIcon[][] icons = new IIcon[EnumBeeType.values().length][3]; - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IIconRegister register) { - String beeIconDir = "bees/default/"; - IIcon body1 = TextureManager.registerTex(register, beeIconDir + "body1"); - - for (int i = 0; i < EnumBeeType.values().length; i++) { - EnumBeeType beeType = EnumBeeType.values()[i]; - if (beeType == EnumBeeType.NONE) { - continue; - } - - String beeTypeNameBase = beeIconDir + beeType.toString().toLowerCase(Locale.ENGLISH); - - icons[i][0] = TextureManager.registerTex(register, beeTypeNameBase + ".outline"); - if (beeType == EnumBeeType.LARVAE) { - icons[i][1] = TextureManager.registerTex(register, beeTypeNameBase + ".body"); - } else { - icons[i][1] = body1; - } - icons[i][2] = TextureManager.registerTex(register, beeTypeNameBase + ".body2"); - } - } - - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(EnumBeeType type, int renderPass) { - return icons[type.ordinal()][renderPass]; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.genetics; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.apiculture.EnumBeeType; +import forestry.api.apiculture.IBeeIconProvider; +import forestry.core.render.TextureManager; +import java.util.Locale; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.util.IIcon; + +public class DefaultBeeIconProvider implements IBeeIconProvider { + + public static final DefaultBeeIconProvider instance = new DefaultBeeIconProvider(); + + private DefaultBeeIconProvider() {} + + private static final IIcon[][] icons = new IIcon[EnumBeeType.values().length][3]; + + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IIconRegister register) { + String beeIconDir = "bees/default/"; + IIcon body1 = TextureManager.registerTex(register, beeIconDir + "body1"); + + for (int i = 0; i < EnumBeeType.values().length; i++) { + EnumBeeType beeType = EnumBeeType.values()[i]; + if (beeType == EnumBeeType.NONE) { + continue; + } + + String beeTypeNameBase = beeIconDir + beeType.toString().toLowerCase(Locale.ENGLISH); + + icons[i][0] = TextureManager.registerTex(register, beeTypeNameBase + ".outline"); + if (beeType == EnumBeeType.LARVAE) { + icons[i][1] = TextureManager.registerTex(register, beeTypeNameBase + ".body"); + } else { + icons[i][1] = body1; + } + icons[i][2] = TextureManager.registerTex(register, beeTypeNameBase + ".body2"); + } + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(EnumBeeType type, int renderPass) { + return icons[type.ordinal()][renderPass]; + } +} diff --git a/src/main/java/forestry/apiculture/genetics/HiveDrop.java b/src/main/java/forestry/apiculture/genetics/HiveDrop.java index eee87976c..af83a2256 100755 --- a/src/main/java/forestry/apiculture/genetics/HiveDrop.java +++ b/src/main/java/forestry/apiculture/genetics/HiveDrop.java @@ -10,66 +10,63 @@ ******************************************************************************/ package forestry.apiculture.genetics; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.IBee; import forestry.api.apiculture.IHiveDrop; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; public class HiveDrop implements IHiveDrop { - private final IBeeDefinition beeTemplate; - private final ArrayList additional = new ArrayList<>(); - private final int chance; - private float ignobleShare = 0.0f; + private final IBeeDefinition beeTemplate; + private final ArrayList additional = new ArrayList<>(); + private final int chance; + private float ignobleShare = 0.0f; - public HiveDrop(int chance, IBeeDefinition beeTemplate, ItemStack... bonus) { - this.beeTemplate = beeTemplate; - this.chance = chance; + public HiveDrop(int chance, IBeeDefinition beeTemplate, ItemStack... bonus) { + this.beeTemplate = beeTemplate; + this.chance = chance; - Collections.addAll(this.additional, bonus); - } + Collections.addAll(this.additional, bonus); + } - public HiveDrop setIgnobleShare(float share) { - this.ignobleShare = share; - return this; - } - - @Override - public ItemStack getPrincess(World world, int x, int y, int z, int fortune) { - IBee bee = beeTemplate.getIndividual(); - if (world.rand.nextFloat() < ignobleShare) { - bee.setIsNatural(false); - } + public HiveDrop setIgnobleShare(float share) { + this.ignobleShare = share; + return this; + } - return BeeManager.beeRoot.getMemberStack(bee, EnumBeeType.PRINCESS.ordinal()); - } + @Override + public ItemStack getPrincess(World world, int x, int y, int z, int fortune) { + IBee bee = beeTemplate.getIndividual(); + if (world.rand.nextFloat() < ignobleShare) { + bee.setIsNatural(false); + } - @Override - public List getDrones(World world, int x, int y, int z, int fortune) { - ItemStack drone = beeTemplate.getMemberStack(EnumBeeType.DRONE); - return Collections.singletonList(drone); - } + return BeeManager.beeRoot.getMemberStack(bee, EnumBeeType.PRINCESS.ordinal()); + } - @Override - public ArrayList getAdditional(World world, int x, int y, int z, int fortune) { - ArrayList ret = new ArrayList<>(); - for (ItemStack stack : additional) { - ret.add(stack.copy()); - } + @Override + public List getDrones(World world, int x, int y, int z, int fortune) { + ItemStack drone = beeTemplate.getMemberStack(EnumBeeType.DRONE); + return Collections.singletonList(drone); + } - return ret; - } + @Override + public ArrayList getAdditional(World world, int x, int y, int z, int fortune) { + ArrayList ret = new ArrayList<>(); + for (ItemStack stack : additional) { + ret.add(stack.copy()); + } - @Override - public int getChance(World world, int x, int y, int z) { - return chance; - } + return ret; + } + @Override + public int getChance(World world, int x, int y, int z) { + return chance; + } } diff --git a/src/main/java/forestry/apiculture/genetics/IBeeDefinition.java b/src/main/java/forestry/apiculture/genetics/IBeeDefinition.java index 71c30aa1c..241b1f7f4 100644 --- a/src/main/java/forestry/apiculture/genetics/IBeeDefinition.java +++ b/src/main/java/forestry/apiculture/genetics/IBeeDefinition.java @@ -1,28 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.genetics; - -import net.minecraft.item.ItemStack; - -import forestry.api.apiculture.EnumBeeType; -import forestry.api.apiculture.IBee; -import forestry.api.apiculture.IBeeGenome; -import forestry.core.genetics.IGeneticDefinition; - -public interface IBeeDefinition extends IGeneticDefinition { - @Override - IBeeGenome getGenome(); - - @Override - IBee getIndividual(); - - ItemStack getMemberStack(EnumBeeType beeType); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.genetics; + +import forestry.api.apiculture.EnumBeeType; +import forestry.api.apiculture.IBee; +import forestry.api.apiculture.IBeeGenome; +import forestry.core.genetics.IGeneticDefinition; +import net.minecraft.item.ItemStack; + +public interface IBeeDefinition extends IGeneticDefinition { + @Override + IBeeGenome getGenome(); + + @Override + IBee getIndividual(); + + ItemStack getMemberStack(EnumBeeType beeType); +} diff --git a/src/main/java/forestry/apiculture/genetics/JubilanceDefault.java b/src/main/java/forestry/apiculture/genetics/JubilanceDefault.java index 9f91162f0..e203a3e93 100755 --- a/src/main/java/forestry/apiculture/genetics/JubilanceDefault.java +++ b/src/main/java/forestry/apiculture/genetics/JubilanceDefault.java @@ -19,18 +19,15 @@ import forestry.api.core.EnumTemperature; public class JubilanceDefault implements IJubilanceProvider { - public static final JubilanceDefault instance = new JubilanceDefault(); + public static final JubilanceDefault instance = new JubilanceDefault(); - protected JubilanceDefault() { + protected JubilanceDefault() {} - } - - @Override - public boolean isJubilant(IAlleleBeeSpecies species, IBeeGenome genome, IBeeHousing housing) { - EnumTemperature temperature = housing.getTemperature(); - EnumHumidity humidity = housing.getHumidity(); - - return temperature == species.getTemperature() && humidity == species.getHumidity(); - } + @Override + public boolean isJubilant(IAlleleBeeSpecies species, IBeeGenome genome, IBeeHousing housing) { + EnumTemperature temperature = housing.getTemperature(); + EnumHumidity humidity = housing.getHumidity(); + return temperature == species.getTemperature() && humidity == species.getHumidity(); + } } diff --git a/src/main/java/forestry/apiculture/genetics/JubilanceFactory.java b/src/main/java/forestry/apiculture/genetics/JubilanceFactory.java index f65c15cf6..1a2aab9cb 100644 --- a/src/main/java/forestry/apiculture/genetics/JubilanceFactory.java +++ b/src/main/java/forestry/apiculture/genetics/JubilanceFactory.java @@ -1,28 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.genetics; - -import net.minecraft.block.Block; - -import forestry.api.apiculture.IJubilanceFactory; -import forestry.api.apiculture.IJubilanceProvider; - -public class JubilanceFactory implements IJubilanceFactory { - @Override - public IJubilanceProvider getDefault() { - return JubilanceDefault.instance; - } - - @Override - public IJubilanceProvider getRequiresResource(Block block, int meta) { - return new JubilanceRequiresResource(block, meta); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.genetics; + +import forestry.api.apiculture.IJubilanceFactory; +import forestry.api.apiculture.IJubilanceProvider; +import net.minecraft.block.Block; + +public class JubilanceFactory implements IJubilanceFactory { + @Override + public IJubilanceProvider getDefault() { + return JubilanceDefault.instance; + } + + @Override + public IJubilanceProvider getRequiresResource(Block block, int meta) { + return new JubilanceRequiresResource(block, meta); + } +} diff --git a/src/main/java/forestry/apiculture/genetics/JubilanceProviderHermit.java b/src/main/java/forestry/apiculture/genetics/JubilanceProviderHermit.java index bb8277784..bc87cd2ca 100755 --- a/src/main/java/forestry/apiculture/genetics/JubilanceProviderHermit.java +++ b/src/main/java/forestry/apiculture/genetics/JubilanceProviderHermit.java @@ -10,22 +10,20 @@ ******************************************************************************/ package forestry.apiculture.genetics; -import java.util.List; - -import net.minecraft.entity.EntityLiving; - import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.apiculture.genetics.alleles.AlleleEffect; +import java.util.List; +import net.minecraft.entity.EntityLiving; /** * Hermits will not produce if there are any other living creatures nearby. */ public class JubilanceProviderHermit extends JubilanceDefault { - @Override - public boolean isJubilant(IAlleleBeeSpecies species, IBeeGenome genome, IBeeHousing housing) { - List list = AlleleEffect.getEntitiesInRange(genome, housing, EntityLiving.class); - return list.size() <= 0; - } + @Override + public boolean isJubilant(IAlleleBeeSpecies species, IBeeGenome genome, IBeeHousing housing) { + List list = AlleleEffect.getEntitiesInRange(genome, housing, EntityLiving.class); + return list.size() <= 0; + } } diff --git a/src/main/java/forestry/apiculture/genetics/JubilanceRequiresResource.java b/src/main/java/forestry/apiculture/genetics/JubilanceRequiresResource.java index 401217547..7623adb36 100644 --- a/src/main/java/forestry/apiculture/genetics/JubilanceRequiresResource.java +++ b/src/main/java/forestry/apiculture/genetics/JubilanceRequiresResource.java @@ -16,45 +16,51 @@ import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IJubilanceProvider; import forestry.core.utils.BlockUtil; import forestry.core.utils.InventoryUtil; -import forestry.core.utils.ItemStackUtil; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -//import forestry.core.utils.ItemStackUtil; +// import forestry.core.utils.ItemStackUtil; public class JubilanceRequiresResource implements IJubilanceProvider { - private final ItemStack blockRequired; + private final ItemStack blockRequired; - public JubilanceRequiresResource(Block block, int meta) { - this.blockRequired = new ItemStack(block, meta); - } + public JubilanceRequiresResource(Block block, int meta) { + this.blockRequired = new ItemStack(block, meta); + } - @Override - public boolean isJubilant(IAlleleBeeSpecies species, IBeeGenome genome, IBeeHousing housing) { - World world = housing.getWorld(); - ChunkCoordinates housingCoords = housing.getCoordinates(); -/* - Block block; - TileEntity tile; - int meta; - int i = 1; - do { - block = world.getBlock(housingCoords.posX, housingCoords.posY - i, housingCoords.posZ); - meta = world.getBlockMetadata(housingCoords.posX, housingCoords.posY - i, housingCoords.posZ); - tile = world.getTileEntity(housingCoords.posX, housingCoords.posY - i, housingCoords.posZ); - i++; - } while (tile instanceof IBeeHousing); + @Override + public boolean isJubilant(IAlleleBeeSpecies species, IBeeGenome genome, IBeeHousing housing) { + World world = housing.getWorld(); + ChunkCoordinates housingCoords = housing.getCoordinates(); + /* + Block block; + TileEntity tile; + int meta; + int i = 1; + do { + block = world.getBlock(housingCoords.posX, housingCoords.posY - i, housingCoords.posZ); + meta = world.getBlockMetadata(housingCoords.posX, housingCoords.posY - i, housingCoords.posZ); + tile = world.getTileEntity(housingCoords.posX, housingCoords.posY - i, housingCoords.posZ); + i++; + } while (tile instanceof IBeeHousing); - return ItemStackUtil.equals(block, meta, blockRequired); -*/ - ItemStack stk = BlockUtil.getItemStackFromBlockBelow(world, housingCoords.posX, housingCoords.posY, housingCoords.posZ, - (TileEntity tile) -> (tile instanceof IBeeHousing) - ); - - return InventoryUtil.isItemEqual(blockRequired, stk, true, true); //ffs dont compare itemsstacks with equal >_> and why tf didnt i got this until i debugged it? im getting old.. - } + return ItemStackUtil.equals(block, meta, blockRequired); + */ + ItemStack stk = BlockUtil.getItemStackFromBlockBelow( + world, + housingCoords.posX, + housingCoords.posY, + housingCoords.posZ, + (TileEntity tile) -> (tile instanceof IBeeHousing)); + return InventoryUtil.isItemEqual( + blockRequired, + stk, + true, + true); // ffs dont compare itemsstacks with equal >_> and why tf didnt i got this until i debugged it? + // im getting old.. + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleBeeSpecies.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleBeeSpecies.java index 4234ee7d9..81e5ce1fc 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleBeeSpecies.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleBeeSpecies.java @@ -10,21 +10,9 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.IAlleleBeeSpeciesCustom; @@ -42,172 +30,189 @@ import forestry.apiculture.genetics.DefaultBeeIconProvider; import forestry.apiculture.genetics.JubilanceDefault; import forestry.core.genetics.alleles.AlleleSpecies; import forestry.core.utils.ItemStackUtil; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; public class AlleleBeeSpecies extends AlleleSpecies implements IAlleleBeeSpeciesCustom { - private final Map productChances = new HashMap<>(); - private final Map specialtyChances = new HashMap<>(); + private final Map productChances = new HashMap<>(); + private final Map specialtyChances = new HashMap<>(); - private IBeeIconProvider beeIconProvider; - private IBeeIconColourProvider beeIconColourProvider; - private IJubilanceProvider jubilanceProvider; - private boolean nocturnal = false; + private IBeeIconProvider beeIconProvider; + private IBeeIconColourProvider beeIconColourProvider; + private IJubilanceProvider jubilanceProvider; + private boolean nocturnal = false; - public AlleleBeeSpecies(String uid, String unlocalizedName, String authority, String unlocalizedDescription, boolean dominant, IClassification branch, String binomial, int primaryColor, int secondaryColor) { - super(uid, unlocalizedName, authority, unlocalizedDescription, dominant, branch, binomial); + public AlleleBeeSpecies( + String uid, + String unlocalizedName, + String authority, + String unlocalizedDescription, + boolean dominant, + IClassification branch, + String binomial, + int primaryColor, + int secondaryColor) { + super(uid, unlocalizedName, authority, unlocalizedDescription, dominant, branch, binomial); - beeIconProvider = DefaultBeeIconProvider.instance; - beeIconColourProvider = new DefaultBeeIconColourProvider(primaryColor, secondaryColor); - jubilanceProvider = JubilanceDefault.instance; - } + beeIconProvider = DefaultBeeIconProvider.instance; + beeIconColourProvider = new DefaultBeeIconColourProvider(primaryColor, secondaryColor); + jubilanceProvider = JubilanceDefault.instance; + } - @Override - public IBeeRoot getRoot() { - return BeeManager.beeRoot; - } + @Override + public IBeeRoot getRoot() { + return BeeManager.beeRoot; + } - @Override - public IAlleleBeeSpeciesCustom addProduct(ItemStack product, Float chance) { - if (product == null || product.getItem() == null) { - throw new IllegalArgumentException("Tried to add null product"); - } - if (chance <= 0.0f || chance > 1.0f) { - throw new IllegalArgumentException("chance must be in the range (0, 1]"); - } - this.productChances.put(product, chance); - return this; - } + @Override + public IAlleleBeeSpeciesCustom addProduct(ItemStack product, Float chance) { + if (product == null || product.getItem() == null) { + throw new IllegalArgumentException("Tried to add null product"); + } + if (chance <= 0.0f || chance > 1.0f) { + throw new IllegalArgumentException("chance must be in the range (0, 1]"); + } + this.productChances.put(product, chance); + return this; + } - @Override - public IAlleleBeeSpeciesCustom addSpecialty(ItemStack specialty, Float chance) { - if (specialty == null || specialty.getItem() == null) { - throw new IllegalArgumentException("Tried to add null specialty"); - } - if (chance <= 0.0f || chance > 1.0f) { - throw new IllegalArgumentException("chance must be in the range (0, 1]"); - } - this.specialtyChances.put(specialty, chance); - return this; - } + @Override + public IAlleleBeeSpeciesCustom addSpecialty(ItemStack specialty, Float chance) { + if (specialty == null || specialty.getItem() == null) { + throw new IllegalArgumentException("Tried to add null specialty"); + } + if (chance <= 0.0f || chance > 1.0f) { + throw new IllegalArgumentException("chance must be in the range (0, 1]"); + } + this.specialtyChances.put(specialty, chance); + return this; + } - @Override - public IAlleleBeeSpeciesCustom setJubilanceProvider(IJubilanceProvider provider) { - this.jubilanceProvider = provider; - return this; - } + @Override + public IAlleleBeeSpeciesCustom setJubilanceProvider(IJubilanceProvider provider) { + this.jubilanceProvider = provider; + return this; + } - @Override - public IAlleleBeeSpeciesCustom setNocturnal() { - nocturnal = true; - return this; - } + @Override + public IAlleleBeeSpeciesCustom setNocturnal() { + nocturnal = true; + return this; + } - @Override - public IAlleleBeeSpeciesCustom setCustomBeeIconProvider(IBeeIconProvider beeIconProvider) { - this.beeIconProvider = beeIconProvider; - return this; - } + @Override + public IAlleleBeeSpeciesCustom setCustomBeeIconProvider(IBeeIconProvider beeIconProvider) { + this.beeIconProvider = beeIconProvider; + return this; + } - @Override - public IAlleleBeeSpeciesCustom setCustomBeeIconColourProvider(IBeeIconColourProvider beeIconColourProvider) { - this.beeIconColourProvider = beeIconColourProvider; - return this; - } + @Override + public IAlleleBeeSpeciesCustom setCustomBeeIconColourProvider(IBeeIconColourProvider beeIconColourProvider) { + this.beeIconColourProvider = beeIconColourProvider; + return this; + } - /* RESEARCH */ - @Override - public float getResearchSuitability(ItemStack itemstack) { - if (itemstack == null) { - return 0f; - } + /* RESEARCH */ + @Override + public float getResearchSuitability(ItemStack itemstack) { + if (itemstack == null) { + return 0f; + } - for (ItemStack stack : productChances.keySet()) { - if (stack.isItemEqual(itemstack)) { - return 1.0f; - } - } - for (ItemStack stack : specialtyChances.keySet()) { - if (stack.isItemEqual(itemstack)) { - return 1.0f; - } - } + for (ItemStack stack : productChances.keySet()) { + if (stack.isItemEqual(itemstack)) { + return 1.0f; + } + } + for (ItemStack stack : specialtyChances.keySet()) { + if (stack.isItemEqual(itemstack)) { + return 1.0f; + } + } - return super.getResearchSuitability(itemstack); - } + return super.getResearchSuitability(itemstack); + } - @Override - public ItemStack[] getResearchBounty(World world, GameProfile researcher, IIndividual individual, int bountyLevel) { - ArrayList bounty = new ArrayList<>(); - Collections.addAll(bounty, super.getResearchBounty(world, researcher, individual, bountyLevel)); + @Override + public ItemStack[] getResearchBounty(World world, GameProfile researcher, IIndividual individual, int bountyLevel) { + ArrayList bounty = new ArrayList<>(); + Collections.addAll(bounty, super.getResearchBounty(world, researcher, individual, bountyLevel)); - if (bountyLevel > 10) { - for (ItemStack stack : specialtyChances.keySet()) { - bounty.add(ItemStackUtil.copyWithRandomSize(stack, (int) ((float) bountyLevel / 2), world.rand)); - } - } - for (ItemStack stack : productChances.keySet()) { - bounty.add(ItemStackUtil.copyWithRandomSize(stack, (int) ((float) bountyLevel / 2), world.rand)); - } - return bounty.toArray(new ItemStack[bounty.size()]); - } + if (bountyLevel > 10) { + for (ItemStack stack : specialtyChances.keySet()) { + bounty.add(ItemStackUtil.copyWithRandomSize(stack, (int) ((float) bountyLevel / 2), world.rand)); + } + } + for (ItemStack stack : productChances.keySet()) { + bounty.add(ItemStackUtil.copyWithRandomSize(stack, (int) ((float) bountyLevel / 2), world.rand)); + } + return bounty.toArray(new ItemStack[bounty.size()]); + } - /* OTHER */ - @Override - public boolean isNocturnal() { - return nocturnal; - } + /* OTHER */ + @Override + public boolean isNocturnal() { + return nocturnal; + } - @Override - public Map getProductChances() { - return productChances; - } + @Override + public Map getProductChances() { + return productChances; + } - @Override - public Map getSpecialtyChances() { - return specialtyChances; - } + @Override + public Map getSpecialtyChances() { + return specialtyChances; + } - @Override - public boolean isJubilant(IBeeGenome genome, IBeeHousing housing) { - return jubilanceProvider.isJubilant(this, genome, housing); - } + @Override + public boolean isJubilant(IBeeGenome genome, IBeeHousing housing) { + return jubilanceProvider.isJubilant(this, genome, housing); + } - @Override - @SideOnly(Side.CLIENT) - public IIconProvider getIconProvider() { - return new BeeIconProviderWrapper(beeIconProvider); - } + @Override + @SideOnly(Side.CLIENT) + public IIconProvider getIconProvider() { + return new BeeIconProviderWrapper(beeIconProvider); + } - @Override - public IIcon getIcon(EnumBeeType type, int renderPass) { - return beeIconProvider.getIcon(type, renderPass); - } + @Override + public IIcon getIcon(EnumBeeType type, int renderPass) { + return beeIconProvider.getIcon(type, renderPass); + } - @Override - public int getIconColour(int renderPass) { - return beeIconColourProvider.getIconColour(renderPass); - } + @Override + public int getIconColour(int renderPass) { + return beeIconColourProvider.getIconColour(renderPass); + } - @Override - public String getEntityTexture() { - return null; - } + @Override + public String getEntityTexture() { + return null; + } - private static class BeeIconProviderWrapper implements IIconProvider { + private static class BeeIconProviderWrapper implements IIconProvider { - private final IBeeIconProvider beeIconProvider; + private final IBeeIconProvider beeIconProvider; - public BeeIconProviderWrapper(IBeeIconProvider beeIconProvider) { - this.beeIconProvider = beeIconProvider; - } + public BeeIconProviderWrapper(IBeeIconProvider beeIconProvider) { + this.beeIconProvider = beeIconProvider; + } - @Override - public IIcon getIcon(short texUID) { - return null; - } + @Override + public IIcon getIcon(short texUID) { + return null; + } - @Override - public void registerIcons(IIconRegister register) { - beeIconProvider.registerIcons(register); - } - } + @Override + public void registerIcons(IIconRegister register) { + beeIconProvider.registerIcons(register); + } + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffect.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffect.java index c95047651..082ab879d 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffect.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffect.java @@ -10,15 +10,6 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import java.util.Arrays; -import java.util.List; - -import net.minecraft.entity.Entity; -import net.minecraft.potion.Potion; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.Vec3; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.IAlleleBeeEffect; @@ -32,129 +23,144 @@ import forestry.core.proxy.Proxies; import forestry.core.utils.EntityUtil; import forestry.core.utils.vect.MutableVect; import forestry.core.utils.vect.Vect; +import java.util.Arrays; +import java.util.List; +import net.minecraft.entity.Entity; +import net.minecraft.potion.Potion; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.Vec3; public abstract class AlleleEffect extends AlleleCategorized implements IAlleleBeeEffect { - public static IAlleleBeeEffect effectNone; - public static IAlleleBeeEffect effectAggressive; - public static IAlleleBeeEffect effectHeroic; - public static IAlleleBeeEffect effectBeatific; - public static IAlleleBeeEffect effectMiasmic; - public static IAlleleBeeEffect effectMisanthrope; - public static IAlleleBeeEffect effectGlacial; - public static IAlleleBeeEffect effectRadioactive; - public static IAlleleBeeEffect effectCreeper; - public static IAlleleBeeEffect effectIgnition; - public static IAlleleBeeEffect effectExploration; - public static IAlleleBeeEffect effectFestiveEaster; - public static IAlleleBeeEffect effectSnowing; - public static IAlleleBeeEffect effectDrunkard; - public static IAlleleBeeEffect effectReanimation; - public static IAlleleBeeEffect effectResurrection; - public static IAlleleBeeEffect effectRepulsion; - public static IAlleleBeeEffect effectFertile; - public static IAlleleBeeEffect effectMycophilic; + public static IAlleleBeeEffect effectNone; + public static IAlleleBeeEffect effectAggressive; + public static IAlleleBeeEffect effectHeroic; + public static IAlleleBeeEffect effectBeatific; + public static IAlleleBeeEffect effectMiasmic; + public static IAlleleBeeEffect effectMisanthrope; + public static IAlleleBeeEffect effectGlacial; + public static IAlleleBeeEffect effectRadioactive; + public static IAlleleBeeEffect effectCreeper; + public static IAlleleBeeEffect effectIgnition; + public static IAlleleBeeEffect effectExploration; + public static IAlleleBeeEffect effectFestiveEaster; + public static IAlleleBeeEffect effectSnowing; + public static IAlleleBeeEffect effectDrunkard; + public static IAlleleBeeEffect effectReanimation; + public static IAlleleBeeEffect effectResurrection; + public static IAlleleBeeEffect effectRepulsion; + public static IAlleleBeeEffect effectFertile; + public static IAlleleBeeEffect effectMycophilic; - public static void createAlleles() { - List beeEffects = Arrays.asList( - effectNone = new AlleleEffectNone("none", true), - effectAggressive = new AlleleEffectAggressive(), - effectHeroic = new AlleleEffectHeroic(), - effectBeatific = new AlleleEffectPotion("beatific", false, Potion.regeneration, 100), - effectMiasmic = new AlleleEffectPotion("miasmic", false, Potion.poison, 600, 100, 0.1f), - effectMisanthrope = new AlleleEffectMisanthrope(), - effectGlacial = new AlleleEffectGlacial(), - effectRadioactive = new AlleleEffectRadioactive(), - effectCreeper = new AlleleEffectCreeper(), - effectIgnition = new AlleleEffectIgnition(), - effectExploration = new AlleleEffectExploration(), - effectFestiveEaster = new AlleleEffectNone("festiveEaster", true), - effectSnowing = new AlleleEffectSnowing(), - effectDrunkard = new AlleleEffectPotion("drunkard", false, Potion.confusion, 100), - effectReanimation = new AlleleEffectResurrection("reanimation", AlleleEffectResurrection.getReanimationList()), - effectResurrection = new AlleleEffectResurrection("resurrection", AlleleEffectResurrection.getResurrectionList()), - effectRepulsion = new AlleleEffectRepulsion(), - effectFertile = new AlleleEffectFertile(), - effectMycophilic = new AlleleEffectFungification() - ); + public static void createAlleles() { + List beeEffects = Arrays.asList( + effectNone = new AlleleEffectNone("none", true), + effectAggressive = new AlleleEffectAggressive(), + effectHeroic = new AlleleEffectHeroic(), + effectBeatific = new AlleleEffectPotion("beatific", false, Potion.regeneration, 100), + effectMiasmic = new AlleleEffectPotion("miasmic", false, Potion.poison, 600, 100, 0.1f), + effectMisanthrope = new AlleleEffectMisanthrope(), + effectGlacial = new AlleleEffectGlacial(), + effectRadioactive = new AlleleEffectRadioactive(), + effectCreeper = new AlleleEffectCreeper(), + effectIgnition = new AlleleEffectIgnition(), + effectExploration = new AlleleEffectExploration(), + effectFestiveEaster = new AlleleEffectNone("festiveEaster", true), + effectSnowing = new AlleleEffectSnowing(), + effectDrunkard = new AlleleEffectPotion("drunkard", false, Potion.confusion, 100), + effectReanimation = + new AlleleEffectResurrection("reanimation", AlleleEffectResurrection.getReanimationList()), + effectResurrection = + new AlleleEffectResurrection("resurrection", AlleleEffectResurrection.getResurrectionList()), + effectRepulsion = new AlleleEffectRepulsion(), + effectFertile = new AlleleEffectFertile(), + effectMycophilic = new AlleleEffectFungification()); - for (IAlleleBeeEffect beeEffect : beeEffects) { - AlleleManager.alleleRegistry.registerAllele(beeEffect, EnumBeeChromosome.EFFECT); - } - } + for (IAlleleBeeEffect beeEffect : beeEffects) { + AlleleManager.alleleRegistry.registerAllele(beeEffect, EnumBeeChromosome.EFFECT); + } + } - protected AlleleEffect(String valueName, boolean isDominant) { - super("forestry", "effect", valueName, isDominant); - } + protected AlleleEffect(String valueName, boolean isDominant) { + super("forestry", "effect", valueName, isDominant); + } - @Override - public IEffectData validateStorage(IEffectData storedData) { - return null; - } + @Override + public IEffectData validateStorage(IEffectData storedData) { + return null; + } - @Override - public boolean isCombinable() { - return false; - } + @Override + public boolean isCombinable() { + return false; + } - @Override - public IEffectData doEffect(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - return storedData; - } + @Override + public IEffectData doEffect(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + return storedData; + } - @Override - public IEffectData doFX(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - Vec3 beeFXCoordinates = getFXCoordinates(housing); - Proxies.render.addBeeHiveFX("particles/swarm_bee", housing.getWorld(), beeFXCoordinates.xCoord, beeFXCoordinates.yCoord, beeFXCoordinates.zCoord, genome.getPrimary().getIconColour(0)); - return storedData; - } + @Override + public IEffectData doFX(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + Vec3 beeFXCoordinates = getFXCoordinates(housing); + Proxies.render.addBeeHiveFX( + "particles/swarm_bee", + housing.getWorld(), + beeFXCoordinates.xCoord, + beeFXCoordinates.yCoord, + beeFXCoordinates.zCoord, + genome.getPrimary().getIconColour(0)); + return storedData; + } - protected Vec3 getFXCoordinates(IBeeHousing housing) { - try { - return housing.getBeeFXCoordinates(); - } catch (Throwable error) { - // getBeeFXCoordinates() is only newly added to the API, fall back on getCoordinates() - ChunkCoordinates coordinates = housing.getCoordinates(); - return Vec3.createVectorHelper(coordinates.posX + 0.5D, coordinates.posY + 0.5D, coordinates.posZ + 0.5D); - } - } + protected Vec3 getFXCoordinates(IBeeHousing housing) { + try { + return housing.getBeeFXCoordinates(); + } catch (Throwable error) { + // getBeeFXCoordinates() is only newly added to the API, fall back on getCoordinates() + ChunkCoordinates coordinates = housing.getCoordinates(); + return Vec3.createVectorHelper(coordinates.posX + 0.5D, coordinates.posY + 0.5D, coordinates.posZ + 0.5D); + } + } - protected Vect getModifiedArea(IBeeGenome genome, IBeeHousing housing) { - IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - float territoryModifier = beeModifier.getTerritoryModifier(genome, 1f); + protected Vect getModifiedArea(IBeeGenome genome, IBeeHousing housing) { + IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); + float territoryModifier = beeModifier.getTerritoryModifier(genome, 1f); - MutableVect area = new MutableVect(genome.getTerritory()); - area.multiply(territoryModifier); + MutableVect area = new MutableVect(genome.getTerritory()); + area.multiply(territoryModifier); - if (area.x < 1) { - area.x = 1; - } - if (area.y < 1) { - area.y = 1; - } - if (area.z < 1) { - area.z = 1; - } + if (area.x < 1) { + area.x = 1; + } + if (area.y < 1) { + area.y = 1; + } + if (area.z < 1) { + area.z = 1; + } - return new Vect(area); - } + return new Vect(area); + } - public static AxisAlignedBB getBounding(IBeeGenome genome, IBeeHousing housing) { - IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); - float territoryModifier = beeModifier.getTerritoryModifier(genome, 1.0f); + public static AxisAlignedBB getBounding(IBeeGenome genome, IBeeHousing housing) { + IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); + float territoryModifier = beeModifier.getTerritoryModifier(genome, 1.0f); - MutableVect area = new MutableVect(genome.getTerritory()); - area.multiply(territoryModifier); - Vect offset = new Vect(area).multiply(-1 / 2.0f); + MutableVect area = new MutableVect(genome.getTerritory()); + area.multiply(territoryModifier); + Vect offset = new Vect(area).multiply(-1 / 2.0f); - Vect min = new Vect(housing.getCoordinates()).add(offset); - Vect max = min.add(area); + Vect min = new Vect(housing.getCoordinates()).add(offset); + Vect max = min.add(area); - return AxisAlignedBB.getBoundingBox(min.x, min.y, min.z, max.x, max.y, max.z); - } + return AxisAlignedBB.getBoundingBox(min.x, min.y, min.z, max.x, max.y, max.z); + } - public static List getEntitiesInRange(IBeeGenome genome, IBeeHousing housing, Class entityClass) { - AxisAlignedBB boundingBox = getBounding(genome, housing); - return EntityUtil.getEntitiesWithinAABB(housing.getWorld(), entityClass, boundingBox); - } + public static List getEntitiesInRange( + IBeeGenome genome, IBeeHousing housing, Class entityClass) { + AxisAlignedBB boundingBox = getBounding(genome, housing); + return EntityUtil.getEntitiesWithinAABB(housing.getWorld(), entityClass, boundingBox); + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectAggressive.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectAggressive.java index 6a1aa9238..f0a78ffa3 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectAggressive.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectAggressive.java @@ -10,41 +10,38 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import java.util.List; - -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.util.DamageSource; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.genetics.IEffectData; import forestry.core.utils.DamageSourceForestry; +import java.util.List; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.DamageSource; public class AlleleEffectAggressive extends AlleleEffectThrottled { - private static final DamageSource damageSourceBeeAggressive = new DamageSourceForestry("bee.aggressive"); + private static final DamageSource damageSourceBeeAggressive = new DamageSourceForestry("bee.aggressive"); - public AlleleEffectAggressive() { - super("aggressive", true, 40, false, false); - } + public AlleleEffectAggressive() { + super("aggressive", true, 40, false, false); + } - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - List entities = getEntitiesInRange(genome, housing, EntityLivingBase.class); - for (EntityLivingBase entity : entities) { - int damage = 4; + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + List entities = getEntitiesInRange(genome, housing, EntityLivingBase.class); + for (EntityLivingBase entity : entities) { + int damage = 4; - // Entities are not attacked if they wear a full set of apiarist's armor. - int count = BeeManager.armorApiaristHelper.wearsItems(entity, getUID(), true); - damage -= count; - if (damage <= 0) { - continue; - } + // Entities are not attacked if they wear a full set of apiarist's armor. + int count = BeeManager.armorApiaristHelper.wearsItems(entity, getUID(), true); + damage -= count; + if (damage <= 0) { + continue; + } - entity.attackEntityFrom(damageSourceBeeAggressive, damage); - } - - return storedData; - } + entity.attackEntityFrom(damageSourceBeeAggressive, damage); + } + return storedData; + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectCreeper.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectCreeper.java index 26b426318..24eec6dbc 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectCreeper.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectCreeper.java @@ -10,97 +10,99 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.genetics.IEffectData; import forestry.core.genetics.EffectData; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; public class AlleleEffectCreeper extends AlleleEffectThrottled { - private static final int explosionChance = 50; - private static final byte defaultForce = 12; - private static final byte indexExplosionTimer = 1; - private static final byte indexExplosionForce = 2; + private static final int explosionChance = 50; + private static final byte defaultForce = 12; + private static final byte indexExplosionTimer = 1; + private static final byte indexExplosionForce = 2; - public AlleleEffectCreeper() { - super("creeper", true, 20, false, true); - } + public AlleleEffectCreeper() { + super("creeper", true, 20, false, true); + } - @Override - public IEffectData validateStorage(IEffectData storedData) { - if (!(storedData instanceof EffectData)) { - return new EffectData(3, 0); - } + @Override + public IEffectData validateStorage(IEffectData storedData) { + if (!(storedData instanceof EffectData)) { + return new EffectData(3, 0); + } - if (((EffectData) storedData).getIntSize() < 3) { - return new EffectData(3, 0); - } + if (((EffectData) storedData).getIntSize() < 3) { + return new EffectData(3, 0); + } - return storedData; - } + return storedData; + } - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - World world = housing.getWorld(); - ChunkCoordinates housingCoords = housing.getCoordinates(); + World world = housing.getWorld(); + ChunkCoordinates housingCoords = housing.getCoordinates(); - // If we are already triggered, we continue the explosion sequence. - if (storedData.getInteger(indexExplosionTimer) > 0) { - progressExplosion(storedData, world, housingCoords.posX, housingCoords.posY, housingCoords.posZ); - return storedData; - } + // If we are already triggered, we continue the explosion sequence. + if (storedData.getInteger(indexExplosionTimer) > 0) { + progressExplosion(storedData, world, housingCoords.posX, housingCoords.posY, housingCoords.posZ); + return storedData; + } - List players = getEntitiesInRange(genome, housing, EntityPlayer.class); - for (EntityPlayer player : players) { - int chance = explosionChance; - storedData.setInteger(indexExplosionForce, defaultForce); + List players = getEntitiesInRange(genome, housing, EntityPlayer.class); + for (EntityPlayer player : players) { + int chance = explosionChance; + storedData.setInteger(indexExplosionForce, defaultForce); - // Entities are not attacked if they wear a full set of apiarist's armor. - int count = BeeManager.armorApiaristHelper.wearsItems(player, getUID(), true); - if (count > 3) { - continue; // Full set, no damage/effect - } else if (count > 2) { - chance = 5; - storedData.setInteger(indexExplosionForce, 6); - } else if (count > 1) { - chance = 20; - storedData.setInteger(indexExplosionForce, 8); - } else if (count > 0) { - chance = 35; - storedData.setInteger(indexExplosionForce, 10); - } + // Entities are not attacked if they wear a full set of apiarist's armor. + int count = BeeManager.armorApiaristHelper.wearsItems(player, getUID(), true); + if (count > 3) { + continue; // Full set, no damage/effect + } else if (count > 2) { + chance = 5; + storedData.setInteger(indexExplosionForce, 6); + } else if (count > 1) { + chance = 20; + storedData.setInteger(indexExplosionForce, 8); + } else if (count > 0) { + chance = 35; + storedData.setInteger(indexExplosionForce, 10); + } - if (world.rand.nextInt(1000) >= chance) { - continue; - } + if (world.rand.nextInt(1000) >= chance) { + continue; + } - world.playSoundEffect(housingCoords.posX, housingCoords.posY, housingCoords.posZ, "mob.creeper", 4F, - (1.0F + (world.rand.nextFloat() - world.rand.nextFloat()) * 0.2F) * 0.7F); - storedData.setInteger(indexExplosionTimer, 2); // Set explosion timer - } + world.playSoundEffect( + housingCoords.posX, + housingCoords.posY, + housingCoords.posZ, + "mob.creeper", + 4F, + (1.0F + (world.rand.nextFloat() - world.rand.nextFloat()) * 0.2F) * 0.7F); + storedData.setInteger(indexExplosionTimer, 2); // Set explosion timer + } - return storedData; - } + return storedData; + } - private static void progressExplosion(IEffectData storedData, World world, int x, int y, int z) { + private static void progressExplosion(IEffectData storedData, World world, int x, int y, int z) { - int explosionTimer = storedData.getInteger(indexExplosionTimer); - explosionTimer--; - storedData.setInteger(indexExplosionTimer, explosionTimer); + int explosionTimer = storedData.getInteger(indexExplosionTimer); + explosionTimer--; + storedData.setInteger(indexExplosionTimer, explosionTimer); - if (explosionTimer > 0) { - return; - } - - world.createExplosion(null, x, y, z, storedData.getInteger(indexExplosionForce), false); - } + if (explosionTimer > 0) { + return; + } + world.createExplosion(null, x, y, z, storedData.getInteger(indexExplosionForce), false); + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectExploration.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectExploration.java index 7624b2bae..ad2709c8a 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectExploration.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectExploration.java @@ -10,28 +10,25 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; - import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.genetics.IEffectData; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; public class AlleleEffectExploration extends AlleleEffectThrottled { - public AlleleEffectExploration() { - super("exploration", false, 80, true, false); - } + public AlleleEffectExploration() { + super("exploration", false, 80, true, false); + } - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - List players = getEntitiesInRange(genome, housing, EntityPlayer.class); - for (EntityPlayer player : players) { - player.addExperience(2); - } - - return storedData; - } + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + List players = getEntitiesInRange(genome, housing, EntityPlayer.class); + for (EntityPlayer player : players) { + player.addExperience(2); + } + return storedData; + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectFertile.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectFertile.java index efcba3f62..2c45f77e8 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectFertile.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectFertile.java @@ -10,64 +10,60 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.block.IGrowable; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; - -import net.minecraftforge.common.IPlantable; - import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.genetics.IEffectData; import forestry.core.utils.vect.IVect; +import java.util.Random; +import net.minecraft.block.Block; +import net.minecraft.block.IGrowable; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; +import net.minecraftforge.common.IPlantable; public class AlleleEffectFertile extends AlleleEffectThrottled { - - private static final int MAX_BLOCK_FIND_TRIES = 5; - public AlleleEffectFertile() { - super("fertile", false, 6, true, false); - } + private static final int MAX_BLOCK_FIND_TRIES = 5; - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - - World world = housing.getWorld(); - ChunkCoordinates housingCoordinates = housing.getCoordinates(); - IVect area = getModifiedArea(genome, housing); - - int blockX = getRandomOffset(world.rand, housingCoordinates.posX, area.getX()); - int blockZ = getRandomOffset(world.rand, housingCoordinates.posZ, area.getZ()); - int blockMaxY = housingCoordinates.posY + (area.getY() / 2) + 1; - int blockMinY = housingCoordinates.posY - (area.getY() / 2) - 1; - - for (int attempt = 0; attempt < MAX_BLOCK_FIND_TRIES; ++attempt) { - if (tryTickColumn(world, blockX, blockZ, blockMaxY, blockMinY)) { - break; - } - blockX = getRandomOffset(world.rand, housingCoordinates.posX, area.getX()); - blockZ = getRandomOffset(world.rand, housingCoordinates.posZ, area.getZ()); - } - - return storedData; - } - - private static int getRandomOffset(Random random, int centrePos, int offset) { - return centrePos + random.nextInt(offset) - (offset / 2); - } + public AlleleEffectFertile() { + super("fertile", false, 6, true, false); + } - private static boolean tryTickColumn(World world, int x, int z, int maxY, int minY) { - for (int y = maxY; y >= minY; --y) { - Block block = world.getBlock(x, y, z); - if (block.getTickRandomly() && (block instanceof IGrowable || block instanceof IPlantable)) { - world.scheduleBlockUpdate(x, y, z, block, 5); - return true; - } - } - return false; - } + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + World world = housing.getWorld(); + ChunkCoordinates housingCoordinates = housing.getCoordinates(); + IVect area = getModifiedArea(genome, housing); + + int blockX = getRandomOffset(world.rand, housingCoordinates.posX, area.getX()); + int blockZ = getRandomOffset(world.rand, housingCoordinates.posZ, area.getZ()); + int blockMaxY = housingCoordinates.posY + (area.getY() / 2) + 1; + int blockMinY = housingCoordinates.posY - (area.getY() / 2) - 1; + + for (int attempt = 0; attempt < MAX_BLOCK_FIND_TRIES; ++attempt) { + if (tryTickColumn(world, blockX, blockZ, blockMaxY, blockMinY)) { + break; + } + blockX = getRandomOffset(world.rand, housingCoordinates.posX, area.getX()); + blockZ = getRandomOffset(world.rand, housingCoordinates.posZ, area.getZ()); + } + + return storedData; + } + + private static int getRandomOffset(Random random, int centrePos, int offset) { + return centrePos + random.nextInt(offset) - (offset / 2); + } + + private static boolean tryTickColumn(World world, int x, int z, int maxY, int minY) { + for (int y = maxY; y >= minY; --y) { + Block block = world.getBlock(x, y, z); + if (block.getTickRandomly() && (block instanceof IGrowable || block instanceof IPlantable)) { + world.scheduleBlockUpdate(x, y, z, block, 5); + return true; + } + } + return false; + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectFungification.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectFungification.java index aa3fa0518..dfcc33ea7 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectFungification.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectFungification.java @@ -1,8 +1,12 @@ package forestry.apiculture.genetics.alleles; +import forestry.api.apiculture.IBeeGenome; +import forestry.api.apiculture.IBeeHousing; +import forestry.api.genetics.IEffectData; +import forestry.core.genetics.EffectData; +import forestry.core.utils.vect.IVect; import java.util.List; import java.util.Random; - import net.minecraft.block.Block; import net.minecraft.entity.passive.EntityCow; import net.minecraft.entity.passive.EntityMooshroom; @@ -11,115 +15,109 @@ import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; import net.minecraft.world.gen.feature.WorldGenBigMushroom; -import forestry.api.apiculture.IBeeGenome; -import forestry.api.apiculture.IBeeHousing; -import forestry.api.genetics.IEffectData; -import forestry.core.genetics.EffectData; -import forestry.core.utils.vect.IVect; - public class AlleleEffectFungification extends AlleleEffectThrottled { - private static final int MAX_BLOCK_FIND_TRIES = 10; - private static final int ENTITY_THROTTLE = 6; - - public AlleleEffectFungification() { - super("mycophilic", true, 10, false, false); - } + private static final int MAX_BLOCK_FIND_TRIES = 10; + private static final int ENTITY_THROTTLE = 6; - @Override - public IEffectData validateStorage(IEffectData storedData) { - if (storedData instanceof EffectData && ((EffectData) storedData).getIntSize() == 2) { - return storedData; - } + public AlleleEffectFungification() { + super("mycophilic", true, 10, false, false); + } - return new EffectData(2, 0); - } + @Override + public IEffectData validateStorage(IEffectData storedData) { + if (storedData instanceof EffectData && ((EffectData) storedData).getIntSize() == 2) { + return storedData; + } - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + return new EffectData(2, 0); + } - doBlockEffect(genome, housing); - - int entityThrottle = storedData.getInteger(1); - if (entityThrottle >= ENTITY_THROTTLE) { - doEntityEffect(genome, housing); - entityThrottle = 0; - } else { - ++entityThrottle; - } - storedData.setInteger(1, entityThrottle); - - return storedData; - } + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - private void doBlockEffect(IBeeGenome genome, IBeeHousing housing) { - World world = housing.getWorld(); - ChunkCoordinates housingCoordinates = housing.getCoordinates(); - IVect area = getModifiedArea(genome, housing); - - int blockX = getRandomOffset(world.rand, housingCoordinates.posX, area.getX()); - int blockY = getRandomOffset(world.rand, housingCoordinates.posY, area.getY()); - int blockZ = getRandomOffset(world.rand, housingCoordinates.posZ, area.getZ()); - - for (int attempt = 0; attempt < MAX_BLOCK_FIND_TRIES; ++attempt) { - Block block = world.getBlock(blockX, blockY, blockZ); - if (isSuitableForMycelium(world, block, blockX, blockY, blockZ)) { - world.setBlock(blockX, blockY, blockZ, Blocks.mycelium); - break; - } else if (isSuitableForGrowth(block)) { - doMushroomGrowth(block, world, blockX, blockY, blockZ); - break; - } - blockX = getRandomOffset(world.rand, housingCoordinates.posX, area.getX()); - blockY = getRandomOffset(world.rand, housingCoordinates.posY, area.getY()); - blockZ = getRandomOffset(world.rand, housingCoordinates.posZ, area.getZ()); - } + doBlockEffect(genome, housing); - } + int entityThrottle = storedData.getInteger(1); + if (entityThrottle >= ENTITY_THROTTLE) { + doEntityEffect(genome, housing); + entityThrottle = 0; + } else { + ++entityThrottle; + } + storedData.setInteger(1, entityThrottle); - private static void doEntityEffect(IBeeGenome genome, IBeeHousing housing) { - List cows = getEntitiesInRange(genome, housing, EntityCow.class); - for (EntityCow cow : cows) { - convertCowToMooshroom(cow); - } - } - - private static int getRandomOffset(Random random, int centrePos, int offset) { - return centrePos + random.nextInt(offset) - (offset / 2); - } - - private static boolean isSuitableForMycelium(World world, Block block, int blockX, int blockY, int blockZ) { - return block == Blocks.grass || (block == Blocks.dirt && world.canBlockSeeTheSky(blockX, blockY, blockZ)); - } + return storedData; + } - private static boolean isSuitableForGrowth(Block block) { - return block == Blocks.red_mushroom || block == Blocks.brown_mushroom; - } - - private static void convertCowToMooshroom(EntityCow cow) { - if (cow instanceof EntityMooshroom) { - return; - } - World worldObj = cow.worldObj; - cow.setDead(); - EntityMooshroom mooshroom = new EntityMooshroom(worldObj); - mooshroom.setLocationAndAngles(cow.posX, cow.posY, cow.posZ, cow.rotationYaw, cow.rotationPitch); - mooshroom.setHealth(cow.getHealth()); - mooshroom.renderYawOffset = cow.renderYawOffset; - worldObj.spawnEntityInWorld(mooshroom); - worldObj.spawnParticle("largeexplode", cow.posX, cow.posY + (double) (cow.height / 2.0F), cow.posZ, 0.0D, 0.0D, 0.0D); - } + private void doBlockEffect(IBeeGenome genome, IBeeHousing housing) { + World world = housing.getWorld(); + ChunkCoordinates housingCoordinates = housing.getCoordinates(); + IVect area = getModifiedArea(genome, housing); - private static void doMushroomGrowth(Block block, World world, int blockX, int blockY, int blockZ) { - WorldGenBigMushroom giantMushroomGenerator; + int blockX = getRandomOffset(world.rand, housingCoordinates.posX, area.getX()); + int blockY = getRandomOffset(world.rand, housingCoordinates.posY, area.getY()); + int blockZ = getRandomOffset(world.rand, housingCoordinates.posZ, area.getZ()); - if (block == Blocks.brown_mushroom) { - giantMushroomGenerator = new WorldGenBigMushroom(0); - } else { - giantMushroomGenerator = new WorldGenBigMushroom(1); - } + for (int attempt = 0; attempt < MAX_BLOCK_FIND_TRIES; ++attempt) { + Block block = world.getBlock(blockX, blockY, blockZ); + if (isSuitableForMycelium(world, block, blockX, blockY, blockZ)) { + world.setBlock(blockX, blockY, blockZ, Blocks.mycelium); + break; + } else if (isSuitableForGrowth(block)) { + doMushroomGrowth(block, world, blockX, blockY, blockZ); + break; + } + blockX = getRandomOffset(world.rand, housingCoordinates.posX, area.getX()); + blockY = getRandomOffset(world.rand, housingCoordinates.posY, area.getY()); + blockZ = getRandomOffset(world.rand, housingCoordinates.posZ, area.getZ()); + } + } - world.setBlockToAir(blockX, blockY, blockZ); - giantMushroomGenerator.generate(world, world.rand, blockX, blockY, blockZ); - } + private static void doEntityEffect(IBeeGenome genome, IBeeHousing housing) { + List cows = getEntitiesInRange(genome, housing, EntityCow.class); + for (EntityCow cow : cows) { + convertCowToMooshroom(cow); + } + } + + private static int getRandomOffset(Random random, int centrePos, int offset) { + return centrePos + random.nextInt(offset) - (offset / 2); + } + + private static boolean isSuitableForMycelium(World world, Block block, int blockX, int blockY, int blockZ) { + return block == Blocks.grass || (block == Blocks.dirt && world.canBlockSeeTheSky(blockX, blockY, blockZ)); + } + + private static boolean isSuitableForGrowth(Block block) { + return block == Blocks.red_mushroom || block == Blocks.brown_mushroom; + } + + private static void convertCowToMooshroom(EntityCow cow) { + if (cow instanceof EntityMooshroom) { + return; + } + World worldObj = cow.worldObj; + cow.setDead(); + EntityMooshroom mooshroom = new EntityMooshroom(worldObj); + mooshroom.setLocationAndAngles(cow.posX, cow.posY, cow.posZ, cow.rotationYaw, cow.rotationPitch); + mooshroom.setHealth(cow.getHealth()); + mooshroom.renderYawOffset = cow.renderYawOffset; + worldObj.spawnEntityInWorld(mooshroom); + worldObj.spawnParticle( + "largeexplode", cow.posX, cow.posY + (double) (cow.height / 2.0F), cow.posZ, 0.0D, 0.0D, 0.0D); + } + + private static void doMushroomGrowth(Block block, World world, int blockX, int blockY, int blockZ) { + WorldGenBigMushroom giantMushroomGenerator; + + if (block == Blocks.brown_mushroom) { + giantMushroomGenerator = new WorldGenBigMushroom(0); + } else { + giantMushroomGenerator = new WorldGenBigMushroom(1); + } + + world.setBlockToAir(blockX, blockY, blockZ); + giantMushroomGenerator.generate(world, world.rand, blockX, blockY, blockZ); + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectGlacial.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectGlacial.java index dda24b591..f7d6a2132 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectGlacial.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectGlacial.java @@ -10,60 +10,59 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.world.World; - import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.core.EnumTemperature; import forestry.api.genetics.IEffectData; import forestry.core.config.Constants; import forestry.core.utils.vect.Vect; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.world.World; public class AlleleEffectGlacial extends AlleleEffectThrottled { - public AlleleEffectGlacial() { - super("glacial", false, 200, true, false); - } + public AlleleEffectGlacial() { + super("glacial", false, 200, true, false); + } - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - World world = housing.getWorld(); - EnumTemperature temp = housing.getTemperature(); + World world = housing.getWorld(); + EnumTemperature temp = housing.getTemperature(); - switch (temp) { - case HELLISH: - case HOT: - case WARM: - return storedData; - default: - } + switch (temp) { + case HELLISH: + case HOT: + case WARM: + return storedData; + default: + } - int[] areaAr = genome.getTerritory(); - Vect area = new Vect(areaAr); - Vect offset = area.multiply(-1 / 2.0f); - Vect housingCoords = new Vect(housing.getCoordinates()); + int[] areaAr = genome.getTerritory(); + Vect area = new Vect(areaAr); + Vect offset = area.multiply(-1 / 2.0f); + Vect housingCoords = new Vect(housing.getCoordinates()); - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) { - Vect randomPos = Vect.getRandomPositionInArea(world.rand, area); - Vect posBlock = Vect.add(randomPos, housingCoords, offset); + Vect randomPos = Vect.getRandomPositionInArea(world.rand, area); + Vect posBlock = Vect.add(randomPos, housingCoords, offset); - // Freeze water - Block block = world.getBlock(posBlock.x, posBlock.y, posBlock.z); - if (block != Blocks.water) { - continue; - } + // Freeze water + Block block = world.getBlock(posBlock.x, posBlock.y, posBlock.z); + if (block != Blocks.water) { + continue; + } - if (!world.isAirBlock(posBlock.x, posBlock.y + 1, posBlock.z)) { - continue; - } + if (!world.isAirBlock(posBlock.x, posBlock.y + 1, posBlock.z)) { + continue; + } - world.setBlock(posBlock.x, posBlock.y, posBlock.z, Blocks.ice, 0, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); - } + world.setBlock(posBlock.x, posBlock.y, posBlock.z, Blocks.ice, 0, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); + } - return storedData; - } + return storedData; + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectHeroic.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectHeroic.java index a4fc69348..a9df650ff 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectHeroic.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectHeroic.java @@ -10,30 +10,28 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import java.util.List; - -import net.minecraft.entity.monster.EntityMob; -import net.minecraft.util.DamageSource; - import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.genetics.IEffectData; import forestry.core.utils.DamageSourceForestry; +import java.util.List; +import net.minecraft.entity.monster.EntityMob; +import net.minecraft.util.DamageSource; public class AlleleEffectHeroic extends AlleleEffectThrottled { - private static final DamageSource damageSourceBeeHeroic = new DamageSourceForestry("bee.heroic"); + private static final DamageSource damageSourceBeeHeroic = new DamageSourceForestry("bee.heroic"); - public AlleleEffectHeroic() { - super("heroic", false, 40, true, false); - } + public AlleleEffectHeroic() { + super("heroic", false, 40, true, false); + } - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - List mobs = getEntitiesInRange(genome, housing, EntityMob.class); - for (EntityMob mob : mobs) { - mob.attackEntityFrom(damageSourceBeeHeroic, 2); - } + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + List mobs = getEntitiesInRange(genome, housing, EntityMob.class); + for (EntityMob mob : mobs) { + mob.attackEntityFrom(damageSourceBeeHeroic, 2); + } - return storedData; - } + return storedData; + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectIgnition.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectIgnition.java index 517335ee8..c52d607cf 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectIgnition.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectIgnition.java @@ -10,68 +10,69 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import java.util.List; - -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.genetics.IEffectData; import forestry.core.proxy.Proxies; +import java.util.List; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; public class AlleleEffectIgnition extends AlleleEffectThrottled { - private static final int ignitionChance = 50; - private static final int fireDuration = 500; + private static final int ignitionChance = 50; + private static final int fireDuration = 500; - public AlleleEffectIgnition() { - super("ignition", false, 20, false, true); - } + public AlleleEffectIgnition() { + super("ignition", false, 20, false, true); + } - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - World world = housing.getWorld(); - List entities = getEntitiesInRange(genome, housing, EntityLivingBase.class); - for (EntityLivingBase entity : entities) { - int chance = ignitionChance; - int duration = fireDuration; + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + World world = housing.getWorld(); + List entities = getEntitiesInRange(genome, housing, EntityLivingBase.class); + for (EntityLivingBase entity : entities) { + int chance = ignitionChance; + int duration = fireDuration; - // Entities are not attacked if they wear a full set of apiarist's armor. - int count = BeeManager.armorApiaristHelper.wearsItems(entity, getUID(), true); - if (count > 3) { - continue; // Full set, no damage/effect - } else if (count > 2) { - chance = 5; - duration = 50; - } else if (count > 1) { - chance = 20; - duration = 200; - } else if (count > 0) { - chance = 35; - duration = 350; - } + // Entities are not attacked if they wear a full set of apiarist's armor. + int count = BeeManager.armorApiaristHelper.wearsItems(entity, getUID(), true); + if (count > 3) { + continue; // Full set, no damage/effect + } else if (count > 2) { + chance = 5; + duration = 50; + } else if (count > 1) { + chance = 20; + duration = 200; + } else if (count > 0) { + chance = 35; + duration = 350; + } - if (world.rand.nextInt(1000) >= chance) { - continue; - } + if (world.rand.nextInt(1000) >= chance) { + continue; + } - entity.setFire(duration); - } + entity.setFire(duration); + } - return storedData; - } - - @Override - public IEffectData doFX(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - if (housing.getWorld().rand.nextInt(2) != 0) { - super.doFX(genome, storedData, housing); - } else { - Vec3 beeFXCoordinates = getFXCoordinates(housing); - Proxies.render.addEntityIgnitionFX(housing.getWorld(), beeFXCoordinates.xCoord, beeFXCoordinates.yCoord + 0.5, beeFXCoordinates.zCoord); - } - return storedData; - } + return storedData; + } + @Override + public IEffectData doFX(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + if (housing.getWorld().rand.nextInt(2) != 0) { + super.doFX(genome, storedData, housing); + } else { + Vec3 beeFXCoordinates = getFXCoordinates(housing); + Proxies.render.addEntityIgnitionFX( + housing.getWorld(), + beeFXCoordinates.xCoord, + beeFXCoordinates.yCoord + 0.5, + beeFXCoordinates.zCoord); + } + return storedData; + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectMisanthrope.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectMisanthrope.java index d683b0e3a..88d87a38c 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectMisanthrope.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectMisanthrope.java @@ -10,42 +10,39 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.DamageSource; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.genetics.IEffectData; import forestry.core.utils.DamageSourceForestry; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.DamageSource; public class AlleleEffectMisanthrope extends AlleleEffectThrottled { - private static final DamageSource damageSourceBeeEnd = new DamageSourceForestry("bee.end"); + private static final DamageSource damageSourceBeeEnd = new DamageSourceForestry("bee.end"); - public AlleleEffectMisanthrope() { - super("misanthrope", true, 20, false, false); - } + public AlleleEffectMisanthrope() { + super("misanthrope", true, 20, false, false); + } - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - List players = getEntitiesInRange(genome, housing, EntityPlayer.class); - for (EntityPlayer player : players) { - int damage = 4; + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + List players = getEntitiesInRange(genome, housing, EntityPlayer.class); + for (EntityPlayer player : players) { + int damage = 4; - // Entities are not attacked if they wear a full set of apiarist's armor. - int count = BeeManager.armorApiaristHelper.wearsItems(player, getUID(), true); - damage -= count; - if (damage <= 0) { - continue; - } + // Entities are not attacked if they wear a full set of apiarist's armor. + int count = BeeManager.armorApiaristHelper.wearsItems(player, getUID(), true); + damage -= count; + if (damage <= 0) { + continue; + } - player.attackEntityFrom(damageSourceBeeEnd, damage); - } - - return storedData; - } + player.attackEntityFrom(damageSourceBeeEnd, damage); + } + return storedData; + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectNone.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectNone.java index 3b583421c..3afccb8be 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectNone.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectNone.java @@ -1,17 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.genetics.alleles; - -public class AlleleEffectNone extends AlleleEffect { - public AlleleEffectNone(String valueName, boolean isDominant) { - super(valueName, isDominant); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.genetics.alleles; + +public class AlleleEffectNone extends AlleleEffect { + public AlleleEffectNone(String valueName, boolean isDominant) { + super(valueName, isDominant); + } +} diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectPotion.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectPotion.java index 5f42aa59a..f347b1b74 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectPotion.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectPotion.java @@ -10,10 +10,16 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; +import cpw.mods.fml.relauncher.ReflectionHelper; +import forestry.api.apiculture.BeeManager; +import forestry.api.apiculture.IBeeGenome; +import forestry.api.apiculture.IBeeHousing; +import forestry.api.genetics.IEffectData; +import forestry.core.proxy.Proxies; +import forestry.core.utils.Log; import java.util.Collection; import java.util.Collections; import java.util.List; - import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.IMob; import net.minecraft.potion.Potion; @@ -22,91 +28,88 @@ import net.minecraft.potion.PotionHelper; import net.minecraft.util.Vec3; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.ReflectionHelper; - -import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.IBeeGenome; -import forestry.api.apiculture.IBeeHousing; -import forestry.api.genetics.IEffectData; -import forestry.core.proxy.Proxies; -import forestry.core.utils.Log; - public class AlleleEffectPotion extends AlleleEffectThrottled { - private final Potion potion; - private final int potionFXColor; - private final boolean isBadEffect; - private final int duration; - private final float chance; + private final Potion potion; + private final int potionFXColor; + private final boolean isBadEffect; + private final int duration; + private final float chance; - public AlleleEffectPotion(String name, boolean isDominant, Potion potion, int duration, int throttle, float chance) { - super(name, isDominant, throttle, true, false); - this.potion = potion; - this.isBadEffect = isBadEffect(potion); - this.duration = duration; - this.chance = chance; + public AlleleEffectPotion( + String name, boolean isDominant, Potion potion, int duration, int throttle, float chance) { + super(name, isDominant, throttle, true, false); + this.potion = potion; + this.isBadEffect = isBadEffect(potion); + this.duration = duration; + this.chance = chance; - Collection potionEffects = Collections.singleton(new PotionEffect(potion.getId(), 1, 0)); - this.potionFXColor = PotionHelper.calcPotionLiquidColor(potionEffects); - } + Collection potionEffects = Collections.singleton(new PotionEffect(potion.getId(), 1, 0)); + this.potionFXColor = PotionHelper.calcPotionLiquidColor(potionEffects); + } - public AlleleEffectPotion(String name, boolean isDominant, Potion potion, int duration) { - this(name, isDominant, potion, duration, 200, 1.0f); - } + public AlleleEffectPotion(String name, boolean isDominant, Potion potion, int duration) { + this(name, isDominant, potion, duration, 200, 1.0f); + } - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - World world = housing.getWorld(); - List entities = getEntitiesInRange(genome, housing, EntityLivingBase.class); - for (EntityLivingBase entity : entities) { - if (world.rand.nextFloat() >= chance) { - continue; - } + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + World world = housing.getWorld(); + List entities = getEntitiesInRange(genome, housing, EntityLivingBase.class); + for (EntityLivingBase entity : entities) { + if (world.rand.nextFloat() >= chance) { + continue; + } - int dur = this.duration; - if (isBadEffect) { - // Entities are not attacked if they wear a full set of apiarist's armor. - int count = BeeManager.armorApiaristHelper.wearsItems(entity, getUID(), true); - if (count >= 4) { - continue; // Full set, no damage/effect - } else if (count == 3) { - dur = this.duration / 4; - } else if (count == 2) { - dur = this.duration / 2; - } else if (count == 1) { - dur = this.duration * 3 / 4; - } - } else { - // don't apply positive effects to mobs - if (entity instanceof IMob) { - continue; - } - } + int dur = this.duration; + if (isBadEffect) { + // Entities are not attacked if they wear a full set of apiarist's armor. + int count = BeeManager.armorApiaristHelper.wearsItems(entity, getUID(), true); + if (count >= 4) { + continue; // Full set, no damage/effect + } else if (count == 3) { + dur = this.duration / 4; + } else if (count == 2) { + dur = this.duration / 2; + } else if (count == 1) { + dur = this.duration * 3 / 4; + } + } else { + // don't apply positive effects to mobs + if (entity instanceof IMob) { + continue; + } + } - entity.addPotionEffect(new PotionEffect(potion.getId(), dur, 0)); - } + entity.addPotionEffect(new PotionEffect(potion.getId(), dur, 0)); + } - return storedData; - } + return storedData; + } - //FIXME: remove when Potion.isBadEffect() is available server-side - private static boolean isBadEffect(Potion potion) { - try { - return (Boolean) ReflectionHelper.getPrivateValue(Potion.class, potion, "field_76418_K", "isBadEffect"); - } catch (ReflectionHelper.UnableToFindFieldException e) { - Log.severe("Could not access potion field isBadEffect."); - return false; - } - } + // FIXME: remove when Potion.isBadEffect() is available server-side + private static boolean isBadEffect(Potion potion) { + try { + return (Boolean) ReflectionHelper.getPrivateValue(Potion.class, potion, "field_76418_K", "isBadEffect"); + } catch (ReflectionHelper.UnableToFindFieldException e) { + Log.severe("Could not access potion field isBadEffect."); + return false; + } + } - @Override - public IEffectData doFX(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - if (housing.getWorld().rand.nextBoolean()) { - super.doFX(genome, storedData, housing); - } else { - Vec3 beeFXCoordinates = getFXCoordinates(housing); - Proxies.render.addEntityPotionFX(housing.getWorld(), beeFXCoordinates.xCoord, beeFXCoordinates.yCoord + 0.5, beeFXCoordinates.zCoord, potionFXColor); - } - return storedData; - } + @Override + public IEffectData doFX(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + if (housing.getWorld().rand.nextBoolean()) { + super.doFX(genome, storedData, housing); + } else { + Vec3 beeFXCoordinates = getFXCoordinates(housing); + Proxies.render.addEntityPotionFX( + housing.getWorld(), + beeFXCoordinates.xCoord, + beeFXCoordinates.yCoord + 0.5, + beeFXCoordinates.zCoord, + potionFXColor); + } + return storedData; + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectRadioactive.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectRadioactive.java index 634a9b88f..f2dbc55a5 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectRadioactive.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectRadioactive.java @@ -10,15 +10,6 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import java.util.List; -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.DamageSource; -import net.minecraft.world.World; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; @@ -26,84 +17,91 @@ import forestry.api.genetics.IEffectData; import forestry.apiculture.blocks.BlockAlveary; import forestry.core.utils.DamageSourceForestry; import forestry.core.utils.vect.Vect; +import java.util.List; +import java.util.Random; +import net.minecraft.block.Block; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.DamageSource; +import net.minecraft.world.World; public class AlleleEffectRadioactive extends AlleleEffectThrottled { - private static final DamageSource damageSourceBeeRadioactive = new DamageSourceForestry("bee.radioactive"); + private static final DamageSource damageSourceBeeRadioactive = new DamageSourceForestry("bee.radioactive"); - public AlleleEffectRadioactive() { - super("radioactive", true, 40, false, true); - } + public AlleleEffectRadioactive() { + super("radioactive", true, 40, false, true); + } - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - harmEntities(genome, housing); + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + harmEntities(genome, housing); - return destroyEnvironment(genome, storedData, housing); - } + return destroyEnvironment(genome, storedData, housing); + } - private void harmEntities(IBeeGenome genome, IBeeHousing housing) { - List entities = getEntitiesInRange(genome, housing, EntityLivingBase.class); - for (EntityLivingBase entity : entities) { - int damage = 8; + private void harmEntities(IBeeGenome genome, IBeeHousing housing) { + List entities = getEntitiesInRange(genome, housing, EntityLivingBase.class); + for (EntityLivingBase entity : entities) { + int damage = 8; - // Entities are not attacked if they wear a full set of apiarist's armor. - int count = BeeManager.armorApiaristHelper.wearsItems(entity, getUID(), true); - damage -= (count * 2); - if (damage <= 0) { - continue; - } + // Entities are not attacked if they wear a full set of apiarist's armor. + int count = BeeManager.armorApiaristHelper.wearsItems(entity, getUID(), true); + damage -= (count * 2); + if (damage <= 0) { + continue; + } - entity.attackEntityFrom(damageSourceBeeRadioactive, damage); - } - } + entity.attackEntityFrom(damageSourceBeeRadioactive, damage); + } + } - private static IEffectData destroyEnvironment(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - World world = housing.getWorld(); - Random rand = world.rand; + private static IEffectData destroyEnvironment(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + World world = housing.getWorld(); + Random rand = world.rand; - int[] areaAr = genome.getTerritory(); - Vect area = new Vect(areaAr).multiply(2); - Vect offset = area.multiply(-1 / 2.0f); - Vect posHousing = new Vect(housing.getCoordinates()); + int[] areaAr = genome.getTerritory(); + Vect area = new Vect(areaAr).multiply(2); + Vect offset = area.multiply(-1 / 2.0f); + Vect posHousing = new Vect(housing.getCoordinates()); - for (int i = 0; i < 20; i++) { - Vect randomPos = Vect.getRandomPositionInArea(rand, area); - Vect posBlock = randomPos.add(posHousing); - posBlock = posBlock.add(offset); + for (int i = 0; i < 20; i++) { + Vect randomPos = Vect.getRandomPositionInArea(rand, area); + Vect posBlock = randomPos.add(posHousing); + posBlock = posBlock.add(offset); - if (posBlock.y <= 1 || posBlock.y >= housing.getWorld().getActualHeight()) { - continue; - } + if (posBlock.y <= 1 || posBlock.y >= housing.getWorld().getActualHeight()) { + continue; + } - // Don't destroy ourselves or blocks below us. - if (posBlock.x == posHousing.x && posBlock.z == posHousing.z && posBlock.y <= posHousing.y) { - continue; - } + // Don't destroy ourselves or blocks below us. + if (posBlock.x == posHousing.x && posBlock.z == posHousing.z && posBlock.y <= posHousing.y) { + continue; + } - if (world.isAirBlock(posBlock.x, posBlock.y, posBlock.z)) { - continue; - } + if (world.isAirBlock(posBlock.x, posBlock.y, posBlock.z)) { + continue; + } - Block block = world.getBlock(posBlock.x, posBlock.y, posBlock.z); + Block block = world.getBlock(posBlock.x, posBlock.y, posBlock.z); - if (block instanceof BlockAlveary) { - continue; - } + if (block instanceof BlockAlveary) { + continue; + } - TileEntity tile = world.getTileEntity(posBlock.x, posBlock.y, posBlock.z); - if (tile instanceof IBeeHousing) { - continue; - } + TileEntity tile = world.getTileEntity(posBlock.x, posBlock.y, posBlock.z); + if (tile instanceof IBeeHousing) { + continue; + } - if (block.getBlockHardness(world, posBlock.x, posBlock.y, posBlock.z) < 0) { - continue; - } + if (block.getBlockHardness(world, posBlock.x, posBlock.y, posBlock.z) < 0) { + continue; + } - world.setBlockToAir(posBlock.x, posBlock.y, posBlock.z); - break; - } + world.setBlockToAir(posBlock.x, posBlock.y, posBlock.z); + break; + } - return storedData; - } + return storedData; + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectRepulsion.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectRepulsion.java index dbc8c5015..b38b2cc06 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectRepulsion.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectRepulsion.java @@ -10,42 +10,40 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import java.util.List; - -import net.minecraft.entity.ai.EntityAITasks.EntityAITaskEntry; -import net.minecraft.entity.monster.EntityMob; - import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.genetics.IEffectData; import forestry.apiculture.entities.AIAvoidPlayers; +import java.util.List; +import net.minecraft.entity.ai.EntityAITasks.EntityAITaskEntry; +import net.minecraft.entity.monster.EntityMob; public class AlleleEffectRepulsion extends AlleleEffectThrottled { - public AlleleEffectRepulsion() { - super("repulsion", false, 100, true, true); - } + public AlleleEffectRepulsion() { + super("repulsion", false, 100, true, true); + } - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - List mobs = getEntitiesInRange(genome, housing, EntityMob.class); - for (EntityMob mob : mobs) { - if (!isMobAvoidingPlayers(mob)) { - mob.tasks.addTask(3, new AIAvoidPlayers(mob, 6.0f, 0.25f, 0.3f)); - mob.tasks.onUpdateTasks(); - } - } + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + List mobs = getEntitiesInRange(genome, housing, EntityMob.class); + for (EntityMob mob : mobs) { + if (!isMobAvoidingPlayers(mob)) { + mob.tasks.addTask(3, new AIAvoidPlayers(mob, 6.0f, 0.25f, 0.3f)); + mob.tasks.onUpdateTasks(); + } + } - return storedData; - } + return storedData; + } - private boolean isMobAvoidingPlayers(EntityMob mob) { - for (Object objT : mob.tasks.taskEntries) { - EntityAITaskEntry task = (EntityAITaskEntry) objT; - if (task.action instanceof AIAvoidPlayers) { - return true; - } - } - return false; - } + private boolean isMobAvoidingPlayers(EntityMob mob) { + for (Object objT : mob.tasks.taskEntries) { + EntityAITaskEntry task = (EntityAITaskEntry) objT; + if (task.action instanceof AIAvoidPlayers) { + return true; + } + } + return false; + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectResurrection.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectResurrection.java index cab3625ed..f6707d263 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectResurrection.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectResurrection.java @@ -10,10 +10,14 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; +import forestry.api.apiculture.IBeeGenome; +import forestry.api.apiculture.IBeeHousing; +import forestry.api.genetics.IEffectData; +import forestry.core.utils.EntityUtil; +import forestry.core.utils.ItemStackUtil; import java.util.ArrayList; import java.util.Collections; import java.util.List; - import net.minecraft.entity.EntityLiving; import net.minecraft.entity.boss.EntityDragon; import net.minecraft.entity.item.EntityItem; @@ -29,86 +33,80 @@ import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -import forestry.api.apiculture.IBeeGenome; -import forestry.api.apiculture.IBeeHousing; -import forestry.api.genetics.IEffectData; -import forestry.core.utils.EntityUtil; -import forestry.core.utils.ItemStackUtil; - public class AlleleEffectResurrection extends AlleleEffectThrottled { - public static class Resurrectable { - public final ItemStack res; - public final Class risen; + public static class Resurrectable { + public final ItemStack res; + public final Class risen; - public Resurrectable(ItemStack res, Class risen) { - this.res = res; - this.risen = risen; - } - } + public Resurrectable(ItemStack res, Class risen) { + this.res = res; + this.risen = risen; + } + } - public static List getReanimationList() { - ArrayList list = new ArrayList<>(); - list.add(new Resurrectable(new ItemStack(Items.bone), EntitySkeleton.class)); - list.add(new Resurrectable(new ItemStack(Items.arrow), EntitySkeleton.class)); - list.add(new Resurrectable(new ItemStack(Items.rotten_flesh), EntityZombie.class)); - list.add(new Resurrectable(new ItemStack(Items.blaze_rod), EntityBlaze.class)); - return list; - } + public static List getReanimationList() { + ArrayList list = new ArrayList<>(); + list.add(new Resurrectable(new ItemStack(Items.bone), EntitySkeleton.class)); + list.add(new Resurrectable(new ItemStack(Items.arrow), EntitySkeleton.class)); + list.add(new Resurrectable(new ItemStack(Items.rotten_flesh), EntityZombie.class)); + list.add(new Resurrectable(new ItemStack(Items.blaze_rod), EntityBlaze.class)); + return list; + } - public static List getResurrectionList() { - ArrayList list = new ArrayList<>(); - list.add(new Resurrectable(new ItemStack(Items.gunpowder), EntityCreeper.class)); - list.add(new Resurrectable(new ItemStack(Items.ender_pearl), EntityEnderman.class)); - list.add(new Resurrectable(new ItemStack(Items.string), EntitySpider.class)); - list.add(new Resurrectable(new ItemStack(Items.spider_eye), EntitySpider.class)); - list.add(new Resurrectable(new ItemStack(Items.string), EntityCaveSpider.class)); - list.add(new Resurrectable(new ItemStack(Items.spider_eye), EntityCaveSpider.class)); - list.add(new Resurrectable(new ItemStack(Items.ghast_tear), EntityGhast.class)); - list.add(new Resurrectable(new ItemStack(Blocks.dragon_egg), EntityDragon.class)); - return list; - } + public static List getResurrectionList() { + ArrayList list = new ArrayList<>(); + list.add(new Resurrectable(new ItemStack(Items.gunpowder), EntityCreeper.class)); + list.add(new Resurrectable(new ItemStack(Items.ender_pearl), EntityEnderman.class)); + list.add(new Resurrectable(new ItemStack(Items.string), EntitySpider.class)); + list.add(new Resurrectable(new ItemStack(Items.spider_eye), EntitySpider.class)); + list.add(new Resurrectable(new ItemStack(Items.string), EntityCaveSpider.class)); + list.add(new Resurrectable(new ItemStack(Items.spider_eye), EntityCaveSpider.class)); + list.add(new Resurrectable(new ItemStack(Items.ghast_tear), EntityGhast.class)); + list.add(new Resurrectable(new ItemStack(Blocks.dragon_egg), EntityDragon.class)); + return list; + } - private final List resurrectables; + private final List resurrectables; - public AlleleEffectResurrection(String name, List resurrectables) { - super(name, true, 40, true, true); - this.resurrectables = resurrectables; - } + public AlleleEffectResurrection(String name, List resurrectables) { + super(name, true, 40, true, true); + this.resurrectables = resurrectables; + } - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - List entities = getEntitiesInRange(genome, housing, EntityItem.class); - if (entities.size() == 0) { - return storedData; - } + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + List entities = getEntitiesInRange(genome, housing, EntityItem.class); + if (entities.size() == 0) { + return storedData; + } - Collections.shuffle(resurrectables); + Collections.shuffle(resurrectables); - for (EntityItem entity : entities) { - if (resurrectEntity(entity)) { - break; - } - } + for (EntityItem entity : entities) { + if (resurrectEntity(entity)) { + break; + } + } - return storedData; - } + return storedData; + } - private boolean resurrectEntity(EntityItem entity) { - if (entity.isDead) { - return false; - } - ItemStack contained = entity.getEntityItem(); - for (Resurrectable entry : resurrectables) { - if (ItemStackUtil.isIdenticalItem(entry.res, contained)) { - EntityUtil.spawnEntity(entity.worldObj, entry.risen, entity.posX, entity.posY, entity.posZ); - contained.stackSize--; - if (contained.stackSize <= 0) { - entity.setDead(); - } - return true; - } - } - return false; - } + private boolean resurrectEntity(EntityItem entity) { + if (entity.isDead) { + return false; + } + ItemStack contained = entity.getEntityItem(); + for (Resurrectable entry : resurrectables) { + if (ItemStackUtil.isIdenticalItem(entry.res, contained)) { + EntityUtil.spawnEntity(entity.worldObj, entry.risen, entity.posX, entity.posY, entity.posZ); + contained.stackSize--; + if (contained.stackSize <= 0) { + entity.setDead(); + } + return true; + } + } + return false; + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectSnowing.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectSnowing.java index 5c1b37381..baa9e564d 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectSnowing.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectSnowing.java @@ -10,13 +10,6 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.core.EnumTemperature; @@ -24,73 +17,86 @@ import forestry.api.genetics.IEffectData; import forestry.core.config.Constants; import forestry.core.proxy.Proxies; import forestry.core.utils.vect.Vect; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; public class AlleleEffectSnowing extends AlleleEffectThrottled { - public AlleleEffectSnowing() { - super("snowing", false, 20, true, true); - } + public AlleleEffectSnowing() { + super("snowing", false, 20, true, true); + } - @Override - public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + @Override + public IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - World world = housing.getWorld(); + World world = housing.getWorld(); - EnumTemperature temp = housing.getTemperature(); + EnumTemperature temp = housing.getTemperature(); - switch (temp) { - case HELLISH: - case HOT: - case WARM: - return storedData; - default: - } + switch (temp) { + case HELLISH: + case HOT: + case WARM: + return storedData; + default: + } - Vect area = getModifiedArea(genome, housing); - Vect offset = area.multiply(-1 / 2.0f); + Vect area = getModifiedArea(genome, housing); + Vect offset = area.multiply(-1 / 2.0f); - for (int i = 0; i < 1; i++) { + for (int i = 0; i < 1; i++) { - Vect randomPos = Vect.getRandomPositionInArea(world.rand, area); + Vect randomPos = Vect.getRandomPositionInArea(world.rand, area); - Vect posBlock = randomPos.add(new Vect(housing.getCoordinates())); - posBlock = posBlock.add(offset); + Vect posBlock = randomPos.add(new Vect(housing.getCoordinates())); + posBlock = posBlock.add(offset); - // Put snow on the ground - if (!world.isSideSolid(posBlock.x, posBlock.y - 1, posBlock.z, ForgeDirection.UP, false)) { - continue; - } + // Put snow on the ground + if (!world.isSideSolid(posBlock.x, posBlock.y - 1, posBlock.z, ForgeDirection.UP, false)) { + continue; + } - Block block = world.getBlock(posBlock.x, posBlock.y, posBlock.z); + Block block = world.getBlock(posBlock.x, posBlock.y, posBlock.z); - if (block == Blocks.snow_layer) { - int meta = world.getBlockMetadata(posBlock.x, posBlock.y, posBlock.z); - if (meta < 7) { - world.setBlockMetadataWithNotify(posBlock.x, posBlock.y, posBlock.z, meta + 1, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); - } - } else if (block.isReplaceable(world, posBlock.x, posBlock.y, posBlock.z)) { - world.setBlock(posBlock.x, posBlock.y, posBlock.z, Blocks.snow_layer, 0, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); - } - } + if (block == Blocks.snow_layer) { + int meta = world.getBlockMetadata(posBlock.x, posBlock.y, posBlock.z); + if (meta < 7) { + world.setBlockMetadataWithNotify( + posBlock.x, posBlock.y, posBlock.z, meta + 1, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); + } + } else if (block.isReplaceable(world, posBlock.x, posBlock.y, posBlock.z)) { + world.setBlock( + posBlock.x, + posBlock.y, + posBlock.z, + Blocks.snow_layer, + 0, + Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); + } + } - return storedData; - } + return storedData; + } - @Override - public IEffectData doFX(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - if (housing.getWorld().rand.nextInt(3) == 0) { - Vect area = getModifiedArea(genome, housing); - Vect offset = area.multiply(-0.5F); + @Override + public IEffectData doFX(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + if (housing.getWorld().rand.nextInt(3) == 0) { + Vect area = getModifiedArea(genome, housing); + Vect offset = area.multiply(-0.5F); - ChunkCoordinates coordinates = housing.getCoordinates(); - World world = housing.getWorld(); - - Vect spawn = Vect.getRandomPositionInArea(world.rand, area).add(coordinates).add(offset); - Proxies.render.addEntitySnowFX(world, spawn.x, spawn.y, spawn.z); - return storedData; - } else { - return super.doFX(genome, storedData, housing); - } - } + ChunkCoordinates coordinates = housing.getCoordinates(); + World world = housing.getWorld(); + Vect spawn = Vect.getRandomPositionInArea(world.rand, area) + .add(coordinates) + .add(offset); + Proxies.render.addEntitySnowFX(world, spawn.x, spawn.y, spawn.z); + return storedData; + } else { + return super.doFX(genome, storedData, housing); + } + } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectThrottled.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectThrottled.java index 6d047ebbc..384e0069e 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectThrottled.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectThrottled.java @@ -17,58 +17,58 @@ import forestry.core.genetics.EffectData; public abstract class AlleleEffectThrottled extends AlleleEffect { - private boolean isCombinable = false; - private final int throttle; - private boolean requiresWorkingQueen = false; + private boolean isCombinable = false; + private final int throttle; + private boolean requiresWorkingQueen = false; - protected AlleleEffectThrottled(String name, boolean isDominant, int throttle, boolean requiresWorking, boolean isCombinable) { - super(name, isDominant); - this.throttle = throttle; - this.isCombinable = isCombinable; - this.requiresWorkingQueen = requiresWorking; - } + protected AlleleEffectThrottled( + String name, boolean isDominant, int throttle, boolean requiresWorking, boolean isCombinable) { + super(name, isDominant); + this.throttle = throttle; + this.isCombinable = isCombinable; + this.requiresWorkingQueen = requiresWorking; + } - @Override - public boolean isCombinable() { - return isCombinable; - } + @Override + public boolean isCombinable() { + return isCombinable; + } - @Override - public IEffectData validateStorage(IEffectData storedData) { - if (storedData instanceof EffectData) { - return storedData; - } + @Override + public IEffectData validateStorage(IEffectData storedData) { + if (storedData instanceof EffectData) { + return storedData; + } - return new EffectData(1, 0); - } + return new EffectData(1, 0); + } - @Override - public final IEffectData doEffect(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { - if (isThrottled(storedData, housing)) { - return storedData; - } - return doEffectThrottled(genome, storedData, housing); - } + @Override + public final IEffectData doEffect(IBeeGenome genome, IEffectData storedData, IBeeHousing housing) { + if (isThrottled(storedData, housing)) { + return storedData; + } + return doEffectThrottled(genome, storedData, housing); + } - private boolean isThrottled(IEffectData storedData, IBeeHousing housing) { + private boolean isThrottled(IEffectData storedData, IBeeHousing housing) { - if (requiresWorkingQueen && housing.getErrorLogic().hasErrors()) { - return true; - } + if (requiresWorkingQueen && housing.getErrorLogic().hasErrors()) { + return true; + } - int time = storedData.getInteger(0); - time++; - storedData.setInteger(0, time); + int time = storedData.getInteger(0); + time++; + storedData.setInteger(0, time); - if (time < throttle) { - return true; - } + if (time < throttle) { + return true; + } - // Reset since we are done throttling. - storedData.setInteger(0, 0); - return false; - } - - abstract IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing); + // Reset since we are done throttling. + storedData.setInteger(0, 0); + return false; + } + abstract IEffectData doEffectThrottled(IBeeGenome genome, IEffectData storedData, IBeeHousing housing); } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleFlowers.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleFlowers.java index 3e08fe43f..cef2130fd 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleFlowers.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleFlowers.java @@ -16,21 +16,20 @@ import forestry.core.genetics.alleles.AlleleCategorized; public class AlleleFlowers extends AlleleCategorized implements IAlleleFlowers { - private final IFlowerProvider provider; + private final IFlowerProvider provider; - public AlleleFlowers(String modId, String category, String name, IFlowerProvider provider, boolean isDominant) { - super(modId, category, name, isDominant); - this.provider = provider; - } + public AlleleFlowers(String modId, String category, String name, IFlowerProvider provider, boolean isDominant) { + super(modId, category, name, isDominant); + this.provider = provider; + } - @Override - public IFlowerProvider getProvider() { - return provider; - } - - @Override - public String getName() { - return getProvider().getDescription(); - } + @Override + public IFlowerProvider getProvider() { + return provider; + } + @Override + public String getName() { + return getProvider().getDescription(); + } } diff --git a/src/main/java/forestry/apiculture/gui/ContainerAlveary.java b/src/main/java/forestry/apiculture/gui/ContainerAlveary.java index e505a9f41..fbe9a9b0c 100755 --- a/src/main/java/forestry/apiculture/gui/ContainerAlveary.java +++ b/src/main/java/forestry/apiculture/gui/ContainerAlveary.java @@ -10,23 +10,22 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.apiculture.multiblock.TileAlveary; import forestry.core.gui.ContainerTile; import forestry.core.network.packets.PacketGuiUpdate; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerAlveary extends ContainerTile { - public ContainerAlveary(InventoryPlayer player, TileAlveary tile) { - super(tile, player, 8, 108); - ContainerBeeHelper.addSlots(this, tile, false); - } + public ContainerAlveary(InventoryPlayer player, TileAlveary tile) { + super(tile, player, 8, 108); + ContainerBeeHelper.addSlots(this, tile, false); + } - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - PacketGuiUpdate packet = new PacketGuiUpdate(tile); - sendPacketToCrafters(packet); - } + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + PacketGuiUpdate packet = new PacketGuiUpdate(tile); + sendPacketToCrafters(packet); + } } diff --git a/src/main/java/forestry/apiculture/gui/ContainerAlvearyHygroregulator.java b/src/main/java/forestry/apiculture/gui/ContainerAlvearyHygroregulator.java index 4292cc6dc..5bf50f1fc 100755 --- a/src/main/java/forestry/apiculture/gui/ContainerAlvearyHygroregulator.java +++ b/src/main/java/forestry/apiculture/gui/ContainerAlvearyHygroregulator.java @@ -10,19 +10,17 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.apiculture.inventory.InventoryHygroregulator; import forestry.apiculture.multiblock.TileAlvearyHygroregulator; import forestry.core.gui.ContainerLiquidTanks; import forestry.core.gui.slots.SlotFiltered; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerAlvearyHygroregulator extends ContainerLiquidTanks { - public ContainerAlvearyHygroregulator(InventoryPlayer playerInventory, TileAlvearyHygroregulator tile) { - super(tile, playerInventory, 8, 84); - - this.addSlotToContainer(new SlotFiltered(tile, InventoryHygroregulator.SLOT_INPUT, 56, 38)); - } + public ContainerAlvearyHygroregulator(InventoryPlayer playerInventory, TileAlvearyHygroregulator tile) { + super(tile, playerInventory, 8, 84); + this.addSlotToContainer(new SlotFiltered(tile, InventoryHygroregulator.SLOT_INPUT, 56, 38)); + } } diff --git a/src/main/java/forestry/apiculture/gui/ContainerAlvearySieve.java b/src/main/java/forestry/apiculture/gui/ContainerAlvearySieve.java index eab1b48d1..4f5a1829a 100755 --- a/src/main/java/forestry/apiculture/gui/ContainerAlvearySieve.java +++ b/src/main/java/forestry/apiculture/gui/ContainerAlvearySieve.java @@ -10,27 +10,26 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.apiculture.inventory.InventoryAlvearySieve; import forestry.apiculture.multiblock.TileAlvearySieve; import forestry.core.gui.ContainerTile; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.core.inventory.watchers.ISlotPickupWatcher; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerAlvearySieve extends ContainerTile { - public ContainerAlvearySieve(InventoryPlayer player, TileAlvearySieve tile) { - super(tile, player, 8, 87); + public ContainerAlvearySieve(InventoryPlayer player, TileAlvearySieve tile) { + super(tile, player, 8, 87); - ISlotPickupWatcher crafter = tile.getCrafter(); + ISlotPickupWatcher crafter = tile.getCrafter(); - addSlotToContainer(new SlotOutput(tile, 0, 94, 52).setPickupWatcher(crafter)); - addSlotToContainer(new SlotOutput(tile, 1, 115, 39).setPickupWatcher(crafter)); - addSlotToContainer(new SlotOutput(tile, 2, 73, 39).setPickupWatcher(crafter)); - addSlotToContainer(new SlotOutput(tile, 3, 94, 26).setPickupWatcher(crafter)); + addSlotToContainer(new SlotOutput(tile, 0, 94, 52).setPickupWatcher(crafter)); + addSlotToContainer(new SlotOutput(tile, 1, 115, 39).setPickupWatcher(crafter)); + addSlotToContainer(new SlotOutput(tile, 2, 73, 39).setPickupWatcher(crafter)); + addSlotToContainer(new SlotOutput(tile, 3, 94, 26).setPickupWatcher(crafter)); - addSlotToContainer(new SlotFiltered(tile, InventoryAlvearySieve.SLOT_SIEVE, 43, 39).setPickupWatcher(crafter)); - } + addSlotToContainer(new SlotFiltered(tile, InventoryAlvearySieve.SLOT_SIEVE, 43, 39).setPickupWatcher(crafter)); + } } diff --git a/src/main/java/forestry/apiculture/gui/ContainerAlvearySwarmer.java b/src/main/java/forestry/apiculture/gui/ContainerAlvearySwarmer.java index 469256b11..bcfa41b22 100755 --- a/src/main/java/forestry/apiculture/gui/ContainerAlvearySwarmer.java +++ b/src/main/java/forestry/apiculture/gui/ContainerAlvearySwarmer.java @@ -10,20 +10,19 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.apiculture.multiblock.TileAlvearySwarmer; import forestry.core.gui.ContainerTile; import forestry.core.gui.slots.SlotFiltered; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerAlvearySwarmer extends ContainerTile { - public ContainerAlvearySwarmer(InventoryPlayer player, TileAlvearySwarmer tile) { - super(tile, player, 8, 87); + public ContainerAlvearySwarmer(InventoryPlayer player, TileAlvearySwarmer tile) { + super(tile, player, 8, 87); - this.addSlotToContainer(new SlotFiltered(tile, 0, 79, 52)); - this.addSlotToContainer(new SlotFiltered(tile, 1, 100, 39)); - this.addSlotToContainer(new SlotFiltered(tile, 2, 58, 39)); - this.addSlotToContainer(new SlotFiltered(tile, 3, 79, 26)); - } + this.addSlotToContainer(new SlotFiltered(tile, 0, 79, 52)); + this.addSlotToContainer(new SlotFiltered(tile, 1, 100, 39)); + this.addSlotToContainer(new SlotFiltered(tile, 2, 58, 39)); + this.addSlotToContainer(new SlotFiltered(tile, 3, 79, 26)); + } } diff --git a/src/main/java/forestry/apiculture/gui/ContainerBeeHelper.java b/src/main/java/forestry/apiculture/gui/ContainerBeeHelper.java index a630aee76..7b7b1043c 100644 --- a/src/main/java/forestry/apiculture/gui/ContainerBeeHelper.java +++ b/src/main/java/forestry/apiculture/gui/ContainerBeeHelper.java @@ -1,48 +1,48 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.gui; - -import net.minecraft.inventory.IInventory; - -import forestry.apiculture.InventoryBeeHousing; -import forestry.apiculture.inventory.InventoryApiary; -import forestry.core.gui.ContainerForestry; -import forestry.core.gui.slots.SlotFiltered; -import forestry.core.gui.slots.SlotOutput; -import forestry.core.tiles.IFilterSlotDelegate; - -public abstract class ContainerBeeHelper { - public static void addSlots(ContainerForestry container, T inventory, boolean hasFrames) { - // Queen/Princess - container.addSlotToContainer(new SlotFiltered(inventory, InventoryBeeHousing.SLOT_QUEEN, 29, 39)); - - // Drone - container.addSlotToContainer(new SlotFiltered(inventory, InventoryBeeHousing.SLOT_DRONE, 29, 65)); - - // Frames - if (hasFrames) { - int slotFrames = InventoryApiary.SLOT_FRAMES_1; - container.addSlotToContainer(new SlotFiltered(inventory, slotFrames++, 66, 23)); - container.addSlotToContainer(new SlotFiltered(inventory, slotFrames++, 66, 52)); - container.addSlotToContainer(new SlotFiltered(inventory, slotFrames, 66, 81)); - } - - // Product Inventory - int slotProduct = InventoryBeeHousing.SLOT_PRODUCT_1; - container.addSlotToContainer(new SlotOutput(inventory, slotProduct++, 116, 52)); - container.addSlotToContainer(new SlotOutput(inventory, slotProduct++, 137, 39)); - container.addSlotToContainer(new SlotOutput(inventory, slotProduct++, 137, 65)); - container.addSlotToContainer(new SlotOutput(inventory, slotProduct++, 116, 78)); - container.addSlotToContainer(new SlotOutput(inventory, slotProduct++, 95, 65)); - container.addSlotToContainer(new SlotOutput(inventory, slotProduct++, 95, 39)); - container.addSlotToContainer(new SlotOutput(inventory, slotProduct, 116, 26)); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.gui; + +import forestry.apiculture.InventoryBeeHousing; +import forestry.apiculture.inventory.InventoryApiary; +import forestry.core.gui.ContainerForestry; +import forestry.core.gui.slots.SlotFiltered; +import forestry.core.gui.slots.SlotOutput; +import forestry.core.tiles.IFilterSlotDelegate; +import net.minecraft.inventory.IInventory; + +public abstract class ContainerBeeHelper { + public static void addSlots( + ContainerForestry container, T inventory, boolean hasFrames) { + // Queen/Princess + container.addSlotToContainer(new SlotFiltered(inventory, InventoryBeeHousing.SLOT_QUEEN, 29, 39)); + + // Drone + container.addSlotToContainer(new SlotFiltered(inventory, InventoryBeeHousing.SLOT_DRONE, 29, 65)); + + // Frames + if (hasFrames) { + int slotFrames = InventoryApiary.SLOT_FRAMES_1; + container.addSlotToContainer(new SlotFiltered(inventory, slotFrames++, 66, 23)); + container.addSlotToContainer(new SlotFiltered(inventory, slotFrames++, 66, 52)); + container.addSlotToContainer(new SlotFiltered(inventory, slotFrames, 66, 81)); + } + + // Product Inventory + int slotProduct = InventoryBeeHousing.SLOT_PRODUCT_1; + container.addSlotToContainer(new SlotOutput(inventory, slotProduct++, 116, 52)); + container.addSlotToContainer(new SlotOutput(inventory, slotProduct++, 137, 39)); + container.addSlotToContainer(new SlotOutput(inventory, slotProduct++, 137, 65)); + container.addSlotToContainer(new SlotOutput(inventory, slotProduct++, 116, 78)); + container.addSlotToContainer(new SlotOutput(inventory, slotProduct++, 95, 65)); + container.addSlotToContainer(new SlotOutput(inventory, slotProduct++, 95, 39)); + container.addSlotToContainer(new SlotOutput(inventory, slotProduct, 116, 26)); + } +} diff --git a/src/main/java/forestry/apiculture/gui/ContainerBeeHousing.java b/src/main/java/forestry/apiculture/gui/ContainerBeeHousing.java index 9235477b5..baf0743e9 100644 --- a/src/main/java/forestry/apiculture/gui/ContainerBeeHousing.java +++ b/src/main/java/forestry/apiculture/gui/ContainerBeeHousing.java @@ -10,32 +10,30 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.apiculture.tiles.TileBeeHousingBase; import forestry.core.gui.ContainerTile; import forestry.core.network.IForestryPacketClient; import forestry.core.network.packets.PacketGuiUpdate; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerBeeHousing extends ContainerTile implements IContainerBeeHousing { - public ContainerBeeHousing(InventoryPlayer player, TileBeeHousingBase tile, boolean hasFrames) { - super(tile, player, 8, 108); - ContainerBeeHelper.addSlots(this, tile, hasFrames); - } + public ContainerBeeHousing(InventoryPlayer player, TileBeeHousingBase tile, boolean hasFrames) { + super(tile, player, 8, 108); + ContainerBeeHelper.addSlots(this, tile, hasFrames); + } - private int beeProgress = 0; + private int beeProgress = 0; - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - int beeProgress = tile.getBeekeepingLogic().getBeeProgressPercent(); - if (this.beeProgress != beeProgress) { - this.beeProgress = beeProgress; - IForestryPacketClient packet = new PacketGuiUpdate(tile); - sendPacketToCrafters(packet); - } - } + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + int beeProgress = tile.getBeekeepingLogic().getBeeProgressPercent(); + if (this.beeProgress != beeProgress) { + this.beeProgress = beeProgress; + IForestryPacketClient packet = new PacketGuiUpdate(tile); + sendPacketToCrafters(packet); + } + } } diff --git a/src/main/java/forestry/apiculture/gui/ContainerHabitatLocator.java b/src/main/java/forestry/apiculture/gui/ContainerHabitatLocator.java index a5a57de0a..dcda97aa9 100755 --- a/src/main/java/forestry/apiculture/gui/ContainerHabitatLocator.java +++ b/src/main/java/forestry/apiculture/gui/ContainerHabitatLocator.java @@ -10,24 +10,23 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.entity.player.EntityPlayer; - import forestry.apiculture.inventory.ItemInventoryHabitatLocator; import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; +import net.minecraft.entity.player.EntityPlayer; public class ContainerHabitatLocator extends ContainerItemInventory { - public ContainerHabitatLocator(EntityPlayer player, ItemInventoryHabitatLocator inventory) { - super(inventory, player.inventory, 8, 102); + public ContainerHabitatLocator(EntityPlayer player, ItemInventoryHabitatLocator inventory) { + super(inventory, player.inventory, 8, 102); - // Energy - this.addSlotToContainer(new SlotFiltered(inventory, 2, 152, 8)); + // Energy + this.addSlotToContainer(new SlotFiltered(inventory, 2, 152, 8)); - // Bee to analyze - this.addSlotToContainer(new SlotFiltered(inventory, 0, 152, 32)); - // Analyzed bee - this.addSlotToContainer(new SlotOutput(inventory, 1, 152, 75)); - } + // Bee to analyze + this.addSlotToContainer(new SlotFiltered(inventory, 0, 152, 32)); + // Analyzed bee + this.addSlotToContainer(new SlotOutput(inventory, 1, 152, 75)); + } } diff --git a/src/main/java/forestry/apiculture/gui/ContainerImprinter.java b/src/main/java/forestry/apiculture/gui/ContainerImprinter.java index 4830e446d..439040298 100755 --- a/src/main/java/forestry/apiculture/gui/ContainerImprinter.java +++ b/src/main/java/forestry/apiculture/gui/ContainerImprinter.java @@ -10,9 +10,6 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.apiculture.inventory.ItemInventoryImprinter; import forestry.apiculture.network.packets.PacketImprintSelectionResponse; import forestry.core.gui.ContainerItemInventory; @@ -21,40 +18,43 @@ import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.proxy.Proxies; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerImprinter extends ContainerItemInventory implements IGuiSelectable { - public ContainerImprinter(InventoryPlayer inventoryplayer, ItemInventoryImprinter inventory) { - super(inventory, inventoryplayer, 8, 103); + public ContainerImprinter(InventoryPlayer inventoryplayer, ItemInventoryImprinter inventory) { + super(inventory, inventoryplayer, 8, 103); - // Input - this.addSlotToContainer(new SlotFiltered(inventory, 0, 152, 12)); - // Output - this.addSlotToContainer(new SlotOutput(inventory, 1, 152, 72)); - } + // Input + this.addSlotToContainer(new SlotFiltered(inventory, 0, 152, 12)); + // Output + this.addSlotToContainer(new SlotOutput(inventory, 1, 152, 72)); + } - @Override - public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packetRequest) { - if (packetRequest.getPrimaryIndex() == 0) { - if (packetRequest.getSecondaryIndex() == 0) { - inventory.advancePrimary(); - } else { - inventory.regressPrimary(); - } - } else { - if (packetRequest.getSecondaryIndex() == 0) { - inventory.advanceSecondary(); - } else { - inventory.regressSecondary(); - } - } + @Override + public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packetRequest) { + if (packetRequest.getPrimaryIndex() == 0) { + if (packetRequest.getSecondaryIndex() == 0) { + inventory.advancePrimary(); + } else { + inventory.regressPrimary(); + } + } else { + if (packetRequest.getSecondaryIndex() == 0) { + inventory.advanceSecondary(); + } else { + inventory.regressSecondary(); + } + } - PacketImprintSelectionResponse packetResponse = new PacketImprintSelectionResponse(inventory.getPrimaryIndex(), inventory.getSecondaryIndex()); - Proxies.net.sendToPlayer(packetResponse, player); - } + PacketImprintSelectionResponse packetResponse = + new PacketImprintSelectionResponse(inventory.getPrimaryIndex(), inventory.getSecondaryIndex()); + Proxies.net.sendToPlayer(packetResponse, player); + } - public void setSelection(PacketImprintSelectionResponse packetPayload) { - inventory.setPrimaryIndex(packetPayload.getPrimaryIndex()); - inventory.setSecondaryIndex(packetPayload.getSecondaryIndex()); - } + public void setSelection(PacketImprintSelectionResponse packetPayload) { + inventory.setPrimaryIndex(packetPayload.getPrimaryIndex()); + inventory.setSecondaryIndex(packetPayload.getSecondaryIndex()); + } } diff --git a/src/main/java/forestry/apiculture/gui/ContainerMinecartBeehouse.java b/src/main/java/forestry/apiculture/gui/ContainerMinecartBeehouse.java index d3a171e81..cf0a7e7ac 100644 --- a/src/main/java/forestry/apiculture/gui/ContainerMinecartBeehouse.java +++ b/src/main/java/forestry/apiculture/gui/ContainerMinecartBeehouse.java @@ -1,40 +1,39 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.gui; - -import net.minecraft.entity.player.InventoryPlayer; - -import forestry.apiculture.entities.EntityMinecartBeeHousingBase; -import forestry.core.gui.ContainerEntity; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.packets.PacketGuiUpdateEntity; - -public class ContainerMinecartBeehouse extends ContainerEntity implements IContainerBeeHousing { - public ContainerMinecartBeehouse(InventoryPlayer player, EntityMinecartBeeHousingBase entity, boolean hasFrames) { - super(entity, player, 8, 108); - ContainerBeeHelper.addSlots(this, entity, hasFrames); - } - - private int beeProgress = 0; - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - int beeProgress = entity.getBeekeepingLogic().getBeeProgressPercent(); - if (this.beeProgress != beeProgress) { - this.beeProgress = beeProgress; - IForestryPacketClient packet = new PacketGuiUpdateEntity(entity, entity); - sendPacketToCrafters(packet); - } - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.gui; + +import forestry.apiculture.entities.EntityMinecartBeeHousingBase; +import forestry.core.gui.ContainerEntity; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.packets.PacketGuiUpdateEntity; +import net.minecraft.entity.player.InventoryPlayer; + +public class ContainerMinecartBeehouse extends ContainerEntity + implements IContainerBeeHousing { + public ContainerMinecartBeehouse(InventoryPlayer player, EntityMinecartBeeHousingBase entity, boolean hasFrames) { + super(entity, player, 8, 108); + ContainerBeeHelper.addSlots(this, entity, hasFrames); + } + + private int beeProgress = 0; + + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + + int beeProgress = entity.getBeekeepingLogic().getBeeProgressPercent(); + if (this.beeProgress != beeProgress) { + this.beeProgress = beeProgress; + IForestryPacketClient packet = new PacketGuiUpdateEntity(entity, entity); + sendPacketToCrafters(packet); + } + } +} diff --git a/src/main/java/forestry/apiculture/gui/GuiAlveary.java b/src/main/java/forestry/apiculture/gui/GuiAlveary.java index 629f43637..e31cab8b2 100755 --- a/src/main/java/forestry/apiculture/gui/GuiAlveary.java +++ b/src/main/java/forestry/apiculture/gui/GuiAlveary.java @@ -10,34 +10,38 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.apiculture.multiblock.IAlvearyControllerInternal; import forestry.apiculture.multiblock.TileAlveary; import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.render.EnumTankLevel; +import net.minecraft.entity.player.InventoryPlayer; public class GuiAlveary extends GuiForestryTitled { - public GuiAlveary(InventoryPlayer inventory, TileAlveary tile) { - super(Constants.TEXTURE_PATH_GUI + "/alveary.png", new ContainerAlveary(inventory, tile), tile); + public GuiAlveary(InventoryPlayer inventory, TileAlveary tile) { + super(Constants.TEXTURE_PATH_GUI + "/alveary.png", new ContainerAlveary(inventory, tile), tile); - ySize = 190; - } + ySize = 190; + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - IAlvearyControllerInternal alvearyController = inventory.getMultiblockLogic().getController(); - drawHealthMeter(guiLeft + 20, guiTop + 37, alvearyController.getHealthScaled(46), EnumTankLevel.rateTankLevel(alvearyController.getHealthScaled(100))); - } + IAlvearyControllerInternal alvearyController = + inventory.getMultiblockLogic().getController(); + drawHealthMeter( + guiLeft + 20, + guiTop + 37, + alvearyController.getHealthScaled(46), + EnumTankLevel.rateTankLevel(alvearyController.getHealthScaled(100))); + } - private void drawHealthMeter(int x, int y, int height, EnumTankLevel rated) { - int i = 176 + rated.getLevelScaled(16); - int k = 0; + private void drawHealthMeter(int x, int y, int height, EnumTankLevel rated) { + int i = 176 + rated.getLevelScaled(16); + int k = 0; - this.drawTexturedModalRect(x, y + 46 - height, i, k + 46 - height, 4, height); - } + this.drawTexturedModalRect(x, y + 46 - height, i, k + 46 - height, 4, height); + } } diff --git a/src/main/java/forestry/apiculture/gui/GuiAlvearyHygroregulator.java b/src/main/java/forestry/apiculture/gui/GuiAlvearyHygroregulator.java index 96c5806ca..87060fd84 100755 --- a/src/main/java/forestry/apiculture/gui/GuiAlvearyHygroregulator.java +++ b/src/main/java/forestry/apiculture/gui/GuiAlvearyHygroregulator.java @@ -10,19 +10,21 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.apiculture.multiblock.TileAlvearyHygroregulator; import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; +import net.minecraft.entity.player.InventoryPlayer; -public class GuiAlvearyHygroregulator extends GuiForestryTitled { +public class GuiAlvearyHygroregulator + extends GuiForestryTitled { - public GuiAlvearyHygroregulator(InventoryPlayer inventory, TileAlvearyHygroregulator tile) { - super(Constants.TEXTURE_PATH_GUI + "/hygroregulator.png", new ContainerAlvearyHygroregulator(inventory, tile), tile); - - widgetManager.add(new TankWidget(this.widgetManager, 104, 17, 0)); - } + public GuiAlvearyHygroregulator(InventoryPlayer inventory, TileAlvearyHygroregulator tile) { + super( + Constants.TEXTURE_PATH_GUI + "/hygroregulator.png", + new ContainerAlvearyHygroregulator(inventory, tile), + tile); + widgetManager.add(new TankWidget(this.widgetManager, 104, 17, 0)); + } } diff --git a/src/main/java/forestry/apiculture/gui/GuiAlvearySieve.java b/src/main/java/forestry/apiculture/gui/GuiAlvearySieve.java index 50ebe2a03..bac6e66f5 100755 --- a/src/main/java/forestry/apiculture/gui/GuiAlvearySieve.java +++ b/src/main/java/forestry/apiculture/gui/GuiAlvearySieve.java @@ -10,16 +10,14 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.apiculture.multiblock.TileAlvearySieve; import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; +import net.minecraft.entity.player.InventoryPlayer; public class GuiAlvearySieve extends GuiForestryTitled { - public GuiAlvearySieve(InventoryPlayer inventory, TileAlvearySieve tile) { - super(Constants.TEXTURE_PATH_GUI + "/sieve.png", new ContainerAlvearySieve(inventory, tile), tile); - } - + public GuiAlvearySieve(InventoryPlayer inventory, TileAlvearySieve tile) { + super(Constants.TEXTURE_PATH_GUI + "/sieve.png", new ContainerAlvearySieve(inventory, tile), tile); + } } diff --git a/src/main/java/forestry/apiculture/gui/GuiAlvearySwarmer.java b/src/main/java/forestry/apiculture/gui/GuiAlvearySwarmer.java index 8d159a1cc..5bca6cacd 100755 --- a/src/main/java/forestry/apiculture/gui/GuiAlvearySwarmer.java +++ b/src/main/java/forestry/apiculture/gui/GuiAlvearySwarmer.java @@ -10,16 +10,14 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.apiculture.multiblock.TileAlvearySwarmer; import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; +import net.minecraft.entity.player.InventoryPlayer; public class GuiAlvearySwarmer extends GuiForestryTitled { - public GuiAlvearySwarmer(InventoryPlayer inventory, TileAlvearySwarmer tile) { - super(Constants.TEXTURE_PATH_GUI + "/swarmer.png", new ContainerAlvearySwarmer(inventory, tile), tile); - } - + public GuiAlvearySwarmer(InventoryPlayer inventory, TileAlvearySwarmer tile) { + super(Constants.TEXTURE_PATH_GUI + "/swarmer.png", new ContainerAlvearySwarmer(inventory, tile), tile); + } } diff --git a/src/main/java/forestry/apiculture/gui/GuiBeeHousing.java b/src/main/java/forestry/apiculture/gui/GuiBeeHousing.java index 45d62dd9c..677313264 100644 --- a/src/main/java/forestry/apiculture/gui/GuiBeeHousing.java +++ b/src/main/java/forestry/apiculture/gui/GuiBeeHousing.java @@ -10,42 +10,45 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.inventory.Container; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.render.EnumTankLevel; +import net.minecraft.inventory.Container; -public class GuiBeeHousing extends GuiForestryTitled { +public class GuiBeeHousing + extends GuiForestryTitled { - public enum Icon { - APIARY("/apiary.png"), - BEE_HOUSE("/alveary.png"); + public enum Icon { + APIARY("/apiary.png"), + BEE_HOUSE("/alveary.png"); - private final String path; + private final String path; - Icon(String path) { - this.path = path; - } - } + Icon(String path) { + this.path = path; + } + } - public GuiBeeHousing(IGuiBeeHousingInventory tile, C container, Icon icon) { - super(Constants.TEXTURE_PATH_GUI + icon.path, container, tile); - ySize = 190; - } + public GuiBeeHousing(IGuiBeeHousingInventory tile, C container, Icon icon) { + super(Constants.TEXTURE_PATH_GUI + icon.path, container, tile); + ySize = 190; + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - drawHealthMeter(guiLeft + 20, guiTop + 37, inventory.getHealthScaled(46), EnumTankLevel.rateTankLevel(inventory.getHealthScaled(100))); - } + drawHealthMeter( + guiLeft + 20, + guiTop + 37, + inventory.getHealthScaled(46), + EnumTankLevel.rateTankLevel(inventory.getHealthScaled(100))); + } - private void drawHealthMeter(int x, int y, int height, EnumTankLevel rated) { - int i = 176 + rated.getLevelScaled(16); - int k = 0; - - this.drawTexturedModalRect(x, y + 46 - height, i, k + 46 - height, 4, height); - } + private void drawHealthMeter(int x, int y, int height, EnumTankLevel rated) { + int i = 176 + rated.getLevelScaled(16); + int k = 0; + this.drawTexturedModalRect(x, y + 46 - height, i, k + 46 - height, 4, height); + } } diff --git a/src/main/java/forestry/apiculture/gui/GuiBeealyzer.java b/src/main/java/forestry/apiculture/gui/GuiBeealyzer.java index bdf93cbc7..873baa063 100755 --- a/src/main/java/forestry/apiculture/gui/GuiBeealyzer.java +++ b/src/main/java/forestry/apiculture/gui/GuiBeealyzer.java @@ -10,11 +10,6 @@ ******************************************************************************/ package forestry.apiculture.gui; -import java.util.ArrayList; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.EnumBeeType; @@ -31,247 +26,278 @@ import forestry.core.gui.GuiAlyzer; import forestry.core.gui.widgets.ItemStackWidget; import forestry.core.utils.StringUtil; import forestry.plugins.PluginApiculture; +import java.util.ArrayList; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; public class GuiBeealyzer extends GuiAlyzer { - public GuiBeealyzer(EntityPlayer player, ItemInventoryBeealyzer inventory) { - super(BeeManager.beeRoot, player, new ContainerAlyzer(inventory, player), inventory, "gui.beealyzer"); + public GuiBeealyzer(EntityPlayer player, ItemInventoryBeealyzer inventory) { + super(BeeManager.beeRoot, player, new ContainerAlyzer(inventory, player), inventory, "gui.beealyzer"); - ArrayList beeList = new ArrayList<>(); - PluginApiculture.items.beeDroneGE.addCreativeItems(beeList, false); - for (ItemStack beeStack : beeList) { - IAlleleBeeSpecies species = BeeGenome.getSpecies(beeStack); - if (species != null) { - iconStacks.put(species.getUID(), beeStack); - } - } - } + ArrayList beeList = new ArrayList<>(); + PluginApiculture.items.beeDroneGE.addCreativeItems(beeList, false); + for (ItemStack beeStack : beeList) { + IAlleleBeeSpecies species = BeeGenome.getSpecies(beeStack); + if (species != null) { + iconStacks.put(species.getUID(), beeStack); + } + } + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - int page = 0; - IBee bee = null; - EnumBeeType beeType = EnumBeeType.DRONE; + int page = 0; + IBee bee = null; + EnumBeeType beeType = EnumBeeType.DRONE; - for (int k = ItemInventoryBeealyzer.SLOT_SPECIMEN; k <= ItemInventoryBeealyzer.SLOT_ANALYZE_5; k++) { - if (k == ItemInventoryBeealyzer.SLOT_ENERGY) { - continue; - } + for (int k = ItemInventoryBeealyzer.SLOT_SPECIMEN; k <= ItemInventoryBeealyzer.SLOT_ANALYZE_5; k++) { + if (k == ItemInventoryBeealyzer.SLOT_ENERGY) { + continue; + } - if (inventory.getStackInSlot(k) == null) { - continue; - } - bee = BeeManager.beeRoot.getMember(inventory.getStackInSlot(k)); - beeType = BeeManager.beeRoot.getType(inventory.getStackInSlot(k)); - if (bee == null || !bee.isAnalyzed()) { - continue; - } + if (inventory.getStackInSlot(k) == null) { + continue; + } + bee = BeeManager.beeRoot.getMember(inventory.getStackInSlot(k)); + beeType = BeeManager.beeRoot.getType(inventory.getStackInSlot(k)); + if (bee == null || !bee.isAnalyzed()) { + continue; + } - page = k; - break; - } + page = k; + break; + } - switch (page) { - case 1: - drawAnalyticsPage1(bee, beeType); - break; - case 2: - drawAnalyticsPage2(bee, beeType); - break; - case 3: - drawAnalyticsPage3(bee); - break; - case 4: - drawAnalyticsPageMutations(bee); - break; - case 6: - drawAnalyticsPageClassification(bee); - break; - default: - drawAnalyticsOverview(); - } + switch (page) { + case 1: + drawAnalyticsPage1(bee, beeType); + break; + case 2: + drawAnalyticsPage2(bee, beeType); + break; + case 3: + drawAnalyticsPage3(bee); + break; + case 4: + drawAnalyticsPageMutations(bee); + break; + case 6: + drawAnalyticsPageClassification(bee); + break; + default: + drawAnalyticsOverview(); + } + } - } + private void drawAnalyticsPage1(IBee bee, EnumBeeType type) { - private void drawAnalyticsPage1(IBee bee, EnumBeeType type) { + textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); - textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); + textLayout.drawLine(StringUtil.localize("gui.active"), COLUMN_1); + textLayout.drawLine(StringUtil.localize("gui.inactive"), COLUMN_2); - textLayout.drawLine(StringUtil.localize("gui.active"), COLUMN_1); - textLayout.drawLine(StringUtil.localize("gui.inactive"), COLUMN_2); + textLayout.newLine(); + textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); + { + String customPrimaryBeeKey = "bees.custom.beealyzer." + type.getName() + "." + + bee.getGenome().getPrimary().getUnlocalizedName().replace("bees.species.", ""); + String customSecondaryBeeKey = "bees.custom.beealyzer." + type.getName() + "." + + bee.getGenome().getSecondary().getUnlocalizedName().replace("bees.species.", ""); - { - String customPrimaryBeeKey = "bees.custom.beealyzer." + type.getName() + "." + bee.getGenome().getPrimary().getUnlocalizedName().replace("bees.species.", ""); - String customSecondaryBeeKey = "bees.custom.beealyzer." + type.getName() + "." + bee.getGenome().getSecondary().getUnlocalizedName().replace("bees.species.", ""); + drawSpeciesRow( + StringUtil.localize("gui.species"), + bee, + EnumBeeChromosome.SPECIES, + checkCustomName(customPrimaryBeeKey), + checkCustomName(customSecondaryBeeKey)); + textLayout.newLine(); + } - drawSpeciesRow(StringUtil.localize("gui.species"), bee, EnumBeeChromosome.SPECIES, checkCustomName(customPrimaryBeeKey), checkCustomName(customSecondaryBeeKey)); - textLayout.newLine(); - } + drawChromosomeRow(StringUtil.localize("gui.lifespan"), bee, EnumBeeChromosome.LIFESPAN); + textLayout.newLine(); + drawChromosomeRow(StringUtil.localize("gui.speed"), bee, EnumBeeChromosome.SPEED); + textLayout.newLine(); + drawChromosomeRow(StringUtil.localize("gui.pollination"), bee, EnumBeeChromosome.FLOWERING); + textLayout.newLine(); + drawChromosomeRow(StringUtil.localize("gui.flowers"), bee, EnumBeeChromosome.FLOWER_PROVIDER); + textLayout.newLine(); - drawChromosomeRow(StringUtil.localize("gui.lifespan"), bee, EnumBeeChromosome.LIFESPAN); - textLayout.newLine(); - drawChromosomeRow(StringUtil.localize("gui.speed"), bee, EnumBeeChromosome.SPEED); - textLayout.newLine(); - drawChromosomeRow(StringUtil.localize("gui.pollination"), bee, EnumBeeChromosome.FLOWERING); - textLayout.newLine(); - drawChromosomeRow(StringUtil.localize("gui.flowers"), bee, EnumBeeChromosome.FLOWER_PROVIDER); - textLayout.newLine(); + textLayout.drawLine(StringUtil.localize("gui.fertility"), COLUMN_0); + IAlleleInteger primaryFertility = (IAlleleInteger) bee.getGenome().getActiveAllele(EnumBeeChromosome.FERTILITY); + IAlleleInteger secondaryFertility = + (IAlleleInteger) bee.getGenome().getInactiveAllele(EnumBeeChromosome.FERTILITY); + drawFertilityInfo(primaryFertility.getValue(), COLUMN_1, getColorCoding(primaryFertility.isDominant()), 0); + drawFertilityInfo(secondaryFertility.getValue(), COLUMN_2, getColorCoding(secondaryFertility.isDominant()), 0); + textLayout.newLine(); - textLayout.drawLine(StringUtil.localize("gui.fertility"), COLUMN_0); - IAlleleInteger primaryFertility = (IAlleleInteger) bee.getGenome().getActiveAllele(EnumBeeChromosome.FERTILITY); - IAlleleInteger secondaryFertility = (IAlleleInteger) bee.getGenome().getInactiveAllele(EnumBeeChromosome.FERTILITY); - drawFertilityInfo(primaryFertility.getValue(), COLUMN_1, getColorCoding(primaryFertility.isDominant()), 0); - drawFertilityInfo(secondaryFertility.getValue(), COLUMN_2, getColorCoding(secondaryFertility.isDominant()), 0); - textLayout.newLine(); + drawChromosomeRow(StringUtil.localize("gui.area"), bee, EnumBeeChromosome.TERRITORY); + textLayout.newLine(); - drawChromosomeRow(StringUtil.localize("gui.area"), bee, EnumBeeChromosome.TERRITORY); - textLayout.newLine(); + drawChromosomeRow(StringUtil.localize("gui.effect"), bee, EnumBeeChromosome.EFFECT); + textLayout.newLine(); - drawChromosomeRow(StringUtil.localize("gui.effect"), bee, EnumBeeChromosome.EFFECT); - textLayout.newLine(); + textLayout.endPage(); + } - textLayout.endPage(); - } + private void drawAnalyticsPage2(IBee bee, EnumBeeType type) { - private void drawAnalyticsPage2(IBee bee, EnumBeeType type) { + textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); - textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); + textLayout.drawLine(StringUtil.localize("gui.active"), COLUMN_1); + textLayout.drawLine(StringUtil.localize("gui.inactive"), COLUMN_2); - textLayout.drawLine(StringUtil.localize("gui.active"), COLUMN_1); - textLayout.drawLine(StringUtil.localize("gui.inactive"), COLUMN_2); + textLayout.newLine(); - textLayout.newLine(); + drawRow( + StringUtil.localize("gui.climate"), + AlleleManager.climateHelper.toDisplay( + bee.getGenome().getPrimary().getTemperature()), + AlleleManager.climateHelper.toDisplay( + bee.getGenome().getSecondary().getTemperature()), + bee, + EnumBeeChromosome.SPECIES); - drawRow(StringUtil.localize("gui.climate"), AlleleManager.climateHelper.toDisplay(bee.getGenome().getPrimary().getTemperature()), - AlleleManager.climateHelper.toDisplay(bee.getGenome().getSecondary().getTemperature()), bee, EnumBeeChromosome.SPECIES); + textLayout.newLine(); - textLayout.newLine(); + IAlleleTolerance tempToleranceActive = + (IAlleleTolerance) bee.getGenome().getActiveAllele(EnumBeeChromosome.TEMPERATURE_TOLERANCE); + IAlleleTolerance tempToleranceInactive = + (IAlleleTolerance) bee.getGenome().getInactiveAllele(EnumBeeChromosome.TEMPERATURE_TOLERANCE); + textLayout.drawLine(" " + StringUtil.localize("gui.tolerance"), COLUMN_0); + drawToleranceInfo(tempToleranceActive, COLUMN_1); + drawToleranceInfo(tempToleranceInactive, COLUMN_2); - IAlleleTolerance tempToleranceActive = (IAlleleTolerance) bee.getGenome().getActiveAllele(EnumBeeChromosome.TEMPERATURE_TOLERANCE); - IAlleleTolerance tempToleranceInactive = (IAlleleTolerance) bee.getGenome().getInactiveAllele(EnumBeeChromosome.TEMPERATURE_TOLERANCE); - textLayout.drawLine(" " + StringUtil.localize("gui.tolerance"), COLUMN_0); - drawToleranceInfo(tempToleranceActive, COLUMN_1); - drawToleranceInfo(tempToleranceInactive, COLUMN_2); + textLayout.newLine(16); - textLayout.newLine(16); + drawRow( + StringUtil.localize("gui.humidity"), + AlleleManager.climateHelper.toDisplay( + bee.getGenome().getPrimary().getHumidity()), + AlleleManager.climateHelper.toDisplay( + bee.getGenome().getSecondary().getHumidity()), + bee, + EnumBeeChromosome.SPECIES); - drawRow(StringUtil.localize("gui.humidity"), AlleleManager.climateHelper.toDisplay(bee.getGenome().getPrimary().getHumidity()), - AlleleManager.climateHelper.toDisplay(bee.getGenome().getSecondary().getHumidity()), bee, EnumBeeChromosome.SPECIES); + textLayout.newLine(); - textLayout.newLine(); + IAlleleTolerance humidToleranceActive = + (IAlleleTolerance) bee.getGenome().getActiveAllele(EnumBeeChromosome.HUMIDITY_TOLERANCE); + IAlleleTolerance humidToleranceInactive = + (IAlleleTolerance) bee.getGenome().getInactiveAllele(EnumBeeChromosome.HUMIDITY_TOLERANCE); + textLayout.drawLine(" " + StringUtil.localize("gui.tolerance"), COLUMN_0); + drawToleranceInfo(humidToleranceActive, COLUMN_1); + drawToleranceInfo(humidToleranceInactive, COLUMN_2); - IAlleleTolerance humidToleranceActive = (IAlleleTolerance) bee.getGenome().getActiveAllele(EnumBeeChromosome.HUMIDITY_TOLERANCE); - IAlleleTolerance humidToleranceInactive = (IAlleleTolerance) bee.getGenome().getInactiveAllele(EnumBeeChromosome.HUMIDITY_TOLERANCE); - textLayout.drawLine(" " + StringUtil.localize("gui.tolerance"), COLUMN_0); - drawToleranceInfo(humidToleranceActive, COLUMN_1); - drawToleranceInfo(humidToleranceInactive, COLUMN_2); + textLayout.newLine(16); - textLayout.newLine(16); + String yes = StringUtil.localize("yes"); + String no = StringUtil.localize("no"); - String yes = StringUtil.localize("yes"); - String no = StringUtil.localize("no"); + String diurnal0, diurnal1, nocturnal0, nocturnal1; + if (bee.getGenome().getNocturnal()) { + nocturnal0 = diurnal0 = yes; + } else { + nocturnal0 = bee.getGenome().getPrimary().isNocturnal() ? yes : no; + diurnal0 = !bee.getGenome().getPrimary().isNocturnal() ? yes : no; + } + if (((AlleleBoolean) bee.getGenome().getInactiveAllele(EnumBeeChromosome.NOCTURNAL)).getValue()) { + nocturnal1 = diurnal1 = yes; + } else { + nocturnal1 = bee.getGenome().getSecondary().isNocturnal() ? yes : no; + diurnal1 = !bee.getGenome().getSecondary().isNocturnal() ? yes : no; + } - String diurnal0, diurnal1, nocturnal0, nocturnal1; - if (bee.getGenome().getNocturnal()) { - nocturnal0 = diurnal0 = yes; - } else { - nocturnal0 = bee.getGenome().getPrimary().isNocturnal() ? yes : no; - diurnal0 = !bee.getGenome().getPrimary().isNocturnal() ? yes : no; - } - if (((AlleleBoolean) bee.getGenome().getInactiveAllele(EnumBeeChromosome.NOCTURNAL)).getValue()) { - nocturnal1 = diurnal1 = yes; - } else { - nocturnal1 = bee.getGenome().getSecondary().isNocturnal() ? yes : no; - diurnal1 = !bee.getGenome().getSecondary().isNocturnal() ? yes : no; - } + textLayout.drawLine(StringUtil.localize("gui.diurnal"), COLUMN_0); + textLayout.drawLine(diurnal0, COLUMN_1, getColorCoding(false)); + textLayout.drawLine(diurnal1, COLUMN_2, getColorCoding(false)); + textLayout.newLineCompressed(); - textLayout.drawLine(StringUtil.localize("gui.diurnal"), COLUMN_0); - textLayout.drawLine(diurnal0, COLUMN_1, getColorCoding(false)); - textLayout.drawLine(diurnal1, COLUMN_2, getColorCoding(false)); - textLayout.newLineCompressed(); + textLayout.drawLine(StringUtil.localize("gui.nocturnal"), COLUMN_0); + textLayout.drawLine(nocturnal0, COLUMN_1, getColorCoding(false)); + textLayout.drawLine(nocturnal1, COLUMN_2, getColorCoding(false)); + textLayout.newLineCompressed(); - textLayout.drawLine(StringUtil.localize("gui.nocturnal"), COLUMN_0); - textLayout.drawLine(nocturnal0, COLUMN_1, getColorCoding(false)); - textLayout.drawLine(nocturnal1, COLUMN_2, getColorCoding(false)); - textLayout.newLineCompressed(); + String primary = StringUtil.readableBoolean(bee.getGenome().getTolerantFlyer(), yes, no); + String secondary = StringUtil.readableBoolean( + ((AlleleBoolean) bee.getGenome().getInactiveAllele(EnumBeeChromosome.TOLERANT_FLYER)).getValue(), + yes, + no); - String primary = StringUtil.readableBoolean(bee.getGenome().getTolerantFlyer(), yes, no); - String secondary = StringUtil.readableBoolean(((AlleleBoolean) bee.getGenome().getInactiveAllele(EnumBeeChromosome.TOLERANT_FLYER)).getValue(), yes, no); + drawRow(StringUtil.localize("gui.flyer"), primary, secondary, bee, EnumBeeChromosome.TOLERANT_FLYER); - drawRow(StringUtil.localize("gui.flyer"), primary, secondary, bee, EnumBeeChromosome.TOLERANT_FLYER); + textLayout.newLineCompressed(); - textLayout.newLineCompressed(); + primary = StringUtil.readableBoolean(bee.getGenome().getCaveDwelling(), yes, no); + secondary = StringUtil.readableBoolean( + ((AlleleBoolean) bee.getGenome().getInactiveAllele(EnumBeeChromosome.CAVE_DWELLING)).getValue(), + yes, + no); - primary = StringUtil.readableBoolean(bee.getGenome().getCaveDwelling(), yes, no); - secondary = StringUtil.readableBoolean(((AlleleBoolean) bee.getGenome().getInactiveAllele(EnumBeeChromosome.CAVE_DWELLING)).getValue(), yes, no); + drawRow(StringUtil.localize("gui.cave"), primary, secondary, bee, EnumBeeChromosome.CAVE_DWELLING); - drawRow(StringUtil.localize("gui.cave"), primary, secondary, bee, EnumBeeChromosome.CAVE_DWELLING); + textLayout.newLine(); - textLayout.newLine(); + String displayText; + if (type == EnumBeeType.PRINCESS || type == EnumBeeType.QUEEN) { + displayText = "bees.stock.pristine"; + if (!bee.isNatural()) { + displayText = "bees.stock.ignoble"; + } + displayText = StringUtil.localize(displayText); + textLayout.drawCenteredLine(displayText, 8, 208, fontColor.get("gui.beealyzer.binomial")); + } - String displayText; - if (type == EnumBeeType.PRINCESS || type == EnumBeeType.QUEEN) { - displayText = "bees.stock.pristine"; - if (!bee.isNatural()) { - displayText = "bees.stock.ignoble"; - } - displayText = StringUtil.localize(displayText); - textLayout.drawCenteredLine(displayText, 8, 208, fontColor.get("gui.beealyzer.binomial")); - } + if (bee.getGeneration() >= 0) { + textLayout.newLineCompressed(); + displayText = StringUtil.localizeAndFormat("gui.beealyzer.generations", bee.getGeneration()); + textLayout.drawCenteredLine(displayText, 8, 208, fontColor.get("gui.beealyzer.binomial")); + } - if (bee.getGeneration() >= 0) { - textLayout.newLineCompressed(); - displayText = StringUtil.localizeAndFormat("gui.beealyzer.generations", bee.getGeneration()); - textLayout.drawCenteredLine(displayText, 8, 208, fontColor.get("gui.beealyzer.binomial")); - } + textLayout.endPage(); + } - textLayout.endPage(); - } + private void drawAnalyticsPage3(IBee bee) { - private void drawAnalyticsPage3(IBee bee) { + textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); - textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); + textLayout.drawLine(StringUtil.localize("gui.beealyzer.produce") + ":", COLUMN_0); - textLayout.drawLine(StringUtil.localize("gui.beealyzer.produce") + ":", COLUMN_0); + textLayout.newLine(); - textLayout.newLine(); + int x = COLUMN_0; + for (ItemStack stack : bee.getProduceList()) { + widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), stack)); - int x = COLUMN_0; - for (ItemStack stack : bee.getProduceList()) { - widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), stack)); + x += 18; + if (x > 148) { + x = COLUMN_0; + textLayout.newLine(); + } + } - x += 18; - if (x > 148) { - x = COLUMN_0; - textLayout.newLine(); - } - } + textLayout.newLine(); + textLayout.newLine(); + textLayout.newLine(); + textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); + textLayout.drawLine(StringUtil.localize("gui.beealyzer.specialty") + ":", COLUMN_0); + textLayout.newLine(); - textLayout.drawLine(StringUtil.localize("gui.beealyzer.specialty") + ":", COLUMN_0); - textLayout.newLine(); + x = COLUMN_0; + for (ItemStack stack : bee.getSpecialtyList()) { + widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), stack)); - x = COLUMN_0; - for (ItemStack stack : bee.getSpecialtyList()) { - widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), stack)); - - x += 18; - if (x > 148) { - x = COLUMN_0; - textLayout.newLine(); - } - } - - textLayout.endPage(); - } + x += 18; + if (x > 148) { + x = COLUMN_0; + textLayout.newLine(); + } + } + textLayout.endPage(); + } } diff --git a/src/main/java/forestry/apiculture/gui/GuiHabitatLocator.java b/src/main/java/forestry/apiculture/gui/GuiHabitatLocator.java index a92cd4585..45ec79e17 100755 --- a/src/main/java/forestry/apiculture/gui/GuiHabitatLocator.java +++ b/src/main/java/forestry/apiculture/gui/GuiHabitatLocator.java @@ -11,7 +11,10 @@ package forestry.apiculture.gui; import com.google.common.collect.LinkedListMultimap; - +import forestry.apiculture.gui.widgets.HabitatSlot; +import forestry.apiculture.inventory.ItemInventoryHabitatLocator; +import forestry.core.config.Constants; +import forestry.core.gui.GuiForestry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -19,96 +22,90 @@ import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.StatCollector; import net.minecraft.world.biome.BiomeGenBase; - import net.minecraftforge.common.BiomeDictionary; - import org.lwjgl.opengl.GL11; -import forestry.apiculture.gui.widgets.HabitatSlot; -import forestry.apiculture.inventory.ItemInventoryHabitatLocator; -import forestry.core.config.Constants; -import forestry.core.gui.GuiForestry; - public class GuiHabitatLocator extends GuiForestry { - private static final LinkedListMultimap habitats = LinkedListMultimap.create(); + private static final LinkedListMultimap habitats = LinkedListMultimap.create(); - static { - habitats.putAll("Ocean", Arrays.asList(BiomeDictionary.Type.OCEAN, BiomeDictionary.Type.BEACH)); - habitats.put("Plains", BiomeDictionary.Type.PLAINS); - habitats.put("Desert", BiomeDictionary.Type.SANDY); - habitats.putAll("Forest", Arrays.asList(BiomeDictionary.Type.FOREST, BiomeDictionary.Type.RIVER)); - habitats.put("Jungle", BiomeDictionary.Type.JUNGLE); - habitats.put("Taiga", BiomeDictionary.Type.CONIFEROUS); - habitats.put("Hills", BiomeDictionary.Type.MOUNTAIN); - habitats.put("Swamp", BiomeDictionary.Type.SWAMP); - habitats.put("Snow", BiomeDictionary.Type.SNOWY); - habitats.put("Mushroom", BiomeDictionary.Type.MUSHROOM); - habitats.put("Nether", BiomeDictionary.Type.NETHER); - habitats.put("End", BiomeDictionary.Type.END); - } + static { + habitats.putAll("Ocean", Arrays.asList(BiomeDictionary.Type.OCEAN, BiomeDictionary.Type.BEACH)); + habitats.put("Plains", BiomeDictionary.Type.PLAINS); + habitats.put("Desert", BiomeDictionary.Type.SANDY); + habitats.putAll("Forest", Arrays.asList(BiomeDictionary.Type.FOREST, BiomeDictionary.Type.RIVER)); + habitats.put("Jungle", BiomeDictionary.Type.JUNGLE); + habitats.put("Taiga", BiomeDictionary.Type.CONIFEROUS); + habitats.put("Hills", BiomeDictionary.Type.MOUNTAIN); + habitats.put("Swamp", BiomeDictionary.Type.SWAMP); + habitats.put("Snow", BiomeDictionary.Type.SNOWY); + habitats.put("Mushroom", BiomeDictionary.Type.MUSHROOM); + habitats.put("Nether", BiomeDictionary.Type.NETHER); + habitats.put("End", BiomeDictionary.Type.END); + } - private final List habitatSlots = new ArrayList<>(habitats.size()); + private final List habitatSlots = new ArrayList<>(habitats.size()); - private int startX; - private int startY; + private int startX; + private int startY; - public GuiHabitatLocator(EntityPlayer player, ItemInventoryHabitatLocator item) { - super(Constants.TEXTURE_PATH_GUI + "/biomefinder.png", new ContainerHabitatLocator(player, item), item); + public GuiHabitatLocator(EntityPlayer player, ItemInventoryHabitatLocator item) { + super(Constants.TEXTURE_PATH_GUI + "/biomefinder.png", new ContainerHabitatLocator(player, item), item); - xSize = 176; - ySize = 184; + xSize = 176; + ySize = 184; - int slot = 0; - for (String habitatName : habitats.keySet()) { - int x; - int y; - if (slot > 5) { - x = 18 + (slot - 6) * 20; - y = 50; - } else { - x = 18 + slot * 20; - y = 32; - } - Collection biomes = habitats.get(habitatName); - HabitatSlot habitatSlot = new HabitatSlot(widgetManager, x, y, habitatName, biomes); - habitatSlots.add(habitatSlot); - widgetManager.add(habitatSlot); - slot++; - } - } + int slot = 0; + for (String habitatName : habitats.keySet()) { + int x; + int y; + if (slot > 5) { + x = 18 + (slot - 6) * 20; + y = 50; + } else { + x = 18 + slot * 20; + y = 32; + } + Collection biomes = habitats.get(habitatName); + HabitatSlot habitatSlot = new HabitatSlot(widgetManager, x, y, habitatName, biomes); + habitatSlots.add(habitatSlot); + widgetManager.add(habitatSlot); + slot++; + } + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - String str = StatCollector.translateToLocal("item.for.habitatLocator.name").toUpperCase(); - fontRendererObj.drawString(str, startX + 8 + textLayout.getCenteredOffset(str, 138), startY + 16, fontColor.get("gui.screen")); + String str = + StatCollector.translateToLocal("item.for.habitatLocator.name").toUpperCase(); + fontRendererObj.drawString( + str, startX + 8 + textLayout.getCenteredOffset(str, 138), startY + 16, fontColor.get("gui.screen")); - // Set active according to valid biomes. - Set activeBiomeTypes = EnumSet.noneOf(BiomeDictionary.Type.class); - for (BiomeGenBase biome : inventory.getBiomesToSearch()) { - Collections.addAll(activeBiomeTypes, BiomeDictionary.getTypesForBiome(biome)); - } + // Set active according to valid biomes. + Set activeBiomeTypes = EnumSet.noneOf(BiomeDictionary.Type.class); + for (BiomeGenBase biome : inventory.getBiomesToSearch()) { + Collections.addAll(activeBiomeTypes, BiomeDictionary.getTypesForBiome(biome)); + } - for (HabitatSlot habitatSlot : habitatSlots) { - habitatSlot.setActive(activeBiomeTypes); - } + for (HabitatSlot habitatSlot : habitatSlots) { + habitatSlot.setActive(activeBiomeTypes); + } - for (HabitatSlot slot : habitatSlots) { - slot.draw(startX, startY); - } - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // Reset afterwards. - } + for (HabitatSlot slot : habitatSlots) { + slot.draw(startX, startY); + } + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // Reset afterwards. + } - @Override - public void initGui() { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - startX = (this.width - this.xSize) / 2; - startY = (this.height - this.ySize) / 2; - } + startX = (this.width - this.xSize) / 2; + startY = (this.height - this.ySize) / 2; + } } diff --git a/src/main/java/forestry/apiculture/gui/GuiImprinter.java b/src/main/java/forestry/apiculture/gui/GuiImprinter.java index e068470f8..8bc2adb16 100755 --- a/src/main/java/forestry/apiculture/gui/GuiImprinter.java +++ b/src/main/java/forestry/apiculture/gui/GuiImprinter.java @@ -10,14 +10,6 @@ ******************************************************************************/ package forestry.apiculture.gui; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; - import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.apiculture.genetics.BeeGenome; import forestry.apiculture.inventory.ItemInventoryImprinter; @@ -28,104 +20,116 @@ import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.proxy.Proxies; import forestry.core.utils.StringUtil; import forestry.plugins.PluginApiculture; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; public class GuiImprinter extends GuiForestry { - private int startX; - private int startY; + private int startX; + private int startY; - private final Map iconStacks = new HashMap<>(); + private final Map iconStacks = new HashMap<>(); - public GuiImprinter(InventoryPlayer inventoryplayer, ItemInventoryImprinter inventory) { - super(Constants.TEXTURE_PATH_GUI + "/imprinter.png", new ContainerImprinter(inventoryplayer, inventory), inventory); + public GuiImprinter(InventoryPlayer inventoryplayer, ItemInventoryImprinter inventory) { + super( + Constants.TEXTURE_PATH_GUI + "/imprinter.png", + new ContainerImprinter(inventoryplayer, inventory), + inventory); - xSize = 176; - ySize = 185; + xSize = 176; + ySize = 185; - List beeList = new ArrayList<>(); - PluginApiculture.items.beeDroneGE.addCreativeItems(beeList, false); - for (ItemStack beeStack : beeList) { - IAlleleBeeSpecies species = BeeGenome.getSpecies(beeStack); - if (species != null) { - iconStacks.put(species.getUID(), beeStack); - } - } - } + List beeList = new ArrayList<>(); + PluginApiculture.items.beeDroneGE.addCreativeItems(beeList, false); + for (ItemStack beeStack : beeList) { + IAlleleBeeSpecies species = BeeGenome.getSpecies(beeStack); + if (species != null) { + iconStacks.put(species.getUID(), beeStack); + } + } + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - int offset = (138 - fontRendererObj.getStringWidth(StringUtil.localize("gui.imprinter.name"))) / 2; - fontRendererObj.drawString(StringUtil.localize("gui.imprinter.name"), startX + 8 + offset, startY + 16, fontColor.get("gui.screen")); + int offset = (138 - fontRendererObj.getStringWidth(StringUtil.localize("gui.imprinter.name"))) / 2; + fontRendererObj.drawString( + StringUtil.localize("gui.imprinter.name"), + startX + 8 + offset, + startY + 16, + fontColor.get("gui.screen")); - IAlleleBeeSpecies primary = inventory.getPrimary(); - drawBeeSpeciesIcon(primary, startX + 12, startY + 32); - fontRendererObj.drawString(primary.getName(), startX + 32, startY + 36, fontColor.get("gui.screen")); + IAlleleBeeSpecies primary = inventory.getPrimary(); + drawBeeSpeciesIcon(primary, startX + 12, startY + 32); + fontRendererObj.drawString(primary.getName(), startX + 32, startY + 36, fontColor.get("gui.screen")); - IAlleleBeeSpecies secondary = inventory.getSecondary(); - drawBeeSpeciesIcon(secondary, startX + 12, startY + 52); - fontRendererObj.drawString(secondary.getName(), startX + 32, startY + 56, fontColor.get("gui.screen")); + IAlleleBeeSpecies secondary = inventory.getSecondary(); + drawBeeSpeciesIcon(secondary, startX + 12, startY + 52); + fontRendererObj.drawString(secondary.getName(), startX + 32, startY + 56, fontColor.get("gui.screen")); - String youCheater = StringUtil.localize("gui.imprinter.cheater"); - offset = (138 - fontRendererObj.getStringWidth(youCheater)) / 2; - fontRendererObj.drawString(youCheater, startX + 8 + offset, startY + 76, fontColor.get("gui.screen")); + String youCheater = StringUtil.localize("gui.imprinter.cheater"); + offset = (138 - fontRendererObj.getStringWidth(youCheater)) / 2; + fontRendererObj.drawString(youCheater, startX + 8 + offset, startY + 76, fontColor.get("gui.screen")); + } - } + private void drawBeeSpeciesIcon(IAlleleBeeSpecies bee, int x, int y) { + GuiUtil.drawItemStack(this, iconStacks.get(bee.getUID()), x, y); + } - private void drawBeeSpeciesIcon(IAlleleBeeSpecies bee, int x, int y) { - GuiUtil.drawItemStack(this, iconStacks.get(bee.getUID()), x, y); - } + private static int getHabitatSlotAtPosition(int i, int j) { + int[] xPos = new int[] {12, 12}; + int[] yPos = new int[] {32, 52}; - private static int getHabitatSlotAtPosition(int i, int j) { - int[] xPos = new int[]{12, 12}; - int[] yPos = new int[]{32, 52}; + for (int l = 0; l < xPos.length; l++) { + if (i >= xPos[l] && i <= xPos[l] + 16 && j >= yPos[l] && j <= yPos[l] + 16) { + return l; + } + } - for (int l = 0; l < xPos.length; l++) { - if (i >= xPos[l] && i <= xPos[l] + 16 && j >= yPos[l] && j <= yPos[l] + 16) { - return l; - } - } + return -1; + } - return -1; - } + @Override + protected void mouseClicked(int i, int j, int k) { + super.mouseClicked(i, j, k); - @Override - protected void mouseClicked(int i, int j, int k) { - super.mouseClicked(i, j, k); + int cornerX = (width - xSize) / 2; + int cornerY = (height - ySize) / 2; - int cornerX = (width - xSize) / 2; - int cornerY = (height - ySize) / 2; + int slot = getHabitatSlotAtPosition(i - cornerX, j - cornerY); + if (slot < 0) { + return; + } - int slot = getHabitatSlotAtPosition(i - cornerX, j - cornerY); - if (slot < 0) { - return; - } + if (k == 0) { + advanceSelection(slot); + } else { + regressSelection(slot); + } + } - if (k == 0) { - advanceSelection(slot); - } else { - regressSelection(slot); - } - } + @Override + public void initGui() { + super.initGui(); - @Override - public void initGui() { - super.initGui(); + startX = (this.width - this.xSize) / 2; + startY = (this.height - this.ySize) / 2; + } - startX = (this.width - this.xSize) / 2; - startY = (this.height - this.ySize) / 2; - } + private static void advanceSelection(int index) { + sendSelectionChange(index, 0); + } - private static void advanceSelection(int index) { - sendSelectionChange(index, 0); - } + private static void regressSelection(int index) { + sendSelectionChange(index, 1); + } - private static void regressSelection(int index) { - sendSelectionChange(index, 1); - } - - private static void sendSelectionChange(int index, int advance) { - Proxies.net.sendToServer(new PacketGuiSelectRequest(index, advance)); - } + private static void sendSelectionChange(int index, int advance) { + Proxies.net.sendToServer(new PacketGuiSelectRequest(index, advance)); + } } diff --git a/src/main/java/forestry/apiculture/gui/IContainerBeeHousing.java b/src/main/java/forestry/apiculture/gui/IContainerBeeHousing.java index 655b91f51..f3dadd359 100644 --- a/src/main/java/forestry/apiculture/gui/IContainerBeeHousing.java +++ b/src/main/java/forestry/apiculture/gui/IContainerBeeHousing.java @@ -1,14 +1,13 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.gui; - -public interface IContainerBeeHousing { -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.gui; + +public interface IContainerBeeHousing {} diff --git a/src/main/java/forestry/apiculture/gui/IGuiBeeHousingInventory.java b/src/main/java/forestry/apiculture/gui/IGuiBeeHousingInventory.java index de37d8878..a0419f464 100644 --- a/src/main/java/forestry/apiculture/gui/IGuiBeeHousingInventory.java +++ b/src/main/java/forestry/apiculture/gui/IGuiBeeHousingInventory.java @@ -1,20 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.gui; - -import net.minecraft.inventory.IInventory; - -import forestry.core.tiles.ITitled; - -public interface IGuiBeeHousingInventory extends ITitled, IInventory { - /** Returns scaled queen health or breeding progress */ - int getHealthScaled(int i); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.gui; + +import forestry.core.tiles.ITitled; +import net.minecraft.inventory.IInventory; + +public interface IGuiBeeHousingInventory extends ITitled, IInventory { + /** Returns scaled queen health or breeding progress */ + int getHealthScaled(int i); +} diff --git a/src/main/java/forestry/apiculture/gui/widgets/HabitatSlot.java b/src/main/java/forestry/apiculture/gui/widgets/HabitatSlot.java index 270d02eb2..abd1c14ca 100644 --- a/src/main/java/forestry/apiculture/gui/widgets/HabitatSlot.java +++ b/src/main/java/forestry/apiculture/gui/widgets/HabitatSlot.java @@ -1,69 +1,66 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.gui.widgets; - -import java.util.Collection; -import java.util.Collections; -import java.util.Locale; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.IIcon; - -import net.minecraftforge.common.BiomeDictionary; - -import org.lwjgl.opengl.GL11; - -import forestry.core.gui.widgets.Widget; -import forestry.core.gui.widgets.WidgetManager; -import forestry.core.proxy.Proxies; -import forestry.core.render.SpriteSheet; -import forestry.core.render.TextureManager; - -public class HabitatSlot extends Widget { - private final Collection biomes; - private final String name; - private final String iconIndex; - public boolean isActive = false; - - public HabitatSlot(WidgetManager widgetManager, int xPos, int yPos, String name, Collection biomes) { - super(widgetManager, xPos, yPos); - this.biomes = biomes; - this.name = name; - this.iconIndex = "habitats/" + name.toLowerCase(Locale.ENGLISH); - } - - @Override - public String getLegacyTooltip(EntityPlayer player) { - return name; - } - - public IIcon getIcon() { - return TextureManager.getInstance().getDefault(iconIndex); - } - - public void setActive(Collection biomes) { - isActive = !Collections.disjoint(this.biomes, biomes); - } - - @Override - public void draw(int startX, int startY) { - if (getIcon() != null) { - if (!isActive) { - GL11.glColor4f(0.2f, 0.2f, 0.2f, 0.2f); - } else { - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - } - - Proxies.render.bindTexture(SpriteSheet.ITEMS); - manager.gui.drawTexturedModelRectFromIcon(startX + xPos, startY + yPos, getIcon(), 16, 16); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.gui.widgets; + +import forestry.core.gui.widgets.Widget; +import forestry.core.gui.widgets.WidgetManager; +import forestry.core.proxy.Proxies; +import forestry.core.render.SpriteSheet; +import forestry.core.render.TextureManager; +import java.util.Collection; +import java.util.Collections; +import java.util.Locale; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.IIcon; +import net.minecraftforge.common.BiomeDictionary; +import org.lwjgl.opengl.GL11; + +public class HabitatSlot extends Widget { + private final Collection biomes; + private final String name; + private final String iconIndex; + public boolean isActive = false; + + public HabitatSlot( + WidgetManager widgetManager, int xPos, int yPos, String name, Collection biomes) { + super(widgetManager, xPos, yPos); + this.biomes = biomes; + this.name = name; + this.iconIndex = "habitats/" + name.toLowerCase(Locale.ENGLISH); + } + + @Override + public String getLegacyTooltip(EntityPlayer player) { + return name; + } + + public IIcon getIcon() { + return TextureManager.getInstance().getDefault(iconIndex); + } + + public void setActive(Collection biomes) { + isActive = !Collections.disjoint(this.biomes, biomes); + } + + @Override + public void draw(int startX, int startY) { + if (getIcon() != null) { + if (!isActive) { + GL11.glColor4f(0.2f, 0.2f, 0.2f, 0.2f); + } else { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } + + Proxies.render.bindTexture(SpriteSheet.ITEMS); + manager.gui.drawTexturedModelRectFromIcon(startX + xPos, startY + yPos, getIcon(), 16, 16); + } + } +} diff --git a/src/main/java/forestry/apiculture/inventory/IApiaryInventory.java b/src/main/java/forestry/apiculture/inventory/IApiaryInventory.java index babac89b3..6fcd2d81b 100644 --- a/src/main/java/forestry/apiculture/inventory/IApiaryInventory.java +++ b/src/main/java/forestry/apiculture/inventory/IApiaryInventory.java @@ -1,18 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.inventory; - -import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeeHousingInventory; - -public interface IApiaryInventory extends IBeeHousingInventory { - void wearOutFrames(IBeeHousing beeHousing, int amount); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.inventory; + +import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeeHousingInventory; + +public interface IApiaryInventory extends IBeeHousingInventory { + void wearOutFrames(IBeeHousing beeHousing, int amount); +} diff --git a/src/main/java/forestry/apiculture/inventory/InventoryAlvearySieve.java b/src/main/java/forestry/apiculture/inventory/InventoryAlvearySieve.java index 31c3f2482..4b3497343 100644 --- a/src/main/java/forestry/apiculture/inventory/InventoryAlvearySieve.java +++ b/src/main/java/forestry/apiculture/inventory/InventoryAlvearySieve.java @@ -1,70 +1,69 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.inventory; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.apiculture.multiblock.TileAlvearySieve; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.inventory.watchers.ISlotPickupWatcher; -import forestry.core.utils.ItemStackUtil; -import forestry.plugins.PluginCore; - -public class InventoryAlvearySieve extends InventoryAdapterTile implements ISlotPickupWatcher { - public static final int SLOT_POLLEN_1 = 0; - public static final int SLOTS_POLLEN_COUNT = 4; - public static final int SLOT_SIEVE = 4; - - public InventoryAlvearySieve(TileAlvearySieve alvearySieve) { - super(alvearySieve, 5, "Items", 1); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return ItemStackUtil.isIdenticalItem(PluginCore.items.craftingMaterial.getWovenSilk(), itemStack); - } - - public boolean canStorePollen() { - if (getStackInSlot(SLOT_SIEVE) == null) { - return false; - } - - for (int i = SLOT_POLLEN_1; i < SLOT_POLLEN_1 + SLOTS_POLLEN_COUNT; i++) { - if (getStackInSlot(i) == null) { - return true; - } - } - - return false; - } - - public void storePollenStack(ItemStack itemstack) { - for (int i = SLOT_POLLEN_1; i < SLOT_POLLEN_1 + SLOTS_POLLEN_COUNT; i++) { - if (getStackInSlot(i) == null) { - setInventorySlotContents(i, itemstack); - return; - } - } - } - - /* ISlotPickupWatcher */ - @Override - public void onPickupFromSlot(int slotIndex, EntityPlayer player) { - if (slotIndex == SLOT_SIEVE) { - for (int i = SLOT_POLLEN_1; i < SLOT_POLLEN_1 + SLOTS_POLLEN_COUNT; i++) { - setInventorySlotContents(i, null); - } - } else { - setInventorySlotContents(SLOT_SIEVE, null); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.inventory; + +import forestry.apiculture.multiblock.TileAlvearySieve; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.core.inventory.watchers.ISlotPickupWatcher; +import forestry.core.utils.ItemStackUtil; +import forestry.plugins.PluginCore; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class InventoryAlvearySieve extends InventoryAdapterTile implements ISlotPickupWatcher { + public static final int SLOT_POLLEN_1 = 0; + public static final int SLOTS_POLLEN_COUNT = 4; + public static final int SLOT_SIEVE = 4; + + public InventoryAlvearySieve(TileAlvearySieve alvearySieve) { + super(alvearySieve, 5, "Items", 1); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return ItemStackUtil.isIdenticalItem(PluginCore.items.craftingMaterial.getWovenSilk(), itemStack); + } + + public boolean canStorePollen() { + if (getStackInSlot(SLOT_SIEVE) == null) { + return false; + } + + for (int i = SLOT_POLLEN_1; i < SLOT_POLLEN_1 + SLOTS_POLLEN_COUNT; i++) { + if (getStackInSlot(i) == null) { + return true; + } + } + + return false; + } + + public void storePollenStack(ItemStack itemstack) { + for (int i = SLOT_POLLEN_1; i < SLOT_POLLEN_1 + SLOTS_POLLEN_COUNT; i++) { + if (getStackInSlot(i) == null) { + setInventorySlotContents(i, itemstack); + return; + } + } + } + + /* ISlotPickupWatcher */ + @Override + public void onPickupFromSlot(int slotIndex, EntityPlayer player) { + if (slotIndex == SLOT_SIEVE) { + for (int i = SLOT_POLLEN_1; i < SLOT_POLLEN_1 + SLOTS_POLLEN_COUNT; i++) { + setInventorySlotContents(i, null); + } + } else { + setInventorySlotContents(SLOT_SIEVE, null); + } + } +} diff --git a/src/main/java/forestry/apiculture/inventory/InventoryApiary.java b/src/main/java/forestry/apiculture/inventory/InventoryApiary.java index 0b0dada6b..6e69e540e 100644 --- a/src/main/java/forestry/apiculture/inventory/InventoryApiary.java +++ b/src/main/java/forestry/apiculture/inventory/InventoryApiary.java @@ -1,96 +1,94 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.inventory; - -import java.util.ArrayList; -import java.util.Collection; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.IBee; -import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeekeepingMode; -import forestry.api.apiculture.IHiveFrame; -import forestry.apiculture.InventoryBeeHousing; -import forestry.core.access.IAccessHandler; -import forestry.core.utils.SlotUtil; - -public class InventoryApiary extends InventoryBeeHousing implements IApiaryInventory { - public static final int SLOT_FRAMES_1 = 9; - public static final int SLOT_FRAMES_COUNT = 3; - - public InventoryApiary(IAccessHandler accessHandler) { - super(12, accessHandler); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (SlotUtil.isSlotInRange(slotIndex, SLOT_FRAMES_1, SLOT_FRAMES_COUNT)) { - return (itemStack.getItem() instanceof IHiveFrame) && (getStackInSlot(slotIndex) == null); - } - - return super.canSlotAccept(slotIndex, itemStack); - } - - // override for pipe automation - @Override - public boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { - if (SlotUtil.isSlotInRange(slotIndex, SLOT_FRAMES_1, SLOT_FRAMES_COUNT)) { - return false; - } - return super.isItemValidForSlot(slotIndex, itemStack); - } - - public Collection getFrames() { - Collection hiveFrames = new ArrayList<>(SLOT_FRAMES_COUNT); - - for (int i = SLOT_FRAMES_1; i < SLOT_FRAMES_1 + SLOT_FRAMES_COUNT; i++) { - ItemStack stackInSlot = getStackInSlot(i); - if (stackInSlot == null) { - continue; - } - - Item itemInSlot = stackInSlot.getItem(); - if (itemInSlot instanceof IHiveFrame) { - hiveFrames.add((IHiveFrame) itemInSlot); - } - } - - return hiveFrames; - } - - public void wearOutFrames(IBeeHousing beeHousing, int amount) { - IBeekeepingMode beekeepingMode = BeeManager.beeRoot.getBeekeepingMode(beeHousing.getWorld()); - int wear = Math.round(amount * beekeepingMode.getWearModifier()); - - for (int i = SLOT_FRAMES_1; i < SLOT_FRAMES_1 + SLOT_FRAMES_COUNT; i++) { - ItemStack hiveFrameStack = getStackInSlot(i); - if (hiveFrameStack == null) { - continue; - } - - Item hiveFrameItem = hiveFrameStack.getItem(); - if (!(hiveFrameItem instanceof IHiveFrame)) { - continue; - } - - IHiveFrame hiveFrame = (IHiveFrame) hiveFrameItem; - - ItemStack queenStack = getQueen(); - IBee queen = BeeManager.beeRoot.getMember(queenStack); - ItemStack usedFrame = hiveFrame.frameUsed(beeHousing, hiveFrameStack, queen, wear); - - setInventorySlotContents(i, usedFrame); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.inventory; + +import forestry.api.apiculture.BeeManager; +import forestry.api.apiculture.IBee; +import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeekeepingMode; +import forestry.api.apiculture.IHiveFrame; +import forestry.apiculture.InventoryBeeHousing; +import forestry.core.access.IAccessHandler; +import forestry.core.utils.SlotUtil; +import java.util.ArrayList; +import java.util.Collection; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +public class InventoryApiary extends InventoryBeeHousing implements IApiaryInventory { + public static final int SLOT_FRAMES_1 = 9; + public static final int SLOT_FRAMES_COUNT = 3; + + public InventoryApiary(IAccessHandler accessHandler) { + super(12, accessHandler); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (SlotUtil.isSlotInRange(slotIndex, SLOT_FRAMES_1, SLOT_FRAMES_COUNT)) { + return (itemStack.getItem() instanceof IHiveFrame) && (getStackInSlot(slotIndex) == null); + } + + return super.canSlotAccept(slotIndex, itemStack); + } + + // override for pipe automation + @Override + public boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { + if (SlotUtil.isSlotInRange(slotIndex, SLOT_FRAMES_1, SLOT_FRAMES_COUNT)) { + return false; + } + return super.isItemValidForSlot(slotIndex, itemStack); + } + + public Collection getFrames() { + Collection hiveFrames = new ArrayList<>(SLOT_FRAMES_COUNT); + + for (int i = SLOT_FRAMES_1; i < SLOT_FRAMES_1 + SLOT_FRAMES_COUNT; i++) { + ItemStack stackInSlot = getStackInSlot(i); + if (stackInSlot == null) { + continue; + } + + Item itemInSlot = stackInSlot.getItem(); + if (itemInSlot instanceof IHiveFrame) { + hiveFrames.add((IHiveFrame) itemInSlot); + } + } + + return hiveFrames; + } + + public void wearOutFrames(IBeeHousing beeHousing, int amount) { + IBeekeepingMode beekeepingMode = BeeManager.beeRoot.getBeekeepingMode(beeHousing.getWorld()); + int wear = Math.round(amount * beekeepingMode.getWearModifier()); + + for (int i = SLOT_FRAMES_1; i < SLOT_FRAMES_1 + SLOT_FRAMES_COUNT; i++) { + ItemStack hiveFrameStack = getStackInSlot(i); + if (hiveFrameStack == null) { + continue; + } + + Item hiveFrameItem = hiveFrameStack.getItem(); + if (!(hiveFrameItem instanceof IHiveFrame)) { + continue; + } + + IHiveFrame hiveFrame = (IHiveFrame) hiveFrameItem; + + ItemStack queenStack = getQueen(); + IBee queen = BeeManager.beeRoot.getMember(queenStack); + ItemStack usedFrame = hiveFrame.frameUsed(beeHousing, hiveFrameStack, queen, wear); + + setInventorySlotContents(i, usedFrame); + } + } +} diff --git a/src/main/java/forestry/apiculture/inventory/InventoryHygroregulator.java b/src/main/java/forestry/apiculture/inventory/InventoryHygroregulator.java index 220bafa1e..49747b10f 100644 --- a/src/main/java/forestry/apiculture/inventory/InventoryHygroregulator.java +++ b/src/main/java/forestry/apiculture/inventory/InventoryHygroregulator.java @@ -1,36 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.inventory; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.Fluid; - -import forestry.apiculture.multiblock.TileAlvearyHygroregulator; -import forestry.core.fluids.FluidHelper; -import forestry.core.inventory.InventoryAdapterTile; - -public class InventoryHygroregulator extends InventoryAdapterTile { - public static final short SLOT_INPUT = 0; - - public InventoryHygroregulator(TileAlvearyHygroregulator alvearyHygroregulator) { - super(alvearyHygroregulator, 1, "CanInv"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_INPUT) { - Fluid fluid = FluidHelper.getFluidInContainer(itemStack); - return tile.getTankManager().accepts(fluid); - } - return false; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.inventory; + +import forestry.apiculture.multiblock.TileAlvearyHygroregulator; +import forestry.core.fluids.FluidHelper; +import forestry.core.inventory.InventoryAdapterTile; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; + +public class InventoryHygroregulator extends InventoryAdapterTile { + public static final short SLOT_INPUT = 0; + + public InventoryHygroregulator(TileAlvearyHygroregulator alvearyHygroregulator) { + super(alvearyHygroregulator, 1, "CanInv"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_INPUT) { + Fluid fluid = FluidHelper.getFluidInContainer(itemStack); + return tile.getTankManager().accepts(fluid); + } + return false; + } +} diff --git a/src/main/java/forestry/apiculture/inventory/InventorySwarmer.java b/src/main/java/forestry/apiculture/inventory/InventorySwarmer.java index 5e2f2bccd..f375bd5a7 100644 --- a/src/main/java/forestry/apiculture/inventory/InventorySwarmer.java +++ b/src/main/java/forestry/apiculture/inventory/InventorySwarmer.java @@ -1,29 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.inventory; - -import net.minecraft.item.ItemStack; - -import forestry.api.apiculture.BeeManager; -import forestry.apiculture.multiblock.TileAlvearySwarmer; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.utils.ItemStackUtil; - -public class InventorySwarmer extends InventoryAdapterTile { - public InventorySwarmer(TileAlvearySwarmer alvearySwarmer) { - super(alvearySwarmer, 4, "SwarmInv"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return ItemStackUtil.containsItemStack(BeeManager.inducers.keySet(), itemStack); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.inventory; + +import forestry.api.apiculture.BeeManager; +import forestry.apiculture.multiblock.TileAlvearySwarmer; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.core.utils.ItemStackUtil; +import net.minecraft.item.ItemStack; + +public class InventorySwarmer extends InventoryAdapterTile { + public InventorySwarmer(TileAlvearySwarmer alvearySwarmer) { + super(alvearySwarmer, 4, "SwarmInv"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return ItemStackUtil.containsItemStack(BeeManager.inducers.keySet(), itemStack); + } +} diff --git a/src/main/java/forestry/apiculture/inventory/ItemInventoryBeealyzer.java b/src/main/java/forestry/apiculture/inventory/ItemInventoryBeealyzer.java index aeca6751e..cfa6e693e 100644 --- a/src/main/java/forestry/apiculture/inventory/ItemInventoryBeealyzer.java +++ b/src/main/java/forestry/apiculture/inventory/ItemInventoryBeealyzer.java @@ -1,34 +1,32 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.inventory; - -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.api.apiculture.BeeManager; -import forestry.core.config.Config; -import forestry.core.gui.IHintSource; -import forestry.core.inventory.ItemInventoryAlyzer; - -public class ItemInventoryBeealyzer extends ItemInventoryAlyzer implements IHintSource { - - public ItemInventoryBeealyzer(EntityPlayer player, ItemStack itemStack) { - super(BeeManager.beeRoot, player, itemStack); - } - - /* IHintSource */ - @Override - public List getHints() { - return Config.hints.get("beealyzer"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.inventory; + +import forestry.api.apiculture.BeeManager; +import forestry.core.config.Config; +import forestry.core.gui.IHintSource; +import forestry.core.inventory.ItemInventoryAlyzer; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class ItemInventoryBeealyzer extends ItemInventoryAlyzer implements IHintSource { + + public ItemInventoryBeealyzer(EntityPlayer player, ItemStack itemStack) { + super(BeeManager.beeRoot, player, itemStack); + } + + /* IHintSource */ + @Override + public List getHints() { + return Config.hints.get("beealyzer"); + } +} diff --git a/src/main/java/forestry/apiculture/inventory/ItemInventoryHabitatLocator.java b/src/main/java/forestry/apiculture/inventory/ItemInventoryHabitatLocator.java index fdfe7c8ca..62c460750 100644 --- a/src/main/java/forestry/apiculture/inventory/ItemInventoryHabitatLocator.java +++ b/src/main/java/forestry/apiculture/inventory/ItemInventoryHabitatLocator.java @@ -1,130 +1,126 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.inventory; - -import com.google.common.collect.ImmutableSet; - -import java.util.List; -import java.util.Set; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.world.biome.BiomeGenBase; - -import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.IBee; -import forestry.api.core.IErrorSource; -import forestry.api.core.IErrorState; -import forestry.apiculture.items.HabitatLocatorLogic; -import forestry.apiculture.items.ItemHabitatLocator; -import forestry.core.config.Config; -import forestry.core.errors.EnumErrorCode; -import forestry.core.gui.IHintSource; -import forestry.core.inventory.ItemInventory; -import forestry.plugins.PluginApiculture; - -public class ItemInventoryHabitatLocator extends ItemInventory implements IErrorSource, IHintSource { - - private static final short SLOT_ENERGY = 2; - private static final short SLOT_SPECIMEN = 0; - private static final short SLOT_ANALYZED = 1; - - private final HabitatLocatorLogic locatorLogic; - - public ItemInventoryHabitatLocator(EntityPlayer player, ItemStack itemstack) { - super(player, 3, itemstack); - ItemHabitatLocator habitatLocator = (ItemHabitatLocator) itemstack.getItem(); - this.locatorLogic = habitatLocator.getLocatorLogic(); - } - - private static boolean isEnergy(ItemStack itemstack) { - if (itemstack == null || itemstack.stackSize <= 0) { - return false; - } - - Item item = itemstack.getItem(); - return PluginApiculture.items.honeyDrop == item || PluginApiculture.items.honeydew == item; - } - - @Override - public void onSlotClick(EntityPlayer player) { - - if (getStackInSlot(SLOT_ANALYZED) != null) { - if (locatorLogic.isBiomeFound()) { - return; - } - } else if (getStackInSlot(SLOT_SPECIMEN) != null) { - // Requires energy - if (!isEnergy(getStackInSlot(SLOT_ENERGY))) { - return; - } - - // Decrease energy - decrStackSize(SLOT_ENERGY, 1); - - setInventorySlotContents(SLOT_ANALYZED, getStackInSlot(SLOT_SPECIMEN)); - setInventorySlotContents(SLOT_SPECIMEN, null); - } - - IBee bee = BeeManager.beeRoot.getMember(getStackInSlot(SLOT_ANALYZED)); - - // No bee, abort - if (bee == null) { - return; - } - - locatorLogic.startBiomeSearch(bee, player); - } - - public Set getBiomesToSearch() { - return locatorLogic.getTargetBiomes(); - } - - /* IHintSource */ - @Override - public List getHints() { - return Config.hints.get("habitat.locator"); - } - - /* IErrorSource */ - @Override - public ImmutableSet getErrorStates() { - if (getStackInSlot(SLOT_ANALYZED) != null) { - return ImmutableSet.of(); - } - - ImmutableSet.Builder errorStates = ImmutableSet.builder(); - - ItemStack specimen = getStackInSlot(SLOT_SPECIMEN); - if (!BeeManager.beeRoot.isMember(specimen)) { - errorStates.add(EnumErrorCode.NO_SPECIMEN); - } - - if (!isEnergy(getStackInSlot(SLOT_ENERGY))) { - errorStates.add(EnumErrorCode.NO_HONEY); - } - - return errorStates.build(); - } - - /* IFilterSlotDelegate */ - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_ENERGY) { - return isEnergy(itemStack); - } else if (slotIndex == SLOT_SPECIMEN) { - return BeeManager.beeRoot.isMember(itemStack); - } - return false; - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.inventory; + +import com.google.common.collect.ImmutableSet; +import forestry.api.apiculture.BeeManager; +import forestry.api.apiculture.IBee; +import forestry.api.core.IErrorSource; +import forestry.api.core.IErrorState; +import forestry.apiculture.items.HabitatLocatorLogic; +import forestry.apiculture.items.ItemHabitatLocator; +import forestry.core.config.Config; +import forestry.core.errors.EnumErrorCode; +import forestry.core.gui.IHintSource; +import forestry.core.inventory.ItemInventory; +import forestry.plugins.PluginApiculture; +import java.util.List; +import java.util.Set; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.world.biome.BiomeGenBase; + +public class ItemInventoryHabitatLocator extends ItemInventory implements IErrorSource, IHintSource { + + private static final short SLOT_ENERGY = 2; + private static final short SLOT_SPECIMEN = 0; + private static final short SLOT_ANALYZED = 1; + + private final HabitatLocatorLogic locatorLogic; + + public ItemInventoryHabitatLocator(EntityPlayer player, ItemStack itemstack) { + super(player, 3, itemstack); + ItemHabitatLocator habitatLocator = (ItemHabitatLocator) itemstack.getItem(); + this.locatorLogic = habitatLocator.getLocatorLogic(); + } + + private static boolean isEnergy(ItemStack itemstack) { + if (itemstack == null || itemstack.stackSize <= 0) { + return false; + } + + Item item = itemstack.getItem(); + return PluginApiculture.items.honeyDrop == item || PluginApiculture.items.honeydew == item; + } + + @Override + public void onSlotClick(EntityPlayer player) { + + if (getStackInSlot(SLOT_ANALYZED) != null) { + if (locatorLogic.isBiomeFound()) { + return; + } + } else if (getStackInSlot(SLOT_SPECIMEN) != null) { + // Requires energy + if (!isEnergy(getStackInSlot(SLOT_ENERGY))) { + return; + } + + // Decrease energy + decrStackSize(SLOT_ENERGY, 1); + + setInventorySlotContents(SLOT_ANALYZED, getStackInSlot(SLOT_SPECIMEN)); + setInventorySlotContents(SLOT_SPECIMEN, null); + } + + IBee bee = BeeManager.beeRoot.getMember(getStackInSlot(SLOT_ANALYZED)); + + // No bee, abort + if (bee == null) { + return; + } + + locatorLogic.startBiomeSearch(bee, player); + } + + public Set getBiomesToSearch() { + return locatorLogic.getTargetBiomes(); + } + + /* IHintSource */ + @Override + public List getHints() { + return Config.hints.get("habitat.locator"); + } + + /* IErrorSource */ + @Override + public ImmutableSet getErrorStates() { + if (getStackInSlot(SLOT_ANALYZED) != null) { + return ImmutableSet.of(); + } + + ImmutableSet.Builder errorStates = ImmutableSet.builder(); + + ItemStack specimen = getStackInSlot(SLOT_SPECIMEN); + if (!BeeManager.beeRoot.isMember(specimen)) { + errorStates.add(EnumErrorCode.NO_SPECIMEN); + } + + if (!isEnergy(getStackInSlot(SLOT_ENERGY))) { + errorStates.add(EnumErrorCode.NO_HONEY); + } + + return errorStates.build(); + } + + /* IFilterSlotDelegate */ + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_ENERGY) { + return isEnergy(itemStack); + } else if (slotIndex == SLOT_SPECIMEN) { + return BeeManager.beeRoot.isMember(itemStack); + } + return false; + } +} diff --git a/src/main/java/forestry/apiculture/inventory/ItemInventoryImprinter.java b/src/main/java/forestry/apiculture/inventory/ItemInventoryImprinter.java index cc3f8204c..a3807df01 100644 --- a/src/main/java/forestry/apiculture/inventory/ItemInventoryImprinter.java +++ b/src/main/java/forestry/apiculture/inventory/ItemInventoryImprinter.java @@ -1,136 +1,152 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.inventory; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.IAlleleBeeSpecies; -import forestry.api.apiculture.IBee; -import forestry.apiculture.genetics.Bee; -import forestry.core.inventory.ItemInventory; - -public class ItemInventoryImprinter extends ItemInventory { - private static final short specimenSlot = 0; - private static final short imprintedSlot = 1; - - private int primaryIndex = 0; - private int secondaryIndex = 0; - - public ItemInventoryImprinter(EntityPlayer player, ItemStack itemStack) { - super(player, 2, itemStack); - } - - public void advancePrimary() { - if (primaryIndex < BeeManager.beeRoot.getIndividualTemplates().size() - 1) { - primaryIndex++; - } else { - primaryIndex = 0; - } - } - - public void advanceSecondary() { - if (secondaryIndex < BeeManager.beeRoot.getIndividualTemplates().size() - 1) { - secondaryIndex++; - } else { - secondaryIndex = 0; - } - } - - public void regressPrimary() { - if (primaryIndex > 0) { - primaryIndex--; - } else { - primaryIndex = BeeManager.beeRoot.getIndividualTemplates().size() - 1; - } - } - - public void regressSecondary() { - if (secondaryIndex > 0) { - secondaryIndex--; - } else { - secondaryIndex = BeeManager.beeRoot.getIndividualTemplates().size() - 1; - } - } - - public IAlleleBeeSpecies getPrimary() { - return BeeManager.beeRoot.getIndividualTemplates().get(primaryIndex).getGenome().getPrimary(); - } - - public IAlleleBeeSpecies getSecondary() { - return BeeManager.beeRoot.getIndividualTemplates().get(secondaryIndex).getGenome().getPrimary(); - } - - public IBee getSelectedBee() { - return new Bee(BeeManager.beeRoot.templateAsGenome( - BeeManager.beeRoot.getGenomeTemplates().get(BeeManager.beeRoot.getIndividualTemplates().get(primaryIndex).getIdent()), - BeeManager.beeRoot.getGenomeTemplates().get(BeeManager.beeRoot.getIndividualTemplates().get(secondaryIndex).getIdent()))); - } - - public int getPrimaryIndex() { - return primaryIndex; - } - - public int getSecondaryIndex() { - return secondaryIndex; - } - - public void setPrimaryIndex(int index) { - primaryIndex = index; - } - - public void setSecondaryIndex(int index) { - secondaryIndex = index; - } - - @Override - public void onSlotClick(EntityPlayer player) { - ItemStack specimen = getStackInSlot(specimenSlot); - if (specimen == null) { - return; - } - - // Only imprint bees - if (!BeeManager.beeRoot.isMember(specimen)) { - return; - } - - // Needs space - if (getStackInSlot(imprintedSlot) != null) { - return; - } - - IBee imprint = getSelectedBee(); - if (imprint == null) { - return; - } - - NBTTagCompound nbttagcompound = new NBTTagCompound(); - imprint.writeToNBT(nbttagcompound); - specimen.setTagCompound(nbttagcompound); - - setInventorySlotContents(imprintedSlot, specimen); - setInventorySlotContents(specimenSlot, null); - } - - @Override - public String getInventoryName() { - return "Imprinter"; - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return BeeManager.beeRoot.isMember(itemStack); - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.inventory; + +import forestry.api.apiculture.BeeManager; +import forestry.api.apiculture.IAlleleBeeSpecies; +import forestry.api.apiculture.IBee; +import forestry.apiculture.genetics.Bee; +import forestry.core.inventory.ItemInventory; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +public class ItemInventoryImprinter extends ItemInventory { + private static final short specimenSlot = 0; + private static final short imprintedSlot = 1; + + private int primaryIndex = 0; + private int secondaryIndex = 0; + + public ItemInventoryImprinter(EntityPlayer player, ItemStack itemStack) { + super(player, 2, itemStack); + } + + public void advancePrimary() { + if (primaryIndex < BeeManager.beeRoot.getIndividualTemplates().size() - 1) { + primaryIndex++; + } else { + primaryIndex = 0; + } + } + + public void advanceSecondary() { + if (secondaryIndex < BeeManager.beeRoot.getIndividualTemplates().size() - 1) { + secondaryIndex++; + } else { + secondaryIndex = 0; + } + } + + public void regressPrimary() { + if (primaryIndex > 0) { + primaryIndex--; + } else { + primaryIndex = BeeManager.beeRoot.getIndividualTemplates().size() - 1; + } + } + + public void regressSecondary() { + if (secondaryIndex > 0) { + secondaryIndex--; + } else { + secondaryIndex = BeeManager.beeRoot.getIndividualTemplates().size() - 1; + } + } + + public IAlleleBeeSpecies getPrimary() { + return BeeManager.beeRoot + .getIndividualTemplates() + .get(primaryIndex) + .getGenome() + .getPrimary(); + } + + public IAlleleBeeSpecies getSecondary() { + return BeeManager.beeRoot + .getIndividualTemplates() + .get(secondaryIndex) + .getGenome() + .getPrimary(); + } + + public IBee getSelectedBee() { + return new Bee(BeeManager.beeRoot.templateAsGenome( + BeeManager.beeRoot + .getGenomeTemplates() + .get(BeeManager.beeRoot + .getIndividualTemplates() + .get(primaryIndex) + .getIdent()), + BeeManager.beeRoot + .getGenomeTemplates() + .get(BeeManager.beeRoot + .getIndividualTemplates() + .get(secondaryIndex) + .getIdent()))); + } + + public int getPrimaryIndex() { + return primaryIndex; + } + + public int getSecondaryIndex() { + return secondaryIndex; + } + + public void setPrimaryIndex(int index) { + primaryIndex = index; + } + + public void setSecondaryIndex(int index) { + secondaryIndex = index; + } + + @Override + public void onSlotClick(EntityPlayer player) { + ItemStack specimen = getStackInSlot(specimenSlot); + if (specimen == null) { + return; + } + + // Only imprint bees + if (!BeeManager.beeRoot.isMember(specimen)) { + return; + } + + // Needs space + if (getStackInSlot(imprintedSlot) != null) { + return; + } + + IBee imprint = getSelectedBee(); + if (imprint == null) { + return; + } + + NBTTagCompound nbttagcompound = new NBTTagCompound(); + imprint.writeToNBT(nbttagcompound); + specimen.setTagCompound(nbttagcompound); + + setInventorySlotContents(imprintedSlot, specimen); + setInventorySlotContents(specimenSlot, null); + } + + @Override + public String getInventoryName() { + return "Imprinter"; + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return BeeManager.beeRoot.isMember(itemStack); + } +} diff --git a/src/main/java/forestry/apiculture/items/EnumHoneyComb.java b/src/main/java/forestry/apiculture/items/EnumHoneyComb.java index 31b53cf7e..e487189e5 100644 --- a/src/main/java/forestry/apiculture/items/EnumHoneyComb.java +++ b/src/main/java/forestry/apiculture/items/EnumHoneyComb.java @@ -1,57 +1,57 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import java.awt.Color; -import java.util.Locale; - -public enum EnumHoneyComb { - HONEY(new Color(0xe8d56a), new Color(0xffa12b)), - COCOA(new Color(0x674016), new Color(0xffb62b), true), - SIMMERING(new Color(0x981919), new Color(0xffb62b)), - STRINGY(new Color(0xc8be67), new Color(0xbda93e)), - FROZEN(new Color(0xf9ffff), new Color(0xa0ffff)), - DRIPPING(new Color(0xdc7613), new Color(0xffff00)), - SILKY(new Color(0x508907), new Color(0xddff00)), - PARCHED(new Color(0xdcbe13), new Color(0xffff00)), - MYSTERIOUS(new Color(0x161616), new Color(0xe099ff), true), - IRRADIATED(new Color(0xeafff3), new Color(0xeeff00), true), - POWDERY(new Color(0xe4e4e4), new Color(0xffffff), true), - REDDENED(new Color(0x4b0000), new Color(0x6200e7), true), - DARKENED(new Color(0x353535), new Color(0x33ebcb), true), - OMEGA(new Color(0x191919), new Color(0x6dcff6), true), - WHEATEN(new Color(0xfeff8f), new Color(0xffffff), true), - MOSSY(new Color(0x2a3313), new Color(0x7e9939)), - MELLOW(new Color(0x886000), new Color(0xfff960)); - //""(new Color(0xd7bee5), new Color(0xfd58ab)); // kindof pinkish - - public static final EnumHoneyComb[] VALUES = values(); - - public final String name; - public final int primaryColor; - public final int secondaryColor; - private final boolean secret; - - EnumHoneyComb(Color primary, Color secondary) { - this(primary, secondary, false); - } - - EnumHoneyComb(Color primary, Color secondary, boolean secret) { - this.name = toString().toLowerCase(Locale.ENGLISH); - this.primaryColor = primary.getRGB(); - this.secondaryColor = secondary.getRGB(); - this.secret = secret; - } - - public boolean isSecret() { - return secret; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.items; + +import java.awt.Color; +import java.util.Locale; + +public enum EnumHoneyComb { + HONEY(new Color(0xe8d56a), new Color(0xffa12b)), + COCOA(new Color(0x674016), new Color(0xffb62b), true), + SIMMERING(new Color(0x981919), new Color(0xffb62b)), + STRINGY(new Color(0xc8be67), new Color(0xbda93e)), + FROZEN(new Color(0xf9ffff), new Color(0xa0ffff)), + DRIPPING(new Color(0xdc7613), new Color(0xffff00)), + SILKY(new Color(0x508907), new Color(0xddff00)), + PARCHED(new Color(0xdcbe13), new Color(0xffff00)), + MYSTERIOUS(new Color(0x161616), new Color(0xe099ff), true), + IRRADIATED(new Color(0xeafff3), new Color(0xeeff00), true), + POWDERY(new Color(0xe4e4e4), new Color(0xffffff), true), + REDDENED(new Color(0x4b0000), new Color(0x6200e7), true), + DARKENED(new Color(0x353535), new Color(0x33ebcb), true), + OMEGA(new Color(0x191919), new Color(0x6dcff6), true), + WHEATEN(new Color(0xfeff8f), new Color(0xffffff), true), + MOSSY(new Color(0x2a3313), new Color(0x7e9939)), + MELLOW(new Color(0x886000), new Color(0xfff960)); + // ""(new Color(0xd7bee5), new Color(0xfd58ab)); // kindof pinkish + + public static final EnumHoneyComb[] VALUES = values(); + + public final String name; + public final int primaryColor; + public final int secondaryColor; + private final boolean secret; + + EnumHoneyComb(Color primary, Color secondary) { + this(primary, secondary, false); + } + + EnumHoneyComb(Color primary, Color secondary, boolean secret) { + this.name = toString().toLowerCase(Locale.ENGLISH); + this.primaryColor = primary.getRGB(); + this.secondaryColor = secondary.getRGB(); + this.secret = secret; + } + + public boolean isSecret() { + return secret; + } +} diff --git a/src/main/java/forestry/apiculture/items/EnumHoneyDrop.java b/src/main/java/forestry/apiculture/items/EnumHoneyDrop.java index 0a2ae32ec..8dd705db2 100644 --- a/src/main/java/forestry/apiculture/items/EnumHoneyDrop.java +++ b/src/main/java/forestry/apiculture/items/EnumHoneyDrop.java @@ -1,60 +1,59 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import java.awt.Color; -import java.util.Locale; - -import forestry.core.items.ItemOverlay; - -public enum EnumHoneyDrop implements ItemOverlay.IOverlayInfo { - HONEY(new Color(0xecb42d), new Color(0xe8c814)), - CHARGED(new Color(0x800505), new Color(0x9c0707), true), - OMEGA(new Color(0x191919), new Color(0x4a8ca7), true); - - public static final EnumHoneyDrop[] VALUES = values(); - - private final String name; - private final int primaryColor; - private final int secondaryColor; - private final boolean secret; - - EnumHoneyDrop(Color primary, Color secondary) { - this(primary, secondary, false); - } - - EnumHoneyDrop(Color primary, Color secondary, boolean secret) { - this.name = toString().toLowerCase(Locale.ENGLISH); - this.primaryColor = primary.getRGB(); - this.secondaryColor = secondary.getRGB(); - this.secret = secret; - } - - @Override - public String getName() { - return name; - } - - @Override - public int getPrimaryColor() { - return primaryColor; - } - - @Override - public int getSecondaryColor() { - return secondaryColor; - } - - @Override - public boolean isSecret() { - return secret; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.items; + +import forestry.core.items.ItemOverlay; +import java.awt.Color; +import java.util.Locale; + +public enum EnumHoneyDrop implements ItemOverlay.IOverlayInfo { + HONEY(new Color(0xecb42d), new Color(0xe8c814)), + CHARGED(new Color(0x800505), new Color(0x9c0707), true), + OMEGA(new Color(0x191919), new Color(0x4a8ca7), true); + + public static final EnumHoneyDrop[] VALUES = values(); + + private final String name; + private final int primaryColor; + private final int secondaryColor; + private final boolean secret; + + EnumHoneyDrop(Color primary, Color secondary) { + this(primary, secondary, false); + } + + EnumHoneyDrop(Color primary, Color secondary, boolean secret) { + this.name = toString().toLowerCase(Locale.ENGLISH); + this.primaryColor = primary.getRGB(); + this.secondaryColor = secondary.getRGB(); + this.secret = secret; + } + + @Override + public String getName() { + return name; + } + + @Override + public int getPrimaryColor() { + return primaryColor; + } + + @Override + public int getSecondaryColor() { + return secondaryColor; + } + + @Override + public boolean isSecret() { + return secret; + } +} diff --git a/src/main/java/forestry/apiculture/items/EnumPollenCluster.java b/src/main/java/forestry/apiculture/items/EnumPollenCluster.java index 4db65e489..6d4e04c38 100644 --- a/src/main/java/forestry/apiculture/items/EnumPollenCluster.java +++ b/src/main/java/forestry/apiculture/items/EnumPollenCluster.java @@ -1,53 +1,52 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import java.awt.Color; -import java.util.Locale; - -import forestry.core.items.ItemOverlay; - -public enum EnumPollenCluster implements ItemOverlay.IOverlayInfo { - NORMAL(new Color(0xa28a25), new Color(0xa28a25)), - CRYSTALLINE(new Color(0xffffff), new Color(0xc5feff)); - - public static final EnumPollenCluster[] VALUES = values(); - - private final String name; - private final int primaryColor; - private final int secondaryColor; - - EnumPollenCluster(Color primary, Color secondary) { - this.name = toString().toLowerCase(Locale.ENGLISH); - this.primaryColor = primary.getRGB(); - this.secondaryColor = secondary.getRGB(); - } - - @Override - public String getName() { - return name; - } - - @Override - public int getPrimaryColor() { - return primaryColor; - } - - @Override - public int getSecondaryColor() { - return secondaryColor; - } - - @Override - public boolean isSecret() { - return false; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.items; + +import forestry.core.items.ItemOverlay; +import java.awt.Color; +import java.util.Locale; + +public enum EnumPollenCluster implements ItemOverlay.IOverlayInfo { + NORMAL(new Color(0xa28a25), new Color(0xa28a25)), + CRYSTALLINE(new Color(0xffffff), new Color(0xc5feff)); + + public static final EnumPollenCluster[] VALUES = values(); + + private final String name; + private final int primaryColor; + private final int secondaryColor; + + EnumPollenCluster(Color primary, Color secondary) { + this.name = toString().toLowerCase(Locale.ENGLISH); + this.primaryColor = primary.getRGB(); + this.secondaryColor = secondary.getRGB(); + } + + @Override + public String getName() { + return name; + } + + @Override + public int getPrimaryColor() { + return primaryColor; + } + + @Override + public int getSecondaryColor() { + return secondaryColor; + } + + @Override + public boolean isSecret() { + return false; + } +} diff --git a/src/main/java/forestry/apiculture/items/EnumPropolis.java b/src/main/java/forestry/apiculture/items/EnumPropolis.java index b12cdf140..a25e0e72d 100644 --- a/src/main/java/forestry/apiculture/items/EnumPropolis.java +++ b/src/main/java/forestry/apiculture/items/EnumPropolis.java @@ -1,59 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import java.awt.Color; -import java.util.Locale; - -import forestry.core.items.ItemOverlay; - -public enum EnumPropolis implements ItemOverlay.IOverlayInfo { - NORMAL(new Color(0xc5b24e)), - STICKY(new Color(0xc68e57)), - PULSATING(new Color(0x2ccdb1), true), - SILKY(new Color(0xddff00)); - - public static final EnumPropolis[] VALUES = values(); - - private final String name; - private final int primaryColor; - private final boolean secret; - - EnumPropolis(Color color) { - this(color, false); - } - - EnumPropolis(Color color, boolean secret) { - this.name = toString().toLowerCase(Locale.ENGLISH); - this.primaryColor = color.getRGB(); - this.secret = secret; - } - - @Override - public String getName() { - return name; - } - - @Override - public int getPrimaryColor() { - return primaryColor; - } - - @Override - public int getSecondaryColor() { - return 0; - } - - @Override - public boolean isSecret() { - return secret; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.items; + +import forestry.core.items.ItemOverlay; +import java.awt.Color; +import java.util.Locale; + +public enum EnumPropolis implements ItemOverlay.IOverlayInfo { + NORMAL(new Color(0xc5b24e)), + STICKY(new Color(0xc68e57)), + PULSATING(new Color(0x2ccdb1), true), + SILKY(new Color(0xddff00)); + + public static final EnumPropolis[] VALUES = values(); + + private final String name; + private final int primaryColor; + private final boolean secret; + + EnumPropolis(Color color) { + this(color, false); + } + + EnumPropolis(Color color, boolean secret) { + this.name = toString().toLowerCase(Locale.ENGLISH); + this.primaryColor = color.getRGB(); + this.secret = secret; + } + + @Override + public String getName() { + return name; + } + + @Override + public int getPrimaryColor() { + return primaryColor; + } + + @Override + public int getSecondaryColor() { + return 0; + } + + @Override + public boolean isSecret() { + return secret; + } +} diff --git a/src/main/java/forestry/apiculture/items/HabitatLocatorLogic.java b/src/main/java/forestry/apiculture/items/HabitatLocatorLogic.java index 6467d6de7..2696fe978 100644 --- a/src/main/java/forestry/apiculture/items/HabitatLocatorLogic.java +++ b/src/main/java/forestry/apiculture/items/HabitatLocatorLogic.java @@ -1,201 +1,199 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - -import net.minecraftforge.common.BiomeDictionary; - -import forestry.api.apiculture.IBee; -import forestry.apiculture.network.packets.PacketHabitatBiomePointer; -import forestry.core.proxy.Proxies; -import forestry.core.utils.vect.Vect; - -public class HabitatLocatorLogic { - private static final int maxChecksPerTick = 100; - private static final int maxSearchRadiusIterations = 500; - private static final int spacing = 20; - private static final int minBiomeRadius = 8; - - private static final Set waterBiomes = new HashSet<>(); - private static final Set netherBiomes = new HashSet<>(); - private static final Set endBiomes = new HashSet<>(); - - static { - Collections.addAll(waterBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.BEACH)); - Collections.addAll(waterBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.OCEAN)); - Collections.addAll(waterBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.RIVER)); - - Collections.addAll(netherBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.NETHER)); - - Collections.addAll(endBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.END)); - } - - private Set targetBiomes = new HashSet<>(); - private boolean biomeFound = false; - private int searchRadiusIteration = 0; - private int searchAngleIteration = 0; - private Vect searchCenter; - - public boolean isBiomeFound() { - return biomeFound; - } - - public Set getTargetBiomes() { - return targetBiomes; - } - - public void startBiomeSearch(IBee bee, EntityPlayer player) { - this.targetBiomes = new HashSet<>(bee.getSuitableBiomes()); - this.searchAngleIteration = 0; - this.searchRadiusIteration = 0; - this.biomeFound = false; - this.searchCenter = new Vect(player); - - BiomeGenBase currentBiome = player.worldObj.getBiomeGenForCoords(searchCenter.x, searchCenter.z); - removeInvalidBiomes(currentBiome, targetBiomes); - - // reset the locator coordinates - Proxies.render.setHabitatLocatorTexture(null, null); - } - - public void onUpdate(World world, Entity player) { - if (world.isRemote) { - return; - } - - if (targetBiomes.isEmpty()) { - return; - } - - // once we've found the biome, slow down to conserve cpu and network data - if (biomeFound && world.getTotalWorldTime() % 20 != 0) { - return; - } - - ChunkCoordinates target = findNearestBiome(player, targetBiomes); - - // send an update if we find the biome - if (target != null && player instanceof EntityPlayerMP) { - Proxies.net.sendToPlayer(new PacketHabitatBiomePointer(target), (EntityPlayerMP) player); - biomeFound = true; - } - } - - private ChunkCoordinates findNearestBiome(Entity player, Collection biomesToSearch) { - Vect playerPos = new Vect(player); - - // If we are in a valid spot, we point to ourselves. - ChunkCoordinates coordinates = getChunkCoordinates(playerPos, player.worldObj, biomesToSearch); - if (coordinates != null) { - searchAngleIteration = 0; - searchRadiusIteration = 0; - return new ChunkCoordinates(playerPos.x, playerPos.y, playerPos.z); - } - - // check in a circular pattern, starting at the center and increasing radius each step - final int radius = spacing * (searchRadiusIteration + 1); - - double angleSpacing = 2.0f * Math.asin(spacing / (2.0 * radius)); - - // round to nearest divisible angle, for an even distribution - angleSpacing = 2.0 * Math.PI / Math.round(2.0 * Math.PI / angleSpacing); - - // do a limited number of checks per tick - for (int i = 0; i < maxChecksPerTick; i++) { - - double angle = angleSpacing * searchAngleIteration; - if (angle > 2.0 * Math.PI) { - searchAngleIteration = 0; - searchRadiusIteration++; - if (searchRadiusIteration > maxSearchRadiusIterations) { - searchAngleIteration = 0; - searchRadiusIteration = 0; - searchCenter = playerPos; - } - return null; - } else { - searchAngleIteration++; - } - - int xOffset = Math.round((float) (radius * Math.cos(angle))); - int zOffset = Math.round((float) (radius * Math.sin(angle))); - Vect pos = searchCenter.add(xOffset, 0, zOffset); - - coordinates = getChunkCoordinates(pos, player.worldObj, biomesToSearch); - if (coordinates != null) { - searchAngleIteration = 0; - searchRadiusIteration = 0; - return coordinates; - } - } - - return null; - } - - private static ChunkCoordinates getChunkCoordinates(Vect pos, World world, Collection biomesToSearch) { - BiomeGenBase biome; - - biome = world.getBiomeGenForCoords(pos.x, pos.z); - if (!biomesToSearch.contains(biome)) { - return null; - } - - biome = world.getBiomeGenForCoords(pos.x - minBiomeRadius, pos.z); - if (!biomesToSearch.contains(biome)) { - return null; - } - - biome = world.getBiomeGenForCoords(pos.x + minBiomeRadius, pos.z); - if (!biomesToSearch.contains(biome)) { - return null; - } - - biome = world.getBiomeGenForCoords(pos.x, pos.z - minBiomeRadius); - if (!biomesToSearch.contains(biome)) { - return null; - } - - biome = world.getBiomeGenForCoords(pos.x, pos.z + minBiomeRadius); - if (!biomesToSearch.contains(biome)) { - return null; - } - - return new ChunkCoordinates(pos.x, pos.y, pos.z); - } - - private static void removeInvalidBiomes(BiomeGenBase currentBiome, Set biomesToSearch) { - - biomesToSearch.removeAll(waterBiomes); - - if (BiomeDictionary.isBiomeOfType(currentBiome, BiomeDictionary.Type.NETHER)) { - biomesToSearch.retainAll(netherBiomes); - } else { - biomesToSearch.removeAll(netherBiomes); - } - - if (BiomeDictionary.isBiomeOfType(currentBiome, BiomeDictionary.Type.END)) { - biomesToSearch.retainAll(endBiomes); - } else { - biomesToSearch.removeAll(endBiomes); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.items; + +import forestry.api.apiculture.IBee; +import forestry.apiculture.network.packets.PacketHabitatBiomePointer; +import forestry.core.proxy.Proxies; +import forestry.core.utils.vect.Vect; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; +import net.minecraftforge.common.BiomeDictionary; + +public class HabitatLocatorLogic { + private static final int maxChecksPerTick = 100; + private static final int maxSearchRadiusIterations = 500; + private static final int spacing = 20; + private static final int minBiomeRadius = 8; + + private static final Set waterBiomes = new HashSet<>(); + private static final Set netherBiomes = new HashSet<>(); + private static final Set endBiomes = new HashSet<>(); + + static { + Collections.addAll(waterBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.BEACH)); + Collections.addAll(waterBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.OCEAN)); + Collections.addAll(waterBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.RIVER)); + + Collections.addAll(netherBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.NETHER)); + + Collections.addAll(endBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.END)); + } + + private Set targetBiomes = new HashSet<>(); + private boolean biomeFound = false; + private int searchRadiusIteration = 0; + private int searchAngleIteration = 0; + private Vect searchCenter; + + public boolean isBiomeFound() { + return biomeFound; + } + + public Set getTargetBiomes() { + return targetBiomes; + } + + public void startBiomeSearch(IBee bee, EntityPlayer player) { + this.targetBiomes = new HashSet<>(bee.getSuitableBiomes()); + this.searchAngleIteration = 0; + this.searchRadiusIteration = 0; + this.biomeFound = false; + this.searchCenter = new Vect(player); + + BiomeGenBase currentBiome = player.worldObj.getBiomeGenForCoords(searchCenter.x, searchCenter.z); + removeInvalidBiomes(currentBiome, targetBiomes); + + // reset the locator coordinates + Proxies.render.setHabitatLocatorTexture(null, null); + } + + public void onUpdate(World world, Entity player) { + if (world.isRemote) { + return; + } + + if (targetBiomes.isEmpty()) { + return; + } + + // once we've found the biome, slow down to conserve cpu and network data + if (biomeFound && world.getTotalWorldTime() % 20 != 0) { + return; + } + + ChunkCoordinates target = findNearestBiome(player, targetBiomes); + + // send an update if we find the biome + if (target != null && player instanceof EntityPlayerMP) { + Proxies.net.sendToPlayer(new PacketHabitatBiomePointer(target), (EntityPlayerMP) player); + biomeFound = true; + } + } + + private ChunkCoordinates findNearestBiome(Entity player, Collection biomesToSearch) { + Vect playerPos = new Vect(player); + + // If we are in a valid spot, we point to ourselves. + ChunkCoordinates coordinates = getChunkCoordinates(playerPos, player.worldObj, biomesToSearch); + if (coordinates != null) { + searchAngleIteration = 0; + searchRadiusIteration = 0; + return new ChunkCoordinates(playerPos.x, playerPos.y, playerPos.z); + } + + // check in a circular pattern, starting at the center and increasing radius each step + final int radius = spacing * (searchRadiusIteration + 1); + + double angleSpacing = 2.0f * Math.asin(spacing / (2.0 * radius)); + + // round to nearest divisible angle, for an even distribution + angleSpacing = 2.0 * Math.PI / Math.round(2.0 * Math.PI / angleSpacing); + + // do a limited number of checks per tick + for (int i = 0; i < maxChecksPerTick; i++) { + + double angle = angleSpacing * searchAngleIteration; + if (angle > 2.0 * Math.PI) { + searchAngleIteration = 0; + searchRadiusIteration++; + if (searchRadiusIteration > maxSearchRadiusIterations) { + searchAngleIteration = 0; + searchRadiusIteration = 0; + searchCenter = playerPos; + } + return null; + } else { + searchAngleIteration++; + } + + int xOffset = Math.round((float) (radius * Math.cos(angle))); + int zOffset = Math.round((float) (radius * Math.sin(angle))); + Vect pos = searchCenter.add(xOffset, 0, zOffset); + + coordinates = getChunkCoordinates(pos, player.worldObj, biomesToSearch); + if (coordinates != null) { + searchAngleIteration = 0; + searchRadiusIteration = 0; + return coordinates; + } + } + + return null; + } + + private static ChunkCoordinates getChunkCoordinates( + Vect pos, World world, Collection biomesToSearch) { + BiomeGenBase biome; + + biome = world.getBiomeGenForCoords(pos.x, pos.z); + if (!biomesToSearch.contains(biome)) { + return null; + } + + biome = world.getBiomeGenForCoords(pos.x - minBiomeRadius, pos.z); + if (!biomesToSearch.contains(biome)) { + return null; + } + + biome = world.getBiomeGenForCoords(pos.x + minBiomeRadius, pos.z); + if (!biomesToSearch.contains(biome)) { + return null; + } + + biome = world.getBiomeGenForCoords(pos.x, pos.z - minBiomeRadius); + if (!biomesToSearch.contains(biome)) { + return null; + } + + biome = world.getBiomeGenForCoords(pos.x, pos.z + minBiomeRadius); + if (!biomesToSearch.contains(biome)) { + return null; + } + + return new ChunkCoordinates(pos.x, pos.y, pos.z); + } + + private static void removeInvalidBiomes(BiomeGenBase currentBiome, Set biomesToSearch) { + + biomesToSearch.removeAll(waterBiomes); + + if (BiomeDictionary.isBiomeOfType(currentBiome, BiomeDictionary.Type.NETHER)) { + biomesToSearch.retainAll(netherBiomes); + } else { + biomesToSearch.removeAll(netherBiomes); + } + + if (BiomeDictionary.isBiomeOfType(currentBiome, BiomeDictionary.Type.END)) { + biomesToSearch.retainAll(endBiomes); + } else { + biomesToSearch.removeAll(endBiomes); + } + } +} diff --git a/src/main/java/forestry/apiculture/items/ItemArmorApiarist.java b/src/main/java/forestry/apiculture/items/ItemArmorApiarist.java index fc3db834d..71c1375f9 100755 --- a/src/main/java/forestry/apiculture/items/ItemArmorApiarist.java +++ b/src/main/java/forestry/apiculture/items/ItemArmorApiarist.java @@ -10,6 +10,15 @@ ******************************************************************************/ package forestry.apiculture.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.apiculture.IArmorApiarist; +import forestry.api.core.IArmorNaturalist; +import forestry.api.core.Tabs; +import forestry.core.config.Constants; +import forestry.core.render.TextureManager; +import forestry.core.utils.StringUtil; +import forestry.plugins.PluginApiculture; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -18,74 +27,62 @@ import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.apiculture.IArmorApiarist; -import forestry.api.core.IArmorNaturalist; -import forestry.api.core.Tabs; -import forestry.core.config.Constants; -import forestry.core.render.TextureManager; -import forestry.core.utils.StringUtil; -import forestry.plugins.PluginApiculture; - public class ItemArmorApiarist extends ItemArmor implements IArmorApiarist, IArmorNaturalist { - public ItemArmorApiarist(int slot) { - super(ArmorMaterial.CLOTH, 0, slot); - this.setMaxDamage(100); - setCreativeTab(Tabs.tabApiculture); - } + public ItemArmorApiarist(int slot) { + super(ArmorMaterial.CLOTH, 0, slot); + this.setMaxDamage(100); + setCreativeTab(Tabs.tabApiculture); + } - @Override - public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) { - if (stack != null && stack.getItem() == PluginApiculture.items.apiaristLegs) { - return Constants.ID + ":" + Constants.TEXTURE_APIARIST_ARMOR_SECONDARY; - } else { - return Constants.ID + ":" + Constants.TEXTURE_APIARIST_ARMOR_PRIMARY; - } - } + @Override + public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) { + if (stack != null && stack.getItem() == PluginApiculture.items.apiaristLegs) { + return Constants.ID + ":" + Constants.TEXTURE_APIARIST_ARMOR_SECONDARY; + } else { + return Constants.ID + ":" + Constants.TEXTURE_APIARIST_ARMOR_PRIMARY; + } + } - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - itemIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this)); - } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + itemIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this)); + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamageForRenderPass(int par1, int par2) { - return itemIcon; - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamageForRenderPass(int par1, int par2) { + return itemIcon; + } - @Override - public boolean requiresMultipleRenderPasses() { - return false; - } + @Override + public boolean requiresMultipleRenderPasses() { + return false; + } - @Override - public int getColorFromItemStack(ItemStack itemstack, int renderPass) { - return 0xffffff; - } + @Override + public int getColorFromItemStack(ItemStack itemstack, int renderPass) { + return 0xffffff; + } - @Override - public boolean hasColor(ItemStack itemstack) { - return false; - } + @Override + public boolean hasColor(ItemStack itemstack) { + return false; + } - @Override - public boolean protectEntity(EntityLivingBase entity, ItemStack armor, String cause, boolean doProtect) { - return true; - } + @Override + public boolean protectEntity(EntityLivingBase entity, ItemStack armor, String cause, boolean doProtect) { + return true; + } - @Override - public boolean protectPlayer(EntityPlayer player, ItemStack armor, String cause, boolean doProtect) { - return true; - } - - @Override - public boolean canSeePollination(EntityPlayer player, ItemStack armor, boolean doSee) { - return armorType == 0; - } + @Override + public boolean protectPlayer(EntityPlayer player, ItemStack armor, String cause, boolean doProtect) { + return true; + } + @Override + public boolean canSeePollination(EntityPlayer player, ItemStack armor, boolean doSee) { + return armorType == 0; + } } diff --git a/src/main/java/forestry/apiculture/items/ItemBeeGE.java b/src/main/java/forestry/apiculture/items/ItemBeeGE.java index 7c09a84af..a1e627763 100755 --- a/src/main/java/forestry/apiculture/items/ItemBeeGE.java +++ b/src/main/java/forestry/apiculture/items/ItemBeeGE.java @@ -10,19 +10,8 @@ ******************************************************************************/ package forestry.apiculture.items; -import java.util.List; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.IIcon; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.EnumBeeType; @@ -36,157 +25,168 @@ import forestry.apiculture.genetics.BeeGenome; import forestry.core.config.Config; import forestry.core.genetics.ItemGE; import forestry.core.utils.StringUtil; +import java.util.List; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.IIcon; public class ItemBeeGE extends ItemGE { - private final EnumBeeType type; + private final EnumBeeType type; - public ItemBeeGE(EnumBeeType type) { - super(Tabs.tabApiculture); - this.type = type; - if (type != EnumBeeType.DRONE) { - setMaxStackSize(1); - } - } + public ItemBeeGE(EnumBeeType type) { + super(Tabs.tabApiculture); + this.type = type; + if (type != EnumBeeType.DRONE) { + setMaxStackSize(1); + } + } - @Override - public IBee getIndividual(ItemStack itemstack) { - return BeeManager.beeRoot.getMember(itemstack); - } + @Override + public IBee getIndividual(ItemStack itemstack) { + return BeeManager.beeRoot.getMember(itemstack); + } - @Override - protected IAlleleSpecies getSpecies(ItemStack itemStack) { - return BeeGenome.getSpecies(itemStack); - } + @Override + protected IAlleleSpecies getSpecies(ItemStack itemStack) { + return BeeGenome.getSpecies(itemStack); + } - @Override - protected int getDefaultPrimaryColour() { - return 0xffffff; - } + @Override + protected int getDefaultPrimaryColour() { + return 0xffffff; + } - @Override - protected int getDefaultSecondaryColour() { - return 0xffdc16; - } + @Override + protected int getDefaultSecondaryColour() { + return 0xffdc16; + } - @Override - public String getItemStackDisplayName(ItemStack itemstack) { + @Override + public String getItemStackDisplayName(ItemStack itemstack) { - if (itemstack.getTagCompound() == null) { - return super.getItemStackDisplayName(itemstack); - } + if (itemstack.getTagCompound() == null) { + return super.getItemStackDisplayName(itemstack); + } - IBee individual = BeeManager.beeRoot.getMember(itemstack); - String customBeeKey = "bees.custom." + type.getName() + "." + individual.getGenome().getPrimary().getUnlocalizedName().replace("bees.species.", ""); - if (StringUtil.canTranslate(customBeeKey)) { - return StringUtil.localize(customBeeKey); - } - String beeGrammar = StringUtil.localize("bees.grammar." + type.getName()); - String beeSpecies = individual.getDisplayName(); - String beeType = StringUtil.localize("bees.grammar." + type.getName() + ".type"); - return beeGrammar.replaceAll("%SPECIES", beeSpecies).replaceAll("%TYPE", beeType); - } + IBee individual = BeeManager.beeRoot.getMember(itemstack); + String customBeeKey = "bees.custom." + type.getName() + "." + + individual.getGenome().getPrimary().getUnlocalizedName().replace("bees.species.", ""); + if (StringUtil.canTranslate(customBeeKey)) { + return StringUtil.localize(customBeeKey); + } + String beeGrammar = StringUtil.localize("bees.grammar." + type.getName()); + String beeSpecies = individual.getDisplayName(); + String beeType = StringUtil.localize("bees.grammar." + type.getName() + ".type"); + return beeGrammar.replaceAll("%SPECIES", beeSpecies).replaceAll("%TYPE", beeType); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { - if (!itemstack.hasTagCompound()) { - return; - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { + if (!itemstack.hasTagCompound()) { + return; + } - if (type != EnumBeeType.DRONE) { - IBee individual = BeeManager.beeRoot.getMember(itemstack); - if (individual.isNatural()) { - list.add(EnumChatFormatting.YELLOW + EnumChatFormatting.ITALIC.toString() + StringUtil.localize("bees.stock.pristine")); - } else { - list.add(EnumChatFormatting.YELLOW + StringUtil.localize("bees.stock.ignoble")); - } - } + if (type != EnumBeeType.DRONE) { + IBee individual = BeeManager.beeRoot.getMember(itemstack); + if (individual.isNatural()) { + list.add(EnumChatFormatting.YELLOW + + EnumChatFormatting.ITALIC.toString() + + StringUtil.localize("bees.stock.pristine")); + } else { + list.add(EnumChatFormatting.YELLOW + StringUtil.localize("bees.stock.ignoble")); + } + } - super.addInformation(itemstack, player, list, flag); - } + super.addInformation(itemstack, player, list, flag); + } - @SuppressWarnings("rawtypes") - @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - addCreativeItems(itemList, true); - } + @SuppressWarnings("rawtypes") + @Override + public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + addCreativeItems(itemList, true); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - public void addCreativeItems(List itemList, boolean hideSecrets) { - for (IBee bee : BeeManager.beeRoot.getIndividualTemplates()) { - // Don't show secret bees unless ordered to. - if (hideSecrets && bee.isSecret() && !Config.isDebug) { - continue; - } + @SuppressWarnings({"rawtypes", "unchecked"}) + public void addCreativeItems(List itemList, boolean hideSecrets) { + for (IBee bee : BeeManager.beeRoot.getIndividualTemplates()) { + // Don't show secret bees unless ordered to. + if (hideSecrets && bee.isSecret() && !Config.isDebug) { + continue; + } - ItemStack beeStack = BeeManager.beeRoot.getMemberStack(bee, type.ordinal()); - if (beeStack != null) { - itemList.add(beeStack); - } - } - } + ItemStack beeStack = BeeManager.beeRoot.getMemberStack(bee, type.ordinal()); + if (beeStack != null) { + itemList.add(beeStack); + } + } + } - /* RENDERING */ - @Override - public int getColorFromItemStack(ItemStack itemstack, int renderPass) { - if (!itemstack.hasTagCompound()) { - return super.getColorFromItemStack(itemstack, renderPass); - } + /* RENDERING */ + @Override + public int getColorFromItemStack(ItemStack itemstack, int renderPass) { + if (!itemstack.hasTagCompound()) { + return super.getColorFromItemStack(itemstack, renderPass); + } - return getColourFromSpecies(BeeGenome.getSpecies(itemstack), renderPass); - } + return getColourFromSpecies(BeeGenome.getSpecies(itemstack), renderPass); + } - @Override - public int getColourFromSpecies(IAlleleSpecies species, int renderPass) { + @Override + public int getColourFromSpecies(IAlleleSpecies species, int renderPass) { - if (species instanceof IAlleleBeeSpecies) { - return species.getIconColour(renderPass); - } else { - return 0xffffff; - } + if (species instanceof IAlleleBeeSpecies) { + return species.getIconColour(renderPass); + } else { + return 0xffffff; + } + } - } + @Override + public boolean requiresMultipleRenderPasses() { + return true; + } - @Override - public boolean requiresMultipleRenderPasses() { - return true; - } + @Override + public int getRenderPasses(int metadata) { + return 3; + } - @Override - public int getRenderPasses(int metadata) { - return 3; - } + /* ICONS */ + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IIconRegister register) { + for (IAllele allele : + AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleBeeSpecies) { + ((IAlleleBeeSpecies) allele).getIconProvider().registerIcons(register); + } + } + } - /* ICONS */ - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IIconRegister register) { - for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { - if (allele instanceof IAlleleBeeSpecies) { - ((IAlleleBeeSpecies) allele).getIconProvider().registerIcons(register); - } - } - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(ItemStack itemstack, int renderPass) { + return getIconFromSpecies(BeeGenome.getSpecies(itemstack), renderPass); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(ItemStack itemstack, int renderPass) { - return getIconFromSpecies(BeeGenome.getSpecies(itemstack), renderPass); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIconIndex(ItemStack stack) { + return getIcon(stack, 0); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIconIndex(ItemStack stack) { - return getIcon(stack, 0); - } + @SideOnly(Side.CLIENT) + public IIcon getIconFromSpecies(IAlleleBeeSpecies species, int renderPass) { + if (species == null) { + species = (IAlleleBeeSpecies) BeeManager.beeRoot.getDefaultTemplate()[EnumBeeChromosome.SPECIES.ordinal()]; + } - @SideOnly(Side.CLIENT) - public IIcon getIconFromSpecies(IAlleleBeeSpecies species, int renderPass) { - if (species == null) { - species = (IAlleleBeeSpecies) BeeManager.beeRoot.getDefaultTemplate()[EnumBeeChromosome.SPECIES.ordinal()]; - } - - return species.getIcon(type, renderPass); - } + return species.getIcon(type, renderPass); + } } diff --git a/src/main/java/forestry/apiculture/items/ItemBeealyzer.java b/src/main/java/forestry/apiculture/items/ItemBeealyzer.java index 98f37bbc3..14bf04ca4 100644 --- a/src/main/java/forestry/apiculture/items/ItemBeealyzer.java +++ b/src/main/java/forestry/apiculture/items/ItemBeealyzer.java @@ -1,38 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.api.core.Tabs; -import forestry.apiculture.gui.GuiBeealyzer; -import forestry.apiculture.inventory.ItemInventoryBeealyzer; -import forestry.core.gui.ContainerAlyzer; -import forestry.core.items.ItemWithGui; - -public class ItemBeealyzer extends ItemWithGui { - public ItemBeealyzer() { - setCreativeTab(Tabs.tabApiculture); - } - - @Override - public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { - ItemInventoryBeealyzer inventory = new ItemInventoryBeealyzer(player, heldItem); - return new GuiBeealyzer(player, inventory); - } - - @Override - public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { - ItemInventoryBeealyzer inventory = new ItemInventoryBeealyzer(player, heldItem); - return new ContainerAlyzer(inventory, player); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.items; + +import forestry.api.core.Tabs; +import forestry.apiculture.gui.GuiBeealyzer; +import forestry.apiculture.inventory.ItemInventoryBeealyzer; +import forestry.core.gui.ContainerAlyzer; +import forestry.core.items.ItemWithGui; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class ItemBeealyzer extends ItemWithGui { + public ItemBeealyzer() { + setCreativeTab(Tabs.tabApiculture); + } + + @Override + public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { + ItemInventoryBeealyzer inventory = new ItemInventoryBeealyzer(player, heldItem); + return new GuiBeealyzer(player, inventory); + } + + @Override + public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { + ItemInventoryBeealyzer inventory = new ItemInventoryBeealyzer(player, heldItem); + return new ContainerAlyzer(inventory, player); + } +} diff --git a/src/main/java/forestry/apiculture/items/ItemBlockCandle.java b/src/main/java/forestry/apiculture/items/ItemBlockCandle.java index 35cfa591d..cab02f201 100644 --- a/src/main/java/forestry/apiculture/items/ItemBlockCandle.java +++ b/src/main/java/forestry/apiculture/items/ItemBlockCandle.java @@ -10,66 +10,63 @@ ******************************************************************************/ package forestry.apiculture.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.apiculture.blocks.BlockCandle; +import forestry.core.items.ItemBlockForestry; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.apiculture.blocks.BlockCandle; -import forestry.core.items.ItemBlockForestry; - public class ItemBlockCandle extends ItemBlockForestry { - public ItemBlockCandle(Block block) { - super(block); - } + public ItemBlockCandle(Block block) { + super(block); + } - @Override - @SideOnly(Side.CLIENT) - public int getColorFromItemStack(ItemStack stack, int pass) { - int value = 0xffffff; - if (pass == 1 && stack.hasTagCompound()) { - NBTTagCompound tag = stack.getTagCompound(); - if (tag.hasKey("colour")) { - value = tag.getInteger("colour"); - } - } - return value; - } + @Override + @SideOnly(Side.CLIENT) + public int getColorFromItemStack(ItemStack stack, int pass) { + int value = 0xffffff; + if (pass == 1 && stack.hasTagCompound()) { + NBTTagCompound tag = stack.getTagCompound(); + if (tag.hasKey("colour")) { + value = tag.getInteger("colour"); + } + } + return value; + } - @Override - public String getUnlocalizedName(ItemStack itemStack) { - String value = getBlock().getUnlocalizedName(); - if (itemStack.hasTagCompound() && itemStack.getTagCompound().hasKey(BlockCandle.colourTagName)) { - value = value + ".dyed"; - } + @Override + public String getUnlocalizedName(ItemStack itemStack) { + String value = getBlock().getUnlocalizedName(); + if (itemStack.hasTagCompound() && itemStack.getTagCompound().hasKey(BlockCandle.colourTagName)) { + value = value + ".dyed"; + } - if (BlockCandle.isLit(itemStack)) { - value = value + ".lit"; - } else { - value = value + ".stump"; - } - return value; - } + if (BlockCandle.isLit(itemStack)) { + value = value + ".lit"; + } else { + value = value + ".stump"; + } + return value; + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIconFromDamageForRenderPass(int meta, int pass) { - return this.getBlock().getIcon((meta != 0) ? 8 : 0, pass); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIconFromDamageForRenderPass(int meta, int pass) { + return this.getBlock().getIcon((meta != 0) ? 8 : 0, pass); + } - @Override - @SideOnly(Side.CLIENT) - public boolean requiresMultipleRenderPasses() { - return true; - } - - @Override - public int getRenderPasses(int metadata) { - return 2; - } + @Override + @SideOnly(Side.CLIENT) + public boolean requiresMultipleRenderPasses() { + return true; + } + @Override + public int getRenderPasses(int metadata) { + return 2; + } } diff --git a/src/main/java/forestry/apiculture/items/ItemHabitatLocator.java b/src/main/java/forestry/apiculture/items/ItemHabitatLocator.java index b4b5b99de..4b629b003 100644 --- a/src/main/java/forestry/apiculture/items/ItemHabitatLocator.java +++ b/src/main/java/forestry/apiculture/items/ItemHabitatLocator.java @@ -10,20 +10,8 @@ ******************************************************************************/ package forestry.apiculture.items; -import java.util.List; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; import forestry.api.core.Tabs; @@ -34,61 +22,71 @@ import forestry.apiculture.inventory.ItemInventoryHabitatLocator; import forestry.apiculture.render.TextureHabitatLocator; import forestry.core.items.ItemWithGui; import forestry.core.utils.StringUtil; +import java.util.List; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; public class ItemHabitatLocator extends ItemWithGui { - private static final String iconName = "forestry:biomefinder"; + private static final String iconName = "forestry:biomefinder"; - private final HabitatLocatorLogic locatorLogic; + private final HabitatLocatorLogic locatorLogic; - public ItemHabitatLocator() { - setCreativeTab(Tabs.tabApiculture); - setMaxStackSize(1); - locatorLogic = new HabitatLocatorLogic(); - } + public ItemHabitatLocator() { + setCreativeTab(Tabs.tabApiculture); + setMaxStackSize(1); + locatorLogic = new HabitatLocatorLogic(); + } - public HabitatLocatorLogic getLocatorLogic() { - return locatorLogic; - } + public HabitatLocatorLogic getLocatorLogic() { + return locatorLogic; + } - @Override - public void onUpdate(ItemStack p_77663_1_, World world, Entity player, int p_77663_4_, boolean p_77663_5_) { - if (!world.isRemote) { - locatorLogic.onUpdate(world, player); - } - } + @Override + public void onUpdate(ItemStack p_77663_1_, World world, Entity player, int p_77663_4_, boolean p_77663_5_) { + if (!world.isRemote) { + locatorLogic.onUpdate(world, player); + } + } - /* TEXTURES */ - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - if (register instanceof TextureMap) { - TextureAtlasSprite texture = new TextureHabitatLocator(iconName); - ((TextureMap) register).setTextureEntry(iconName, texture); - itemIcon = texture; - } - } + /* TEXTURES */ + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + if (register instanceof TextureMap) { + TextureAtlasSprite texture = new TextureHabitatLocator(iconName); + ((TextureMap) register).setTextureEntry(iconName, texture); + itemIcon = texture; + } + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { - BiomeGenBase currentBiome = player.worldObj.getBiomeGenForCoords((int) player.posX, (int) player.posZ); + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { + BiomeGenBase currentBiome = player.worldObj.getBiomeGenForCoords((int) player.posX, (int) player.posZ); - float temperatureValue = currentBiome.getFloatTemperature((int) player.posX, (int) player.posY, (int) player.posZ); - EnumTemperature temperature = EnumTemperature.getFromValue(temperatureValue); - EnumHumidity humidity = EnumHumidity.getFromValue(currentBiome.rainfall); + float temperatureValue = + currentBiome.getFloatTemperature((int) player.posX, (int) player.posY, (int) player.posZ); + EnumTemperature temperature = EnumTemperature.getFromValue(temperatureValue); + EnumHumidity humidity = EnumHumidity.getFromValue(currentBiome.rainfall); - list.add(StringUtil.localize("gui.currentBiome") + ": " + currentBiome.biomeName); - list.add(StringUtil.localize("gui.temperature") + ": " + AlleleManager.climateHelper.toDisplay(temperature)); - list.add(StringUtil.localize("gui.humidity") + ": " + AlleleManager.climateHelper.toDisplay(humidity)); - } + list.add(StringUtil.localize("gui.currentBiome") + ": " + currentBiome.biomeName); + list.add(StringUtil.localize("gui.temperature") + ": " + AlleleManager.climateHelper.toDisplay(temperature)); + list.add(StringUtil.localize("gui.humidity") + ": " + AlleleManager.climateHelper.toDisplay(humidity)); + } - @Override - public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { - return new GuiHabitatLocator(player, new ItemInventoryHabitatLocator(player, heldItem)); - } + @Override + public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { + return new GuiHabitatLocator(player, new ItemInventoryHabitatLocator(player, heldItem)); + } - @Override - public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { - return new ContainerHabitatLocator(player, new ItemInventoryHabitatLocator(player, heldItem)); - } + @Override + public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { + return new ContainerHabitatLocator(player, new ItemInventoryHabitatLocator(player, heldItem)); + } } diff --git a/src/main/java/forestry/apiculture/items/ItemHiveFrame.java b/src/main/java/forestry/apiculture/items/ItemHiveFrame.java index 8898afa57..0753a2dea 100755 --- a/src/main/java/forestry/apiculture/items/ItemHiveFrame.java +++ b/src/main/java/forestry/apiculture/items/ItemHiveFrame.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.apiculture.items; -import net.minecraft.item.ItemStack; - import forestry.api.apiculture.DefaultBeeModifier; import forestry.api.apiculture.IBee; import forestry.api.apiculture.IBeeGenome; @@ -20,49 +18,50 @@ import forestry.api.apiculture.IBeeModifier; import forestry.api.apiculture.IHiveFrame; import forestry.api.core.Tabs; import forestry.core.items.ItemForestry; +import net.minecraft.item.ItemStack; public class ItemHiveFrame extends ItemForestry implements IHiveFrame { - private final IBeeModifier beeModifier; + private final IBeeModifier beeModifier; - public ItemHiveFrame(int maxDamage, float geneticDecay) { - setMaxStackSize(1); - setMaxDamage(maxDamage); - setCreativeTab(Tabs.tabApiculture); + public ItemHiveFrame(int maxDamage, float geneticDecay) { + setMaxStackSize(1); + setMaxDamage(maxDamage); + setCreativeTab(Tabs.tabApiculture); - this.beeModifier = new HiveFrameBeeModifier(geneticDecay); - } + this.beeModifier = new HiveFrameBeeModifier(geneticDecay); + } - @Override - public ItemStack frameUsed(IBeeHousing housing, ItemStack frame, IBee queen, int wear) { - frame.setItemDamage(frame.getItemDamage() + wear); - if (frame.getItemDamage() >= frame.getMaxDamage()) { - return null; - } else { - return frame; - } - } + @Override + public ItemStack frameUsed(IBeeHousing housing, ItemStack frame, IBee queen, int wear) { + frame.setItemDamage(frame.getItemDamage() + wear); + if (frame.getItemDamage() >= frame.getMaxDamage()) { + return null; + } else { + return frame; + } + } - @Override - public IBeeModifier getBeeModifier() { - return beeModifier; - } + @Override + public IBeeModifier getBeeModifier() { + return beeModifier; + } - private static class HiveFrameBeeModifier extends DefaultBeeModifier { - private final float geneticDecay; + private static class HiveFrameBeeModifier extends DefaultBeeModifier { + private final float geneticDecay; - public HiveFrameBeeModifier(float geneticDecay) { - this.geneticDecay = geneticDecay; - } + public HiveFrameBeeModifier(float geneticDecay) { + this.geneticDecay = geneticDecay; + } - @Override - public float getProductionModifier(IBeeGenome genome, float currentModifier) { - return (currentModifier < 10f) ? 2f : 1f; - } + @Override + public float getProductionModifier(IBeeGenome genome, float currentModifier) { + return (currentModifier < 10f) ? 2f : 1f; + } - @Override - public float getGeneticDecay(IBeeGenome genome, float currentModifier) { - return this.geneticDecay; - } - } + @Override + public float getGeneticDecay(IBeeGenome genome, float currentModifier) { + return this.geneticDecay; + } + } } diff --git a/src/main/java/forestry/apiculture/items/ItemHoneycomb.java b/src/main/java/forestry/apiculture/items/ItemHoneycomb.java index c2cd26a66..c1d32cb2e 100755 --- a/src/main/java/forestry/apiculture/items/ItemHoneycomb.java +++ b/src/main/java/forestry/apiculture/items/ItemHoneycomb.java @@ -10,85 +10,83 @@ ******************************************************************************/ package forestry.apiculture.items; +import forestry.api.core.Tabs; +import forestry.core.config.Config; +import forestry.core.items.ItemForestryMultiPass; import java.util.ArrayList; import java.util.List; import java.util.Random; - import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import forestry.api.core.Tabs; -import forestry.core.config.Config; -import forestry.core.items.ItemForestryMultiPass; - public class ItemHoneycomb extends ItemForestryMultiPass { - public ItemHoneycomb() { - super(); - setMaxDamage(0); - setHasSubtypes(true); - setCreativeTab(Tabs.tabApiculture); - } + public ItemHoneycomb() { + super(); + setMaxDamage(0); + setHasSubtypes(true); + setCreativeTab(Tabs.tabApiculture); + } - @Override - public boolean isDamageable() { - return false; - } + @Override + public boolean isDamageable() { + return false; + } - @Override - public boolean isRepairable() { - return false; - } + @Override + public boolean isRepairable() { + return false; + } - @Override - public String getUnlocalizedName(ItemStack stack) { - EnumHoneyComb honeyComb = EnumHoneyComb.VALUES[stack.getItemDamage()]; - return super.getUnlocalizedName(stack) + "." + honeyComb.name; - } + @Override + public String getUnlocalizedName(ItemStack stack) { + EnumHoneyComb honeyComb = EnumHoneyComb.VALUES[stack.getItemDamage()]; + return super.getUnlocalizedName(stack) + "." + honeyComb.name; + } - @Override - public int getColorFromItemStack(ItemStack itemstack, int j) { - EnumHoneyComb honeyComb = EnumHoneyComb.VALUES[itemstack.getItemDamage()]; - if (j == 0) { - return honeyComb.primaryColor; - } else { - return honeyComb.secondaryColor; - } - } + @Override + public int getColorFromItemStack(ItemStack itemstack, int j) { + EnumHoneyComb honeyComb = EnumHoneyComb.VALUES[itemstack.getItemDamage()]; + if (j == 0) { + return honeyComb.primaryColor; + } else { + return honeyComb.secondaryColor; + } + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - for (int i = 0; i < EnumHoneyComb.VALUES.length; i++) { - EnumHoneyComb honeyComb = EnumHoneyComb.VALUES[i]; - if (!honeyComb.isSecret() || Config.isDebug) { - itemList.add(new ItemStack(this, 1, i)); - } - } - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + for (int i = 0; i < EnumHoneyComb.VALUES.length; i++) { + EnumHoneyComb honeyComb = EnumHoneyComb.VALUES[i]; + if (!honeyComb.isSecret() || Config.isDebug) { + itemList.add(new ItemStack(this, 1, i)); + } + } + } - private static EnumHoneyComb getRandomCombType(Random random, boolean includeSecret) { - List validCombs = new ArrayList<>(EnumHoneyComb.VALUES.length); - for (int i = 0; i < EnumHoneyComb.VALUES.length; i++) { - EnumHoneyComb honeyComb = EnumHoneyComb.VALUES[i]; - if (!honeyComb.isSecret() || includeSecret) { - validCombs.add(honeyComb); - } - } + private static EnumHoneyComb getRandomCombType(Random random, boolean includeSecret) { + List validCombs = new ArrayList<>(EnumHoneyComb.VALUES.length); + for (int i = 0; i < EnumHoneyComb.VALUES.length; i++) { + EnumHoneyComb honeyComb = EnumHoneyComb.VALUES[i]; + if (!honeyComb.isSecret() || includeSecret) { + validCombs.add(honeyComb); + } + } - if (validCombs.isEmpty()) { - return null; - } else { - return validCombs.get(random.nextInt(validCombs.size())); - } - } + if (validCombs.isEmpty()) { + return null; + } else { + return validCombs.get(random.nextInt(validCombs.size())); + } + } - public ItemStack getRandomComb(int amount, Random random, boolean includeSecret) { - EnumHoneyComb honeyComb = getRandomCombType(random, includeSecret); - return get(honeyComb, amount); - } + public ItemStack getRandomComb(int amount, Random random, boolean includeSecret) { + EnumHoneyComb honeyComb = getRandomCombType(random, includeSecret); + return get(honeyComb, amount); + } - public ItemStack get(EnumHoneyComb honeyComb, int amount) { - return new ItemStack(this, amount, honeyComb.ordinal()); - } + public ItemStack get(EnumHoneyComb honeyComb, int amount) { + return new ItemStack(this, amount, honeyComb.ordinal()); + } } diff --git a/src/main/java/forestry/apiculture/items/ItemImprinter.java b/src/main/java/forestry/apiculture/items/ItemImprinter.java index 76176c2c0..d0c6de395 100644 --- a/src/main/java/forestry/apiculture/items/ItemImprinter.java +++ b/src/main/java/forestry/apiculture/items/ItemImprinter.java @@ -1,36 +1,35 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.api.core.Tabs; -import forestry.apiculture.gui.ContainerImprinter; -import forestry.apiculture.gui.GuiImprinter; -import forestry.apiculture.inventory.ItemInventoryImprinter; -import forestry.core.items.ItemWithGui; - -public class ItemImprinter extends ItemWithGui { - public ItemImprinter() { - setCreativeTab(Tabs.tabApiculture); - } - - @Override - public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { - return new GuiImprinter(player.inventory, new ItemInventoryImprinter(player, heldItem)); - } - - @Override - public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { - return new ContainerImprinter(player.inventory, new ItemInventoryImprinter(player, heldItem)); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.items; + +import forestry.api.core.Tabs; +import forestry.apiculture.gui.ContainerImprinter; +import forestry.apiculture.gui.GuiImprinter; +import forestry.apiculture.inventory.ItemInventoryImprinter; +import forestry.core.items.ItemWithGui; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class ItemImprinter extends ItemWithGui { + public ItemImprinter() { + setCreativeTab(Tabs.tabApiculture); + } + + @Override + public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { + return new GuiImprinter(player.inventory, new ItemInventoryImprinter(player, heldItem)); + } + + @Override + public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { + return new ContainerImprinter(player.inventory, new ItemInventoryImprinter(player, heldItem)); + } +} diff --git a/src/main/java/forestry/apiculture/items/ItemMinecartBeehouse.java b/src/main/java/forestry/apiculture/items/ItemMinecartBeehouse.java index fbfb482e4..64b1c3aca 100644 --- a/src/main/java/forestry/apiculture/items/ItemMinecartBeehouse.java +++ b/src/main/java/forestry/apiculture/items/ItemMinecartBeehouse.java @@ -1,116 +1,125 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import java.util.List; - -import net.minecraft.block.BlockDispenser; -import net.minecraft.block.BlockRailBase; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemMinecart; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.apiculture.entities.EntityMinecartApiary; -import forestry.apiculture.entities.EntityMinecartBeeHousingBase; -import forestry.apiculture.entities.EntityMinecartBeehouse; -import forestry.core.render.TextureManager; - -public class ItemMinecartBeehouse extends ItemMinecart { - private final String[] definition = new String[]{"cart.beehouse", "cart.apiary"}; - - public ItemMinecartBeehouse() { - super(0); - setMaxDamage(0); - setHasSubtypes(true); - BlockDispenser.dispenseBehaviorRegistry.putObject(this, null); - } - - @Override - public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float facingX, float facingY, float facingZ) { - if (!BlockRailBase.func_150051_a(world.getBlock(x, y, z))) { - return false; - } - - if (!world.isRemote) { - EntityMinecartBeeHousingBase entityMinecart; - if (itemStack.getItemDamage() == 0) { - entityMinecart = new EntityMinecartBeehouse(world, (double) ((float) x + 0.5F), (double) ((float) y + 0.5F), (double) ((float) z + 0.5F)); - } else { - entityMinecart = new EntityMinecartApiary(world, (double) ((float) x + 0.5F), (double) ((float) y + 0.5F), (double) ((float) z + 0.5F)); - } - entityMinecart.setOwner(player.getGameProfile()); - - if (itemStack.hasDisplayName()) { - entityMinecart.setMinecartName(itemStack.getDisplayName()); - } - - world.spawnEntityInWorld(entityMinecart); - } - - --itemStack.stackSize; - return true; - } - - @Override - public String getUnlocalizedName(ItemStack stack) { - if (stack.getItemDamage() >= definition.length || stack.getItemDamage() < 0) { - return "item.forestry.unknown"; - } else { - return "item.for." + definition[stack.getItemDamage()]; - } - } - - /* ICONS */ - @SideOnly(Side.CLIENT) - private IIcon[] icons; - - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - icons = new IIcon[definition.length]; - for (int i = 0; i < definition.length; i++) { - icons[i] = TextureManager.registerTex(register, definition[i]); - } - } - - @Override - public IIcon getIconFromDamage(int damage) { - if (damage >= definition.length || damage < 0) { - return icons[0]; - } else { - return icons[damage]; - } - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - for (int i = 0; i < definition.length; i++) { - itemList.add(new ItemStack(this, 1, i)); - } - } - - public ItemStack getBeeHouseMinecart() { - return new ItemStack(this, 1, 0); - } - - public ItemStack getApiaryMinecart() { - return new ItemStack(this, 1, 1); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.items; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.apiculture.entities.EntityMinecartApiary; +import forestry.apiculture.entities.EntityMinecartBeeHousingBase; +import forestry.apiculture.entities.EntityMinecartBeehouse; +import forestry.core.render.TextureManager; +import java.util.List; +import net.minecraft.block.BlockDispenser; +import net.minecraft.block.BlockRailBase; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemMinecart; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; + +public class ItemMinecartBeehouse extends ItemMinecart { + private final String[] definition = new String[] {"cart.beehouse", "cart.apiary"}; + + public ItemMinecartBeehouse() { + super(0); + setMaxDamage(0); + setHasSubtypes(true); + BlockDispenser.dispenseBehaviorRegistry.putObject(this, null); + } + + @Override + public boolean onItemUse( + ItemStack itemStack, + EntityPlayer player, + World world, + int x, + int y, + int z, + int side, + float facingX, + float facingY, + float facingZ) { + if (!BlockRailBase.func_150051_a(world.getBlock(x, y, z))) { + return false; + } + + if (!world.isRemote) { + EntityMinecartBeeHousingBase entityMinecart; + if (itemStack.getItemDamage() == 0) { + entityMinecart = new EntityMinecartBeehouse( + world, (double) ((float) x + 0.5F), (double) ((float) y + 0.5F), (double) ((float) z + 0.5F)); + } else { + entityMinecart = new EntityMinecartApiary( + world, (double) ((float) x + 0.5F), (double) ((float) y + 0.5F), (double) ((float) z + 0.5F)); + } + entityMinecart.setOwner(player.getGameProfile()); + + if (itemStack.hasDisplayName()) { + entityMinecart.setMinecartName(itemStack.getDisplayName()); + } + + world.spawnEntityInWorld(entityMinecart); + } + + --itemStack.stackSize; + return true; + } + + @Override + public String getUnlocalizedName(ItemStack stack) { + if (stack.getItemDamage() >= definition.length || stack.getItemDamage() < 0) { + return "item.forestry.unknown"; + } else { + return "item.for." + definition[stack.getItemDamage()]; + } + } + + /* ICONS */ + @SideOnly(Side.CLIENT) + private IIcon[] icons; + + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + icons = new IIcon[definition.length]; + for (int i = 0; i < definition.length; i++) { + icons[i] = TextureManager.registerTex(register, definition[i]); + } + } + + @Override + public IIcon getIconFromDamage(int damage) { + if (damage >= definition.length || damage < 0) { + return icons[0]; + } else { + return icons[damage]; + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + for (int i = 0; i < definition.length; i++) { + itemList.add(new ItemStack(this, 1, i)); + } + } + + public ItemStack getBeeHouseMinecart() { + return new ItemStack(this, 1, 0); + } + + public ItemStack getApiaryMinecart() { + return new ItemStack(this, 1, 1); + } +} diff --git a/src/main/java/forestry/apiculture/items/ItemPollenCluster.java b/src/main/java/forestry/apiculture/items/ItemPollenCluster.java index dd08cf65d..09b059113 100644 --- a/src/main/java/forestry/apiculture/items/ItemPollenCluster.java +++ b/src/main/java/forestry/apiculture/items/ItemPollenCluster.java @@ -1,26 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import net.minecraft.item.ItemStack; - -import forestry.api.core.Tabs; -import forestry.core.items.ItemOverlay; - -public class ItemPollenCluster extends ItemOverlay { - public ItemPollenCluster() { - super(Tabs.tabApiculture, EnumPollenCluster.VALUES); - } - - public ItemStack get(EnumPollenCluster pollenCluster, int amount) { - return new ItemStack(this, amount, pollenCluster.ordinal()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.items; + +import forestry.api.core.Tabs; +import forestry.core.items.ItemOverlay; +import net.minecraft.item.ItemStack; + +public class ItemPollenCluster extends ItemOverlay { + public ItemPollenCluster() { + super(Tabs.tabApiculture, EnumPollenCluster.VALUES); + } + + public ItemStack get(EnumPollenCluster pollenCluster, int amount) { + return new ItemStack(this, amount, pollenCluster.ordinal()); + } +} diff --git a/src/main/java/forestry/apiculture/items/ItemPropolis.java b/src/main/java/forestry/apiculture/items/ItemPropolis.java index 585400343..dfd124e3b 100644 --- a/src/main/java/forestry/apiculture/items/ItemPropolis.java +++ b/src/main/java/forestry/apiculture/items/ItemPropolis.java @@ -1,26 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import net.minecraft.item.ItemStack; - -import forestry.api.core.Tabs; -import forestry.core.items.ItemOverlay; - -public class ItemPropolis extends ItemOverlay { - public ItemPropolis() { - super(Tabs.tabApiculture, EnumPropolis.VALUES); - } - - public ItemStack get(EnumPropolis propolis, int amount) { - return new ItemStack(this, amount, propolis.ordinal()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.items; + +import forestry.api.core.Tabs; +import forestry.core.items.ItemOverlay; +import net.minecraft.item.ItemStack; + +public class ItemPropolis extends ItemOverlay { + public ItemPropolis() { + super(Tabs.tabApiculture, EnumPropolis.VALUES); + } + + public ItemStack get(EnumPropolis propolis, int amount) { + return new ItemStack(this, amount, propolis.ordinal()); + } +} diff --git a/src/main/java/forestry/apiculture/items/ItemRegistryApiculture.java b/src/main/java/forestry/apiculture/items/ItemRegistryApiculture.java index da47bf97b..3e55e407b 100644 --- a/src/main/java/forestry/apiculture/items/ItemRegistryApiculture.java +++ b/src/main/java/forestry/apiculture/items/ItemRegistryApiculture.java @@ -1,102 +1,101 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import net.minecraftforge.oredict.OreDictionary; - -import forestry.api.apiculture.EnumBeeType; -import forestry.api.core.Tabs; -import forestry.core.items.ItemForestry; -import forestry.core.items.ItemOverlay; -import forestry.core.items.ItemRegistry; -import forestry.core.items.ItemScoop; - -public class ItemRegistryApiculture extends ItemRegistry { - public final ItemBeeGE beeQueenGE; - public final ItemBeeGE beeDroneGE; - public final ItemBeeGE beePrincessGE; - public final ItemBeeGE beeLarvaeGE; - - public final ItemHabitatLocator habitatLocator; - public final ItemBeealyzer beealyzer; - public final ItemImprinter imprinter; - - public final ItemMinecartBeehouse minecartBeehouse; - - public final ItemHiveFrame frameUntreated; - public final ItemHiveFrame frameImpregnated; - public final ItemHiveFrame frameProven; - - public final ItemOverlay honeyDrop; - public final ItemPollenCluster pollenCluster; - public final ItemPropolis propolis; - public final ItemForestry honeydew; - public final ItemForestry royalJelly; - public final ItemForestry waxCast; - public final ItemHoneycomb beeComb; - - public final ItemArmorApiarist apiaristHat; - public final ItemArmorApiarist apiaristChest; - public final ItemArmorApiarist apiaristLegs; - public final ItemArmorApiarist apiaristBoots; - - public final ItemScoop scoop; - - public ItemRegistryApiculture() { - // / BEES - beeQueenGE = registerItem(new ItemBeeGE(EnumBeeType.QUEEN), "beeQueenGE"); - beeDroneGE = registerItem(new ItemBeeGE(EnumBeeType.DRONE), "beeDroneGE"); - beePrincessGE = registerItem(new ItemBeeGE(EnumBeeType.PRINCESS), "beePrincessGE"); - beeLarvaeGE = registerItem(new ItemBeeGE(EnumBeeType.LARVAE), "beeLarvaeGE"); - - beealyzer = registerItem(new ItemBeealyzer(), "beealyzer"); - habitatLocator = registerItem(new ItemHabitatLocator(), "habitatLocator"); - imprinter = registerItem(new ItemImprinter(), "imprinter"); - - minecartBeehouse = registerItem(new ItemMinecartBeehouse(), "cart.beehouse"); - - // / COMB FRAMES - frameUntreated = registerItem(new ItemHiveFrame(80, 0.9f), "frameUntreated"); - frameImpregnated = registerItem(new ItemHiveFrame(240, 0.4f), "frameImpregnated"); - frameProven = registerItem(new ItemHiveFrame(720, 0.3f), "frameProven"); - - // / BEE RESOURCES - honeyDrop = registerItem(new ItemOverlay(Tabs.tabApiculture, EnumHoneyDrop.VALUES), "honeyDrop"); - OreDictionary.registerOre("dropHoney", honeyDrop); - - pollenCluster = registerItem(new ItemPollenCluster(), "pollen"); - OreDictionary.registerOre("itemPollen", pollenCluster); - - propolis = registerItem(new ItemPropolis(), "propolis"); - - honeydew = registerItem(new ItemForestry(Tabs.tabApiculture), "honeydew"); - OreDictionary.registerOre("dropHoneydew", honeydew); - - royalJelly = registerItem(new ItemForestry(Tabs.tabApiculture), "royalJelly"); - OreDictionary.registerOre("dropRoyalJelly", royalJelly); - - waxCast = registerItem(new ItemWaxCast(), "waxCast"); - - // / BEE COMBS - beeComb = registerItem(new ItemHoneycomb(), "beeCombs"); - OreDictionary.registerOre("beeComb", beeComb.getWildcard()); - - // / APIARIST'S CLOTHES - apiaristHat = registerItem(new ItemArmorApiarist(0), "apiaristHelmet"); - apiaristChest = registerItem(new ItemArmorApiarist(1), "apiaristChest"); - apiaristLegs = registerItem(new ItemArmorApiarist(2), "apiaristLegs"); - apiaristBoots = registerItem(new ItemArmorApiarist(3), "apiaristBoots"); - - // TOOLS - scoop = registerItem(new ItemScoop(), "scoop"); - scoop.setHarvestLevel("scoop", 3); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.items; + +import forestry.api.apiculture.EnumBeeType; +import forestry.api.core.Tabs; +import forestry.core.items.ItemForestry; +import forestry.core.items.ItemOverlay; +import forestry.core.items.ItemRegistry; +import forestry.core.items.ItemScoop; +import net.minecraftforge.oredict.OreDictionary; + +public class ItemRegistryApiculture extends ItemRegistry { + public final ItemBeeGE beeQueenGE; + public final ItemBeeGE beeDroneGE; + public final ItemBeeGE beePrincessGE; + public final ItemBeeGE beeLarvaeGE; + + public final ItemHabitatLocator habitatLocator; + public final ItemBeealyzer beealyzer; + public final ItemImprinter imprinter; + + public final ItemMinecartBeehouse minecartBeehouse; + + public final ItemHiveFrame frameUntreated; + public final ItemHiveFrame frameImpregnated; + public final ItemHiveFrame frameProven; + + public final ItemOverlay honeyDrop; + public final ItemPollenCluster pollenCluster; + public final ItemPropolis propolis; + public final ItemForestry honeydew; + public final ItemForestry royalJelly; + public final ItemForestry waxCast; + public final ItemHoneycomb beeComb; + + public final ItemArmorApiarist apiaristHat; + public final ItemArmorApiarist apiaristChest; + public final ItemArmorApiarist apiaristLegs; + public final ItemArmorApiarist apiaristBoots; + + public final ItemScoop scoop; + + public ItemRegistryApiculture() { + // / BEES + beeQueenGE = registerItem(new ItemBeeGE(EnumBeeType.QUEEN), "beeQueenGE"); + beeDroneGE = registerItem(new ItemBeeGE(EnumBeeType.DRONE), "beeDroneGE"); + beePrincessGE = registerItem(new ItemBeeGE(EnumBeeType.PRINCESS), "beePrincessGE"); + beeLarvaeGE = registerItem(new ItemBeeGE(EnumBeeType.LARVAE), "beeLarvaeGE"); + + beealyzer = registerItem(new ItemBeealyzer(), "beealyzer"); + habitatLocator = registerItem(new ItemHabitatLocator(), "habitatLocator"); + imprinter = registerItem(new ItemImprinter(), "imprinter"); + + minecartBeehouse = registerItem(new ItemMinecartBeehouse(), "cart.beehouse"); + + // / COMB FRAMES + frameUntreated = registerItem(new ItemHiveFrame(80, 0.9f), "frameUntreated"); + frameImpregnated = registerItem(new ItemHiveFrame(240, 0.4f), "frameImpregnated"); + frameProven = registerItem(new ItemHiveFrame(720, 0.3f), "frameProven"); + + // / BEE RESOURCES + honeyDrop = registerItem(new ItemOverlay(Tabs.tabApiculture, EnumHoneyDrop.VALUES), "honeyDrop"); + OreDictionary.registerOre("dropHoney", honeyDrop); + + pollenCluster = registerItem(new ItemPollenCluster(), "pollen"); + OreDictionary.registerOre("itemPollen", pollenCluster); + + propolis = registerItem(new ItemPropolis(), "propolis"); + + honeydew = registerItem(new ItemForestry(Tabs.tabApiculture), "honeydew"); + OreDictionary.registerOre("dropHoneydew", honeydew); + + royalJelly = registerItem(new ItemForestry(Tabs.tabApiculture), "royalJelly"); + OreDictionary.registerOre("dropRoyalJelly", royalJelly); + + waxCast = registerItem(new ItemWaxCast(), "waxCast"); + + // / BEE COMBS + beeComb = registerItem(new ItemHoneycomb(), "beeCombs"); + OreDictionary.registerOre("beeComb", beeComb.getWildcard()); + + // / APIARIST'S CLOTHES + apiaristHat = registerItem(new ItemArmorApiarist(0), "apiaristHelmet"); + apiaristChest = registerItem(new ItemArmorApiarist(1), "apiaristChest"); + apiaristLegs = registerItem(new ItemArmorApiarist(2), "apiaristLegs"); + apiaristBoots = registerItem(new ItemArmorApiarist(3), "apiaristBoots"); + + // TOOLS + scoop = registerItem(new ItemScoop(), "scoop"); + scoop.setHarvestLevel("scoop", 3); + } +} diff --git a/src/main/java/forestry/apiculture/items/ItemWaxCast.java b/src/main/java/forestry/apiculture/items/ItemWaxCast.java index 8a5f4ea9e..24daf4d2b 100755 --- a/src/main/java/forestry/apiculture/items/ItemWaxCast.java +++ b/src/main/java/forestry/apiculture/items/ItemWaxCast.java @@ -10,29 +10,27 @@ ******************************************************************************/ package forestry.apiculture.items; -import net.minecraft.item.ItemStack; - import forestry.api.core.Tabs; import forestry.core.items.ICraftingPlan; import forestry.core.items.ItemForestry; +import net.minecraft.item.ItemStack; public class ItemWaxCast extends ItemForestry implements ICraftingPlan { - public ItemWaxCast() { - super(Tabs.tabApiculture); - setMaxStackSize(1); - setMaxDamage(16); - setNoRepair(); - } - - @Override - public ItemStack planUsed(ItemStack plan, ItemStack result) { - plan.setItemDamage(plan.getItemDamage() + result.stackSize); - if (plan.getItemDamage() >= plan.getMaxDamage()) { - return null; - } else { - return plan; - } - } + public ItemWaxCast() { + super(Tabs.tabApiculture); + setMaxStackSize(1); + setMaxDamage(16); + setNoRepair(); + } + @Override + public ItemStack planUsed(ItemStack plan, ItemStack result) { + plan.setItemDamage(plan.getItemDamage() + result.stackSize); + if (plan.getItemDamage() >= plan.getMaxDamage()) { + return null; + } else { + return plan; + } + } } diff --git a/src/main/java/forestry/apiculture/multiblock/AlvearyController.java b/src/main/java/forestry/apiculture/multiblock/AlvearyController.java index 059e0cc41..d0adbec31 100644 --- a/src/main/java/forestry/apiculture/multiblock/AlvearyController.java +++ b/src/main/java/forestry/apiculture/multiblock/AlvearyController.java @@ -1,445 +1,448 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.multiblock; - -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; - -import forestry.api.core.BiomeHelper; -import net.minecraft.block.Block; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.StatCollector; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - -import com.mojang.authlib.GameProfile; - -import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.IBeeHousingInventory; -import forestry.api.apiculture.IBeeListener; -import forestry.api.apiculture.IBeeModifier; -import forestry.api.apiculture.IBeekeepingLogic; -import forestry.api.core.EnumHumidity; -import forestry.api.core.EnumTemperature; -import forestry.api.core.IClimateControlled; -import forestry.api.multiblock.IAlvearyComponent; -import forestry.api.multiblock.IMultiblockComponent; -import forestry.apiculture.AlvearyBeeModifier; -import forestry.apiculture.InventoryBeeHousing; -import forestry.core.access.EnumAccess; -import forestry.core.inventory.FakeInventoryAdapter; -import forestry.core.inventory.IInventoryAdapter; -import forestry.core.multiblock.IMultiblockControllerInternal; -import forestry.core.multiblock.MultiblockValidationException; -import forestry.core.multiblock.RectangularMultiblockControllerBase; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.proxy.Proxies; -import forestry.core.utils.BlockUtil; - -public class AlvearyController extends RectangularMultiblockControllerBase implements IAlvearyControllerInternal, IClimateControlled { - - private final InventoryBeeHousing inventory; - private final IBeekeepingLogic beekeepingLogic; - - private float tempChange = 0.0f; - private float humidChange = 0.0f; - - // PARTS - private final Set beeModifiers = new HashSet<>(); - private final Set beeListeners = new HashSet<>(); - private final Set climatisers = new HashSet<>(); - private final Set activeComponents = new HashSet<>(); - - // CLIENT - private int breedingProgressPercent = 0; - - public AlvearyController(World world) { - super(world, AlvearyMultiblockSizeLimits.instance); - this.inventory = new InventoryBeeHousing(9, getAccessHandler()); - this.beekeepingLogic = BeeManager.beeRoot.createBeekeepingLogic(this); - - this.beeModifiers.add(new AlvearyBeeModifier()); - } - - @Override - public IBeeHousingInventory getBeeInventory() { - return inventory; - } - - @Override - public IBeekeepingLogic getBeekeepingLogic() { - return beekeepingLogic; - } - - @Override - public IInventoryAdapter getInternalInventory() { - if (isAssembled()) { - return inventory; - } else { - return FakeInventoryAdapter.instance(); - } - } - - @Override - public Iterable getBeeListeners() { - return beeListeners; - } - - @Override - public Iterable getBeeModifiers() { - return beeModifiers; - } - - @Override - public void onAttachedPartWithMultiblockData(IMultiblockComponent part, NBTTagCompound data) { - this.readFromNBT(data); - } - - @Override - protected void onBlockAdded(IMultiblockComponent newPart) { - if (newPart instanceof IAlvearyComponent) { - if (newPart instanceof IAlvearyComponent.BeeModifier) { - IAlvearyComponent.BeeModifier alvearyBeeModifier = (IAlvearyComponent.BeeModifier) newPart; - IBeeModifier beeModifier = alvearyBeeModifier.getBeeModifier(); - beeModifiers.add(beeModifier); - } - - if (newPart instanceof IAlvearyComponent.BeeListener) { - IAlvearyComponent.BeeListener beeListenerSource = (IAlvearyComponent.BeeListener) newPart; - IBeeListener beeListener = beeListenerSource.getBeeListener(); - beeListeners.add(beeListener); - } - - if (newPart instanceof IAlvearyComponent.Climatiser) { - climatisers.add((IAlvearyComponent.Climatiser) newPart); - } - - if (newPart instanceof IAlvearyComponent.Active) { - activeComponents.add((IAlvearyComponent.Active) newPart); - } - } - } - - @Override - protected void onBlockRemoved(IMultiblockComponent oldPart) { - if (oldPart instanceof IAlvearyComponent) { - if (oldPart instanceof IAlvearyComponent.BeeModifier) { - IAlvearyComponent.BeeModifier alvearyBeeModifier = (IAlvearyComponent.BeeModifier) oldPart; - IBeeModifier beeModifier = alvearyBeeModifier.getBeeModifier(); - beeModifiers.remove(beeModifier); - } - - if (oldPart instanceof IAlvearyComponent.BeeListener) { - IAlvearyComponent.BeeListener beeListenerSource = (IAlvearyComponent.BeeListener) oldPart; - IBeeListener beeListener = beeListenerSource.getBeeListener(); - beeListeners.remove(beeListener); - } - - if (oldPart instanceof IAlvearyComponent.Climatiser) { - climatisers.remove(oldPart); - } - - if (oldPart instanceof IAlvearyComponent.Active) { - activeComponents.remove(oldPart); - } - } - } - - @Override - protected void isMachineWhole() throws MultiblockValidationException { - super.isMachineWhole(); - - final ChunkCoordinates maximumCoord = getMaximumCoord(); - final ChunkCoordinates minimumCoord = getMinimumCoord(); - - // check that the top is covered in wood slabs - - final int slabY = maximumCoord.posY + 1; - for (int slabX = minimumCoord.posX; slabX <= maximumCoord.posX; slabX++) { - for (int slabZ = minimumCoord.posZ; slabZ <= maximumCoord.posZ; slabZ++) { - Block block = worldObj.getBlock(slabX, slabY, slabZ); - if (!BlockUtil.isWoodSlabBlock(block)) { - throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.alveary.error.needSlabs")); - } - - int meta = worldObj.getBlockMetadata(slabX, slabY, slabZ); - if ((meta & 8) != 0) { - throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.alveary.error.needSlabs")); - } - } - } - - // check that there is space all around the alveary entrances - - int airY = maximumCoord.posY; - for (int airX = minimumCoord.posX - 1; airX <= maximumCoord.posX + 1; airX++) { - for (int airZ = minimumCoord.posZ - 1; airZ <= maximumCoord.posZ + 1; airZ++) { - if (isCoordInMultiblock(airX, airY, airZ)) { - continue; - } - Block block = worldObj.getBlock(airX, airY, airZ); - if (block.isOpaqueCube()) { - throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.alveary.error.needSpace")); - } - } - } - } - - @Override - protected void isGoodForExteriorLevel(IMultiblockComponent part, int level) throws MultiblockValidationException { - if (level == 2 && !(part instanceof TileAlvearyPlain)) { - throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.alveary.error.needPlainOnTop")); - } - } - - @Override - protected void isGoodForInterior(IMultiblockComponent part) throws MultiblockValidationException { - if (!(part instanceof TileAlvearyPlain)) { - throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.alveary.error.needPlainInterior")); - } - } - - @Override - protected void onAssimilate(IMultiblockControllerInternal assimilated) { - - } - - @Override - public void onAssimilated(IMultiblockControllerInternal assimilator) { - - } - - @Override - protected boolean updateServer(int tickCount) { - for (IAlvearyComponent.Active activeComponent : activeComponents) { - activeComponent.updateServer(tickCount); - } - - final boolean canWork = beekeepingLogic.canWork(); - if (canWork) { - beekeepingLogic.doWork(); - } - - for (IAlvearyComponent.Climatiser climatiser : climatisers) { - climatiser.changeClimate(tickCount, this); - } - - tempChange = equalizeChange(tempChange); - humidChange = equalizeChange(humidChange); - - return canWork; - } - - private static float equalizeChange(float change) { - if (change == 0) { - return 0; - } - - change *= 0.95f; - if (change <= 0.001f && change >= -0.001f) { - change = 0; - } - return change; - } - - @Override - protected void updateClient(int tickCount) { - for (IAlvearyComponent.Active activeComponent : activeComponents) { - activeComponent.updateClient(tickCount); - } - - if (beekeepingLogic.canDoBeeFX() && updateOnInterval(2)) { - beekeepingLogic.doBeeFX(); - - if (updateOnInterval(50)) { - ChunkCoordinates center = getCenterCoord(); - float fxX = center.posX + 0.5F; - float fxY = center.posY + 1.0F; - float fxZ = center.posZ + 0.5F; - float distanceFromCenter = 1.6F; - - float leftRightSpreadFromCenter = distanceFromCenter * (worldObj.rand.nextFloat() - 0.5F); - float upSpread = worldObj.rand.nextFloat() * 0.8F; - fxY += upSpread; - - // display fx on all 4 sides - Proxies.render.addEntitySwarmFX(worldObj, (fxX - distanceFromCenter), fxY, (fxZ + leftRightSpreadFromCenter)); - Proxies.render.addEntitySwarmFX(worldObj, (fxX + distanceFromCenter), fxY, (fxZ + leftRightSpreadFromCenter)); - Proxies.render.addEntitySwarmFX(worldObj, (fxX + leftRightSpreadFromCenter), fxY, (fxZ - distanceFromCenter)); - Proxies.render.addEntitySwarmFX(worldObj, (fxX + leftRightSpreadFromCenter), fxY, (fxZ + distanceFromCenter)); - } - } - } - - @Override - public void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - - data.setFloat("TempChange", tempChange); - data.setFloat("HumidChange", humidChange); - beekeepingLogic.writeToNBT(data); - inventory.writeToNBT(data); - } - - @Override - public void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - - tempChange = data.getFloat("TempChange"); - humidChange = data.getFloat("HumidChange"); - - beekeepingLogic.readFromNBT(data); - inventory.readFromNBT(data); - } - - @Override - public void formatDescriptionPacket(NBTTagCompound data) { - writeToNBT(data); - beekeepingLogic.syncToClient(); - } - - @Override - public void decodeDescriptionPacket(NBTTagCompound data) { - readFromNBT(data); - } - - /* IActivatable */ - - @Override - public ChunkCoordinates getCoordinates() { - ChunkCoordinates coord = getCenterCoord(); - return new ChunkCoordinates(coord.posX, coord.posY + 1, coord.posZ); - } - - @Override - public Vec3 getBeeFXCoordinates() { - ChunkCoordinates coord = getCenterCoord(); - return Vec3.createVectorHelper(coord.posX + 0.5, coord.posY + 1.5, coord.posZ + 0.5); - } - - @Override - public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { - if (oldAccess == EnumAccess.SHARED || newAccess == EnumAccess.SHARED) { - // pipes connected to this need to update - for (IMultiblockComponent part : connectedParts) { - if (part instanceof TileEntity) { - TileEntity tile = (TileEntity) part; - worldObj.notifyBlocksOfNeighborChange(tile.xCoord, tile.yCoord, tile.zCoord, tile.getBlockType()); - } - } - markDirty(); - } - } - - @Override - public float getExactTemperature() { - ChunkCoordinates coords = getReferenceCoord(); - return getBiome().getFloatTemperature(coords.posX, coords.posY, coords.posZ) + tempChange; - } - - @Override - public float getExactHumidity() { - return getBiome().rainfall + humidChange; - } - - @Override - public EnumTemperature getTemperature() { - IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(this); - BiomeGenBase biome = getBiome(); - if (beeModifier.isHellish() || BiomeHelper.isBiomeHellish(biome)) { - if (tempChange >= 0) { - return EnumTemperature.HELLISH; - } - } - - return EnumTemperature.getFromValue(getExactTemperature()); - } - - @Override - public EnumHumidity getHumidity() { - return EnumHumidity.getFromValue(getExactHumidity()); - } - - @Override - public GameProfile getOwner() { - return getAccessHandler().getOwner(); - } - - @Override - public World getWorld() { - return worldObj; - } - - @Override - public BiomeGenBase getBiome() { - ChunkCoordinates coords = getReferenceCoord(); - return worldObj.getBiomeGenForCoords(coords.posX, coords.posZ); - } - - @Override - public int getBlockLightValue() { - ChunkCoordinates topCenter = getTopCenterCoord(); - return worldObj.getBlockLightValue(topCenter.posX, topCenter.posY + 1, topCenter.posZ); - } - - @Override - public boolean canBlockSeeTheSky() { - ChunkCoordinates topCenter = getTopCenterCoord(); - return worldObj.canBlockSeeTheSky(topCenter.posX, topCenter.posY + 2, topCenter.posZ); - } - - @Override - public void addTemperatureChange(float change, float boundaryDown, float boundaryUp) { - ChunkCoordinates coordinates = getCoordinates(); - - float temperature = getBiome().getFloatTemperature(coordinates.posX, coordinates.posY, coordinates.posZ); - - tempChange += change; - tempChange = Math.max(boundaryDown - temperature, tempChange); - tempChange = Math.min(boundaryUp - temperature, tempChange); - tempChange = (change > 0 && tempChange < 0) || (change < 0 && tempChange > 0) ? 0 : tempChange; - } - - @Override - public void addHumidityChange(float change, float boundaryDown, float boundaryUp) { - float humidity = getBiome().rainfall; - - humidChange += change; - humidChange = Math.max(boundaryDown - humidity, humidChange); - humidChange = Math.min(boundaryUp - humidity, humidChange); - humidChange = (change > 0 && humidChange < 0) || (change < 0 && humidChange > 0) ? 0 : humidChange; - } - - /* GUI */ - @Override - public int getHealthScaled(int i) { - return (breedingProgressPercent * i) / 100; - } - - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - data.writeVarInt(beekeepingLogic.getBeeProgressPercent()); - data.writeVarInt(Math.round(tempChange * 100)); - data.writeVarInt(Math.round(humidChange * 100)); - } - - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - breedingProgressPercent = data.readVarInt(); - tempChange = data.readVarInt() / 100.0F; - humidChange = data.readVarInt() / 100.0F; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.multiblock; + +import com.mojang.authlib.GameProfile; +import forestry.api.apiculture.BeeManager; +import forestry.api.apiculture.IBeeHousingInventory; +import forestry.api.apiculture.IBeeListener; +import forestry.api.apiculture.IBeeModifier; +import forestry.api.apiculture.IBeekeepingLogic; +import forestry.api.core.BiomeHelper; +import forestry.api.core.EnumHumidity; +import forestry.api.core.EnumTemperature; +import forestry.api.core.IClimateControlled; +import forestry.api.multiblock.IAlvearyComponent; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.apiculture.AlvearyBeeModifier; +import forestry.apiculture.InventoryBeeHousing; +import forestry.core.access.EnumAccess; +import forestry.core.inventory.FakeInventoryAdapter; +import forestry.core.inventory.IInventoryAdapter; +import forestry.core.multiblock.IMultiblockControllerInternal; +import forestry.core.multiblock.MultiblockValidationException; +import forestry.core.multiblock.RectangularMultiblockControllerBase; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.proxy.Proxies; +import forestry.core.utils.BlockUtil; +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; +import net.minecraft.block.Block; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.StatCollector; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; + +public class AlvearyController extends RectangularMultiblockControllerBase + implements IAlvearyControllerInternal, IClimateControlled { + + private final InventoryBeeHousing inventory; + private final IBeekeepingLogic beekeepingLogic; + + private float tempChange = 0.0f; + private float humidChange = 0.0f; + + // PARTS + private final Set beeModifiers = new HashSet<>(); + private final Set beeListeners = new HashSet<>(); + private final Set climatisers = new HashSet<>(); + private final Set activeComponents = new HashSet<>(); + + // CLIENT + private int breedingProgressPercent = 0; + + public AlvearyController(World world) { + super(world, AlvearyMultiblockSizeLimits.instance); + this.inventory = new InventoryBeeHousing(9, getAccessHandler()); + this.beekeepingLogic = BeeManager.beeRoot.createBeekeepingLogic(this); + + this.beeModifiers.add(new AlvearyBeeModifier()); + } + + @Override + public IBeeHousingInventory getBeeInventory() { + return inventory; + } + + @Override + public IBeekeepingLogic getBeekeepingLogic() { + return beekeepingLogic; + } + + @Override + public IInventoryAdapter getInternalInventory() { + if (isAssembled()) { + return inventory; + } else { + return FakeInventoryAdapter.instance(); + } + } + + @Override + public Iterable getBeeListeners() { + return beeListeners; + } + + @Override + public Iterable getBeeModifiers() { + return beeModifiers; + } + + @Override + public void onAttachedPartWithMultiblockData(IMultiblockComponent part, NBTTagCompound data) { + this.readFromNBT(data); + } + + @Override + protected void onBlockAdded(IMultiblockComponent newPart) { + if (newPart instanceof IAlvearyComponent) { + if (newPart instanceof IAlvearyComponent.BeeModifier) { + IAlvearyComponent.BeeModifier alvearyBeeModifier = (IAlvearyComponent.BeeModifier) newPart; + IBeeModifier beeModifier = alvearyBeeModifier.getBeeModifier(); + beeModifiers.add(beeModifier); + } + + if (newPart instanceof IAlvearyComponent.BeeListener) { + IAlvearyComponent.BeeListener beeListenerSource = (IAlvearyComponent.BeeListener) newPart; + IBeeListener beeListener = beeListenerSource.getBeeListener(); + beeListeners.add(beeListener); + } + + if (newPart instanceof IAlvearyComponent.Climatiser) { + climatisers.add((IAlvearyComponent.Climatiser) newPart); + } + + if (newPart instanceof IAlvearyComponent.Active) { + activeComponents.add((IAlvearyComponent.Active) newPart); + } + } + } + + @Override + protected void onBlockRemoved(IMultiblockComponent oldPart) { + if (oldPart instanceof IAlvearyComponent) { + if (oldPart instanceof IAlvearyComponent.BeeModifier) { + IAlvearyComponent.BeeModifier alvearyBeeModifier = (IAlvearyComponent.BeeModifier) oldPart; + IBeeModifier beeModifier = alvearyBeeModifier.getBeeModifier(); + beeModifiers.remove(beeModifier); + } + + if (oldPart instanceof IAlvearyComponent.BeeListener) { + IAlvearyComponent.BeeListener beeListenerSource = (IAlvearyComponent.BeeListener) oldPart; + IBeeListener beeListener = beeListenerSource.getBeeListener(); + beeListeners.remove(beeListener); + } + + if (oldPart instanceof IAlvearyComponent.Climatiser) { + climatisers.remove(oldPart); + } + + if (oldPart instanceof IAlvearyComponent.Active) { + activeComponents.remove(oldPart); + } + } + } + + @Override + protected void isMachineWhole() throws MultiblockValidationException { + super.isMachineWhole(); + + final ChunkCoordinates maximumCoord = getMaximumCoord(); + final ChunkCoordinates minimumCoord = getMinimumCoord(); + + // check that the top is covered in wood slabs + + final int slabY = maximumCoord.posY + 1; + for (int slabX = minimumCoord.posX; slabX <= maximumCoord.posX; slabX++) { + for (int slabZ = minimumCoord.posZ; slabZ <= maximumCoord.posZ; slabZ++) { + Block block = worldObj.getBlock(slabX, slabY, slabZ); + if (!BlockUtil.isWoodSlabBlock(block)) { + throw new MultiblockValidationException( + StatCollector.translateToLocal("for.multiblock.alveary.error.needSlabs")); + } + + int meta = worldObj.getBlockMetadata(slabX, slabY, slabZ); + if ((meta & 8) != 0) { + throw new MultiblockValidationException( + StatCollector.translateToLocal("for.multiblock.alveary.error.needSlabs")); + } + } + } + + // check that there is space all around the alveary entrances + + int airY = maximumCoord.posY; + for (int airX = minimumCoord.posX - 1; airX <= maximumCoord.posX + 1; airX++) { + for (int airZ = minimumCoord.posZ - 1; airZ <= maximumCoord.posZ + 1; airZ++) { + if (isCoordInMultiblock(airX, airY, airZ)) { + continue; + } + Block block = worldObj.getBlock(airX, airY, airZ); + if (block.isOpaqueCube()) { + throw new MultiblockValidationException( + StatCollector.translateToLocal("for.multiblock.alveary.error.needSpace")); + } + } + } + } + + @Override + protected void isGoodForExteriorLevel(IMultiblockComponent part, int level) throws MultiblockValidationException { + if (level == 2 && !(part instanceof TileAlvearyPlain)) { + throw new MultiblockValidationException( + StatCollector.translateToLocal("for.multiblock.alveary.error.needPlainOnTop")); + } + } + + @Override + protected void isGoodForInterior(IMultiblockComponent part) throws MultiblockValidationException { + if (!(part instanceof TileAlvearyPlain)) { + throw new MultiblockValidationException( + StatCollector.translateToLocal("for.multiblock.alveary.error.needPlainInterior")); + } + } + + @Override + protected void onAssimilate(IMultiblockControllerInternal assimilated) {} + + @Override + public void onAssimilated(IMultiblockControllerInternal assimilator) {} + + @Override + protected boolean updateServer(int tickCount) { + for (IAlvearyComponent.Active activeComponent : activeComponents) { + activeComponent.updateServer(tickCount); + } + + final boolean canWork = beekeepingLogic.canWork(); + if (canWork) { + beekeepingLogic.doWork(); + } + + for (IAlvearyComponent.Climatiser climatiser : climatisers) { + climatiser.changeClimate(tickCount, this); + } + + tempChange = equalizeChange(tempChange); + humidChange = equalizeChange(humidChange); + + return canWork; + } + + private static float equalizeChange(float change) { + if (change == 0) { + return 0; + } + + change *= 0.95f; + if (change <= 0.001f && change >= -0.001f) { + change = 0; + } + return change; + } + + @Override + protected void updateClient(int tickCount) { + for (IAlvearyComponent.Active activeComponent : activeComponents) { + activeComponent.updateClient(tickCount); + } + + if (beekeepingLogic.canDoBeeFX() && updateOnInterval(2)) { + beekeepingLogic.doBeeFX(); + + if (updateOnInterval(50)) { + ChunkCoordinates center = getCenterCoord(); + float fxX = center.posX + 0.5F; + float fxY = center.posY + 1.0F; + float fxZ = center.posZ + 0.5F; + float distanceFromCenter = 1.6F; + + float leftRightSpreadFromCenter = distanceFromCenter * (worldObj.rand.nextFloat() - 0.5F); + float upSpread = worldObj.rand.nextFloat() * 0.8F; + fxY += upSpread; + + // display fx on all 4 sides + Proxies.render.addEntitySwarmFX( + worldObj, (fxX - distanceFromCenter), fxY, (fxZ + leftRightSpreadFromCenter)); + Proxies.render.addEntitySwarmFX( + worldObj, (fxX + distanceFromCenter), fxY, (fxZ + leftRightSpreadFromCenter)); + Proxies.render.addEntitySwarmFX( + worldObj, (fxX + leftRightSpreadFromCenter), fxY, (fxZ - distanceFromCenter)); + Proxies.render.addEntitySwarmFX( + worldObj, (fxX + leftRightSpreadFromCenter), fxY, (fxZ + distanceFromCenter)); + } + } + } + + @Override + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + + data.setFloat("TempChange", tempChange); + data.setFloat("HumidChange", humidChange); + beekeepingLogic.writeToNBT(data); + inventory.writeToNBT(data); + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + + tempChange = data.getFloat("TempChange"); + humidChange = data.getFloat("HumidChange"); + + beekeepingLogic.readFromNBT(data); + inventory.readFromNBT(data); + } + + @Override + public void formatDescriptionPacket(NBTTagCompound data) { + writeToNBT(data); + beekeepingLogic.syncToClient(); + } + + @Override + public void decodeDescriptionPacket(NBTTagCompound data) { + readFromNBT(data); + } + + /* IActivatable */ + + @Override + public ChunkCoordinates getCoordinates() { + ChunkCoordinates coord = getCenterCoord(); + return new ChunkCoordinates(coord.posX, coord.posY + 1, coord.posZ); + } + + @Override + public Vec3 getBeeFXCoordinates() { + ChunkCoordinates coord = getCenterCoord(); + return Vec3.createVectorHelper(coord.posX + 0.5, coord.posY + 1.5, coord.posZ + 0.5); + } + + @Override + public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { + if (oldAccess == EnumAccess.SHARED || newAccess == EnumAccess.SHARED) { + // pipes connected to this need to update + for (IMultiblockComponent part : connectedParts) { + if (part instanceof TileEntity) { + TileEntity tile = (TileEntity) part; + worldObj.notifyBlocksOfNeighborChange(tile.xCoord, tile.yCoord, tile.zCoord, tile.getBlockType()); + } + } + markDirty(); + } + } + + @Override + public float getExactTemperature() { + ChunkCoordinates coords = getReferenceCoord(); + return getBiome().getFloatTemperature(coords.posX, coords.posY, coords.posZ) + tempChange; + } + + @Override + public float getExactHumidity() { + return getBiome().rainfall + humidChange; + } + + @Override + public EnumTemperature getTemperature() { + IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(this); + BiomeGenBase biome = getBiome(); + if (beeModifier.isHellish() || BiomeHelper.isBiomeHellish(biome)) { + if (tempChange >= 0) { + return EnumTemperature.HELLISH; + } + } + + return EnumTemperature.getFromValue(getExactTemperature()); + } + + @Override + public EnumHumidity getHumidity() { + return EnumHumidity.getFromValue(getExactHumidity()); + } + + @Override + public GameProfile getOwner() { + return getAccessHandler().getOwner(); + } + + @Override + public World getWorld() { + return worldObj; + } + + @Override + public BiomeGenBase getBiome() { + ChunkCoordinates coords = getReferenceCoord(); + return worldObj.getBiomeGenForCoords(coords.posX, coords.posZ); + } + + @Override + public int getBlockLightValue() { + ChunkCoordinates topCenter = getTopCenterCoord(); + return worldObj.getBlockLightValue(topCenter.posX, topCenter.posY + 1, topCenter.posZ); + } + + @Override + public boolean canBlockSeeTheSky() { + ChunkCoordinates topCenter = getTopCenterCoord(); + return worldObj.canBlockSeeTheSky(topCenter.posX, topCenter.posY + 2, topCenter.posZ); + } + + @Override + public void addTemperatureChange(float change, float boundaryDown, float boundaryUp) { + ChunkCoordinates coordinates = getCoordinates(); + + float temperature = getBiome().getFloatTemperature(coordinates.posX, coordinates.posY, coordinates.posZ); + + tempChange += change; + tempChange = Math.max(boundaryDown - temperature, tempChange); + tempChange = Math.min(boundaryUp - temperature, tempChange); + tempChange = (change > 0 && tempChange < 0) || (change < 0 && tempChange > 0) ? 0 : tempChange; + } + + @Override + public void addHumidityChange(float change, float boundaryDown, float boundaryUp) { + float humidity = getBiome().rainfall; + + humidChange += change; + humidChange = Math.max(boundaryDown - humidity, humidChange); + humidChange = Math.min(boundaryUp - humidity, humidChange); + humidChange = (change > 0 && humidChange < 0) || (change < 0 && humidChange > 0) ? 0 : humidChange; + } + + /* GUI */ + @Override + public int getHealthScaled(int i) { + return (breedingProgressPercent * i) / 100; + } + + @Override + public void writeGuiData(DataOutputStreamForestry data) throws IOException { + data.writeVarInt(beekeepingLogic.getBeeProgressPercent()); + data.writeVarInt(Math.round(tempChange * 100)); + data.writeVarInt(Math.round(humidChange * 100)); + } + + @Override + public void readGuiData(DataInputStreamForestry data) throws IOException { + breedingProgressPercent = data.readVarInt(); + tempChange = data.readVarInt() / 100.0F; + humidChange = data.readVarInt() / 100.0F; + } +} diff --git a/src/main/java/forestry/apiculture/multiblock/AlvearyMultiblockSizeLimits.java b/src/main/java/forestry/apiculture/multiblock/AlvearyMultiblockSizeLimits.java index 81763e209..bb4d48a4d 100644 --- a/src/main/java/forestry/apiculture/multiblock/AlvearyMultiblockSizeLimits.java +++ b/src/main/java/forestry/apiculture/multiblock/AlvearyMultiblockSizeLimits.java @@ -1,57 +1,55 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.multiblock; - -import forestry.core.multiblock.IMultiblockSizeLimits; - -class AlvearyMultiblockSizeLimits implements IMultiblockSizeLimits { - - public static final AlvearyMultiblockSizeLimits instance = new AlvearyMultiblockSizeLimits(); - - private AlvearyMultiblockSizeLimits() { - - } - - @Override - public int getMinimumNumberOfBlocksForAssembledMachine() { - return 27; - } - - @Override - public int getMaximumXSize() { - return 3; - } - - @Override - public int getMaximumZSize() { - return 3; - } - - @Override - public int getMaximumYSize() { - return 3; - } - - @Override - public int getMinimumXSize() { - return 3; - } - - @Override - public int getMinimumYSize() { - return 3; - } - - @Override - public int getMinimumZSize() { - return 3; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.multiblock; + +import forestry.core.multiblock.IMultiblockSizeLimits; + +class AlvearyMultiblockSizeLimits implements IMultiblockSizeLimits { + + public static final AlvearyMultiblockSizeLimits instance = new AlvearyMultiblockSizeLimits(); + + private AlvearyMultiblockSizeLimits() {} + + @Override + public int getMinimumNumberOfBlocksForAssembledMachine() { + return 27; + } + + @Override + public int getMaximumXSize() { + return 3; + } + + @Override + public int getMaximumZSize() { + return 3; + } + + @Override + public int getMaximumYSize() { + return 3; + } + + @Override + public int getMinimumXSize() { + return 3; + } + + @Override + public int getMinimumYSize() { + return 3; + } + + @Override + public int getMinimumZSize() { + return 3; + } +} diff --git a/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java b/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java index b81792571..a327aa77e 100644 --- a/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java +++ b/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java @@ -1,130 +1,119 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.multiblock; - -import java.util.Collections; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.Vec3; -import net.minecraft.world.biome.BiomeGenBase; - -import com.mojang.authlib.GameProfile; - -import forestry.api.apiculture.IBeeHousingInventory; -import forestry.api.apiculture.IBeeListener; -import forestry.api.apiculture.IBeeModifier; -import forestry.api.apiculture.IBeekeepingLogic; -import forestry.apiculture.FakeBeekeepingLogic; -import forestry.core.inventory.FakeInventoryAdapter; -import forestry.core.inventory.IInventoryAdapter; -import forestry.core.multiblock.FakeMultiblockController; - -public class FakeAlvearyController extends FakeMultiblockController implements IAlvearyControllerInternal { - public static final FakeAlvearyController instance = new FakeAlvearyController(); - - private FakeAlvearyController() { - - } - - @Override - public Iterable getBeeModifiers() { - return Collections.emptyList(); - } - - @Override - public Iterable getBeeListeners() { - return Collections.emptyList(); - } - - @Override - public IBeeHousingInventory getBeeInventory() { - return FakeBeeHousingInventory.instance; - } - - @Override - public IBeekeepingLogic getBeekeepingLogic() { - return FakeBeekeepingLogic.instance; - } - - @Override - public int getBlockLightValue() { - return 0; - } - - @Override - public boolean canBlockSeeTheSky() { - return false; - } - - @Override - public GameProfile getOwner() { - return null; - } - - @Override - public ChunkCoordinates getCoordinates() { - return null; - } - - @Override - public Vec3 getBeeFXCoordinates() { - return null; - } - - @Override - public BiomeGenBase getBiome() { - return null; - } - - @Override - public IInventoryAdapter getInternalInventory() { - return FakeInventoryAdapter.instance(); - } - - @Override - public int getHealthScaled(int i) { - return 0; - } - - private static class FakeBeeHousingInventory implements IBeeHousingInventory { - public static final FakeBeeHousingInventory instance = new FakeBeeHousingInventory(); - - private FakeBeeHousingInventory() { - - } - - @Override - public ItemStack getQueen() { - return null; - } - - @Override - public ItemStack getDrone() { - return null; - } - - @Override - public void setQueen(ItemStack itemstack) { - - } - - @Override - public void setDrone(ItemStack itemstack) { - - } - - @Override - public boolean addProduct(ItemStack product, boolean all) { - return false; - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.multiblock; + +import com.mojang.authlib.GameProfile; +import forestry.api.apiculture.IBeeHousingInventory; +import forestry.api.apiculture.IBeeListener; +import forestry.api.apiculture.IBeeModifier; +import forestry.api.apiculture.IBeekeepingLogic; +import forestry.apiculture.FakeBeekeepingLogic; +import forestry.core.inventory.FakeInventoryAdapter; +import forestry.core.inventory.IInventoryAdapter; +import forestry.core.multiblock.FakeMultiblockController; +import java.util.Collections; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.Vec3; +import net.minecraft.world.biome.BiomeGenBase; + +public class FakeAlvearyController extends FakeMultiblockController implements IAlvearyControllerInternal { + public static final FakeAlvearyController instance = new FakeAlvearyController(); + + private FakeAlvearyController() {} + + @Override + public Iterable getBeeModifiers() { + return Collections.emptyList(); + } + + @Override + public Iterable getBeeListeners() { + return Collections.emptyList(); + } + + @Override + public IBeeHousingInventory getBeeInventory() { + return FakeBeeHousingInventory.instance; + } + + @Override + public IBeekeepingLogic getBeekeepingLogic() { + return FakeBeekeepingLogic.instance; + } + + @Override + public int getBlockLightValue() { + return 0; + } + + @Override + public boolean canBlockSeeTheSky() { + return false; + } + + @Override + public GameProfile getOwner() { + return null; + } + + @Override + public ChunkCoordinates getCoordinates() { + return null; + } + + @Override + public Vec3 getBeeFXCoordinates() { + return null; + } + + @Override + public BiomeGenBase getBiome() { + return null; + } + + @Override + public IInventoryAdapter getInternalInventory() { + return FakeInventoryAdapter.instance(); + } + + @Override + public int getHealthScaled(int i) { + return 0; + } + + private static class FakeBeeHousingInventory implements IBeeHousingInventory { + public static final FakeBeeHousingInventory instance = new FakeBeeHousingInventory(); + + private FakeBeeHousingInventory() {} + + @Override + public ItemStack getQueen() { + return null; + } + + @Override + public ItemStack getDrone() { + return null; + } + + @Override + public void setQueen(ItemStack itemstack) {} + + @Override + public void setDrone(ItemStack itemstack) {} + + @Override + public boolean addProduct(ItemStack product, boolean all) { + return false; + } + } +} diff --git a/src/main/java/forestry/apiculture/multiblock/IAlvearyControllerInternal.java b/src/main/java/forestry/apiculture/multiblock/IAlvearyControllerInternal.java index f944bfcb3..630eed670 100644 --- a/src/main/java/forestry/apiculture/multiblock/IAlvearyControllerInternal.java +++ b/src/main/java/forestry/apiculture/multiblock/IAlvearyControllerInternal.java @@ -1,24 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.multiblock; - -import forestry.api.multiblock.IAlvearyController; -import forestry.core.access.IRestrictedAccess; -import forestry.core.inventory.IInventoryAdapter; -import forestry.core.multiblock.IMultiblockControllerInternal; -import forestry.core.network.IStreamableGui; -import forestry.core.tiles.IClimatised; - -public interface IAlvearyControllerInternal extends IAlvearyController, IMultiblockControllerInternal, IClimatised, IRestrictedAccess, IStreamableGui { - IInventoryAdapter getInternalInventory(); - - int getHealthScaled(int i); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.multiblock; + +import forestry.api.multiblock.IAlvearyController; +import forestry.core.access.IRestrictedAccess; +import forestry.core.inventory.IInventoryAdapter; +import forestry.core.multiblock.IMultiblockControllerInternal; +import forestry.core.network.IStreamableGui; +import forestry.core.tiles.IClimatised; + +public interface IAlvearyControllerInternal + extends IAlvearyController, IMultiblockControllerInternal, IClimatised, IRestrictedAccess, IStreamableGui { + IInventoryAdapter getInternalInventory(); + + int getHealthScaled(int i); +} diff --git a/src/main/java/forestry/apiculture/multiblock/MultiblockLogicAlveary.java b/src/main/java/forestry/apiculture/multiblock/MultiblockLogicAlveary.java index 92a209664..457589f97 100644 --- a/src/main/java/forestry/apiculture/multiblock/MultiblockLogicAlveary.java +++ b/src/main/java/forestry/apiculture/multiblock/MultiblockLogicAlveary.java @@ -1,35 +1,35 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.multiblock; - -import net.minecraft.world.World; - -import forestry.api.multiblock.IMultiblockLogicAlveary; -import forestry.core.multiblock.MultiblockLogic; - -public class MultiblockLogicAlveary extends MultiblockLogic implements IMultiblockLogicAlveary { - public MultiblockLogicAlveary() { - super(IAlvearyControllerInternal.class); - } - - @Override - public IAlvearyControllerInternal getController() { - if (super.isConnected()) { - return controller; - } else { - return FakeAlvearyController.instance; - } - } - - public IAlvearyControllerInternal createNewController(World world) { - return new AlvearyController(world); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.multiblock; + +import forestry.api.multiblock.IMultiblockLogicAlveary; +import forestry.core.multiblock.MultiblockLogic; +import net.minecraft.world.World; + +public class MultiblockLogicAlveary extends MultiblockLogic + implements IMultiblockLogicAlveary { + public MultiblockLogicAlveary() { + super(IAlvearyControllerInternal.class); + } + + @Override + public IAlvearyControllerInternal getController() { + if (super.isConnected()) { + return controller; + } else { + return FakeAlvearyController.instance; + } + } + + public IAlvearyControllerInternal createNewController(World world) { + return new AlvearyController(world); + } +} diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlveary.java b/src/main/java/forestry/apiculture/multiblock/TileAlveary.java index 409ac1bdb..fb34d3c9b 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlveary.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlveary.java @@ -10,14 +10,6 @@ ******************************************************************************/ package forestry.apiculture.multiblock; -import java.io.IOException; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.Vec3; -import net.minecraft.world.biome.BiomeGenBase; - import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; @@ -43,157 +35,171 @@ import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamableGui; import forestry.core.tiles.IClimatised; import forestry.core.tiles.ITitled; +import java.io.IOException; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.Vec3; +import net.minecraft.world.biome.BiomeGenBase; -public abstract class TileAlveary extends MultiblockTileEntityForestry implements IBeeHousing, IAlvearyComponent, IRestrictedAccess, IStreamableGui, ITitled, IClimatised, IHintSource { - private final String unlocalizedTitle; +public abstract class TileAlveary extends MultiblockTileEntityForestry + implements IBeeHousing, + IAlvearyComponent, + IRestrictedAccess, + IStreamableGui, + ITitled, + IClimatised, + IHintSource { + private final String unlocalizedTitle; - protected TileAlveary() { - this(BlockAlveary.Type.PLAIN); - } + protected TileAlveary() { + this(BlockAlveary.Type.PLAIN); + } - protected TileAlveary(BlockAlveary.Type type) { - super(new MultiblockLogicAlveary()); - this.unlocalizedTitle = "tile.for.alveary." + type.ordinal() + ".name"; - } + protected TileAlveary(BlockAlveary.Type type) { + super(new MultiblockLogicAlveary()); + this.unlocalizedTitle = "tile.for.alveary." + type.ordinal() + ".name"; + } - /* TEXTURES */ - public int getIcon(int side) { - return BlockAlveary.PLAIN; - } + /* TEXTURES */ + public int getIcon(int side) { + return BlockAlveary.PLAIN; + } - @Override - public void onMachineAssembled(IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord) { - // Re-render this block on the client - if (worldObj.isRemote) { - this.worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); - } - worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); - markDirty(); - } + @Override + public void onMachineAssembled( + IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord) { + // Re-render this block on the client + if (worldObj.isRemote) { + this.worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); + } + worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); + markDirty(); + } - @Override - public void onMachineBroken() { - // Re-render this block on the client - if (worldObj.isRemote) { - this.worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); - } - worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); - markDirty(); - } + @Override + public void onMachineBroken() { + // Re-render this block on the client + if (worldObj.isRemote) { + this.worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); + } + worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); + markDirty(); + } - /* IHousing */ - @Override - public BiomeGenBase getBiome() { - return getMultiblockLogic().getController().getBiome(); - } + /* IHousing */ + @Override + public BiomeGenBase getBiome() { + return getMultiblockLogic().getController().getBiome(); + } - /* IBeeHousing */ - @Override - public Iterable getBeeModifiers() { - return getMultiblockLogic().getController().getBeeModifiers(); - } + /* IBeeHousing */ + @Override + public Iterable getBeeModifiers() { + return getMultiblockLogic().getController().getBeeModifiers(); + } - @Override - public Iterable getBeeListeners() { - return getMultiblockLogic().getController().getBeeListeners(); - } + @Override + public Iterable getBeeListeners() { + return getMultiblockLogic().getController().getBeeListeners(); + } - @Override - public IBeeHousingInventory getBeeInventory() { - return getMultiblockLogic().getController().getBeeInventory(); - } + @Override + public IBeeHousingInventory getBeeInventory() { + return getMultiblockLogic().getController().getBeeInventory(); + } - @Override - public IBeekeepingLogic getBeekeepingLogic() { - return getMultiblockLogic().getController().getBeekeepingLogic(); - } + @Override + public IBeekeepingLogic getBeekeepingLogic() { + return getMultiblockLogic().getController().getBeekeepingLogic(); + } - @Override - public Vec3 getBeeFXCoordinates() { - return getMultiblockLogic().getController().getBeeFXCoordinates(); - } + @Override + public Vec3 getBeeFXCoordinates() { + return getMultiblockLogic().getController().getBeeFXCoordinates(); + } - /* IClimatised */ - @Override - public EnumTemperature getTemperature() { - return getMultiblockLogic().getController().getTemperature(); - } + /* IClimatised */ + @Override + public EnumTemperature getTemperature() { + return getMultiblockLogic().getController().getTemperature(); + } - @Override - public EnumHumidity getHumidity() { - return getMultiblockLogic().getController().getHumidity(); - } + @Override + public EnumHumidity getHumidity() { + return getMultiblockLogic().getController().getHumidity(); + } - @Override - public int getBlockLightValue() { - return getMultiblockLogic().getController().getBlockLightValue(); - } + @Override + public int getBlockLightValue() { + return getMultiblockLogic().getController().getBlockLightValue(); + } - @Override - public boolean canBlockSeeTheSky() { - return getMultiblockLogic().getController().canBlockSeeTheSky(); - } + @Override + public boolean canBlockSeeTheSky() { + return getMultiblockLogic().getController().canBlockSeeTheSky(); + } - @Override - public IErrorLogic getErrorLogic() { - return getMultiblockLogic().getController().getErrorLogic(); - } + @Override + public IErrorLogic getErrorLogic() { + return getMultiblockLogic().getController().getErrorLogic(); + } - @Override - public IAccessHandler getAccessHandler() { - return getMultiblockLogic().getController().getAccessHandler(); - } + @Override + public IAccessHandler getAccessHandler() { + return getMultiblockLogic().getController().getAccessHandler(); + } - @Override - public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { - getMultiblockLogic().getController().onSwitchAccess(oldAccess, newAccess); - } + @Override + public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { + getMultiblockLogic().getController().onSwitchAccess(oldAccess, newAccess); + } - @Override - public IInventoryAdapter getInternalInventory() { - return getMultiblockLogic().getController().getInternalInventory(); - } + @Override + public IInventoryAdapter getInternalInventory() { + return getMultiblockLogic().getController().getInternalInventory(); + } - @Override - public String getUnlocalizedTitle() { - return unlocalizedTitle; - } + @Override + public String getUnlocalizedTitle() { + return unlocalizedTitle; + } - /* IHintSource */ - @Override - public List getHints() { - return Config.hints.get("apiary"); - } + /* IHintSource */ + @Override + public List getHints() { + return Config.hints.get("apiary"); + } - /* IClimatised */ - @Override - public float getExactTemperature() { - return getMultiblockLogic().getController().getExactTemperature(); - } + /* IClimatised */ + @Override + public float getExactTemperature() { + return getMultiblockLogic().getController().getExactTemperature(); + } - @Override - public float getExactHumidity() { - return getMultiblockLogic().getController().getExactHumidity(); - } + @Override + public float getExactHumidity() { + return getMultiblockLogic().getController().getExactHumidity(); + } - /* IStreamableGui */ - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - getMultiblockLogic().getController().writeGuiData(data); - } + /* IStreamableGui */ + @Override + public void writeGuiData(DataOutputStreamForestry data) throws IOException { + getMultiblockLogic().getController().writeGuiData(data); + } - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - getMultiblockLogic().getController().readGuiData(data); - } + @Override + public void readGuiData(DataInputStreamForestry data) throws IOException { + getMultiblockLogic().getController().readGuiData(data); + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiAlveary(player.inventory, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiAlveary(player.inventory, this); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerAlveary(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerAlveary(player.inventory, this); + } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyClimatiser.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyClimatiser.java index 81f2ff88a..287d15c9d 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyClimatiser.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyClimatiser.java @@ -10,153 +10,151 @@ ******************************************************************************/ package forestry.apiculture.multiblock; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.util.ForgeDirection; - +import cofh.api.energy.IEnergyHandler; import forestry.api.core.IClimateControlled; import forestry.api.multiblock.IAlvearyComponent; import forestry.apiculture.network.packets.PacketActiveUpdate; import forestry.core.proxy.Proxies; import forestry.core.tiles.IActivatable; import forestry.energy.EnergyManager; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; -import cofh.api.energy.IEnergyHandler; +public abstract class TileAlvearyClimatiser extends TileAlveary + implements IEnergyHandler, IActivatable, IAlvearyComponent.Climatiser { -public abstract class TileAlvearyClimatiser extends TileAlveary implements IEnergyHandler, IActivatable, IAlvearyComponent.Climatiser { + private static final int WORK_CYCLES = 1; + private static final int ENERGY_PER_OPERATION = 50; - private static final int WORK_CYCLES = 1; - private static final int ENERGY_PER_OPERATION = 50; + protected interface IClimitiserDefinition { + float getChangePerTransfer(); - protected interface IClimitiserDefinition { - float getChangePerTransfer(); + float getBoundaryUp(); - float getBoundaryUp(); + float getBoundaryDown(); - float getBoundaryDown(); + int getIconOff(); - int getIconOff(); + int getIconOn(); + } - int getIconOn(); - } + private final EnergyManager energyManager; + private final IClimitiserDefinition definition; - private final EnergyManager energyManager; - private final IClimitiserDefinition definition; + private int workingTime = 0; - private int workingTime = 0; + // CLIENT + private boolean active; - // CLIENT - private boolean active; + protected TileAlvearyClimatiser(IClimitiserDefinition definition) { + this.definition = definition; - protected TileAlvearyClimatiser(IClimitiserDefinition definition) { - this.definition = definition; + this.energyManager = new EnergyManager(1000, 2000); + this.energyManager.setReceiveOnly(); + } - this.energyManager = new EnergyManager(1000, 2000); - this.energyManager.setReceiveOnly(); - } + /* UPDATING */ + @Override + public void changeClimate(int tick, IClimateControlled climateControlled) { + if (workingTime < 20 && energyManager.consumeEnergyToDoWork(WORK_CYCLES, ENERGY_PER_OPERATION)) { + // one tick of work for every 10 RF + workingTime += ENERGY_PER_OPERATION / 10; + } - /* UPDATING */ - @Override - public void changeClimate(int tick, IClimateControlled climateControlled) { - if (workingTime < 20 && energyManager.consumeEnergyToDoWork(WORK_CYCLES, ENERGY_PER_OPERATION)) { - // one tick of work for every 10 RF - workingTime += ENERGY_PER_OPERATION / 10; - } + if (workingTime > 0) { + workingTime--; + climateControlled.addTemperatureChange( + definition.getChangePerTransfer(), definition.getBoundaryDown(), definition.getBoundaryUp()); + } - if (workingTime > 0) { - workingTime--; - climateControlled.addTemperatureChange(definition.getChangePerTransfer(), definition.getBoundaryDown(), definition.getBoundaryUp()); - } + setActive(workingTime > 0); + } - setActive(workingTime > 0); - } + /* TEXTURES */ + @Override + public int getIcon(int side) { + if (active) { + return definition.getIconOn(); + } else { + return definition.getIconOff(); + } + } - /* TEXTURES */ - @Override - public int getIcon(int side) { - if (active) { - return definition.getIconOn(); - } else { - return definition.getIconOff(); - } - } + /* LOADING & SAVING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + energyManager.readFromNBT(nbttagcompound); + workingTime = nbttagcompound.getInteger("Heating"); + setActive(workingTime > 0); + } - /* LOADING & SAVING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - energyManager.readFromNBT(nbttagcompound); - workingTime = nbttagcompound.getInteger("Heating"); - setActive(workingTime > 0); - } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + energyManager.writeToNBT(nbttagcompound); + nbttagcompound.setInteger("Heating", workingTime); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - energyManager.writeToNBT(nbttagcompound); - nbttagcompound.setInteger("Heating", workingTime); - } + /* Network */ + @Override + protected void encodeDescriptionPacket(NBTTagCompound packetData) { + super.encodeDescriptionPacket(packetData); + packetData.setBoolean("Active", active); + } - /* Network */ - @Override - protected void encodeDescriptionPacket(NBTTagCompound packetData) { - super.encodeDescriptionPacket(packetData); - packetData.setBoolean("Active", active); - } + @Override + protected void decodeDescriptionPacket(NBTTagCompound packetData) { + super.decodeDescriptionPacket(packetData); + setActive(packetData.getBoolean("Active")); + } - @Override - protected void decodeDescriptionPacket(NBTTagCompound packetData) { - super.decodeDescriptionPacket(packetData); - setActive(packetData.getBoolean("Active")); - } + /* IActivatable */ + @Override + public boolean isActive() { + return active; + } - /* IActivatable */ - @Override - public boolean isActive() { - return active; - } + @Override + public void setActive(boolean active) { + if (this.active == active) { + return; + } - @Override - public void setActive(boolean active) { - if (this.active == active) { - return; - } + this.active = active; - this.active = active; + if (worldObj != null) { + if (worldObj.isRemote) { + worldObj.func_147479_m(xCoord, yCoord, zCoord); + } else { + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), worldObj); + } + } + } - if (worldObj != null) { - if (worldObj.isRemote) { - worldObj.func_147479_m(xCoord, yCoord, zCoord); - } else { - Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), worldObj); - } - } - } + /* IEnergyHandler */ + @Override + public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + return energyManager.receiveEnergy(from, maxReceive, simulate); + } - /* IEnergyHandler */ - @Override - public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { - return energyManager.receiveEnergy(from, maxReceive, simulate); - } + @Override + public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { + return energyManager.extractEnergy(from, maxExtract, simulate); + } - @Override - public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { - return energyManager.extractEnergy(from, maxExtract, simulate); - } + @Override + public int getEnergyStored(ForgeDirection from) { + return energyManager.getEnergyStored(from); + } - @Override - public int getEnergyStored(ForgeDirection from) { - return energyManager.getEnergyStored(from); - } - - @Override - public int getMaxEnergyStored(ForgeDirection from) { - return energyManager.getMaxEnergyStored(from); - } - - @Override - public boolean canConnectEnergy(ForgeDirection from) { - return energyManager.canConnectEnergy(from); - } + @Override + public int getMaxEnergyStored(ForgeDirection from) { + return energyManager.getMaxEnergyStored(from); + } + @Override + public boolean canConnectEnergy(ForgeDirection from) { + return energyManager.canConnectEnergy(from); + } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyFan.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyFan.java index c66bbe88f..0e7bc0134 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyFan.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyFan.java @@ -14,37 +14,37 @@ import forestry.apiculture.blocks.BlockAlveary; public class TileAlvearyFan extends TileAlvearyClimatiser { - private static final FanDefinition definition = new FanDefinition(); + private static final FanDefinition definition = new FanDefinition(); - public TileAlvearyFan() { - super(definition); - } + public TileAlvearyFan() { + super(definition); + } - private static class FanDefinition implements IClimitiserDefinition { + private static class FanDefinition implements IClimitiserDefinition { - @Override - public float getChangePerTransfer() { - return -0.01f; - } + @Override + public float getChangePerTransfer() { + return -0.01f; + } - @Override - public float getBoundaryUp() { - return 2.5f; - } + @Override + public float getBoundaryUp() { + return 2.5f; + } - @Override - public float getBoundaryDown() { - return 0.05f; - } + @Override + public float getBoundaryDown() { + return 0.05f; + } - @Override - public int getIconOff() { - return BlockAlveary.ALVEARY_FAN_OFF; - } + @Override + public int getIconOff() { + return BlockAlveary.ALVEARY_FAN_OFF; + } - @Override - public int getIconOn() { - return BlockAlveary.ALVEARY_FAN_ON; - } - } + @Override + public int getIconOn() { + return BlockAlveary.ALVEARY_FAN_ON; + } + } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyHeater.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyHeater.java index 18f8fc7ea..2fa84674e 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyHeater.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyHeater.java @@ -14,37 +14,37 @@ import forestry.apiculture.blocks.BlockAlveary; public class TileAlvearyHeater extends TileAlvearyClimatiser { - private static final HeaterDefinition definition = new HeaterDefinition(); + private static final HeaterDefinition definition = new HeaterDefinition(); - public TileAlvearyHeater() { - super(definition); - } + public TileAlvearyHeater() { + super(definition); + } - private static class HeaterDefinition implements IClimitiserDefinition { + private static class HeaterDefinition implements IClimitiserDefinition { - @Override - public float getChangePerTransfer() { - return 0.01f; - } + @Override + public float getChangePerTransfer() { + return 0.01f; + } - @Override - public float getBoundaryUp() { - return 2.5f; - } + @Override + public float getBoundaryUp() { + return 2.5f; + } - @Override - public float getBoundaryDown() { - return 0.0f; - } + @Override + public float getBoundaryDown() { + return 0.0f; + } - @Override - public int getIconOff() { - return BlockAlveary.ALVEARY_HEATER_OFF; - } + @Override + public int getIconOff() { + return BlockAlveary.ALVEARY_HEATER_OFF; + } - @Override - public int getIconOn() { - return BlockAlveary.ALVEARY_HEATER_ON; - } - } + @Override + public int getIconOn() { + return BlockAlveary.ALVEARY_HEATER_ON; + } + } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java index 491b6c718..78ba873a7 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java @@ -10,16 +10,6 @@ ******************************************************************************/ package forestry.apiculture.multiblock; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; - import forestry.api.core.IClimateControlled; import forestry.api.multiblock.IAlvearyComponent; import forestry.apiculture.blocks.BlockAlveary; @@ -33,174 +23,185 @@ import forestry.core.fluids.TankManager; import forestry.core.fluids.tanks.FilteredTank; import forestry.core.inventory.IInventoryAdapter; import forestry.core.tiles.ILiquidTankTile; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; -public class TileAlvearyHygroregulator extends TileAlveary implements IInventory, ILiquidTankTile, IFluidHandler, IAlvearyComponent.Climatiser { - private final HygroregulatorRecipe[] recipes; +public class TileAlvearyHygroregulator extends TileAlveary + implements IInventory, ILiquidTankTile, IFluidHandler, IAlvearyComponent.Climatiser { + private final HygroregulatorRecipe[] recipes; - private final TankManager tankManager; - private final FilteredTank liquidTank; - private final IInventoryAdapter inventory; + private final TankManager tankManager; + private final FilteredTank liquidTank; + private final IInventoryAdapter inventory; - private HygroregulatorRecipe currentRecipe; - private int transferTime; + private HygroregulatorRecipe currentRecipe; + private int transferTime; - public TileAlvearyHygroregulator() { - super(BlockAlveary.Type.HYGRO); + public TileAlvearyHygroregulator() { + super(BlockAlveary.Type.HYGRO); - this.inventory = new InventoryHygroregulator(this); + this.inventory = new InventoryHygroregulator(this); - Fluid water = Fluids.WATER.getFluid(); - Fluid lava = Fluids.LAVA.getFluid(); - Fluid liquidIce = Fluids.ICE.getFluid(); + Fluid water = Fluids.WATER.getFluid(); + Fluid lava = Fluids.LAVA.getFluid(); + Fluid liquidIce = Fluids.ICE.getFluid(); - this.liquidTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, water, lava, liquidIce); - this.tankManager = new TankManager(this, liquidTank); + this.liquidTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, water, lava, liquidIce); + this.tankManager = new TankManager(this, liquidTank); - this.recipes = new HygroregulatorRecipe[]{new HygroregulatorRecipe(new FluidStack(water, 1), 1, 0.01f, -0.005f), - new HygroregulatorRecipe(new FluidStack(lava, 1), 10, -0.01f, +0.005f), - new HygroregulatorRecipe(new FluidStack(liquidIce, 1), 10, 0.02f, -0.01f)}; - } + this.recipes = new HygroregulatorRecipe[] { + new HygroregulatorRecipe(new FluidStack(water, 1), 1, 0.01f, -0.005f), + new HygroregulatorRecipe(new FluidStack(lava, 1), 10, -0.01f, +0.005f), + new HygroregulatorRecipe(new FluidStack(liquidIce, 1), 10, 0.02f, -0.01f) + }; + } - @Override - public IInventoryAdapter getInternalInventory() { - return inventory; - } + @Override + public IInventoryAdapter getInternalInventory() { + return inventory; + } - @Override - public boolean allowsAutomation() { - return true; - } + @Override + public boolean allowsAutomation() { + return true; + } - /* UPDATING */ - private HygroregulatorRecipe getRecipe(FluidStack liquid) { - HygroregulatorRecipe recipe = null; - for (HygroregulatorRecipe rec : recipes) { - if (rec.liquid.isFluidEqual(liquid)) { - recipe = rec; - break; - } - } - return recipe; - } + /* UPDATING */ + private HygroregulatorRecipe getRecipe(FluidStack liquid) { + HygroregulatorRecipe recipe = null; + for (HygroregulatorRecipe rec : recipes) { + if (rec.liquid.isFluidEqual(liquid)) { + recipe = rec; + break; + } + } + return recipe; + } - @Override - public void changeClimate(int tickCount, IClimateControlled climateControlled) { - if (transferTime <= 0 && liquidTank.getFluidAmount() > 0) { - currentRecipe = getRecipe(liquidTank.getFluid()); + @Override + public void changeClimate(int tickCount, IClimateControlled climateControlled) { + if (transferTime <= 0 && liquidTank.getFluidAmount() > 0) { + currentRecipe = getRecipe(liquidTank.getFluid()); - if (currentRecipe != null) { - liquidTank.drain(currentRecipe.liquid.amount, true); - transferTime = currentRecipe.transferTime; - } - } + if (currentRecipe != null) { + liquidTank.drain(currentRecipe.liquid.amount, true); + transferTime = currentRecipe.transferTime; + } + } - if (transferTime > 0) { + if (transferTime > 0) { - transferTime--; - if (currentRecipe != null) { - climateControlled.addHumidityChange(currentRecipe.humidChange, 0.0f, 1.0f); - climateControlled.addTemperatureChange(currentRecipe.tempChange, 0.0f, 2.0f); - } else { - transferTime = 0; - } - } + transferTime--; + if (currentRecipe != null) { + climateControlled.addHumidityChange(currentRecipe.humidChange, 0.0f, 1.0f); + climateControlled.addTemperatureChange(currentRecipe.tempChange, 0.0f, 2.0f); + } else { + transferTime = 0; + } + } - if (tickCount % 20 == 0) { - // Check if we have suitable items waiting in the item slot - FluidHelper.drainContainers(tankManager, this, 0); - } - } + if (tickCount % 20 == 0) { + // Check if we have suitable items waiting in the item slot + FluidHelper.drainContainers(tankManager, this, 0); + } + } - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - tankManager.readFromNBT(nbttagcompound); + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + tankManager.readFromNBT(nbttagcompound); - transferTime = nbttagcompound.getInteger("TransferTime"); + transferTime = nbttagcompound.getInteger("TransferTime"); - if (nbttagcompound.hasKey("CurrentLiquid")) { - FluidStack liquid = FluidStack.loadFluidStackFromNBT(nbttagcompound.getCompoundTag("CurrentLiquid")); - currentRecipe = getRecipe(liquid); - } - } + if (nbttagcompound.hasKey("CurrentLiquid")) { + FluidStack liquid = FluidStack.loadFluidStackFromNBT(nbttagcompound.getCompoundTag("CurrentLiquid")); + currentRecipe = getRecipe(liquid); + } + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - tankManager.writeToNBT(nbttagcompound); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + tankManager.writeToNBT(nbttagcompound); - nbttagcompound.setInteger("TransferTime", transferTime); - if (currentRecipe != null) { - NBTTagCompound subcompound = new NBTTagCompound(); - currentRecipe.liquid.writeToNBT(subcompound); - nbttagcompound.setTag("CurrentLiquid", subcompound); - } - } + nbttagcompound.setInteger("TransferTime", transferTime); + if (currentRecipe != null) { + NBTTagCompound subcompound = new NBTTagCompound(); + currentRecipe.liquid.writeToNBT(subcompound); + nbttagcompound.setTag("CurrentLiquid", subcompound); + } + } - /* TEXTURES */ - @Override - public int getIcon(int side) { - return BlockAlveary.ALVEARY_HYGRO; - } + /* TEXTURES */ + @Override + public int getIcon(int side) { + return BlockAlveary.ALVEARY_HYGRO; + } - /* ILIQUIDTANKCONTAINER */ - @Override - public TankManager getTankManager() { - return tankManager; - } + /* ILIQUIDTANKCONTAINER */ + @Override + public TankManager getTankManager() { + return tankManager; + } - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return tankManager.fill(from, resource, doFill); - } + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return tankManager.drain(from, resource, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return tankManager.drain(from, maxDrain, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return tankManager.canFill(from, fluid); - } + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return tankManager.canDrain(from, fluid); - } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return tankManager.getTankInfo(from); - } + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiAlvearyHygroregulator(player.inventory, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiAlvearyHygroregulator(player.inventory, this); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerAlvearyHygroregulator(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerAlvearyHygroregulator(player.inventory, this); + } - private static class HygroregulatorRecipe { - public final FluidStack liquid; - public final int transferTime; - public final float humidChange; - public final float tempChange; + private static class HygroregulatorRecipe { + public final FluidStack liquid; + public final int transferTime; + public final float humidChange; + public final float tempChange; - public HygroregulatorRecipe(FluidStack liquid, int transferTime, float humidChange, float tempChange) { - this.liquid = liquid; - this.transferTime = transferTime; - this.humidChange = humidChange; - this.tempChange = tempChange; - } - } + public HygroregulatorRecipe(FluidStack liquid, int transferTime, float humidChange, float tempChange) { + this.liquid = liquid; + this.transferTime = transferTime; + this.humidChange = humidChange; + this.tempChange = tempChange; + } + } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyPlain.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyPlain.java index 0337c7041..e21e87a4b 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyPlain.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyPlain.java @@ -10,70 +10,68 @@ ******************************************************************************/ package forestry.apiculture.multiblock; -import java.util.ArrayList; -import java.util.Collection; - -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChunkCoordinates; - -import net.minecraftforge.common.util.ForgeDirection; - -import cpw.mods.fml.common.Optional; - -import forestry.api.multiblock.IMultiblockController; -import forestry.apiculture.blocks.BlockAlveary; -import forestry.apiculture.trigger.ApicultureTriggers; - import buildcraft.api.statements.IStatementContainer; import buildcraft.api.statements.ITriggerExternal; import buildcraft.api.statements.ITriggerInternal; import buildcraft.api.statements.ITriggerProvider; +import cpw.mods.fml.common.Optional; +import forestry.api.multiblock.IMultiblockController; +import forestry.apiculture.blocks.BlockAlveary; +import forestry.apiculture.trigger.ApicultureTriggers; +import java.util.ArrayList; +import java.util.Collection; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChunkCoordinates; +import net.minecraftforge.common.util.ForgeDirection; @Optional.Interface(iface = "buildcraft.api.statements.ITriggerProvider", modid = "BuildCraftAPI|statements") public class TileAlvearyPlain extends TileAlveary implements ITriggerProvider { - @Override - public void onMachineAssembled(IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord) { - super.onMachineAssembled(multiblockController, minCoord, maxCoord); + @Override + public void onMachineAssembled( + IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord) { + super.onMachineAssembled(multiblockController, minCoord, maxCoord); - if (!worldObj.isRemote) { - // set alveary entrance block meta - if (yCoord == maxCoord.posY) { - if ((xCoord > minCoord.posX && xCoord < maxCoord.posX) || (zCoord > minCoord.posZ && zCoord < maxCoord.posZ)) { - this.worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, BlockAlveary.Type.ENTRANCE.ordinal(), 2); - } - } - } - } + if (!worldObj.isRemote) { + // set alveary entrance block meta + if (yCoord == maxCoord.posY) { + if ((xCoord > minCoord.posX && xCoord < maxCoord.posX) + || (zCoord > minCoord.posZ && zCoord < maxCoord.posZ)) { + this.worldObj.setBlockMetadataWithNotify( + xCoord, yCoord, zCoord, BlockAlveary.Type.ENTRANCE.ordinal(), 2); + } + } + } + } - @Override - public void onMachineBroken() { - super.onMachineBroken(); + @Override + public void onMachineBroken() { + super.onMachineBroken(); - if (!worldObj.isRemote) { - // set alveary entrance block meta back to normal - this.worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, BlockAlveary.Type.PLAIN.ordinal(), 2); - } - } + if (!worldObj.isRemote) { + // set alveary entrance block meta back to normal + this.worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, BlockAlveary.Type.PLAIN.ordinal(), 2); + } + } - @Override - public boolean allowsAutomation() { - return true; - } + @Override + public boolean allowsAutomation() { + return true; + } - /* ITRIGGERPROVIDER */ - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getInternalTriggers(IStatementContainer container) { - return null; - } + /* ITRIGGERPROVIDER */ + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getInternalTriggers(IStatementContainer container) { + return null; + } - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { - Collection res = new ArrayList<>(); - res.add(ApicultureTriggers.missingQueen); - res.add(ApicultureTriggers.missingDrone); - return res; - } + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { + Collection res = new ArrayList<>(); + res.add(ApicultureTriggers.missingQueen); + res.add(ApicultureTriggers.missingDrone); + return res; + } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearySieve.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearySieve.java index e3ab0240a..a776ae03e 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearySieve.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearySieve.java @@ -10,9 +10,6 @@ ******************************************************************************/ package forestry.apiculture.multiblock; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - import forestry.api.apiculture.DefaultBeeListener; import forestry.api.apiculture.IBeeListener; import forestry.api.arboriculture.EnumGermlingType; @@ -26,71 +23,73 @@ import forestry.apiculture.gui.GuiAlvearySieve; import forestry.apiculture.inventory.InventoryAlvearySieve; import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.watchers.ISlotPickupWatcher; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; public class TileAlvearySieve extends TileAlveary implements IAlvearyComponent.BeeListener { - private final IBeeListener beeListener; - private final InventoryAlvearySieve inventory; + private final IBeeListener beeListener; + private final InventoryAlvearySieve inventory; - public TileAlvearySieve() { - super(BlockAlveary.Type.SIEVE); - this.inventory = new InventoryAlvearySieve(this); - this.beeListener = new AlvearySieveBeeListener(inventory); - } + public TileAlvearySieve() { + super(BlockAlveary.Type.SIEVE); + this.inventory = new InventoryAlvearySieve(this); + this.beeListener = new AlvearySieveBeeListener(inventory); + } - @Override - public IInventoryAdapter getInternalInventory() { - return inventory; - } + @Override + public IInventoryAdapter getInternalInventory() { + return inventory; + } - public ISlotPickupWatcher getCrafter() { - return inventory; - } + public ISlotPickupWatcher getCrafter() { + return inventory; + } - @Override - public IBeeListener getBeeListener() { - return beeListener; - } - - @Override - public int getIcon(int side) { - if (side == 0 || side == 1) { - return BlockAlveary.BOTTOM; - } - return BlockAlveary.SIEVE; - } + @Override + public IBeeListener getBeeListener() { + return beeListener; + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiAlvearySieve(player.inventory, this); - } + @Override + public int getIcon(int side) { + if (side == 0 || side == 1) { + return BlockAlveary.BOTTOM; + } + return BlockAlveary.SIEVE; + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerAlvearySieve(player.inventory, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiAlvearySieve(player.inventory, this); + } - static class AlvearySieveBeeListener extends DefaultBeeListener { - private final InventoryAlvearySieve inventory; + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerAlvearySieve(player.inventory, this); + } - public AlvearySieveBeeListener(InventoryAlvearySieve inventory) { - this.inventory = inventory; - } + static class AlvearySieveBeeListener extends DefaultBeeListener { + private final InventoryAlvearySieve inventory; - @Override - public boolean onPollenRetrieved(IIndividual pollen) { - if (!inventory.canStorePollen()) { - return false; - } + public AlvearySieveBeeListener(InventoryAlvearySieve inventory) { + this.inventory = inventory; + } - ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(pollen.getClass()); + @Override + public boolean onPollenRetrieved(IIndividual pollen) { + if (!inventory.canStorePollen()) { + return false; + } - ItemStack pollenStack = speciesRoot.getMemberStack(pollen, EnumGermlingType.POLLEN.ordinal()); - if (pollenStack != null) { - inventory.storePollenStack(pollenStack); - return true; - } - return false; - } - } + ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(pollen.getClass()); + + ItemStack pollenStack = speciesRoot.getMemberStack(pollen, EnumGermlingType.POLLEN.ordinal()); + if (pollenStack != null) { + inventory.storePollenStack(pollenStack); + return true; + } + return false; + } + } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyStabiliser.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyStabiliser.java index e95c0907b..5ebbf4371 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyStabiliser.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyStabiliser.java @@ -18,27 +18,27 @@ import forestry.apiculture.blocks.BlockAlveary; public class TileAlvearyStabiliser extends TileAlveary implements IAlvearyComponent.BeeModifier { - private static final IBeeModifier beeModifier = new AlvearyStabiliserBeeModifier(); + private static final IBeeModifier beeModifier = new AlvearyStabiliserBeeModifier(); - /* TEXTURES */ - @Override - public int getIcon(int side) { - if (side == 0 || side == 1) { - return BlockAlveary.BOTTOM; - } + /* TEXTURES */ + @Override + public int getIcon(int side) { + if (side == 0 || side == 1) { + return BlockAlveary.BOTTOM; + } - return BlockAlveary.STABILISER; - } + return BlockAlveary.STABILISER; + } - @Override - public IBeeModifier getBeeModifier() { - return beeModifier; - } + @Override + public IBeeModifier getBeeModifier() { + return beeModifier; + } - private static class AlvearyStabiliserBeeModifier extends DefaultBeeModifier { - @Override - public float getMutationModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { - return 0.0f; - } - } + private static class AlvearyStabiliserBeeModifier extends DefaultBeeModifier { + @Override + public float getMutationModifier(IBeeGenome genome, IBeeGenome mate, float currentModifier) { + return 0.0f; + } + } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearySwarmer.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearySwarmer.java index 9aae5f4df..0eda234e6 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearySwarmer.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearySwarmer.java @@ -10,15 +10,6 @@ ******************************************************************************/ package forestry.apiculture.multiblock; -import java.util.Map.Entry; -import java.util.Stack; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.IBee; @@ -37,196 +28,202 @@ import forestry.core.inventory.wrappers.InventoryIterator; import forestry.core.proxy.Proxies; import forestry.core.tiles.IActivatable; import forestry.core.utils.ItemStackUtil; +import java.util.Map.Entry; +import java.util.Stack; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory, IActivatable, IAlvearyComponent.Active { - private final InventorySwarmer inventory; - private final Stack pendingSpawns = new Stack<>(); - private boolean active; + private final InventorySwarmer inventory; + private final Stack pendingSpawns = new Stack<>(); + private boolean active; - public TileAlvearySwarmer() { - super(BlockAlveary.Type.SWARMER); - this.inventory = new InventorySwarmer(this); - } + public TileAlvearySwarmer() { + super(BlockAlveary.Type.SWARMER); + this.inventory = new InventorySwarmer(this); + } - @Override - public IInventoryAdapter getInternalInventory() { - return inventory; - } + @Override + public IInventoryAdapter getInternalInventory() { + return inventory; + } - @Override - public boolean allowsAutomation() { - return true; - } + @Override + public boolean allowsAutomation() { + return true; + } - /* UPDATING */ - @Override - public void updateServer(int tickCount) { - if (pendingSpawns.size() > 0) { - setActive(true); - if (tickCount % 1000 == 0) { - trySpawnSwarm(); - } - } else { - setActive(false); - } + /* UPDATING */ + @Override + public void updateServer(int tickCount) { + if (pendingSpawns.size() > 0) { + setActive(true); + if (tickCount % 1000 == 0) { + trySpawnSwarm(); + } + } else { + setActive(false); + } - if (tickCount % 500 != 0) { - return; - } + if (tickCount % 500 != 0) { + return; + } - ItemStack princessStack = getPrincessStack(); - if (princessStack == null) { - return; - } + ItemStack princessStack = getPrincessStack(); + if (princessStack == null) { + return; + } - int chance = consumeInducerAndGetChance(); - if (chance == 0) { - return; - } + int chance = consumeInducerAndGetChance(); + if (chance == 0) { + return; + } - // Try to spawn princess - if (worldObj.rand.nextInt(1000) >= chance) { - return; - } + // Try to spawn princess + if (worldObj.rand.nextInt(1000) >= chance) { + return; + } - // Queue swarm spawn - IBee princess = BeeManager.beeRoot.getMember(princessStack); - princess.setIsNatural(false); - pendingSpawns.push(BeeManager.beeRoot.getMemberStack(princess, EnumBeeType.PRINCESS.ordinal())); - } + // Queue swarm spawn + IBee princess = BeeManager.beeRoot.getMember(princessStack); + princess.setIsNatural(false); + pendingSpawns.push(BeeManager.beeRoot.getMemberStack(princess, EnumBeeType.PRINCESS.ordinal())); + } - @Override - public void updateClient(int tickCount) { + @Override + public void updateClient(int tickCount) {} - } + private ItemStack getPrincessStack() { + ItemStack princessStack = + getMultiblockLogic().getController().getBeeInventory().getQueen(); - private ItemStack getPrincessStack() { - ItemStack princessStack = getMultiblockLogic().getController().getBeeInventory().getQueen(); + if (BeeManager.beeRoot.isMated(princessStack)) { + return princessStack; + } - if (BeeManager.beeRoot.isMated(princessStack)) { - return princessStack; - } + return null; + } - return null; - } + private int consumeInducerAndGetChance() { + if (getInternalInventory() == null) { + return 0; + } - private int consumeInducerAndGetChance() { - if (getInternalInventory() == null) { - return 0; - } + for (IInvSlot slot : InventoryIterator.getIterable(getInternalInventory())) { + ItemStack stack = slot.getStackInSlot(); + for (Entry entry : BeeManager.inducers.entrySet()) { + if (ItemStackUtil.isIdenticalItem(entry.getKey(), stack)) { + slot.decreaseStackInSlot(); + return entry.getValue(); + } + } + } - for (IInvSlot slot : InventoryIterator.getIterable(getInternalInventory())) { - ItemStack stack = slot.getStackInSlot(); - for (Entry entry : BeeManager.inducers.entrySet()) { - if (ItemStackUtil.isIdenticalItem(entry.getKey(), stack)) { - slot.decreaseStackInSlot(); - return entry.getValue(); - } - } - } + return 0; + } - return 0; - } + private void trySpawnSwarm() { - private void trySpawnSwarm() { + ItemStack toSpawn = pendingSpawns.peek(); + HiveDescriptionSwarmer hiveDescription = new HiveDescriptionSwarmer(toSpawn); + Hive hive = new Hive(hiveDescription); - ItemStack toSpawn = pendingSpawns.peek(); - HiveDescriptionSwarmer hiveDescription = new HiveDescriptionSwarmer(toSpawn); - Hive hive = new Hive(hiveDescription); + int chunkX = (xCoord + worldObj.rand.nextInt(40 * 2) - 40) / 16; + int chunkZ = (zCoord + worldObj.rand.nextInt(40 * 2) - 40) / 16; - int chunkX = (xCoord + worldObj.rand.nextInt(40 * 2) - 40) / 16; - int chunkZ = (zCoord + worldObj.rand.nextInt(40 * 2) - 40) / 16; + if (HiveDecorator.genHive(worldObj, worldObj.rand, chunkX, chunkZ, hive)) { + pendingSpawns.pop(); + } + } - if (HiveDecorator.genHive(worldObj, worldObj.rand, chunkX, chunkZ, hive)) { - pendingSpawns.pop(); - } - } + /* NETWORK */ - /* NETWORK */ + @Override + protected void encodeDescriptionPacket(NBTTagCompound packetData) { + super.encodeDescriptionPacket(packetData); + packetData.setBoolean("Active", active); + } - @Override - protected void encodeDescriptionPacket(NBTTagCompound packetData) { - super.encodeDescriptionPacket(packetData); - packetData.setBoolean("Active", active); - } + @Override + protected void decodeDescriptionPacket(NBTTagCompound packetData) { + super.decodeDescriptionPacket(packetData); + setActive(packetData.getBoolean("Active")); + } - @Override - protected void decodeDescriptionPacket(NBTTagCompound packetData) { - super.decodeDescriptionPacket(packetData); - setActive(packetData.getBoolean("Active")); - } + /* TEXTURES */ + @Override + public int getIcon(int side) { + if (side == 0 || side == 1) { + return BlockAlveary.BOTTOM; + } - /* TEXTURES */ - @Override - public int getIcon(int side) { - if (side == 0 || side == 1) { - return BlockAlveary.BOTTOM; - } + if (active) { + return BlockAlveary.ALVEARY_SWARMER_ON; + } else { + return BlockAlveary.ALVEARY_SWARMER_OFF; + } + } - if (active) { - return BlockAlveary.ALVEARY_SWARMER_ON; - } else { - return BlockAlveary.ALVEARY_SWARMER_OFF; - } - } + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + setActive(nbttagcompound.getBoolean("Active")); - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - setActive(nbttagcompound.getBoolean("Active")); + NBTTagList nbttaglist = nbttagcompound.getTagList("PendingSpawns", 10); + for (int i = 0; i < nbttaglist.tagCount(); i++) { + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + pendingSpawns.add(ItemStack.loadItemStackFromNBT(nbttagcompound1)); + } + } - NBTTagList nbttaglist = nbttagcompound.getTagList("PendingSpawns", 10); - for (int i = 0; i < nbttaglist.tagCount(); i++) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - pendingSpawns.add(ItemStack.loadItemStackFromNBT(nbttagcompound1)); - } - } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + nbttagcompound.setBoolean("Active", active); - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - nbttagcompound.setBoolean("Active", active); + NBTTagList nbttaglist = new NBTTagList(); + ItemStack[] offspring = pendingSpawns.toArray(new ItemStack[pendingSpawns.size()]); + for (int i = 0; i < offspring.length; i++) { + if (offspring[i] != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setByte("Slot", (byte) i); + offspring[i].writeToNBT(nbttagcompound1); + nbttaglist.appendTag(nbttagcompound1); + } + } + nbttagcompound.setTag("PendingSpawns", nbttaglist); + } - NBTTagList nbttaglist = new NBTTagList(); - ItemStack[] offspring = pendingSpawns.toArray(new ItemStack[pendingSpawns.size()]); - for (int i = 0; i < offspring.length; i++) { - if (offspring[i] != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte("Slot", (byte) i); - offspring[i].writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); - } - } - nbttagcompound.setTag("PendingSpawns", nbttaglist); - } + @Override + public boolean isActive() { + return active; + } - @Override - public boolean isActive() { - return active; - } + @Override + public void setActive(boolean active) { + if (this.active == active) { + return; + } - @Override - public void setActive(boolean active) { - if (this.active == active) { - return; - } + this.active = active; - this.active = active; + if (!worldObj.isRemote) { + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), worldObj); + } + } - if (!worldObj.isRemote) { - Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), worldObj); - } - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiAlvearySwarmer(player.inventory, this); + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiAlvearySwarmer(player.inventory, this); - } - - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerAlvearySwarmer(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerAlvearySwarmer(player.inventory, this); + } } diff --git a/src/main/java/forestry/apiculture/network/PacketRegistryApiculture.java b/src/main/java/forestry/apiculture/network/PacketRegistryApiculture.java index c92709727..874324ccf 100644 --- a/src/main/java/forestry/apiculture/network/PacketRegistryApiculture.java +++ b/src/main/java/forestry/apiculture/network/PacketRegistryApiculture.java @@ -1,34 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.network; - -import forestry.apiculture.network.packets.PacketActiveUpdate; -import forestry.apiculture.network.packets.PacketBeeLogicActive; -import forestry.apiculture.network.packets.PacketBeeLogicActiveEntity; -import forestry.apiculture.network.packets.PacketBeeLogicEntityRequest; -import forestry.apiculture.network.packets.PacketCandleUpdate; -import forestry.apiculture.network.packets.PacketHabitatBiomePointer; -import forestry.apiculture.network.packets.PacketImprintSelectionResponse; -import forestry.core.network.PacketRegistry; - -public class PacketRegistryApiculture extends PacketRegistry { - @Override - public void registerPackets() { - registerClientPacket(new PacketImprintSelectionResponse()); - registerClientPacket(new PacketActiveUpdate()); - registerClientPacket(new PacketBeeLogicActive()); - registerClientPacket(new PacketBeeLogicActiveEntity()); - registerClientPacket(new PacketHabitatBiomePointer()); - registerClientPacket(new PacketCandleUpdate()); - - registerServerPacket(new PacketBeeLogicEntityRequest()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.network; + +import forestry.apiculture.network.packets.PacketActiveUpdate; +import forestry.apiculture.network.packets.PacketBeeLogicActive; +import forestry.apiculture.network.packets.PacketBeeLogicActiveEntity; +import forestry.apiculture.network.packets.PacketBeeLogicEntityRequest; +import forestry.apiculture.network.packets.PacketCandleUpdate; +import forestry.apiculture.network.packets.PacketHabitatBiomePointer; +import forestry.apiculture.network.packets.PacketImprintSelectionResponse; +import forestry.core.network.PacketRegistry; + +public class PacketRegistryApiculture extends PacketRegistry { + @Override + public void registerPackets() { + registerClientPacket(new PacketImprintSelectionResponse()); + registerClientPacket(new PacketActiveUpdate()); + registerClientPacket(new PacketBeeLogicActive()); + registerClientPacket(new PacketBeeLogicActiveEntity()); + registerClientPacket(new PacketHabitatBiomePointer()); + registerClientPacket(new PacketCandleUpdate()); + + registerServerPacket(new PacketBeeLogicEntityRequest()); + } +} diff --git a/src/main/java/forestry/apiculture/network/packets/PacketActiveUpdate.java b/src/main/java/forestry/apiculture/network/packets/PacketActiveUpdate.java index 249c024f3..4f923cc72 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketActiveUpdate.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketActiveUpdate.java @@ -1,62 +1,59 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.IActivatable; - -public class PacketActiveUpdate extends PacketCoordinates implements IForestryPacketClient { - - private boolean active; - - public PacketActiveUpdate() { - } - - public PacketActiveUpdate(IActivatable tile) { - super(tile.getCoordinates()); - this.active = tile.isActive(); - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.TILE_FORESTRY_ACTIVE; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeBoolean(active); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - active = data.readBoolean(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IActivatable) { - ((IActivatable) tile).setActive(active); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.network.packets.PacketCoordinates; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.IActivatable; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; + +public class PacketActiveUpdate extends PacketCoordinates implements IForestryPacketClient { + + private boolean active; + + public PacketActiveUpdate() {} + + public PacketActiveUpdate(IActivatable tile) { + super(tile.getCoordinates()); + this.active = tile.isActive(); + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.TILE_FORESTRY_ACTIVE; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeBoolean(active); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + active = data.readBoolean(); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) { + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof IActivatable) { + ((IActivatable) tile).setActive(active); + } + } +} diff --git a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActive.java b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActive.java index 167bed090..5b6550ad8 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActive.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActive.java @@ -1,61 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeekeepingLogic; -import forestry.apiculture.BeekeepingLogic; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.core.proxy.Proxies; - -public class PacketBeeLogicActive extends PacketCoordinates implements IForestryPacketClient { - private BeekeepingLogic beekeepingLogic; - - public PacketBeeLogicActive() { - } - - public PacketBeeLogicActive(IBeeHousing tile) { - super(tile.getCoordinates()); - this.beekeepingLogic = (BeekeepingLogic) tile.getBeekeepingLogic(); - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.BEE_LOGIC_ACTIVE; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - beekeepingLogic.writeData(data); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IBeeHousing) { - IBeeHousing beeHousing = (IBeeHousing) tile; - IBeekeepingLogic beekeepingLogic = beeHousing.getBeekeepingLogic(); - if (beekeepingLogic instanceof BeekeepingLogic) { - ((BeekeepingLogic) beekeepingLogic).readData(data); - } - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.network.packets; + +import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeekeepingLogic; +import forestry.apiculture.BeekeepingLogic; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.network.packets.PacketCoordinates; +import forestry.core.proxy.Proxies; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; + +public class PacketBeeLogicActive extends PacketCoordinates implements IForestryPacketClient { + private BeekeepingLogic beekeepingLogic; + + public PacketBeeLogicActive() {} + + public PacketBeeLogicActive(IBeeHousing tile) { + super(tile.getCoordinates()); + this.beekeepingLogic = (BeekeepingLogic) tile.getBeekeepingLogic(); + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.BEE_LOGIC_ACTIVE; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + beekeepingLogic.writeData(data); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof IBeeHousing) { + IBeeHousing beeHousing = (IBeeHousing) tile; + IBeekeepingLogic beekeepingLogic = beeHousing.getBeekeepingLogic(); + if (beekeepingLogic instanceof BeekeepingLogic) { + ((BeekeepingLogic) beekeepingLogic).readData(data); + } + } + } +} diff --git a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActiveEntity.java b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActiveEntity.java index 0b94cd232..280d50be4 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActiveEntity.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActiveEntity.java @@ -1,61 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; - -import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeekeepingLogic; -import forestry.apiculture.BeekeepingLogic; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketEntityUpdate; -import forestry.core.proxy.Proxies; - -public class PacketBeeLogicActiveEntity extends PacketEntityUpdate implements IForestryPacketClient { - private BeekeepingLogic beekeepingLogic; - - public PacketBeeLogicActiveEntity() { - } - - public PacketBeeLogicActiveEntity(IBeeHousing housing, Entity entity) { - super(entity); - this.beekeepingLogic = (BeekeepingLogic) housing.getBeekeepingLogic(); - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.BEE_LOGIC_ACTIVE_ENTITY; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - beekeepingLogic.writeData(data); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Entity entity = getTarget(Proxies.common.getRenderWorld()); - if (entity instanceof IBeeHousing) { - IBeeHousing beeHousing = (IBeeHousing) entity; - IBeekeepingLogic beekeepingLogic = beeHousing.getBeekeepingLogic(); - if (beekeepingLogic instanceof BeekeepingLogic) { - ((BeekeepingLogic) beekeepingLogic).readData(data); - } - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.network.packets; + +import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeekeepingLogic; +import forestry.apiculture.BeekeepingLogic; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.network.packets.PacketEntityUpdate; +import forestry.core.proxy.Proxies; +import java.io.IOException; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; + +public class PacketBeeLogicActiveEntity extends PacketEntityUpdate implements IForestryPacketClient { + private BeekeepingLogic beekeepingLogic; + + public PacketBeeLogicActiveEntity() {} + + public PacketBeeLogicActiveEntity(IBeeHousing housing, Entity entity) { + super(entity); + this.beekeepingLogic = (BeekeepingLogic) housing.getBeekeepingLogic(); + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.BEE_LOGIC_ACTIVE_ENTITY; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + beekeepingLogic.writeData(data); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + Entity entity = getTarget(Proxies.common.getRenderWorld()); + if (entity instanceof IBeeHousing) { + IBeeHousing beeHousing = (IBeeHousing) entity; + IBeekeepingLogic beekeepingLogic = beeHousing.getBeekeepingLogic(); + if (beekeepingLogic instanceof BeekeepingLogic) { + ((BeekeepingLogic) beekeepingLogic).readData(data); + } + } + } +} diff --git a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicEntityRequest.java b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicEntityRequest.java index ec94f48b4..3a7aa5f0b 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicEntityRequest.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicEntityRequest.java @@ -1,51 +1,47 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayerMP; - -import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeekeepingLogic; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; -import forestry.core.network.packets.PacketEntityUpdate; - -public class PacketBeeLogicEntityRequest extends PacketEntityUpdate implements IForestryPacketServer { - - public PacketBeeLogicEntityRequest() { - } - - public PacketBeeLogicEntityRequest(Entity entity) { - super(entity); - } - - @Override - public PacketIdServer getPacketId() { - return PacketIdServer.BEE_LOGIC_ACTIVE_ENTITY_REQUEST; - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - Entity entity = getTarget(player.worldObj); - if (entity instanceof IBeeHousing) { - IBeeHousing beeHousing = (IBeeHousing) entity; - IBeekeepingLogic beekeepingLogic = beeHousing.getBeekeepingLogic(); - if (beekeepingLogic != null) { - beekeepingLogic.syncToClient(player); - } - } - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.network.packets; + +import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeekeepingLogic; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketIdServer; +import forestry.core.network.packets.PacketEntityUpdate; +import java.io.IOException; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayerMP; + +public class PacketBeeLogicEntityRequest extends PacketEntityUpdate implements IForestryPacketServer { + + public PacketBeeLogicEntityRequest() {} + + public PacketBeeLogicEntityRequest(Entity entity) { + super(entity); + } + + @Override + public PacketIdServer getPacketId() { + return PacketIdServer.BEE_LOGIC_ACTIVE_ENTITY_REQUEST; + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { + Entity entity = getTarget(player.worldObj); + if (entity instanceof IBeeHousing) { + IBeeHousing beeHousing = (IBeeHousing) entity; + IBeekeepingLogic beekeepingLogic = beeHousing.getBeekeepingLogic(); + if (beekeepingLogic != null) { + beekeepingLogic.syncToClient(player); + } + } + } +} diff --git a/src/main/java/forestry/apiculture/network/packets/PacketCandleUpdate.java b/src/main/java/forestry/apiculture/network/packets/PacketCandleUpdate.java index 4200ac7d1..48a2a4363 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketCandleUpdate.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketCandleUpdate.java @@ -1,67 +1,64 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.apiculture.tiles.TileCandle; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.core.proxy.Proxies; - -public class PacketCandleUpdate extends PacketCoordinates implements IForestryPacketClient { - - private int colour; - private boolean lit; - - public PacketCandleUpdate() { - } - - public PacketCandleUpdate(TileCandle tileCandle) { - super(tileCandle); - - colour = tileCandle.getColour(); - lit = tileCandle.isLit(); - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.CANDLE_UPDATE; - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeInt(colour); - data.writeBoolean(lit); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - colour = data.readInt(); - lit = data.readBoolean(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tileEntity = getTarget(Proxies.common.getRenderWorld()); - if (tileEntity instanceof TileCandle) { - ((TileCandle) tileEntity).onPacketUpdate(colour, lit); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.network.packets; + +import forestry.apiculture.tiles.TileCandle; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.network.packets.PacketCoordinates; +import forestry.core.proxy.Proxies; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; + +public class PacketCandleUpdate extends PacketCoordinates implements IForestryPacketClient { + + private int colour; + private boolean lit; + + public PacketCandleUpdate() {} + + public PacketCandleUpdate(TileCandle tileCandle) { + super(tileCandle); + + colour = tileCandle.getColour(); + lit = tileCandle.isLit(); + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.CANDLE_UPDATE; + } + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeInt(colour); + data.writeBoolean(lit); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + colour = data.readInt(); + lit = data.readBoolean(); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + TileEntity tileEntity = getTarget(Proxies.common.getRenderWorld()); + if (tileEntity instanceof TileCandle) { + ((TileCandle) tileEntity).onPacketUpdate(colour, lit); + } + } +} diff --git a/src/main/java/forestry/apiculture/network/packets/PacketHabitatBiomePointer.java b/src/main/java/forestry/apiculture/network/packets/PacketHabitatBiomePointer.java index 8393cf2e7..b986c2225 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketHabitatBiomePointer.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketHabitatBiomePointer.java @@ -1,42 +1,39 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.ChunkCoordinates; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.core.proxy.Proxies; - -public class PacketHabitatBiomePointer extends PacketCoordinates implements IForestryPacketClient { - - public PacketHabitatBiomePointer() { - } - - public PacketHabitatBiomePointer(ChunkCoordinates coordinates) { - super(coordinates); - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.HABITAT_BIOME_POINTER; - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Proxies.render.setHabitatLocatorTexture(player, getCoordinates()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.network.packets.PacketCoordinates; +import forestry.core.proxy.Proxies; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.ChunkCoordinates; + +public class PacketHabitatBiomePointer extends PacketCoordinates implements IForestryPacketClient { + + public PacketHabitatBiomePointer() {} + + public PacketHabitatBiomePointer(ChunkCoordinates coordinates) { + super(coordinates); + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.HABITAT_BIOME_POINTER; + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + Proxies.render.setHabitatLocatorTexture(player, getCoordinates()); + } +} diff --git a/src/main/java/forestry/apiculture/network/packets/PacketImprintSelectionResponse.java b/src/main/java/forestry/apiculture/network/packets/PacketImprintSelectionResponse.java index bd1905fc4..3af290796 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketImprintSelectionResponse.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketImprintSelectionResponse.java @@ -1,47 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; - -import forestry.apiculture.gui.ContainerImprinter; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketGuiSelect; - -public class PacketImprintSelectionResponse extends PacketGuiSelect implements IForestryPacketClient { - - public PacketImprintSelectionResponse() { - } - - public PacketImprintSelectionResponse(int primaryIndex, int secondaryIndex) { - super(primaryIndex, secondaryIndex); - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.IMPRINT_SELECTION_RESPONSE; - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Container container = player.openContainer; - if (!(container instanceof ContainerImprinter)) { - return; - } - - ((ContainerImprinter) container).setSelection(this); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.network.packets; + +import forestry.apiculture.gui.ContainerImprinter; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.network.packets.PacketGuiSelect; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; + +public class PacketImprintSelectionResponse extends PacketGuiSelect implements IForestryPacketClient { + + public PacketImprintSelectionResponse() {} + + public PacketImprintSelectionResponse(int primaryIndex, int secondaryIndex) { + super(primaryIndex, secondaryIndex); + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.IMPRINT_SELECTION_RESPONSE; + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + Container container = player.openContainer; + if (!(container instanceof ContainerImprinter)) { + return; + } + + ((ContainerImprinter) container).setSelection(this); + } +} diff --git a/src/main/java/forestry/apiculture/proxy/ProxyApiculture.java b/src/main/java/forestry/apiculture/proxy/ProxyApiculture.java index 6b50cdc75..78ca88b8b 100755 --- a/src/main/java/forestry/apiculture/proxy/ProxyApiculture.java +++ b/src/main/java/forestry/apiculture/proxy/ProxyApiculture.java @@ -14,11 +14,9 @@ import forestry.core.render.IBlockRenderer; public class ProxyApiculture { - public IBlockRenderer getRendererAnalyzer(String string) { - return null; - } - - public void initializeRendering() { - } + public IBlockRenderer getRendererAnalyzer(String string) { + return null; + } + public void initializeRendering() {} } diff --git a/src/main/java/forestry/apiculture/proxy/ProxyApicultureClient.java b/src/main/java/forestry/apiculture/proxy/ProxyApicultureClient.java index 15c18c8c7..20c4793a7 100644 --- a/src/main/java/forestry/apiculture/proxy/ProxyApicultureClient.java +++ b/src/main/java/forestry/apiculture/proxy/ProxyApicultureClient.java @@ -10,33 +10,30 @@ ******************************************************************************/ package forestry.apiculture.proxy; -import net.minecraftforge.client.MinecraftForgeClient; - import cpw.mods.fml.client.registry.RenderingRegistry; - import forestry.apiculture.entities.EntityBee; import forestry.apiculture.render.RenderBeeEntity; import forestry.apiculture.render.RenderBeeItem; import forestry.core.render.IBlockRenderer; import forestry.core.render.RenderAnalyzer; import forestry.plugins.PluginApiculture; +import net.minecraftforge.client.MinecraftForgeClient; public class ProxyApicultureClient extends ProxyApiculture { - @Override - public void initializeRendering() { - if (PluginApiculture.fancyRenderedBees) { - RenderingRegistry.registerEntityRenderingHandler(EntityBee.class, new RenderBeeEntity()); + @Override + public void initializeRendering() { + if (PluginApiculture.fancyRenderedBees) { + RenderingRegistry.registerEntityRenderingHandler(EntityBee.class, new RenderBeeEntity()); - MinecraftForgeClient.registerItemRenderer(PluginApiculture.items.beeDroneGE, new RenderBeeItem()); - MinecraftForgeClient.registerItemRenderer(PluginApiculture.items.beePrincessGE, new RenderBeeItem()); - MinecraftForgeClient.registerItemRenderer(PluginApiculture.items.beeQueenGE, new RenderBeeItem()); - } - } - - @Override - public IBlockRenderer getRendererAnalyzer(String gfxBase) { - return new RenderAnalyzer(gfxBase); - } + MinecraftForgeClient.registerItemRenderer(PluginApiculture.items.beeDroneGE, new RenderBeeItem()); + MinecraftForgeClient.registerItemRenderer(PluginApiculture.items.beePrincessGE, new RenderBeeItem()); + MinecraftForgeClient.registerItemRenderer(PluginApiculture.items.beeQueenGE, new RenderBeeItem()); + } + } + @Override + public IBlockRenderer getRendererAnalyzer(String gfxBase) { + return new RenderAnalyzer(gfxBase); + } } diff --git a/src/main/java/forestry/apiculture/render/ModelAnalyzer.java b/src/main/java/forestry/apiculture/render/ModelAnalyzer.java index e56e17146..50c250340 100755 --- a/src/main/java/forestry/apiculture/render/ModelAnalyzer.java +++ b/src/main/java/forestry/apiculture/render/ModelAnalyzer.java @@ -10,105 +10,99 @@ ******************************************************************************/ package forestry.apiculture.render; +import forestry.core.proxy.Proxies; +import forestry.core.render.ForestryResource; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.util.ResourceLocation; - import net.minecraftforge.common.util.ForgeDirection; - import org.lwjgl.opengl.GL11; -import forestry.core.proxy.Proxies; -import forestry.core.render.ForestryResource; - public class ModelAnalyzer extends ModelBase { - private final ModelRenderer pedestal; - private final ModelRenderer cover; - private final ModelRenderer tower1; - private final ModelRenderer tower2; + private final ModelRenderer pedestal; + private final ModelRenderer cover; + private final ModelRenderer tower1; + private final ModelRenderer tower2; - private final ResourceLocation[] textures; + private final ResourceLocation[] textures; - public ModelAnalyzer(String gfxBase) { + public ModelAnalyzer(String gfxBase) { - textures = new ResourceLocation[]{ - new ForestryResource(gfxBase + "pedestal.png"), - new ForestryResource(gfxBase + "tower1.png"), - new ForestryResource(gfxBase + "tower2.png"), - }; + textures = new ResourceLocation[] { + new ForestryResource(gfxBase + "pedestal.png"), + new ForestryResource(gfxBase + "tower1.png"), + new ForestryResource(gfxBase + "tower2.png"), + }; - pedestal = new ModelRenderer(this, 0, 0); - pedestal.addBox(-8F, -8F, -8F, 16, 1, 16); - pedestal.setRotationPoint(8, 8, 8); + pedestal = new ModelRenderer(this, 0, 0); + pedestal.addBox(-8F, -8F, -8F, 16, 1, 16); + pedestal.setRotationPoint(8, 8, 8); - cover = new ModelRenderer(this, 0, 0); - cover.addBox(-8F, -8F, -8F, 16, 1, 16); - cover.setRotationPoint(8, 8, 8); + cover = new ModelRenderer(this, 0, 0); + cover.addBox(-8F, -8F, -8F, 16, 1, 16); + cover.setRotationPoint(8, 8, 8); - tower1 = new ModelRenderer(this, 0, 0); - tower1.addBox(-8, -7, -7, 2, 14, 14); - tower1.setRotationPoint(8, 8, 8); + tower1 = new ModelRenderer(this, 0, 0); + tower1.addBox(-8, -7, -7, 2, 14, 14); + tower1.setRotationPoint(8, 8, 8); - tower2 = new ModelRenderer(this, 0, 0); - tower2.addBox(6, -7, -7, 2, 14, 14); - tower2.setRotationPoint(8, 8, 8); + tower2 = new ModelRenderer(this, 0, 0); + tower2.addBox(6, -7, -7, 2, 14, 14); + tower2.setRotationPoint(8, 8, 8); + } - } + public void render(ForgeDirection orientation, float posX, float posY, float posZ) { - public void render(ForgeDirection orientation, float posX, float posY, float posZ) { + GL11.glPushMatrix(); - GL11.glPushMatrix(); + GL11.glTranslatef(posX, posY, posZ); + float[] angle = {0, 0, 0}; - GL11.glTranslatef(posX, posY, posZ); - float[] angle = {0, 0, 0}; + if (orientation == null) { + orientation = ForgeDirection.WEST; + } + switch (orientation) { + case EAST: + angle[1] = (float) Math.PI / 2; + break; + case WEST: + angle[1] = -(float) Math.PI / 2; + break; + case SOUTH: + break; + case NORTH: + default: + angle[1] = (float) Math.PI; + break; + } - if (orientation == null) { - orientation = ForgeDirection.WEST; - } - switch (orientation) { - case EAST: - angle[1] = (float) Math.PI / 2; - break; - case WEST: - angle[1] = -(float) Math.PI / 2; - break; - case SOUTH: - break; - case NORTH: - default: - angle[1] = (float) Math.PI; - break; - } + float factor = (float) (1.0 / 16.0); - float factor = (float) (1.0 / 16.0); + Proxies.render.bindTexture(textures[0]); - Proxies.render.bindTexture(textures[0]); + pedestal.rotateAngleX = angle[0]; + pedestal.rotateAngleY = angle[1]; + pedestal.rotateAngleZ = angle[2]; + pedestal.render(factor); - pedestal.rotateAngleX = angle[0]; - pedestal.rotateAngleY = angle[1]; - pedestal.rotateAngleZ = angle[2]; - pedestal.render(factor); + cover.rotateAngleX = angle[0]; + cover.rotateAngleY = angle[1]; + cover.rotateAngleZ = (float) Math.PI; + cover.render(factor); - cover.rotateAngleX = angle[0]; - cover.rotateAngleY = angle[1]; - cover.rotateAngleZ = (float) Math.PI; - cover.render(factor); + tower1.rotateAngleX = angle[0]; + tower1.rotateAngleY = angle[1]; + tower1.rotateAngleZ = angle[2]; + Proxies.render.bindTexture(textures[1]); + tower1.render(factor); - tower1.rotateAngleX = angle[0]; - tower1.rotateAngleY = angle[1]; - tower1.rotateAngleZ = angle[2]; - Proxies.render.bindTexture(textures[1]); - tower1.render(factor); - - tower2.rotateAngleX = angle[0]; - tower2.rotateAngleY = angle[1]; - tower2.rotateAngleZ = angle[2]; - Proxies.render.bindTexture(textures[2]); - tower2.render(factor); - - GL11.glPopMatrix(); - - } + tower2.rotateAngleX = angle[0]; + tower2.rotateAngleY = angle[1]; + tower2.rotateAngleZ = angle[2]; + Proxies.render.bindTexture(textures[2]); + tower2.render(factor); + GL11.glPopMatrix(); + } } diff --git a/src/main/java/forestry/apiculture/render/ModelBee.java b/src/main/java/forestry/apiculture/render/ModelBee.java index 5f8a0800d..2cc94e307 100755 --- a/src/main/java/forestry/apiculture/render/ModelBee.java +++ b/src/main/java/forestry/apiculture/render/ModelBee.java @@ -10,158 +10,154 @@ ******************************************************************************/ package forestry.apiculture.render; +import forestry.api.apiculture.EnumBeeType; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; - import org.lwjgl.opengl.GL11; -import forestry.api.apiculture.EnumBeeType; - public class ModelBee extends ModelBase { - //fields - private final ModelRenderer snout; - private final ModelRenderer torsoWing; - private final ModelRenderer rump; - private final ModelRenderer tail; - private final ModelRenderer tailEnd; - private final ModelRenderer bridge; - private final ModelRenderer eyeRight; - private final ModelRenderer eyeLeft; - private final ModelRenderer wingLeft; - private final ModelRenderer wingRight; - private final ModelRenderer crownQueen; - private final ModelRenderer crownPrincess; + // fields + private final ModelRenderer snout; + private final ModelRenderer torsoWing; + private final ModelRenderer rump; + private final ModelRenderer tail; + private final ModelRenderer tailEnd; + private final ModelRenderer bridge; + private final ModelRenderer eyeRight; + private final ModelRenderer eyeLeft; + private final ModelRenderer wingLeft; + private final ModelRenderer wingRight; + private final ModelRenderer crownQueen; + private final ModelRenderer crownPrincess; - private EnumBeeType type = EnumBeeType.DRONE; + private EnumBeeType type = EnumBeeType.DRONE; - public ModelBee() { - textureWidth = 64; - textureHeight = 32; + public ModelBee() { + textureWidth = 64; + textureHeight = 32; - snout = new ModelRenderer(this, 18, 11); - snout.addBox(0F, 0F, 0F, 1, 2, 1); - snout.setRotationPoint(0F, 1F, -2F); - snout.setTextureSize(64, 32); - snout.mirror = true; - setRotation(snout, 0F, 0F, 0F); - torsoWing = new ModelRenderer(this, 28, 14); - torsoWing.addBox(0F, 0F, 0F, 3, 3, 1); - torsoWing.setRotationPoint(-1F, 0F, -1F); - torsoWing.setTextureSize(64, 32); - torsoWing.mirror = true; - setRotation(torsoWing, 0F, 0F, 0F); - rump = new ModelRenderer(this, 10, 14); - rump.addBox(-1F, -1F, 0F, 3, 3, 3); - rump.setRotationPoint(0F, 1F, 1F); - rump.setTextureSize(64, 32); - rump.mirror = true; - setRotation(rump, 0F, 0F, 0F); - tail = new ModelRenderer(this, 4, 14); - tail.addBox(0F, 0F, 0F, 2, 2, 1); - tail.setRotationPoint(-0.5F, 0.5333334F, 4F); - tail.setTextureSize(64, 32); - tail.mirror = true; - setRotation(tail, 0F, 0F, 0F); - tailEnd = new ModelRenderer(this, 0, 14); - tailEnd.addBox(0F, 0F, 0F, 1, 1, 1); - tailEnd.setRotationPoint(0F, 1F, 5F); - tailEnd.setTextureSize(64, 32); - tailEnd.mirror = true; - setRotation(tailEnd, 0F, 0F, 0F); - bridge = new ModelRenderer(this, 22, 14); - bridge.addBox(0F, 0F, 0F, 2, 2, 1); - bridge.setRotationPoint(-0.5F, 0.5F, 0F); - bridge.setTextureSize(64, 32); - bridge.mirror = true; - setRotation(bridge, 0F, 0F, 0F); - eyeRight = new ModelRenderer(this, 22, 9); - eyeRight.addBox(0F, 0F, 0F, 1, 1, 1); - eyeRight.setRotationPoint(-1F, 0F, -2F); - eyeRight.setTextureSize(64, 32); - eyeRight.mirror = true; - setRotation(eyeRight, 0F, 0F, 0F); - eyeLeft = new ModelRenderer(this, 18, 9); - eyeLeft.addBox(0F, 0F, 0F, 1, 1, 1); - eyeLeft.setRotationPoint(1F, 0F, -2F); - eyeLeft.setTextureSize(64, 32); - eyeLeft.mirror = true; - setRotation(eyeLeft, 0F, 0F, 0F); - wingLeft = new ModelRenderer(this, 0, 0); - wingLeft.addBox(0F, 0F, 0F, 3, 1, 6); - wingLeft.setRotationPoint(1F, -0.1F, -0.5F); - wingLeft.setTextureSize(64, 32); - wingLeft.mirror = true; - setRotation(wingLeft, 0F, 0.1396263F, 0F); - wingRight = new ModelRenderer(this, 0, 7); - wingRight.addBox(-3F, 0F, 0F, 3, 1, 6); - wingRight.setRotationPoint(0F, -0.1F, -0.5F); - wingRight.setTextureSize(64, 32); - wingRight.mirror = true; - setRotation(wingRight, 0F, -0.1396263F, 0F); + snout = new ModelRenderer(this, 18, 11); + snout.addBox(0F, 0F, 0F, 1, 2, 1); + snout.setRotationPoint(0F, 1F, -2F); + snout.setTextureSize(64, 32); + snout.mirror = true; + setRotation(snout, 0F, 0F, 0F); + torsoWing = new ModelRenderer(this, 28, 14); + torsoWing.addBox(0F, 0F, 0F, 3, 3, 1); + torsoWing.setRotationPoint(-1F, 0F, -1F); + torsoWing.setTextureSize(64, 32); + torsoWing.mirror = true; + setRotation(torsoWing, 0F, 0F, 0F); + rump = new ModelRenderer(this, 10, 14); + rump.addBox(-1F, -1F, 0F, 3, 3, 3); + rump.setRotationPoint(0F, 1F, 1F); + rump.setTextureSize(64, 32); + rump.mirror = true; + setRotation(rump, 0F, 0F, 0F); + tail = new ModelRenderer(this, 4, 14); + tail.addBox(0F, 0F, 0F, 2, 2, 1); + tail.setRotationPoint(-0.5F, 0.5333334F, 4F); + tail.setTextureSize(64, 32); + tail.mirror = true; + setRotation(tail, 0F, 0F, 0F); + tailEnd = new ModelRenderer(this, 0, 14); + tailEnd.addBox(0F, 0F, 0F, 1, 1, 1); + tailEnd.setRotationPoint(0F, 1F, 5F); + tailEnd.setTextureSize(64, 32); + tailEnd.mirror = true; + setRotation(tailEnd, 0F, 0F, 0F); + bridge = new ModelRenderer(this, 22, 14); + bridge.addBox(0F, 0F, 0F, 2, 2, 1); + bridge.setRotationPoint(-0.5F, 0.5F, 0F); + bridge.setTextureSize(64, 32); + bridge.mirror = true; + setRotation(bridge, 0F, 0F, 0F); + eyeRight = new ModelRenderer(this, 22, 9); + eyeRight.addBox(0F, 0F, 0F, 1, 1, 1); + eyeRight.setRotationPoint(-1F, 0F, -2F); + eyeRight.setTextureSize(64, 32); + eyeRight.mirror = true; + setRotation(eyeRight, 0F, 0F, 0F); + eyeLeft = new ModelRenderer(this, 18, 9); + eyeLeft.addBox(0F, 0F, 0F, 1, 1, 1); + eyeLeft.setRotationPoint(1F, 0F, -2F); + eyeLeft.setTextureSize(64, 32); + eyeLeft.mirror = true; + setRotation(eyeLeft, 0F, 0F, 0F); + wingLeft = new ModelRenderer(this, 0, 0); + wingLeft.addBox(0F, 0F, 0F, 3, 1, 6); + wingLeft.setRotationPoint(1F, -0.1F, -0.5F); + wingLeft.setTextureSize(64, 32); + wingLeft.mirror = true; + setRotation(wingLeft, 0F, 0.1396263F, 0F); + wingRight = new ModelRenderer(this, 0, 7); + wingRight.addBox(-3F, 0F, 0F, 3, 1, 6); + wingRight.setRotationPoint(0F, -0.1F, -0.5F); + wingRight.setTextureSize(64, 32); + wingRight.mirror = true; + setRotation(wingRight, 0F, -0.1396263F, 0F); - crownQueen = new ModelRenderer(this, 0, 17); - crownQueen.addBox(0F, 0F, 0F, 2, 1, 2); - crownQueen.setRotationPoint(-0.5F, -1.5F, -1.5F); - crownQueen.setTextureSize(64, 32); - crownQueen.mirror = true; - setRotation(crownQueen, 0F, 0F, 0F); + crownQueen = new ModelRenderer(this, 0, 17); + crownQueen.addBox(0F, 0F, 0F, 2, 1, 2); + crownQueen.setRotationPoint(-0.5F, -1.5F, -1.5F); + crownQueen.setTextureSize(64, 32); + crownQueen.mirror = true; + setRotation(crownQueen, 0F, 0F, 0F); - crownPrincess = new ModelRenderer(this, 0, 20); - crownPrincess.addBox(0F, 0F, 0F, 2, 1, 2); - crownPrincess.setRotationPoint(-0.5F, -1.5F, -1.5F); - crownPrincess.setTextureSize(64, 32); - crownPrincess.mirror = true; - setRotation(crownPrincess, 0F, 0F, 0F); + crownPrincess = new ModelRenderer(this, 0, 20); + crownPrincess.addBox(0F, 0F, 0F, 2, 1, 2); + crownPrincess.setRotationPoint(-0.5F, -1.5F, -1.5F); + crownPrincess.setTextureSize(64, 32); + crownPrincess.mirror = true; + setRotation(crownPrincess, 0F, 0F, 0F); + } - } + public void setType(EnumBeeType type) { + this.type = type; + } - public void setType(EnumBeeType type) { - this.type = type; - } + public void render(Entity entity, float f, float f1, float swing, float f3, float f4, float f5) { + super.render(entity, f, f1, swing, f3, f4, f5); + // setRotationAngles(f, f1, f2, f3, f4, f5, entity); - public void render(Entity entity, float f, float f1, float swing, float f3, float f4, float f5) { - super.render(entity, f, f1, swing, f3, f4, f5); - //setRotationAngles(f, f1, f2, f3, f4, f5, entity); + wingRight.rotateAngleZ = MathHelper.cos(swing * 1.3F) * (float) Math.PI * 0.25F; + wingLeft.rotateAngleZ = -wingRight.rotateAngleZ; - wingRight.rotateAngleZ = MathHelper.cos(swing * 1.3F) * (float) Math.PI * 0.25F; - wingLeft.rotateAngleZ = -wingRight.rotateAngleZ; + GL11.glPushMatrix(); + float scale = 0.75f; + GL11.glScalef(scale, scale, scale); + GL11.glTranslatef(0.0F, (12.0f / scale) * f5, 0.0F); - GL11.glPushMatrix(); - float scale = 0.75f; - GL11.glScalef(scale, scale, scale); - GL11.glTranslatef(0.0F, (12.0f / scale) * f5, 0.0F); + snout.render(f5); + torsoWing.render(f5); + rump.render(f5); + tail.render(f5); + tailEnd.render(f5); + bridge.render(f5); + eyeRight.render(f5); + eyeLeft.render(f5); + wingLeft.render(f5); + wingRight.render(f5); - snout.render(f5); - torsoWing.render(f5); - rump.render(f5); - tail.render(f5); - tailEnd.render(f5); - bridge.render(f5); - eyeRight.render(f5); - eyeLeft.render(f5); - wingLeft.render(f5); - wingRight.render(f5); + if (type == EnumBeeType.PRINCESS) { + crownPrincess.render(f5); + } else if (type == EnumBeeType.QUEEN) { + crownQueen.render(f5); + } - if (type == EnumBeeType.PRINCESS) { - crownPrincess.render(f5); - } else if (type == EnumBeeType.QUEEN) { - crownQueen.render(f5); - } + GL11.glPopMatrix(); + } - GL11.glPopMatrix(); - } - - private static void setRotation(ModelRenderer model, float x, float y, float z) { - model.rotateAngleX = x; - model.rotateAngleY = y; - model.rotateAngleZ = z; - } - - public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { - super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); - } + private static void setRotation(ModelRenderer model, float x, float y, float z) { + model.rotateAngleX = x; + model.rotateAngleY = y; + model.rotateAngleZ = z; + } + public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { + super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); + } } diff --git a/src/main/java/forestry/apiculture/render/ParticleRenderer.java b/src/main/java/forestry/apiculture/render/ParticleRenderer.java index 3a5ff6b0f..6c02d7c5e 100755 --- a/src/main/java/forestry/apiculture/render/ParticleRenderer.java +++ b/src/main/java/forestry/apiculture/render/ParticleRenderer.java @@ -10,155 +10,150 @@ ******************************************************************************/ package forestry.apiculture.render; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.particle.EntityFX; -import net.minecraft.client.renderer.ActiveRenderInfo; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.entity.EntityLivingBase; - -import net.minecraftforge.client.event.RenderWorldLastEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.world.WorldEvent; - import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import net.minecraft.client.Minecraft; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.client.renderer.ActiveRenderInfo; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.entity.EntityLivingBase; +import net.minecraftforge.client.event.RenderWorldLastEvent; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.world.WorldEvent; import org.lwjgl.opengl.GL11; @SideOnly(Side.CLIENT) public class ParticleRenderer { - private static final String name = "forestry-particles"; + private static final String name = "forestry-particles"; - // singleton getter >> + // singleton getter >> - public static synchronized ParticleRenderer getInstance() { - if (instance == null) { - instance = new ParticleRenderer(); - } + public static synchronized ParticleRenderer getInstance() { + if (instance == null) { + instance = new ParticleRenderer(); + } - return instance; - } + return instance; + } - private static ParticleRenderer instance = null; + private static ParticleRenderer instance = null; - // << singleton getter + // << singleton getter + public synchronized void addEffect(EntityFX particle) { + if (lazyAdd) { + newParticles.add(particle); + } else { + particles.add(particle); + } + } - public synchronized void addEffect(EntityFX particle) { - if (lazyAdd) { - newParticles.add(particle); - } else { - particles.add(particle); - } - } + // forge + fml handlers >> + @SubscribeEvent + public void onRenderWorldLast(RenderWorldLastEvent event) { + render(event.partialTicks); + } - // forge + fml handlers >> + @SubscribeEvent + public void onWorldUnload(WorldEvent.Unload event) { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + synchronized (this) { + particles.clear(); + } + } + } - @SubscribeEvent - public void onRenderWorldLast(RenderWorldLastEvent event) { - render(event.partialTicks); - } + @SubscribeEvent + public void onClientTick(TickEvent.ClientTickEvent event) { + if (event.phase == Phase.END) { + update(); + } + } - @SubscribeEvent - public void onWorldUnload(WorldEvent.Unload event) { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - synchronized (this) { - particles.clear(); - } - } - } + // << forge + fml handlers - @SubscribeEvent - public void onClientTick(TickEvent.ClientTickEvent event) { - if (event.phase == Phase.END) { - update(); - } - } + private ParticleRenderer() { + MinecraftForge.EVENT_BUS.register(this); + FMLCommonHandler.instance().bus().register(this); + } - // << forge + fml handlers + private synchronized void update() { + Minecraft.getMinecraft().mcProfiler.startSection(name + "-update"); - private ParticleRenderer() { - MinecraftForge.EVENT_BUS.register(this); - FMLCommonHandler.instance().bus().register(this); - } + lazyAdd = true; - private synchronized void update() { - Minecraft.getMinecraft().mcProfiler.startSection(name + "-update"); + for (Iterator it = particles.iterator(); it.hasNext(); ) { + EntityFX particle = it.next(); - lazyAdd = true; + particle.onUpdate(); - for (Iterator it = particles.iterator(); it.hasNext(); ) { - EntityFX particle = it.next(); + if (particle.isDead) { + it.remove(); + } + } - particle.onUpdate(); + lazyAdd = false; + particles.addAll(newParticles); + newParticles.clear(); - if (particle.isDead) { - it.remove(); - } - } + Minecraft.getMinecraft().mcProfiler.endSection(); + } - lazyAdd = false; - particles.addAll(newParticles); - newParticles.clear(); + private synchronized void render(float partialTicks) { + Minecraft.getMinecraft().mcProfiler.startSection(name + "-render"); - Minecraft.getMinecraft().mcProfiler.endSection(); - } + float rotationX = ActiveRenderInfo.rotationX; + float rotationZ = ActiveRenderInfo.rotationZ; + float rotationYZ = ActiveRenderInfo.rotationYZ; + float rotationXY = ActiveRenderInfo.rotationXY; + float rotationXZ = ActiveRenderInfo.rotationXZ; - private synchronized void render(float partialTicks) { - Minecraft.getMinecraft().mcProfiler.startSection(name + "-render"); + EntityLivingBase player = Minecraft.getMinecraft().renderViewEntity; + EntityFX.interpPosX = player.lastTickPosX + (player.posX - player.lastTickPosX) * partialTicks; + EntityFX.interpPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * partialTicks; + EntityFX.interpPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * partialTicks; - float rotationX = ActiveRenderInfo.rotationX; - float rotationZ = ActiveRenderInfo.rotationZ; - float rotationYZ = ActiveRenderInfo.rotationYZ; - float rotationXY = ActiveRenderInfo.rotationXY; - float rotationXZ = ActiveRenderInfo.rotationXZ; + // bind the texture + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationItemsTexture); - EntityLivingBase player = Minecraft.getMinecraft().renderViewEntity; - EntityFX.interpPosX = player.lastTickPosX + (player.posX - player.lastTickPosX) * partialTicks; - EntityFX.interpPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * partialTicks; - EntityFX.interpPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * partialTicks; + // save the old gl state + GL11.glPushAttrib(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); - // bind the texture - Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationItemsTexture); + // gl states/settings for drawing + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glDepthMask(false); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); + GL11.glAlphaFunc(GL11.GL_GREATER, 0.003921569F); - // save the old gl state - GL11.glPushAttrib(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); - // gl states/settings for drawing - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glDepthMask(false); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); - GL11.glAlphaFunc(GL11.GL_GREATER, 0.003921569F); + for (EntityFX particle : particles) { + tessellator.setBrightness(particle.getBrightnessForRender(partialTicks)); - Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); + particle.renderParticle( + tessellator, partialTicks, rotationX, rotationXZ, rotationZ, rotationYZ, rotationXY); + } - for (EntityFX particle : particles) { - tessellator.setBrightness(particle.getBrightnessForRender(partialTicks)); + tessellator.draw(); - particle.renderParticle(tessellator, partialTicks, rotationX, rotationXZ, rotationZ, rotationYZ, rotationXY); - } + // restore previous gl state + GL11.glPopAttrib(); - tessellator.draw(); + Minecraft.getMinecraft().mcProfiler.endSection(); + } - // restore previous gl state - GL11.glPopAttrib(); - - Minecraft.getMinecraft().mcProfiler.endSection(); - } - - private boolean lazyAdd = false; - private final List particles = new ArrayList<>(); - private final List newParticles = new ArrayList<>(); + private boolean lazyAdd = false; + private final List particles = new ArrayList<>(); + private final List newParticles = new ArrayList<>(); } diff --git a/src/main/java/forestry/apiculture/render/RenderBeeEntity.java b/src/main/java/forestry/apiculture/render/RenderBeeEntity.java index 79b23e4b7..41634e841 100644 --- a/src/main/java/forestry/apiculture/render/RenderBeeEntity.java +++ b/src/main/java/forestry/apiculture/render/RenderBeeEntity.java @@ -10,33 +10,32 @@ ******************************************************************************/ package forestry.apiculture.render; +import forestry.apiculture.entities.EntityBee; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; -import forestry.apiculture.entities.EntityBee; - public class RenderBeeEntity extends RenderLiving { - private final ModelBee beeModel; + private final ModelBee beeModel; - public RenderBeeEntity() { - super(new ModelBee(), 0.15f); - beeModel = (ModelBee) mainModel; - } + public RenderBeeEntity() { + super(new ModelBee(), 0.15f); + beeModel = (ModelBee) mainModel; + } - private void renderBee(EntityBee entity, double posX, double posY, double posZ, float par8, float par9) { - beeModel.setType(entity.getType()); - this.doRender(entity, posX, posY, posZ, par8, par9); - } + private void renderBee(EntityBee entity, double posX, double posY, double posZ, float par8, float par9) { + beeModel.setType(entity.getType()); + this.doRender(entity, posX, posY, posZ, par8, par9); + } - @Override - public void doRender(Entity entity, double posX, double posY, double posZ, float par8, float par9) { - renderBee((EntityBee) entity, posX, posY, posZ, par8, par9); - } + @Override + public void doRender(Entity entity, double posX, double posY, double posZ, float par8, float par9) { + renderBee((EntityBee) entity, posX, posY, posZ, par8, par9); + } - @Override - protected ResourceLocation getEntityTexture(Entity entity) { - return ((EntityBee) entity).getTexture(); - } + @Override + protected ResourceLocation getEntityTexture(Entity entity) { + return ((EntityBee) entity).getTexture(); + } } diff --git a/src/main/java/forestry/apiculture/render/RenderBeeItem.java b/src/main/java/forestry/apiculture/render/RenderBeeItem.java index 235e09bfb..ad596b105 100644 --- a/src/main/java/forestry/apiculture/render/RenderBeeItem.java +++ b/src/main/java/forestry/apiculture/render/RenderBeeItem.java @@ -10,215 +10,209 @@ ******************************************************************************/ package forestry.apiculture.render; -import net.minecraft.client.renderer.OpenGlHelper; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.client.renderer.entity.RenderManager; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.client.IItemRenderer; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBee; import forestry.apiculture.entities.EntityBee; import forestry.core.proxy.Proxies; +import net.minecraft.client.renderer.OpenGlHelper; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.item.ItemStack; +import net.minecraftforge.client.IItemRenderer; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; public class RenderBeeItem implements IItemRenderer { - private EntityBee entity; + private EntityBee entity; - private static float getWingYaw(IBee bee) { - float wingYaw = 1f; + private static float getWingYaw(IBee bee) { + float wingYaw = 1f; - if (bee.isAlive()) { - long systemTime = System.currentTimeMillis(); - long flapping = systemTime + bee.getIdent().hashCode(); - float flap = (float) (flapping % 1000) / 1000; // 0 to 1 + if (bee.isAlive()) { + long systemTime = System.currentTimeMillis(); + long flapping = systemTime + bee.getIdent().hashCode(); + float flap = (float) (flapping % 1000) / 1000; // 0 to 1 - wingYaw = getIrregularWingYaw(flapping, flap); + wingYaw = getIrregularWingYaw(flapping, flap); + } - } + return wingYaw; + } - return wingYaw; - } + private static float getIrregularWingYaw(long flapping, float flap) { + long irregular = flapping / 1000; + float wingYaw; - private static float getIrregularWingYaw(long flapping, float flap) { - long irregular = flapping / 1000; - float wingYaw; + if (irregular % 11 == 0) { + wingYaw = 0.75f; + } else { + if (irregular % 7 == 0 || irregular % 19 == 0) { + flap *= 8; + flap = flap % 1; + } + wingYaw = getRegularWingYaw(flap); + } - if (irregular % 11 == 0) { - wingYaw = 0.75f; - } else { - if (irregular % 7 == 0 || irregular % 19 == 0) { - flap *= 8; - flap = flap % 1; - } - wingYaw = getRegularWingYaw(flap); - } + return wingYaw; + } - return wingYaw; - } + private static float getRegularWingYaw(float flap) { + return flap < 0.5 ? 0.75f + flap : 1.75f - flap; + } - private static float getRegularWingYaw(float flap) { - return flap < 0.5 ? 0.75f + flap : 1.75f - flap; - } + private IBee initBee(ItemStack item, boolean scaled) { + IBee bee = BeeManager.beeRoot.getMember(item); + if (bee == null) { + bee = BeeManager.beeRoot.templateAsIndividual(BeeManager.beeRoot.getDefaultTemplate()); + } - private IBee initBee(ItemStack item, boolean scaled) { - IBee bee = BeeManager.beeRoot.getMember(item); - if (bee == null) { - bee = BeeManager.beeRoot.templateAsIndividual(BeeManager.beeRoot.getDefaultTemplate()); - } + if (entity == null) { + entity = new EntityBee(Proxies.common.getClientInstance().theWorld); + } + entity.setSpecies(bee.getGenome().getPrimary()); + entity.setType(BeeManager.beeRoot.getType(item)); + /* + if(scaled) + entity.setScale(butterfly.getSize()); + else + entity.setScale(EntityButterfly.DEFAULT_BUTTERFLY_SIZE); + */ - if (entity == null) { - entity = new EntityBee(Proxies.common.getClientInstance().theWorld); - } - entity.setSpecies(bee.getGenome().getPrimary()); - entity.setType(BeeManager.beeRoot.getType(item)); - /* - if(scaled) - entity.setScale(butterfly.getSize()); - else - entity.setScale(EntityButterfly.DEFAULT_BUTTERFLY_SIZE); - */ + return bee; + } - return bee; - } + /*private void renderBeeHalo() { - /*private void renderBeeHalo() { + IIcon background = TextureManager.getInstance().getDefault("habitats/desert"); + float xPos = 1.0f; float yPos = 1.0f; + float width = 1f; float height = 1f; - IIcon background = TextureManager.getInstance().getDefault("habitats/desert"); - float xPos = 1.0f; float yPos = 1.0f; - float width = 1f; float height = 1f; + Proxies.render.bindTexture(SpriteSheet.ITEMS); + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.addVertexWithUV((double)(xPos + 0), (double)(yPos + height), 0f, (double)background.getMinU(), (double)background.getMaxV()); + tessellator.addVertexWithUV((double)(xPos + width), (double)(yPos + height), 0f, (double)background.getMaxU(), (double)background.getMaxV()); + tessellator.addVertexWithUV((double)(xPos + width), (double)(yPos + 0), 0f, (double)background.getMaxU(), (double)background.getMinV()); + tessellator.addVertexWithUV((double)(xPos + 0), (double)(yPos + 0), 0f, (double)background.getMinU(), (double)background.getMinV()); + tessellator.draw(); + }*/ - Proxies.render.bindTexture(SpriteSheet.ITEMS); - Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); - tessellator.addVertexWithUV((double)(xPos + 0), (double)(yPos + height), 0f, (double)background.getMinU(), (double)background.getMaxV()); - tessellator.addVertexWithUV((double)(xPos + width), (double)(yPos + height), 0f, (double)background.getMaxU(), (double)background.getMaxV()); - tessellator.addVertexWithUV((double)(xPos + width), (double)(yPos + 0), 0f, (double)background.getMaxU(), (double)background.getMinV()); - tessellator.addVertexWithUV((double)(xPos + 0), (double)(yPos + 0), 0f, (double)background.getMinU(), (double)background.getMinV()); - tessellator.draw(); - }*/ + private void renderBeeItem(IBee bee, float translateX, float translateY, float translateZ) { + float yaw = 1; + float pitch = 1; - private void renderBeeItem(IBee bee, float translateX, float translateY, float translateZ) { - float yaw = 1; - float pitch = 1; + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_COLOR_MATERIAL); - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_COLOR_MATERIAL); + GL11.glPushMatrix(); - GL11.glPushMatrix(); - - GL11.glScalef(2.0f, 2.0f, 2.0f); - GL11.glTranslatef(translateX, translateY, translateZ); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glRotatef(-135.0F, 0.0F, 1.0F, 0.0F); - GL11.glRotatef(-((float) Math.atan(pitch / 40.0F)) * 20.0F, 1.0F, 0.0F, 0.0F); - - entity.renderYawOffset = (float) Math.atan(yaw / 40.0F) * 20.0F; - entity.rotationYaw = (float) Math.atan(yaw / 40.0F) * 40.0F; - entity.rotationPitch = -((float) Math.atan(pitch / 40.0F)) * 20.0F; - entity.rotationYawHead = entity.rotationYaw; - - RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, getWingYaw(bee)); - - GL11.glPopMatrix(); - - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GL11.glDisable(GL11.GL_TEXTURE_2D); - OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); - GL11.glPopAttrib(); - - } - - private void renderBeeInInventory(IBee bee) { - - /* - GL11.glPushMatrix(); - //GL11.glTranslatef(-0.3f, -2.5f, 0f); - GL11.glScalef(-1.0f, 1.0f, 1.0f); - //GL11.glScalef((float)Math.PI / 2, 1.0f, 1.0f); + GL11.glScalef(2.0f, 2.0f, 2.0f); + GL11.glTranslatef(translateX, translateY, translateZ); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glRotatef(-135.0F, 0.0F, 1.0F, 0.0F); - //GL11.glRotatef(-((float) Math.atan((double) (1 / 40.0F))) * 20.0F, 1.0F, 0.0F, 0.0F); - renderBeeHalo(); + GL11.glRotatef(-((float) Math.atan(pitch / 40.0F)) * 20.0F, 1.0F, 0.0F, 0.0F); + + entity.renderYawOffset = (float) Math.atan(yaw / 40.0F) * 20.0F; + entity.rotationYaw = (float) Math.atan(yaw / 40.0F) * 40.0F; + entity.rotationPitch = -((float) Math.atan(pitch / 40.0F)) * 20.0F; + entity.rotationYawHead = entity.rotationYaw; + + RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, getWingYaw(bee)); + GL11.glPopMatrix(); - */ - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_COLOR_MATERIAL); - RenderHelper.enableStandardItemLighting(); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GL11.glDisable(GL11.GL_TEXTURE_2D); + OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); + GL11.glPopAttrib(); + } - GL11.glPushMatrix(); + private void renderBeeInInventory(IBee bee) { - GL11.glTranslatef(-0.3f, -2.5f, 0f); - GL11.glScalef(-3.0f, 3.0f, 3.0f); - GL11.glRotatef(32.0F, 0.0F, 1.0F, 0.0F); - GL11.glScalef(1.6f, 1f, 1f); + /* + GL11.glPushMatrix(); + //GL11.glTranslatef(-0.3f, -2.5f, 0f); + GL11.glScalef(-1.0f, 1.0f, 1.0f); + //GL11.glScalef((float)Math.PI / 2, 1.0f, 1.0f); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glRotatef(-135.0F, 0.0F, 1.0F, 0.0F); + //GL11.glRotatef(-((float) Math.atan((double) (1 / 40.0F))) * 20.0F, 1.0F, 0.0F, 0.0F); + renderBeeHalo(); + GL11.glPopMatrix(); + */ - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - entity.renderYawOffset = 0; - entity.rotationYaw = 0; - entity.rotationPitch = 0; - entity.rotationYawHead = entity.rotationYaw; + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_COLOR_MATERIAL); + RenderHelper.enableStandardItemLighting(); - RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, getWingYaw(bee)); + GL11.glPushMatrix(); - GL11.glPopMatrix(); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GL11.glDisable(GL11.GL_TEXTURE_2D); - OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); - GL11.glPopAttrib(); - } + GL11.glTranslatef(-0.3f, -2.5f, 0f); + GL11.glScalef(-3.0f, 3.0f, 3.0f); + GL11.glRotatef(32.0F, 0.0F, 1.0F, 0.0F); + GL11.glScalef(1.6f, 1f, 1f); - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - switch (type) { - case ENTITY: - return true; - case EQUIPPED: - return true; - case INVENTORY: - return true; - default: - return false; - } - } + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + entity.renderYawOffset = 0; + entity.rotationYaw = 0; + entity.rotationPitch = 0; + entity.rotationYawHead = entity.rotationYaw; - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { - switch (helper) { - case ENTITY_BOBBING: - case ENTITY_ROTATION: - return false; - default: - return true; - } - } + RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, getWingYaw(bee)); - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + GL11.glPopMatrix(); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GL11.glDisable(GL11.GL_TEXTURE_2D); + OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); + GL11.glPopAttrib(); + } - switch (type) { - case ENTITY: - renderBeeItem(initBee(item, true), 0f, 0f, 0f); - break; - case EQUIPPED: - renderBeeItem(initBee(item, true), 1.0f, 0f, 0.5f); - break; - case INVENTORY: - renderBeeInInventory(initBee(item, false)); - break; - default: - } - } + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + switch (type) { + case ENTITY: + return true; + case EQUIPPED: + return true; + case INVENTORY: + return true; + default: + return false; + } + } + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + switch (helper) { + case ENTITY_BOBBING: + case ENTITY_ROTATION: + return false; + default: + return true; + } + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + + switch (type) { + case ENTITY: + renderBeeItem(initBee(item, true), 0f, 0f, 0f); + break; + case EQUIPPED: + renderBeeItem(initBee(item, true), 1.0f, 0f, 0.5f); + break; + case INVENTORY: + renderBeeInInventory(initBee(item, false)); + break; + default: + } + } } diff --git a/src/main/java/forestry/apiculture/render/RenderCandleBlock.java b/src/main/java/forestry/apiculture/render/RenderCandleBlock.java index ca43fd63c..8a9a182f7 100644 --- a/src/main/java/forestry/apiculture/render/RenderCandleBlock.java +++ b/src/main/java/forestry/apiculture/render/RenderCandleBlock.java @@ -10,6 +10,10 @@ ******************************************************************************/ package forestry.apiculture.render; +import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; +import forestry.apiculture.blocks.BlockCandle; +import forestry.apiculture.tiles.TileCandle; +import forestry.core.proxy.Proxies; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; @@ -17,130 +21,128 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; -import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; - -import forestry.apiculture.blocks.BlockCandle; -import forestry.apiculture.tiles.TileCandle; -import forestry.core.proxy.Proxies; - public class RenderCandleBlock implements ISimpleBlockRenderingHandler { - @Override - public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { + @Override + public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) {} - } + @Override + public boolean renderWorldBlock( + IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { + if (block.getRenderType() == Proxies.render.getCandleRenderId()) { + renderBlockCandle(world, x, y, z, (BlockCandle) block); + } + return true; + } - @Override - public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { - if (block.getRenderType() == Proxies.render.getCandleRenderId()) { - renderBlockCandle(world, x, y, z, (BlockCandle) block); - } - return true; - } + @Override + public boolean shouldRender3DInInventory(int modelId) { + return false; + } - @Override - public boolean shouldRender3DInInventory(int modelId) { - return false; - } + @Override + public int getRenderId() { + return Proxies.render.getCandleRenderId(); + } - @Override - public int getRenderId() { - return Proxies.render.getCandleRenderId(); - } + private static boolean renderBlockCandle(IBlockAccess world, int x, int y, int z, BlockCandle block) { + int meta = world.getBlockMetadata(x, y, z); + TileEntity tileEntity = world.getTileEntity(x, y, z); + if (!(tileEntity instanceof TileCandle)) { + return false; + } + TileCandle tileCandle = (TileCandle) tileEntity; - private static boolean renderBlockCandle(IBlockAccess world, int x, int y, int z, BlockCandle block) { - int meta = world.getBlockMetadata(x, y, z); - TileEntity tileEntity = world.getTileEntity(x, y, z); - if (!(tileEntity instanceof TileCandle)) { - return false; - } - TileCandle tileCandle = (TileCandle) tileEntity; + boolean isLit = tileCandle.isLit(); - boolean isLit = tileCandle.isLit(); + IIcon iconA = block.getTextureFromPassAndLit(0, isLit); + IIcon iconB = block.getTextureFromPassAndLit(1, isLit); - IIcon iconA = block.getTextureFromPassAndLit(0, isLit); - IIcon iconB = block.getTextureFromPassAndLit(1, isLit); + int colour = tileCandle.getColour(); + Tessellator tessellator = Tessellator.instance; + tessellator.setBrightness(world.getLightBrightnessForSkyBlocks(x, y, z, block.getLightValue(world, x, y, z))); + tessellator.setColorOpaque_F(1.0F, 1.0F, 1.0F); + double d0 = 0.4000000059604645D; + double d1 = 0.5D - d0; + double d2 = 0.20000000298023224D; - int colour = tileCandle.getColour(); - Tessellator tessellator = Tessellator.instance; - tessellator.setBrightness(world.getLightBrightnessForSkyBlocks(x, y, z, block.getLightValue(world, x, y, z))); - tessellator.setColorOpaque_F(1.0F, 1.0F, 1.0F); - double d0 = 0.4000000059604645D; - double d1 = 0.5D - d0; - double d2 = 0.20000000298023224D; + if (meta == 1) { + renderCandleAtAngle(iconA, x - d1, y + d2, z, -d0, 0.0D, 0xffffff); + renderCandleAtAngle(iconB, x - d1, y + d2, z, -d0, 0.0D, colour); + } else if (meta == 2) { + renderCandleAtAngle(iconA, x + d1, y + d2, z, d0, 0.0D, 0xffffff); + renderCandleAtAngle(iconB, x + d1, y + d2, z, d0, 0.0D, colour); + } else if (meta == 3) { + renderCandleAtAngle(iconA, x, y + d2, z - d1, 0.0D, -d0, 0xffffff); + renderCandleAtAngle(iconB, x, y + d2, z - d1, 0.0D, -d0, colour); + } else if (meta == 4) { + renderCandleAtAngle(iconA, x, y + d2, z + d1, 0.0D, d0, 0xffffff); + renderCandleAtAngle(iconB, x, y + d2, z + d1, 0.0D, d0, colour); + } else { + renderCandleAtAngle(iconA, x, y, z, 0.0D, 0.0D, 0xffffff); + renderCandleAtAngle(iconB, x, y, z, 0.0D, 0.0D, colour); + } - if (meta == 1) { - renderCandleAtAngle(iconA, x - d1, y + d2, z, -d0, 0.0D, 0xffffff); - renderCandleAtAngle(iconB, x - d1, y + d2, z, -d0, 0.0D, colour); - } else if (meta == 2) { - renderCandleAtAngle(iconA, x + d1, y + d2, z, d0, 0.0D, 0xffffff); - renderCandleAtAngle(iconB, x + d1, y + d2, z, d0, 0.0D, colour); - } else if (meta == 3) { - renderCandleAtAngle(iconA, x, y + d2, z - d1, 0.0D, -d0, 0xffffff); - renderCandleAtAngle(iconB, x, y + d2, z - d1, 0.0D, -d0, colour); - } else if (meta == 4) { - renderCandleAtAngle(iconA, x, y + d2, z + d1, 0.0D, d0, 0xffffff); - renderCandleAtAngle(iconB, x, y + d2, z + d1, 0.0D, d0, colour); - } else { - renderCandleAtAngle(iconA, x, y, z, 0.0D, 0.0D, 0xffffff); - renderCandleAtAngle(iconB, x, y, z, 0.0D, 0.0D, colour); - } + return true; + } - return true; - } - - private static void renderCandleAtAngle(IIcon icon, double x, double y, double z, double par8, double par10, int colour) { - Tessellator tessellator = Tessellator.instance; - double minU = icon.getMinU(); - double minV = icon.getMinV(); - double maxU = icon.getMaxU(); - double maxV = icon.getMaxV(); - double textureLightTopU = icon.getInterpolatedU(7.0D); - double d10 = icon.getInterpolatedV(6.0D); - double textureLightBottomU = icon.getInterpolatedU(9.0D); - double d12 = icon.getInterpolatedV(8.0D); - //double d13 = (double)icon.getInterpolatedV(7.0D); - double d14 = icon.getInterpolatedV(13.0D); - //double textureLightBottomV = (double)icon.getInterpolatedV(8.0D); - double d16 = icon.getInterpolatedV(15.0D); - x += 0.5D; - z += 0.5D; - double d17 = x - 0.5D; - double d18 = x + 0.5D; - double d19 = z - 0.5D; - double d20 = z + 0.5D; - double d21 = 0.0625D; - double d22 = 0.625D; - tessellator.setColorOpaque_I(colour); - // top quad - tessellator.addVertexWithUV(x + par8 * (1.0D - d22) - d21, y + d22, z + par10 * (1.0D - d22) - d21, textureLightTopU, d10); - tessellator.addVertexWithUV(x + par8 * (1.0D - d22) - d21, y + d22, z + par10 * (1.0D - d22) + d21, textureLightTopU, d12); - tessellator.addVertexWithUV(x + par8 * (1.0D - d22) + d21, y + d22, z + par10 * (1.0D - d22) + d21, textureLightBottomU, d12); - tessellator.addVertexWithUV(x + par8 * (1.0D - d22) + d21, y + d22, z + par10 * (1.0D - d22) - d21, textureLightBottomU, d10); - // -x quad - tessellator.addVertexWithUV(x - d21, y + 1d, d19, minU, minV); - tessellator.addVertexWithUV(x - d21 + par8, y, d19 + par10, minU, maxV); - tessellator.addVertexWithUV(x - d21 + par8, y, d20 + par10, maxU, maxV); - tessellator.addVertexWithUV(x - d21, y + 1d, d20, maxU, minV); - // +x quad - tessellator.addVertexWithUV(x + d21, y + 1.0D, d20, minU, minV); - tessellator.addVertexWithUV(x + par8 + d21, y, d20 + par10, minU, maxV); - tessellator.addVertexWithUV(x + par8 + d21, y, d19 + par10, maxU, maxV); - tessellator.addVertexWithUV(x + d21, y + 1.0D, d19, maxU, minV); - // -z quad - tessellator.addVertexWithUV(d18, y + 1.0D, z - d21, minU, minV); - tessellator.addVertexWithUV(d18 + par8, y, z - d21 + par10, minU, maxV); - tessellator.addVertexWithUV(d17 + par8, y, z - d21 + par10, maxU, maxV); - tessellator.addVertexWithUV(d17, y + 1.0D, z - d21, maxU, minV); - // +z quad - tessellator.addVertexWithUV(d17, y + 1.0D, z + d21, minU, minV); - tessellator.addVertexWithUV(d17 + par8, y, z + d21 + par10, minU, maxV); - tessellator.addVertexWithUV(d18 + par8, y, z + d21 + par10, maxU, maxV); - tessellator.addVertexWithUV(d18, y + 1.0D, z + d21, maxU, minV); - // bottom quad - tessellator.addVertexWithUV(x + d21 + par8, y, z - d21 + par10, textureLightBottomU, d14); - tessellator.addVertexWithUV(x + d21 + par8, y, z + d21 + par10, textureLightBottomU, d16); - tessellator.addVertexWithUV(x - d21 + par8, y, z + d21 + par10, textureLightTopU, d16); - tessellator.addVertexWithUV(x - d21 + par8, y, z - d21 + par10, textureLightTopU, d14); - } + private static void renderCandleAtAngle( + IIcon icon, double x, double y, double z, double par8, double par10, int colour) { + Tessellator tessellator = Tessellator.instance; + double minU = icon.getMinU(); + double minV = icon.getMinV(); + double maxU = icon.getMaxU(); + double maxV = icon.getMaxV(); + double textureLightTopU = icon.getInterpolatedU(7.0D); + double d10 = icon.getInterpolatedV(6.0D); + double textureLightBottomU = icon.getInterpolatedU(9.0D); + double d12 = icon.getInterpolatedV(8.0D); + // double d13 = (double)icon.getInterpolatedV(7.0D); + double d14 = icon.getInterpolatedV(13.0D); + // double textureLightBottomV = (double)icon.getInterpolatedV(8.0D); + double d16 = icon.getInterpolatedV(15.0D); + x += 0.5D; + z += 0.5D; + double d17 = x - 0.5D; + double d18 = x + 0.5D; + double d19 = z - 0.5D; + double d20 = z + 0.5D; + double d21 = 0.0625D; + double d22 = 0.625D; + tessellator.setColorOpaque_I(colour); + // top quad + tessellator.addVertexWithUV( + x + par8 * (1.0D - d22) - d21, y + d22, z + par10 * (1.0D - d22) - d21, textureLightTopU, d10); + tessellator.addVertexWithUV( + x + par8 * (1.0D - d22) - d21, y + d22, z + par10 * (1.0D - d22) + d21, textureLightTopU, d12); + tessellator.addVertexWithUV( + x + par8 * (1.0D - d22) + d21, y + d22, z + par10 * (1.0D - d22) + d21, textureLightBottomU, d12); + tessellator.addVertexWithUV( + x + par8 * (1.0D - d22) + d21, y + d22, z + par10 * (1.0D - d22) - d21, textureLightBottomU, d10); + // -x quad + tessellator.addVertexWithUV(x - d21, y + 1d, d19, minU, minV); + tessellator.addVertexWithUV(x - d21 + par8, y, d19 + par10, minU, maxV); + tessellator.addVertexWithUV(x - d21 + par8, y, d20 + par10, maxU, maxV); + tessellator.addVertexWithUV(x - d21, y + 1d, d20, maxU, minV); + // +x quad + tessellator.addVertexWithUV(x + d21, y + 1.0D, d20, minU, minV); + tessellator.addVertexWithUV(x + par8 + d21, y, d20 + par10, minU, maxV); + tessellator.addVertexWithUV(x + par8 + d21, y, d19 + par10, maxU, maxV); + tessellator.addVertexWithUV(x + d21, y + 1.0D, d19, maxU, minV); + // -z quad + tessellator.addVertexWithUV(d18, y + 1.0D, z - d21, minU, minV); + tessellator.addVertexWithUV(d18 + par8, y, z - d21 + par10, minU, maxV); + tessellator.addVertexWithUV(d17 + par8, y, z - d21 + par10, maxU, maxV); + tessellator.addVertexWithUV(d17, y + 1.0D, z - d21, maxU, minV); + // +z quad + tessellator.addVertexWithUV(d17, y + 1.0D, z + d21, minU, minV); + tessellator.addVertexWithUV(d17 + par8, y, z + d21 + par10, minU, maxV); + tessellator.addVertexWithUV(d18 + par8, y, z + d21 + par10, maxU, maxV); + tessellator.addVertexWithUV(d18, y + 1.0D, z + d21, maxU, minV); + // bottom quad + tessellator.addVertexWithUV(x + d21 + par8, y, z - d21 + par10, textureLightBottomU, d14); + tessellator.addVertexWithUV(x + d21 + par8, y, z + d21 + par10, textureLightBottomU, d16); + tessellator.addVertexWithUV(x - d21 + par8, y, z + d21 + par10, textureLightTopU, d16); + tessellator.addVertexWithUV(x - d21 + par8, y, z - d21 + par10, textureLightTopU, d14); + } } diff --git a/src/main/java/forestry/apiculture/render/TextureHabitatLocator.java b/src/main/java/forestry/apiculture/render/TextureHabitatLocator.java index f12fdc79a..c98a15051 100644 --- a/src/main/java/forestry/apiculture/render/TextureHabitatLocator.java +++ b/src/main/java/forestry/apiculture/render/TextureHabitatLocator.java @@ -18,90 +18,101 @@ import net.minecraft.world.World; public class TextureHabitatLocator extends TextureAtlasSprite { - private static TextureHabitatLocator instance; + private static TextureHabitatLocator instance; - public static TextureHabitatLocator getInstance() { - return instance; - } + public static TextureHabitatLocator getInstance() { + return instance; + } - private ChunkCoordinates targetBiome; - private boolean targetBiomeFound; + private ChunkCoordinates targetBiome; + private boolean targetBiomeFound; - private double currentAngle; - private double angleDelta; + private double currentAngle; + private double angleDelta; - public TextureHabitatLocator(String iconName) { - super(iconName); - instance = this; - } + public TextureHabitatLocator(String iconName) { + super(iconName); + instance = this; + } - public void setTargetCoordinates(ChunkCoordinates coordinates) { - this.targetBiome = coordinates; - this.targetBiomeFound = false; - } + public void setTargetCoordinates(ChunkCoordinates coordinates) { + this.targetBiome = coordinates; + this.targetBiomeFound = false; + } - @Override - public void updateAnimation() { - Minecraft minecraft = Minecraft.getMinecraft(); + @Override + public void updateAnimation() { + Minecraft minecraft = Minecraft.getMinecraft(); - if (minecraft.theWorld != null && minecraft.thePlayer != null) { - updateCompass(minecraft.theWorld, minecraft.thePlayer.posX, minecraft.thePlayer.posZ, minecraft.thePlayer.rotationYaw); - } else { - updateCompass(null, 0.0d, 0.0d, 0.0d); - } - } + if (minecraft.theWorld != null && minecraft.thePlayer != null) { + updateCompass( + minecraft.theWorld, + minecraft.thePlayer.posX, + minecraft.thePlayer.posZ, + minecraft.thePlayer.rotationYaw); + } else { + updateCompass(null, 0.0d, 0.0d, 0.0d); + } + } - private void updateCompass(World world, double playerX, double playerZ, double playerYaw) { + private void updateCompass(World world, double playerX, double playerZ, double playerYaw) { - double targetAngle; + double targetAngle; - if (world == null || targetBiome == null) { - // No target has the locator spinning wildly. - targetAngle = Math.random() * Math.PI * 2.0d; - } else { - double xPart = targetBiome.posX - playerX; - double zPart = targetBiome.posZ - playerZ; + if (world == null || targetBiome == null) { + // No target has the locator spinning wildly. + targetAngle = Math.random() * Math.PI * 2.0d; + } else { + double xPart = targetBiome.posX - playerX; + double zPart = targetBiome.posZ - playerZ; - if (Math.abs(xPart) + Math.abs(zPart) < 10 || targetBiomeFound) { - // spin steadily when the biome is found - targetAngle = currentAngle + 1; - targetBiomeFound = true; - } else { - playerYaw %= 360.0D; - targetAngle = -((playerYaw - 90.0f) * Math.PI / 180.0d - Math.atan2(zPart, xPart)); - } - } + if (Math.abs(xPart) + Math.abs(zPart) < 10 || targetBiomeFound) { + // spin steadily when the biome is found + targetAngle = currentAngle + 1; + targetBiomeFound = true; + } else { + playerYaw %= 360.0D; + targetAngle = -((playerYaw - 90.0f) * Math.PI / 180.0d - Math.atan2(zPart, xPart)); + } + } - double angleChange = targetAngle - currentAngle; - while (angleChange < -Math.PI) { - angleChange += (Math.PI * 2D); - } + double angleChange = targetAngle - currentAngle; + while (angleChange < -Math.PI) { + angleChange += (Math.PI * 2D); + } - while (angleChange >= Math.PI) { - angleChange -= (Math.PI * 2D); - } + while (angleChange >= Math.PI) { + angleChange -= (Math.PI * 2D); + } - if (angleChange < -1.0D) { - angleChange = -1.0D; - } + if (angleChange < -1.0D) { + angleChange = -1.0D; + } - if (angleChange > 1.0D) { - angleChange = 1.0D; - } + if (angleChange > 1.0D) { + angleChange = 1.0D; + } - this.angleDelta += angleChange * 0.1D; - this.angleDelta *= 0.8D; - this.currentAngle += this.angleDelta; + this.angleDelta += angleChange * 0.1D; + this.angleDelta *= 0.8D; + this.currentAngle += this.angleDelta; - int i = (int) ((this.currentAngle / (Math.PI * 2D) + 1.0d) * this.framesTextureData.size()) % this.framesTextureData.size(); - while (i < 0) { - i = (i + this.framesTextureData.size()) % this.framesTextureData.size(); - } + int i = (int) ((this.currentAngle / (Math.PI * 2D) + 1.0d) * this.framesTextureData.size()) + % this.framesTextureData.size(); + while (i < 0) { + i = (i + this.framesTextureData.size()) % this.framesTextureData.size(); + } - if (i != this.frameCounter) { - this.frameCounter = i; - TextureUtil.uploadTextureMipmap((int[][]) this.framesTextureData.get(this.frameCounter), this.width, this.height, this.originX, this.originY, false, false); - } - - } + if (i != this.frameCounter) { + this.frameCounter = i; + TextureUtil.uploadTextureMipmap( + (int[][]) this.framesTextureData.get(this.frameCounter), + this.width, + this.height, + this.originX, + this.originY, + false, + false); + } + } } diff --git a/src/main/java/forestry/apiculture/tiles/TileApiaristChest.java b/src/main/java/forestry/apiculture/tiles/TileApiaristChest.java index 14c4fec50..c17a67713 100644 --- a/src/main/java/forestry/apiculture/tiles/TileApiaristChest.java +++ b/src/main/java/forestry/apiculture/tiles/TileApiaristChest.java @@ -10,55 +10,59 @@ ******************************************************************************/ package forestry.apiculture.tiles; -import net.minecraft.block.Block; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - import forestry.api.apiculture.BeeManager; import forestry.core.config.Constants; import forestry.core.inventory.InventoryPlain; import forestry.core.tiles.TileNaturalistChest; import forestry.core.tiles.TileUtil; import forestry.plugins.PluginApiculture; +import net.minecraft.block.Block; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; public class TileApiaristChest extends TileNaturalistChest { - private boolean checkedForLegacyBlock = false; + private boolean checkedForLegacyBlock = false; - public TileApiaristChest() { - super(BeeManager.beeRoot); - } + public TileApiaristChest() { + super(BeeManager.beeRoot); + } - @Override - protected void updateServerSide() { - if (worldObj != null && !checkedForLegacyBlock) { - Block block = worldObj.getBlock(xCoord, yCoord, zCoord); - if (PluginApiculture.blocks.apiculture == block) { - migrateFromLegacyBlock(); - } + @Override + protected void updateServerSide() { + if (worldObj != null && !checkedForLegacyBlock) { + Block block = worldObj.getBlock(xCoord, yCoord, zCoord); + if (PluginApiculture.blocks.apiculture == block) { + migrateFromLegacyBlock(); + } - checkedForLegacyBlock = true; - } - super.updateServerSide(); - } + checkedForLegacyBlock = true; + } + super.updateServerSide(); + } - private void migrateFromLegacyBlock() { - IInventory inventoryCopy = new InventoryPlain(getInternalInventory()); + private void migrateFromLegacyBlock() { + IInventory inventoryCopy = new InventoryPlain(getInternalInventory()); - // clear the inventory so it isn't dropped when the block is replaced - for (int i = 0; i < getSizeInventory(); i++) { - setInventorySlotContents(i, null); - } + // clear the inventory so it isn't dropped when the block is replaced + for (int i = 0; i < getSizeInventory(); i++) { + setInventorySlotContents(i, null); + } - worldObj.setBlockToAir(xCoord, yCoord, zCoord); - worldObj.setBlock(xCoord, yCoord, zCoord, PluginApiculture.blocks.apicultureChest, 0, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); - - TileApiaristChest tile = TileUtil.getTile(worldObj, xCoord, yCoord, zCoord, TileApiaristChest.class); - for (int i = 0; i < getSizeInventory(); i++) { - ItemStack stack = inventoryCopy.getStackInSlot(i); - tile.setInventorySlotContents(i, stack); - } - tile.markDirty(); - } + worldObj.setBlockToAir(xCoord, yCoord, zCoord); + worldObj.setBlock( + xCoord, + yCoord, + zCoord, + PluginApiculture.blocks.apicultureChest, + 0, + Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); + TileApiaristChest tile = TileUtil.getTile(worldObj, xCoord, yCoord, zCoord, TileApiaristChest.class); + for (int i = 0; i < getSizeInventory(); i++) { + ItemStack stack = inventoryCopy.getStackInSlot(i); + tile.setInventorySlotContents(i, stack); + } + tile.markDirty(); + } } diff --git a/src/main/java/forestry/apiculture/tiles/TileApiary.java b/src/main/java/forestry/apiculture/tiles/TileApiary.java index 2b00bfe61..099f6c26f 100644 --- a/src/main/java/forestry/apiculture/tiles/TileApiary.java +++ b/src/main/java/forestry/apiculture/tiles/TileApiary.java @@ -10,19 +10,8 @@ ******************************************************************************/ package forestry.apiculture.tiles; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.statements.ITriggerExternal; import cpw.mods.fml.common.Optional; - import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; import forestry.api.apiculture.IBeeModifier; @@ -35,66 +24,72 @@ import forestry.apiculture.gui.GuiBeeHousing; import forestry.apiculture.inventory.IApiaryInventory; import forestry.apiculture.inventory.InventoryApiary; import forestry.apiculture.trigger.ApicultureTriggers; - -import buildcraft.api.statements.ITriggerExternal; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TileApiary extends TileBeeHousingBase implements IApiary { - private final IBeeModifier beeModifier = new ApiaryBeeModifier(); - private final IBeeListener beeListener = new ApiaryBeeListener(this); - private final InventoryApiary inventory = new InventoryApiary(getAccessHandler()); + private final IBeeModifier beeModifier = new ApiaryBeeModifier(); + private final IBeeListener beeListener = new ApiaryBeeListener(this); + private final InventoryApiary inventory = new InventoryApiary(getAccessHandler()); - public TileApiary() { - super("apiary"); - setInternalInventory(inventory); - } + public TileApiary() { + super("apiary"); + setInternalInventory(inventory); + } - @Override - public IBeeHousingInventory getBeeInventory() { - return inventory; - } + @Override + public IBeeHousingInventory getBeeInventory() { + return inventory; + } - @Override - public IApiaryInventory getApiaryInventory() { - return inventory; - } + @Override + public IApiaryInventory getApiaryInventory() { + return inventory; + } - @Override - public Collection getBeeModifiers() { - List beeModifiers = new ArrayList<>(); + @Override + public Collection getBeeModifiers() { + List beeModifiers = new ArrayList<>(); - beeModifiers.add(beeModifier); + beeModifiers.add(beeModifier); - for (IHiveFrame frame : inventory.getFrames()) { - beeModifiers.add(frame.getBeeModifier()); - } + for (IHiveFrame frame : inventory.getFrames()) { + beeModifiers.add(frame.getBeeModifier()); + } - return beeModifiers; - } + return beeModifiers; + } - @Override - public Iterable getBeeListeners() { - return Collections.singleton(beeListener); - } + @Override + public Iterable getBeeListeners() { + return Collections.singleton(beeListener); + } - /* ITRIGGERPROVIDER */ - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { - LinkedList res = new LinkedList<>(); - res.add(ApicultureTriggers.missingQueen); - res.add(ApicultureTriggers.missingDrone); - res.add(ApicultureTriggers.noFrames); - return res; - } + /* ITRIGGERPROVIDER */ + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { + LinkedList res = new LinkedList<>(); + res.add(ApicultureTriggers.missingQueen); + res.add(ApicultureTriggers.missingDrone); + res.add(ApicultureTriggers.noFrames); + return res; + } - @Override - public Object getGui(EntityPlayer player, int data) { - ContainerBeeHousing container = new ContainerBeeHousing(player.inventory, this, true); - return new GuiBeeHousing<>(this, container, GuiBeeHousing.Icon.APIARY); - } + @Override + public Object getGui(EntityPlayer player, int data) { + ContainerBeeHousing container = new ContainerBeeHousing(player.inventory, this, true); + return new GuiBeeHousing<>(this, container, GuiBeeHousing.Icon.APIARY); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerBeeHousing(player.inventory, this, true); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerBeeHousing(player.inventory, this, true); + } } diff --git a/src/main/java/forestry/apiculture/tiles/TileBeeHousingBase.java b/src/main/java/forestry/apiculture/tiles/TileBeeHousingBase.java index b92d7833b..e419e2a60 100644 --- a/src/main/java/forestry/apiculture/tiles/TileBeeHousingBase.java +++ b/src/main/java/forestry/apiculture/tiles/TileBeeHousingBase.java @@ -1,172 +1,169 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.tiles; - -import java.io.IOException; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.Packet; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - -import com.mojang.authlib.GameProfile; - -import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeekeepingLogic; -import forestry.api.core.EnumHumidity; -import forestry.api.core.EnumTemperature; -import forestry.apiculture.gui.IGuiBeeHousingInventory; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamableGui; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.IClimatised; -import forestry.core.tiles.TileBase; - -public abstract class TileBeeHousingBase extends TileBase implements IBeeHousing, IClimatised, IGuiBeeHousingInventory, IStreamableGui { - private final IBeekeepingLogic beeLogic; - - // CLIENT - private int breedingProgressPercent = 0; - - protected TileBeeHousingBase(String hintKey) { - super(hintKey); - this.beeLogic = BeeManager.beeRoot.createBeekeepingLogic(this); - } - - @Override - public IBeekeepingLogic getBeekeepingLogic() { - return beeLogic; - } - - /* LOADING & SAVING */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - beeLogic.writeToNBT(nbttagcompound); - } - - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - beeLogic.readFromNBT(nbttagcompound); - } - - @Override - public Packet getDescriptionPacket() { - beeLogic.syncToClient(); - return super.getDescriptionPacket(); - } - - /* ICLIMATISED */ - @Override - public EnumTemperature getTemperature() { - return EnumTemperature.getFromBiome(getBiome(), xCoord, yCoord, zCoord); - } - - @Override - public EnumHumidity getHumidity() { - return EnumHumidity.getFromValue(getExactHumidity()); - } - - @Override - public float getExactTemperature() { - return getBiome().getFloatTemperature(xCoord, yCoord, zCoord); - } - - @Override - public float getExactHumidity() { - return getBiome().rainfall; - } - - /* UPDATING */ - @Override - public void updateClientSide() { - if (beeLogic.canDoBeeFX() && updateOnInterval(4)) { - beeLogic.doBeeFX(); - - if (updateOnInterval(50)) { - doPollenFX(worldObj, xCoord, yCoord, zCoord); - } - } - } - - public static void doPollenFX(World world, double xCoord, double yCoord, double zCoord) { - double fxX = xCoord + 0.5F; - double fxY = yCoord + 0.25F; - double fxZ = zCoord + 0.5F; - float distanceFromCenter = 0.6F; - float leftRightSpreadFromCenter = distanceFromCenter * (world.rand.nextFloat() - 0.5F); - float upSpread = (world.rand.nextFloat() * 6F) / 16F; - fxY += upSpread; - - Proxies.render.addEntitySwarmFX(world, (fxX - distanceFromCenter), fxY, (fxZ + leftRightSpreadFromCenter)); - Proxies.render.addEntitySwarmFX(world, (fxX + distanceFromCenter), fxY, (fxZ + leftRightSpreadFromCenter)); - Proxies.render.addEntitySwarmFX(world, (fxX + leftRightSpreadFromCenter), fxY, (fxZ - distanceFromCenter)); - Proxies.render.addEntitySwarmFX(world, (fxX + leftRightSpreadFromCenter), fxY, (fxZ + distanceFromCenter)); - } - - @Override - public void updateServerSide() { - if (beeLogic.canWork()) { - beeLogic.doWork(); - } - } - - @Override - public int getHealthScaled(int i) { - return (breedingProgressPercent * i) / 100; - } - - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - data.writeVarInt(beeLogic.getBeeProgressPercent()); - } - - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - breedingProgressPercent = data.readVarInt(); - } - - // / IBEEHOUSING - @Override - public BiomeGenBase getBiome() { - return worldObj.getBiomeGenForCoordsBody(xCoord, zCoord); - } - - @Override - public int getBlockLightValue() { - return worldObj.getBlockLightValue(xCoord, yCoord + 1, zCoord); - } - - @Override - public boolean canBlockSeeTheSky() { - return worldObj.canBlockSeeTheSky(xCoord, yCoord + 1, zCoord); - } - - @Override - public GameProfile getOwner() { - return getAccessHandler().getOwner(); - } - - @Override - public World getWorld() { - return worldObj; - } - - @Override - public Vec3 getBeeFXCoordinates() { - return Vec3.createVectorHelper(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5); - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.tiles; + +import com.mojang.authlib.GameProfile; +import forestry.api.apiculture.BeeManager; +import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeekeepingLogic; +import forestry.api.core.EnumHumidity; +import forestry.api.core.EnumTemperature; +import forestry.apiculture.gui.IGuiBeeHousingInventory; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamableGui; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.IClimatised; +import forestry.core.tiles.TileBase; +import java.io.IOException; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.Packet; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; + +public abstract class TileBeeHousingBase extends TileBase + implements IBeeHousing, IClimatised, IGuiBeeHousingInventory, IStreamableGui { + private final IBeekeepingLogic beeLogic; + + // CLIENT + private int breedingProgressPercent = 0; + + protected TileBeeHousingBase(String hintKey) { + super(hintKey); + this.beeLogic = BeeManager.beeRoot.createBeekeepingLogic(this); + } + + @Override + public IBeekeepingLogic getBeekeepingLogic() { + return beeLogic; + } + + /* LOADING & SAVING */ + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + beeLogic.writeToNBT(nbttagcompound); + } + + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + beeLogic.readFromNBT(nbttagcompound); + } + + @Override + public Packet getDescriptionPacket() { + beeLogic.syncToClient(); + return super.getDescriptionPacket(); + } + + /* ICLIMATISED */ + @Override + public EnumTemperature getTemperature() { + return EnumTemperature.getFromBiome(getBiome(), xCoord, yCoord, zCoord); + } + + @Override + public EnumHumidity getHumidity() { + return EnumHumidity.getFromValue(getExactHumidity()); + } + + @Override + public float getExactTemperature() { + return getBiome().getFloatTemperature(xCoord, yCoord, zCoord); + } + + @Override + public float getExactHumidity() { + return getBiome().rainfall; + } + + /* UPDATING */ + @Override + public void updateClientSide() { + if (beeLogic.canDoBeeFX() && updateOnInterval(4)) { + beeLogic.doBeeFX(); + + if (updateOnInterval(50)) { + doPollenFX(worldObj, xCoord, yCoord, zCoord); + } + } + } + + public static void doPollenFX(World world, double xCoord, double yCoord, double zCoord) { + double fxX = xCoord + 0.5F; + double fxY = yCoord + 0.25F; + double fxZ = zCoord + 0.5F; + float distanceFromCenter = 0.6F; + float leftRightSpreadFromCenter = distanceFromCenter * (world.rand.nextFloat() - 0.5F); + float upSpread = (world.rand.nextFloat() * 6F) / 16F; + fxY += upSpread; + + Proxies.render.addEntitySwarmFX(world, (fxX - distanceFromCenter), fxY, (fxZ + leftRightSpreadFromCenter)); + Proxies.render.addEntitySwarmFX(world, (fxX + distanceFromCenter), fxY, (fxZ + leftRightSpreadFromCenter)); + Proxies.render.addEntitySwarmFX(world, (fxX + leftRightSpreadFromCenter), fxY, (fxZ - distanceFromCenter)); + Proxies.render.addEntitySwarmFX(world, (fxX + leftRightSpreadFromCenter), fxY, (fxZ + distanceFromCenter)); + } + + @Override + public void updateServerSide() { + if (beeLogic.canWork()) { + beeLogic.doWork(); + } + } + + @Override + public int getHealthScaled(int i) { + return (breedingProgressPercent * i) / 100; + } + + @Override + public void writeGuiData(DataOutputStreamForestry data) throws IOException { + data.writeVarInt(beeLogic.getBeeProgressPercent()); + } + + @Override + public void readGuiData(DataInputStreamForestry data) throws IOException { + breedingProgressPercent = data.readVarInt(); + } + + // / IBEEHOUSING + @Override + public BiomeGenBase getBiome() { + return worldObj.getBiomeGenForCoordsBody(xCoord, zCoord); + } + + @Override + public int getBlockLightValue() { + return worldObj.getBlockLightValue(xCoord, yCoord + 1, zCoord); + } + + @Override + public boolean canBlockSeeTheSky() { + return worldObj.canBlockSeeTheSky(xCoord, yCoord + 1, zCoord); + } + + @Override + public GameProfile getOwner() { + return getAccessHandler().getOwner(); + } + + @Override + public World getWorld() { + return worldObj; + } + + @Override + public Vec3 getBeeFXCoordinates() { + return Vec3.createVectorHelper(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5); + } +} diff --git a/src/main/java/forestry/apiculture/tiles/TileBeehouse.java b/src/main/java/forestry/apiculture/tiles/TileBeehouse.java index d1c499b1c..2d4eaddad 100644 --- a/src/main/java/forestry/apiculture/tiles/TileBeehouse.java +++ b/src/main/java/forestry/apiculture/tiles/TileBeehouse.java @@ -10,10 +10,6 @@ ******************************************************************************/ package forestry.apiculture.tiles; -import java.util.Collections; - -import net.minecraft.entity.player.EntityPlayer; - import forestry.api.apiculture.DefaultBeeListener; import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; @@ -22,45 +18,47 @@ import forestry.apiculture.BeehouseBeeModifier; import forestry.apiculture.InventoryBeeHousing; import forestry.apiculture.gui.ContainerBeeHousing; import forestry.apiculture.gui.GuiBeeHousing; +import java.util.Collections; +import net.minecraft.entity.player.EntityPlayer; public class TileBeehouse extends TileBeeHousingBase { - private static final IBeeModifier beeModifier = new BeehouseBeeModifier(); + private static final IBeeModifier beeModifier = new BeehouseBeeModifier(); - private final IBeeListener beeListener; - private final InventoryBeeHousing beeInventory; + private final IBeeListener beeListener; + private final InventoryBeeHousing beeInventory; - public TileBeehouse() { - super("bee.house"); - this.beeListener = new DefaultBeeListener(); + public TileBeehouse() { + super("bee.house"); + this.beeListener = new DefaultBeeListener(); - beeInventory = new InventoryBeeHousing(12, getAccessHandler()); - beeInventory.disableAutomation(); - setInternalInventory(beeInventory); - } + beeInventory = new InventoryBeeHousing(12, getAccessHandler()); + beeInventory.disableAutomation(); + setInternalInventory(beeInventory); + } - @Override - public IBeeHousingInventory getBeeInventory() { - return beeInventory; - } + @Override + public IBeeHousingInventory getBeeInventory() { + return beeInventory; + } - @Override - public Iterable getBeeModifiers() { - return Collections.singleton(beeModifier); - } + @Override + public Iterable getBeeModifiers() { + return Collections.singleton(beeModifier); + } - @Override - public Iterable getBeeListeners() { - return Collections.singleton(beeListener); - } + @Override + public Iterable getBeeListeners() { + return Collections.singleton(beeListener); + } - @Override - public Object getGui(EntityPlayer player, int data) { - ContainerBeeHousing container = new ContainerBeeHousing(player.inventory, this, false); - return new GuiBeeHousing<>(this, container, GuiBeeHousing.Icon.BEE_HOUSE); - } + @Override + public Object getGui(EntityPlayer player, int data) { + ContainerBeeHousing container = new ContainerBeeHousing(player.inventory, this, false); + return new GuiBeeHousing<>(this, container, GuiBeeHousing.Icon.BEE_HOUSE); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerBeeHousing(player.inventory, this, false); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerBeeHousing(player.inventory, this, false); + } } diff --git a/src/main/java/forestry/apiculture/tiles/TileCandle.java b/src/main/java/forestry/apiculture/tiles/TileCandle.java index fe11313df..169da7135 100644 --- a/src/main/java/forestry/apiculture/tiles/TileCandle.java +++ b/src/main/java/forestry/apiculture/tiles/TileCandle.java @@ -10,78 +10,78 @@ ******************************************************************************/ package forestry.apiculture.tiles; +import forestry.apiculture.network.packets.PacketCandleUpdate; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.Packet; import net.minecraft.tileentity.TileEntity; -import forestry.apiculture.network.packets.PacketCandleUpdate; - public class TileCandle extends TileEntity { - private int colour; - private boolean lit; + private int colour; + private boolean lit; - // This is a non-ticking Tile Entity. - @Override - public boolean canUpdate() { - return false; - } + // This is a non-ticking Tile Entity. + @Override + public boolean canUpdate() { + return false; + } - @Override - public Packet getDescriptionPacket() { - PacketCandleUpdate updateCandle = new PacketCandleUpdate(this); - return updateCandle.getPacket(); - } + @Override + public Packet getDescriptionPacket() { + PacketCandleUpdate updateCandle = new PacketCandleUpdate(this); + return updateCandle.getPacket(); + } - public void onPacketUpdate(int colour, boolean isLit) { - this.colour = colour; - this.lit = isLit; - } + public void onPacketUpdate(int colour, boolean isLit) { + this.colour = colour; + this.lit = isLit; + } - @Override - public void readFromNBT(NBTTagCompound tagRoot) { - super.readFromNBT(tagRoot); - colour = tagRoot.getInteger("colour"); - lit = tagRoot.getBoolean("lit"); - } + @Override + public void readFromNBT(NBTTagCompound tagRoot) { + super.readFromNBT(tagRoot); + colour = tagRoot.getInteger("colour"); + lit = tagRoot.getBoolean("lit"); + } - @Override - public void writeToNBT(NBTTagCompound tagRoot) { - super.writeToNBT(tagRoot); - tagRoot.setInteger("colour", this.colour); - tagRoot.setBoolean("lit", this.lit); - } + @Override + public void writeToNBT(NBTTagCompound tagRoot) { + super.writeToNBT(tagRoot); + tagRoot.setInteger("colour", this.colour); + tagRoot.setBoolean("lit", this.lit); + } - public boolean isLit() { - return lit; - } + public boolean isLit() { + return lit; + } - public void setLit(boolean lit) { - this.lit = lit; - } + public void setLit(boolean lit) { + this.lit = lit; + } - public int getColour() { - return colour; - } + public int getColour() { + return colour; + } - public void setColour(int value) { - this.colour = value; - } + public void setColour(int value) { + this.colour = value; + } - public void addColour(int colour2) { - int[] myColour = fromIntColour(this.colour); - int[] addColour = fromIntColour(colour2); - this.colour = toIntColour((addColour[0] + myColour[0]) / 2, (addColour[0] + myColour[0]) / 2, (addColour[2] + myColour[2]) / 2); - } + public void addColour(int colour2) { + int[] myColour = fromIntColour(this.colour); + int[] addColour = fromIntColour(colour2); + this.colour = toIntColour( + (addColour[0] + myColour[0]) / 2, (addColour[0] + myColour[0]) / 2, (addColour[2] + myColour[2]) / 2); + } - private static int[] fromIntColour(int value) { - int[] cs = new int[3]; - cs[0] = (value & 0xff0000) >> 16; - cs[1] = (value & 0x00ff00) >> 8; - cs[2] = value & 0x0000ff; - return cs; - } + private static int[] fromIntColour(int value) { + int[] cs = new int[3]; + cs[0] = (value & 0xff0000) >> 16; + cs[1] = (value & 0x00ff00) >> 8; + cs[2] = value & 0x0000ff; + return cs; + } - private static int toIntColour(int r, int g, int b) { - return r << 16 | g << 8 | b; - } + private static int toIntColour(int r, int g, int b) { + return r << 16 | g << 8 | b; + } } diff --git a/src/main/java/forestry/apiculture/tiles/TileSwarm.java b/src/main/java/forestry/apiculture/tiles/TileSwarm.java index 026bae37a..602e8b24a 100644 --- a/src/main/java/forestry/apiculture/tiles/TileSwarm.java +++ b/src/main/java/forestry/apiculture/tiles/TileSwarm.java @@ -10,65 +10,63 @@ ******************************************************************************/ package forestry.apiculture.tiles; +import forestry.core.inventory.InventoryAdapter; +import forestry.core.utils.InventoryUtil; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.EnumSkyBlock; -import forestry.core.inventory.InventoryAdapter; -import forestry.core.utils.InventoryUtil; - public class TileSwarm extends TileEntity { - public final InventoryAdapter contained = new InventoryAdapter(2, "Contained"); + public final InventoryAdapter contained = new InventoryAdapter(2, "Contained"); - @Override - public boolean canUpdate() { - return true; - } + @Override + public boolean canUpdate() { + return true; + } - // Hack to make sure that hives glow. - // TODO: remove when Mojang fixes this bug: https://bugs.mojang.com/browse/MC-3329 - // Hives should not need to tick normally. - private boolean updatedLight; + // Hack to make sure that hives glow. + // TODO: remove when Mojang fixes this bug: https://bugs.mojang.com/browse/MC-3329 + // Hives should not need to tick normally. + private boolean updatedLight; - @Override - public void updateEntity() { - super.updateEntity(); + @Override + public void updateEntity() { + super.updateEntity(); - if (worldObj.isRemote && !updatedLight && worldObj.getWorldTime() % 20 == 0) { - updatedLight = worldObj.updateLightByType(EnumSkyBlock.Block, xCoord, yCoord, zCoord); - } - } + if (worldObj.isRemote && !updatedLight && worldObj.getWorldTime() % 20 == 0) { + updatedLight = worldObj.updateLightByType(EnumSkyBlock.Block, xCoord, yCoord, zCoord); + } + } - public TileSwarm setContained(ItemStack[] bees) { - for (ItemStack itemstack : bees) { - InventoryUtil.addStack(contained, itemstack, true); - } + public TileSwarm setContained(ItemStack[] bees) { + for (ItemStack itemstack : bees) { + InventoryUtil.addStack(contained, itemstack, true); + } - return this; - } + return this; + } - public boolean containsBees() { - for (int i = 0; i < contained.getSizeInventory(); i++) { - if (contained.getStackInSlot(i) != null) { - return true; - } - } + public boolean containsBees() { + for (int i = 0; i < contained.getSizeInventory(); i++) { + if (contained.getStackInSlot(i) != null) { + return true; + } + } - return false; - } + return false; + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - contained.readFromNBT(nbttagcompound); - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - contained.writeToNBT(nbttagcompound); - } + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + contained.readFromNBT(nbttagcompound); + } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + contained.writeToNBT(nbttagcompound); + } } diff --git a/src/main/java/forestry/apiculture/trigger/ApicultureTriggers.java b/src/main/java/forestry/apiculture/trigger/ApicultureTriggers.java index 27cd7735b..73ee0d616 100644 --- a/src/main/java/forestry/apiculture/trigger/ApicultureTriggers.java +++ b/src/main/java/forestry/apiculture/trigger/ApicultureTriggers.java @@ -13,14 +13,14 @@ package forestry.apiculture.trigger; import forestry.core.triggers.Trigger; public class ApicultureTriggers { - public static Trigger noFrames; - public static Trigger missingQueen; - public static Trigger missingDrone; + public static Trigger noFrames; + public static Trigger missingQueen; + public static Trigger missingDrone; - public static void initialize() { - noFrames = new TriggerNoFrames(); + public static void initialize() { + noFrames = new TriggerNoFrames(); - missingQueen = new TriggerMissingQueen(); - missingDrone = new TriggerMissingDrone(); - } + missingQueen = new TriggerMissingQueen(); + missingDrone = new TriggerMissingDrone(); + } } diff --git a/src/main/java/forestry/apiculture/trigger/TriggerMissingDrone.java b/src/main/java/forestry/apiculture/trigger/TriggerMissingDrone.java index b3f93c850..f060a7f2b 100644 --- a/src/main/java/forestry/apiculture/trigger/TriggerMissingDrone.java +++ b/src/main/java/forestry/apiculture/trigger/TriggerMissingDrone.java @@ -10,35 +10,32 @@ ******************************************************************************/ package forestry.apiculture.trigger; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.statements.IStatementContainer; +import buildcraft.api.statements.IStatementParameter; import forestry.api.core.IErrorLogicSource; import forestry.core.errors.EnumErrorCode; import forestry.core.triggers.Trigger; - -import buildcraft.api.statements.IStatementContainer; -import buildcraft.api.statements.IStatementParameter; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TriggerMissingDrone extends Trigger { - public TriggerMissingDrone() { - super("missingDrone"); - } + public TriggerMissingDrone() { + super("missingDrone"); + } - /** - * Return true if the tile given in parameter activates the trigger, given the parameters. - */ - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + /** + * Return true if the tile given in parameter activates the trigger, given the parameters. + */ + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - if (!(tile instanceof IErrorLogicSource)) { - return false; - } - - IErrorLogicSource apiary = (IErrorLogicSource) tile; - return apiary.getErrorLogic().contains(EnumErrorCode.NO_DRONE); - } + if (!(tile instanceof IErrorLogicSource)) { + return false; + } + IErrorLogicSource apiary = (IErrorLogicSource) tile; + return apiary.getErrorLogic().contains(EnumErrorCode.NO_DRONE); + } } diff --git a/src/main/java/forestry/apiculture/trigger/TriggerMissingQueen.java b/src/main/java/forestry/apiculture/trigger/TriggerMissingQueen.java index 598faf93d..f7b02bca4 100644 --- a/src/main/java/forestry/apiculture/trigger/TriggerMissingQueen.java +++ b/src/main/java/forestry/apiculture/trigger/TriggerMissingQueen.java @@ -10,34 +10,32 @@ ******************************************************************************/ package forestry.apiculture.trigger; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.statements.IStatementContainer; +import buildcraft.api.statements.IStatementParameter; import forestry.api.core.IErrorLogicSource; import forestry.core.errors.EnumErrorCode; import forestry.core.triggers.Trigger; - -import buildcraft.api.statements.IStatementContainer; -import buildcraft.api.statements.IStatementParameter; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TriggerMissingQueen extends Trigger { - public TriggerMissingQueen() { - super("missingQueen"); - } + public TriggerMissingQueen() { + super("missingQueen"); + } - /** - * Return true if the tile given in parameter activates the trigger, given the parameters. - */ - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + /** + * Return true if the tile given in parameter activates the trigger, given the parameters. + */ + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - if (!(tile instanceof IErrorLogicSource)) { - return false; - } + if (!(tile instanceof IErrorLogicSource)) { + return false; + } - IErrorLogicSource apiary = (IErrorLogicSource) tile; - return apiary.getErrorLogic().contains(EnumErrorCode.NO_QUEEN); - } + IErrorLogicSource apiary = (IErrorLogicSource) tile; + return apiary.getErrorLogic().contains(EnumErrorCode.NO_QUEEN); + } } diff --git a/src/main/java/forestry/apiculture/trigger/TriggerNoFrames.java b/src/main/java/forestry/apiculture/trigger/TriggerNoFrames.java index 070ec4bcf..7e4835625 100755 --- a/src/main/java/forestry/apiculture/trigger/TriggerNoFrames.java +++ b/src/main/java/forestry/apiculture/trigger/TriggerNoFrames.java @@ -10,38 +10,35 @@ ******************************************************************************/ package forestry.apiculture.trigger; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.statements.IStatementContainer; +import buildcraft.api.statements.IStatementParameter; import forestry.apiculture.inventory.InventoryApiary; import forestry.apiculture.tiles.TileApiary; import forestry.core.triggers.Trigger; - -import buildcraft.api.statements.IStatementContainer; -import buildcraft.api.statements.IStatementParameter; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TriggerNoFrames extends Trigger { - public TriggerNoFrames() { - super("noFrames"); - } + public TriggerNoFrames() { + super("noFrames"); + } - /** - * Return true if the tile given in parameter activates the trigger, given the parameters. - */ - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + /** + * Return true if the tile given in parameter activates the trigger, given the parameters. + */ + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - if (!(tile instanceof TileApiary)) { - return false; - } + if (!(tile instanceof TileApiary)) { + return false; + } - TileApiary apiary = (TileApiary) tile; + TileApiary apiary = (TileApiary) tile; - InventoryApiary inventory = (InventoryApiary) apiary.getInternalInventory(); - - return inventory.getFrames().size() == 0; - } + InventoryApiary inventory = (InventoryApiary) apiary.getInternalInventory(); + return inventory.getFrames().size() == 0; + } } diff --git a/src/main/java/forestry/apiculture/worldgen/ComponentVillageBeeHouse.java b/src/main/java/forestry/apiculture/worldgen/ComponentVillageBeeHouse.java index 8b8ed2f86..b47120628 100755 --- a/src/main/java/forestry/apiculture/worldgen/ComponentVillageBeeHouse.java +++ b/src/main/java/forestry/apiculture/worldgen/ComponentVillageBeeHouse.java @@ -10,22 +10,6 @@ ******************************************************************************/ package forestry.apiculture.worldgen; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; -import net.minecraft.world.gen.structure.StructureBoundingBox; -import net.minecraft.world.gen.structure.StructureComponent; -import net.minecraft.world.gen.structure.StructureVillagePieces; - -import net.minecraftforge.common.ChestGenHooks; -import net.minecraftforge.common.util.ForgeDirection; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.FlowerManager; @@ -54,363 +38,441 @@ import forestry.core.worldgen.IBlockType; import forestry.plugins.PluginApiculture; import forestry.plugins.PluginCore; import forestry.plugins.PluginManager; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; +import net.minecraft.world.gen.structure.StructureBoundingBox; +import net.minecraft.world.gen.structure.StructureComponent; +import net.minecraft.world.gen.structure.StructureVillagePieces; +import net.minecraftforge.common.ChestGenHooks; +import net.minecraftforge.common.util.ForgeDirection; public class ComponentVillageBeeHouse extends StructureVillagePieces.House1 { - private static final Random random = new Random(); - - private int averageGroundLevel = -1; - private boolean isInDesert = false; - private IBlockType planks; - private IBlockType logs; - private IBlockType stairs; - private IBlockType fence; - - public ComponentVillageBeeHouse() { - createBuildingBlocks(random); - } - - public ComponentVillageBeeHouse(StructureVillagePieces.Start startPiece, int componentType, Random random, StructureBoundingBox boundingBox, int coordBaseMode) { - super(startPiece, componentType, random, boundingBox, coordBaseMode); - - isInDesert = startPiece.inDesert; - - createBuildingBlocks(random); - } - - private void createBuildingBlocks(Random random) { - if (PluginManager.Module.ARBORICULTURE.isEnabled()) { - - boolean fireproof = (random.nextInt(4) == 0); - - EnumWoodType roofWood = EnumWoodType.getRandom(random); - EnumWoodType logWood = EnumWoodType.getRandom(random); - EnumWoodType fenceWood = EnumWoodType.getRandom(random); - - logs = new BlockTypeLog(TreeManager.woodItemAccess.getLog(logWood, fireproof)); - planks = new BlockTypeWood(TreeManager.woodItemAccess.getPlanks(roofWood, fireproof)); - stairs = new BlockTypeWoodStairs(TreeManager.woodItemAccess.getStairs(roofWood, fireproof)); - fence = new BlockTypeWood(TreeManager.woodItemAccess.getFence(fenceWood, fireproof)); - } else { - int roofMeta = random.nextInt(16); - - logs = new BlockType(Blocks.log, random.nextInt(4)); - planks = new BlockType(Blocks.planks, roofMeta); - stairs = new BlockTypeVanillaStairs(roofMeta); - fence = new BlockType(Blocks.fence, 0); - } - } - - @SuppressWarnings("rawtypes") - public static ComponentVillageBeeHouse buildComponent(StructureVillagePieces.Start startPiece, List par1List, Random random, int par3, int par4, int par5, int par6, int par7) { - StructureBoundingBox bbox = StructureBoundingBox.getComponentToAddBoundingBox(par3, par4, par5, 0, 0, 0, 10, 9, 11, par6); - if (!canVillageGoDeeper(bbox) || StructureComponent.findIntersecting(par1List, bbox) != null) { - return null; - } - - return new ComponentVillageBeeHouse(startPiece, par7, random, bbox, par6); - } - - @Override - public boolean addComponentParts(World world, Random random, StructureBoundingBox structBoundingBox) { - - if (averageGroundLevel < 0) { - averageGroundLevel = getAverageGroundLevel(world, structBoundingBox); - if (averageGroundLevel < 0) { - return true; - } - - boundingBox.offset(0, averageGroundLevel - boundingBox.maxY + 8 - 1, 0); - } - - fillWithBlocks(world, structBoundingBox, 1, 1, 1, 7, 4, 4, Blocks.air, Blocks.air, false); - fillWithBlocks(world, structBoundingBox, 2, 1, 6, 8, 4, 10, Blocks.air, Blocks.air, false); - - // Garden - buildGarden(world, structBoundingBox); - - // Garden fence - fillBoxWith(world, structBoundingBox, 1, 1, 6, 1, 1, 10, fence, false); - fillBoxWith(world, structBoundingBox, 8, 1, 6, 8, 1, 10, fence, false); - fillBoxWith(world, structBoundingBox, 2, 1, 10, 7, 1, 10, fence, false); - - // Flowers - plantFlowerGarden(world, structBoundingBox, 2, 1, 5, 7, 1, 9); - - // Apiaries - buildApiaries(world, structBoundingBox); - - // Floor - fillWithBlocks(world, structBoundingBox, 1, 0, 1, 7, 0, 4, Blocks.planks, Blocks.planks, false); - - fillWithBlocks(world, structBoundingBox, 0, 0, 0, 0, 3, 5, Blocks.cobblestone, Blocks.cobblestone, false); - fillWithBlocks(world, structBoundingBox, 8, 0, 0, 8, 3, 5, Blocks.cobblestone, Blocks.cobblestone, false); - fillWithBlocks(world, structBoundingBox, 1, 0, 0, 7, 1, 0, Blocks.cobblestone, Blocks.cobblestone, false); - fillWithBlocks(world, structBoundingBox, 1, 0, 5, 7, 1, 5, Blocks.cobblestone, Blocks.cobblestone, false); - - fillBoxWith(world, structBoundingBox, 1, 2, 0, 7, 3, 0, planks, false); - fillBoxWith(world, structBoundingBox, 1, 2, 5, 7, 3, 5, planks, false); - fillBoxWith(world, structBoundingBox, 0, 4, 1, 8, 4, 1, planks, false); - fillBoxWith(world, structBoundingBox, 0, 4, 4, 8, 4, 4, planks, false); - fillBoxWith(world, structBoundingBox, 0, 5, 2, 8, 5, 3, planks, false); - - placeBlockAtCurrentPosition(world, planks, 0, 4, 2, structBoundingBox); - placeBlockAtCurrentPosition(world, planks, 0, 4, 3, structBoundingBox); - placeBlockAtCurrentPosition(world, planks, 8, 4, 2, structBoundingBox); - placeBlockAtCurrentPosition(world, planks, 8, 4, 3, structBoundingBox); - - buildRoof(world, structBoundingBox); - - placeBlockAtCurrentPosition(world, logs, 0, 2, 1, structBoundingBox); - placeBlockAtCurrentPosition(world, logs, 0, 2, 4, structBoundingBox); - placeBlockAtCurrentPosition(world, logs, 8, 2, 1, structBoundingBox); - placeBlockAtCurrentPosition(world, logs, 8, 2, 4, structBoundingBox); - - placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 2, structBoundingBox); - placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 3, structBoundingBox); - - placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 8, 2, 2, structBoundingBox); - placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 8, 2, 3, structBoundingBox); - - // Windows garden side - placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 2, 2, 5, structBoundingBox); - placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 3, 2, 5, structBoundingBox); - placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 4, 2, 5, structBoundingBox); - - placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 5, 2, 0, structBoundingBox); - placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 5, structBoundingBox); - - // Escritoire - if (random.nextInt(2) == 0) { - IBlockType escritoireBlock = new BlockTypeTileForestry(PluginCore.blocks.core, BlockCoreType.ESCRITOIRE.ordinal()); - escritoireBlock.setDirection(getRotatedDirection(ForgeDirection.EAST)); - placeBlockAtCurrentPosition(world, escritoireBlock, 1, 1, 3, structBoundingBox); - } - - placeBlockAtCurrentPosition(world, Blocks.air, 0, 2, 1, 0, structBoundingBox); - placeBlockAtCurrentPosition(world, Blocks.air, 0, 2, 2, 0, structBoundingBox); - placeDoorAtCurrentPosition(world, structBoundingBox, random, 2, 1, 0, getMetadataWithOffset(Blocks.wooden_door, 1)); - - if (isAirBlockAtCurrentPosition(world, 2, 0, -1, structBoundingBox) && !isAirBlockAtCurrentPosition(world, 2, -1, -1, structBoundingBox)) { - placeBlockAtCurrentPosition(world, Blocks.stone_stairs, getMetadataWithOffset(Blocks.stone_stairs, 3), 2, 0, -1, structBoundingBox); - } - - placeBlockAtCurrentPosition(world, Blocks.air, 0, 6, 1, 5, structBoundingBox); - placeBlockAtCurrentPosition(world, Blocks.air, 0, 6, 2, 5, structBoundingBox); - - // Candles / Lighting - placeBlockAtCurrentPosition(world, Blocks.torch, 0, 2, 3, 4, structBoundingBox); - placeBlockAtCurrentPosition(world, Blocks.torch, 0, 6, 3, 4, structBoundingBox); - placeBlockAtCurrentPosition(world, Blocks.torch, 0, 2, 3, 1, structBoundingBox); - placeBlockAtCurrentPosition(world, Blocks.torch, 0, 6, 3, 1, structBoundingBox); - - placeDoorAtCurrentPosition(world, structBoundingBox, random, 6, 1, 5, getMetadataWithOffset(Blocks.wooden_door, 1)); - - for (int i = 0; i < 5; ++i) { - for (int j = 0; j < 9; ++j) { - clearCurrentPositionBlocksUpwards(world, j, 7, i, structBoundingBox); - func_151554_b(world, Blocks.cobblestone, 0, j, -1, i, structBoundingBox); - } - } - - generateStructureChestContents(world, structBoundingBox, random, 7, 1, 4, - ChestGenHooks.getItems(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, random), - random.nextInt(4) + random.nextInt(4) + 5); - - spawnVillagers(world, boundingBox, 7, 1, 1, 2); - - return true; - } - - private void buildRoof(World world, StructureBoundingBox structBoundingBox) { - for (int i = -1; i <= 2; ++i) { - for (int j = 0; j <= 8; ++j) { - stairs.setDirection(getRotatedDirection(ForgeDirection.NORTH)); - placeBlockAtCurrentPosition(world, stairs, j, 4 + i, i, structBoundingBox); - - stairs.setDirection(getRotatedDirection(ForgeDirection.SOUTH)); - placeBlockAtCurrentPosition(world, stairs, j, 4 + i, 5 - i, structBoundingBox); - } - } - } - - private void buildGarden(World world, StructureBoundingBox box) { - - Block ground = Blocks.dirt; - if (isInDesert) { - ground = Blocks.sand; - } - - for (int i = 1; i <= 8; i++) { - for (int j = 6; j <= 10; j++) { - func_151554_b(world, ground, 0, i, 0, j, box); - } - } - } - - private void plantFlowerGarden(World world, StructureBoundingBox box, int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { - - if (isInDesert) { - placeBlockAtCurrentPosition(world, Blocks.cactus, 0, 4, 1, 7, box); - return; - } - - for (int i = minY; i <= maxY; ++i) { - for (int j = minX; j <= maxX; ++j) { - for (int k = minZ; k <= maxZ; ++k) { - if (world.rand.nextBoolean()) { - int xCoord = getXWithOffset(j, k); - int yCoord = getYWithOffset(i); - int zCoord = getZWithOffset(j, k); - - if (!Blocks.red_flower.canBlockStay(world, xCoord, yCoord, zCoord)) { - continue; - } - - IFlower flower = FlowerManager.flowerRegistry.getRandomPlantableFlower(FlowerManager.FlowerTypeVanilla, world.rand); - placeBlockAtCurrentPosition(world, flower.getBlock(), flower.getMeta(), j, i, k, box); - } - } - } - } - } - - private void buildApiaries(World world, StructureBoundingBox box) { - populateApiary(world, box, 3, 1, 8); - populateApiary(world, box, 6, 1, 8); - } - - private void populateApiary(World world, StructureBoundingBox box, int x, int y, int z) { - int xCoord = getXWithOffset(x, z); - int yCoord = getYWithOffset(y); - int zCoord = getZWithOffset(x, z); - - if (!box.isVecInside(xCoord, yCoord, zCoord)) { - return; - } - - Block block = world.getBlock(xCoord, yCoord, zCoord); - if (PluginApiculture.blocks.apiculture == block || !world.blockExists(xCoord, yCoord - 1, zCoord)) { - return; - } - - world.setBlock(xCoord, yCoord, zCoord, PluginApiculture.blocks.apiculture, BlockApicultureType.APIARY.ordinal(), Constants.FLAG_BLOCK_SYNCH); - PluginApiculture.blocks.apiculture.onBlockAdded(world, xCoord, yCoord, zCoord); - - TileApiary apiary = TileUtil.getTile(world, xCoord, yCoord, zCoord, TileApiary.class); - if (apiary == null) { - return; - } - - ItemStack randomVillagePrincess = getRandomVillageBeeStack(world, xCoord, yCoord, zCoord, EnumBeeType.PRINCESS); - apiary.getBeeInventory().setQueen(randomVillagePrincess); - - ItemStack randomVillageDrone = getRandomVillageBeeStack(world, xCoord, yCoord, zCoord, EnumBeeType.DRONE); - apiary.getBeeInventory().setDrone(randomVillageDrone); - - for (int i = InventoryApiary.SLOT_FRAMES_1; i < InventoryApiary.SLOT_FRAMES_1 + InventoryApiary.SLOT_FRAMES_COUNT; i++) { - ItemStack randomFrame = getRandomFrame(world.rand); - apiary.setInventorySlotContents(i, randomFrame); - } - } - - private static ItemStack getRandomFrame(Random random) { - float roll = random.nextFloat(); - if (roll < 0.2f) { - return PluginApiculture.items.frameUntreated.getItemStack(); - } else if (roll < 0.4f) { - return PluginApiculture.items.frameImpregnated.getItemStack(); - } else if (roll < 0.6) { - return PluginApiculture.items.frameProven.getItemStack(); - } else { - return null; - } - } - - private static ItemStack getRandomVillageBeeStack(World world, int xCoord, int yCoord, int zCoord, EnumBeeType beeType) { - IBee randomVillageBee = getRandomVillageBee(world, xCoord, yCoord, zCoord); - return BeeManager.beeRoot.getMemberStack(randomVillageBee, beeType.ordinal()); - } - - private static IBee getRandomVillageBee(World world, int xCoord, int yCoord, int zCoord) { - - // Get current biome - BiomeGenBase biome = world.getBiomeGenForCoords(xCoord, zCoord); - - ArrayList candidates; - if (BeeManager.villageBees[1] != null && BeeManager.villageBees[1].size() > 0 && world.rand.nextDouble() < 0.2) { - candidates = BeeManager.villageBees[1]; - } else { - candidates = BeeManager.villageBees[0]; - } - - EnumTemperature biomeTemperature = EnumTemperature.getFromBiome(biome, xCoord, yCoord, zCoord); - EnumHumidity biomeHumidity = EnumHumidity.getFromValue(biome.rainfall); - - // Add bees that can live in this environment - List valid = new ArrayList<>(); - for (IBeeGenome genome : candidates) { - if (checkBiomeHazard(genome, biomeTemperature, biomeHumidity)) { - valid.add(genome); - } - } - - // No valid ones found, return any of the common ones. - if (valid.isEmpty()) { - return BeeManager.beeRoot.getBee(world, BeeManager.villageBees[0].get(world.rand.nextInt(BeeManager.villageBees[0].size()))); - } - - return BeeManager.beeRoot.getBee(world, valid.get(world.rand.nextInt(valid.size()))); - } - - private static boolean checkBiomeHazard(IBeeGenome genome, EnumTemperature biomeTemperature, EnumHumidity biomeHumidity) { - IAlleleBeeSpecies species = genome.getPrimary(); - return AlleleManager.climateHelper.isWithinLimits(biomeTemperature, biomeHumidity, - species.getTemperature(), genome.getToleranceTemp(), - species.getHumidity(), genome.getToleranceHumid()); - } - - private void fillBoxWith(World world, StructureBoundingBox box, int par3, int par4, int par5, int par6, int par7, int par8, IBlockType block, boolean replace) { - - for (int var14 = par4; var14 <= par7; ++var14) { - for (int var15 = par3; var15 <= par6; ++var15) { - for (int var16 = par5; var16 <= par8; ++var16) { - if (!replace || !isAirBlockAtCurrentPosition(world, var15, var14, var16, box)) { - placeBlockAtCurrentPosition(world, block, var15, var14, var16, box); - } - } - } - } - } - - private void placeBlockAtCurrentPosition(World world, IBlockType block, int par4, int par5, int par6, StructureBoundingBox par7StructureBoundingBox) { - int x = getXWithOffset(par4, par6); - int y = getYWithOffset(par5); - int z = getZWithOffset(par4, par6); - - if (par7StructureBoundingBox.isVecInside(x, y, z)) { - block.setBlock(world, x, y, z); - } - } - - @Override - protected int getVillagerType(int villagerCount) { - if (villagerCount <= 0) { - return Constants.ID_VILLAGER_BEEKEEPER; - } else { - return Constants.ID_VILLAGER_LUMBERJACK; - } - } - - private boolean isAirBlockAtCurrentPosition(World world, int x, int y, int z, StructureBoundingBox box) { - return getBlockAtCurrentPosition(world, x, y, z, box).isAir(world, x, y, z); - } - - /** rotates a direction according to the way the structure is facing **/ - private ForgeDirection getRotatedDirection(ForgeDirection direction) { - int stairDirection = 5 - direction.ordinal(); - int meta = getMetadataWithOffset(Blocks.oak_stairs, stairDirection); - return ForgeDirection.getOrientation(5 - meta); - } - + private static final Random random = new Random(); + + private int averageGroundLevel = -1; + private boolean isInDesert = false; + private IBlockType planks; + private IBlockType logs; + private IBlockType stairs; + private IBlockType fence; + + public ComponentVillageBeeHouse() { + createBuildingBlocks(random); + } + + public ComponentVillageBeeHouse( + StructureVillagePieces.Start startPiece, + int componentType, + Random random, + StructureBoundingBox boundingBox, + int coordBaseMode) { + super(startPiece, componentType, random, boundingBox, coordBaseMode); + + isInDesert = startPiece.inDesert; + + createBuildingBlocks(random); + } + + private void createBuildingBlocks(Random random) { + if (PluginManager.Module.ARBORICULTURE.isEnabled()) { + + boolean fireproof = (random.nextInt(4) == 0); + + EnumWoodType roofWood = EnumWoodType.getRandom(random); + EnumWoodType logWood = EnumWoodType.getRandom(random); + EnumWoodType fenceWood = EnumWoodType.getRandom(random); + + logs = new BlockTypeLog(TreeManager.woodItemAccess.getLog(logWood, fireproof)); + planks = new BlockTypeWood(TreeManager.woodItemAccess.getPlanks(roofWood, fireproof)); + stairs = new BlockTypeWoodStairs(TreeManager.woodItemAccess.getStairs(roofWood, fireproof)); + fence = new BlockTypeWood(TreeManager.woodItemAccess.getFence(fenceWood, fireproof)); + } else { + int roofMeta = random.nextInt(16); + + logs = new BlockType(Blocks.log, random.nextInt(4)); + planks = new BlockType(Blocks.planks, roofMeta); + stairs = new BlockTypeVanillaStairs(roofMeta); + fence = new BlockType(Blocks.fence, 0); + } + } + + @SuppressWarnings("rawtypes") + public static ComponentVillageBeeHouse buildComponent( + StructureVillagePieces.Start startPiece, + List par1List, + Random random, + int par3, + int par4, + int par5, + int par6, + int par7) { + StructureBoundingBox bbox = + StructureBoundingBox.getComponentToAddBoundingBox(par3, par4, par5, 0, 0, 0, 10, 9, 11, par6); + if (!canVillageGoDeeper(bbox) || StructureComponent.findIntersecting(par1List, bbox) != null) { + return null; + } + + return new ComponentVillageBeeHouse(startPiece, par7, random, bbox, par6); + } + + @Override + public boolean addComponentParts(World world, Random random, StructureBoundingBox structBoundingBox) { + + if (averageGroundLevel < 0) { + averageGroundLevel = getAverageGroundLevel(world, structBoundingBox); + if (averageGroundLevel < 0) { + return true; + } + + boundingBox.offset(0, averageGroundLevel - boundingBox.maxY + 8 - 1, 0); + } + + fillWithBlocks(world, structBoundingBox, 1, 1, 1, 7, 4, 4, Blocks.air, Blocks.air, false); + fillWithBlocks(world, structBoundingBox, 2, 1, 6, 8, 4, 10, Blocks.air, Blocks.air, false); + + // Garden + buildGarden(world, structBoundingBox); + + // Garden fence + fillBoxWith(world, structBoundingBox, 1, 1, 6, 1, 1, 10, fence, false); + fillBoxWith(world, structBoundingBox, 8, 1, 6, 8, 1, 10, fence, false); + fillBoxWith(world, structBoundingBox, 2, 1, 10, 7, 1, 10, fence, false); + + // Flowers + plantFlowerGarden(world, structBoundingBox, 2, 1, 5, 7, 1, 9); + + // Apiaries + buildApiaries(world, structBoundingBox); + + // Floor + fillWithBlocks(world, structBoundingBox, 1, 0, 1, 7, 0, 4, Blocks.planks, Blocks.planks, false); + + fillWithBlocks(world, structBoundingBox, 0, 0, 0, 0, 3, 5, Blocks.cobblestone, Blocks.cobblestone, false); + fillWithBlocks(world, structBoundingBox, 8, 0, 0, 8, 3, 5, Blocks.cobblestone, Blocks.cobblestone, false); + fillWithBlocks(world, structBoundingBox, 1, 0, 0, 7, 1, 0, Blocks.cobblestone, Blocks.cobblestone, false); + fillWithBlocks(world, structBoundingBox, 1, 0, 5, 7, 1, 5, Blocks.cobblestone, Blocks.cobblestone, false); + + fillBoxWith(world, structBoundingBox, 1, 2, 0, 7, 3, 0, planks, false); + fillBoxWith(world, structBoundingBox, 1, 2, 5, 7, 3, 5, planks, false); + fillBoxWith(world, structBoundingBox, 0, 4, 1, 8, 4, 1, planks, false); + fillBoxWith(world, structBoundingBox, 0, 4, 4, 8, 4, 4, planks, false); + fillBoxWith(world, structBoundingBox, 0, 5, 2, 8, 5, 3, planks, false); + + placeBlockAtCurrentPosition(world, planks, 0, 4, 2, structBoundingBox); + placeBlockAtCurrentPosition(world, planks, 0, 4, 3, structBoundingBox); + placeBlockAtCurrentPosition(world, planks, 8, 4, 2, structBoundingBox); + placeBlockAtCurrentPosition(world, planks, 8, 4, 3, structBoundingBox); + + buildRoof(world, structBoundingBox); + + placeBlockAtCurrentPosition(world, logs, 0, 2, 1, structBoundingBox); + placeBlockAtCurrentPosition(world, logs, 0, 2, 4, structBoundingBox); + placeBlockAtCurrentPosition(world, logs, 8, 2, 1, structBoundingBox); + placeBlockAtCurrentPosition(world, logs, 8, 2, 4, structBoundingBox); + + placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 2, structBoundingBox); + placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 3, structBoundingBox); + + placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 8, 2, 2, structBoundingBox); + placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 8, 2, 3, structBoundingBox); + + // Windows garden side + placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 2, 2, 5, structBoundingBox); + placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 3, 2, 5, structBoundingBox); + placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 4, 2, 5, structBoundingBox); + + placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 5, 2, 0, structBoundingBox); + placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 5, structBoundingBox); + + // Escritoire + if (random.nextInt(2) == 0) { + IBlockType escritoireBlock = + new BlockTypeTileForestry(PluginCore.blocks.core, BlockCoreType.ESCRITOIRE.ordinal()); + escritoireBlock.setDirection(getRotatedDirection(ForgeDirection.EAST)); + placeBlockAtCurrentPosition(world, escritoireBlock, 1, 1, 3, structBoundingBox); + } + + placeBlockAtCurrentPosition(world, Blocks.air, 0, 2, 1, 0, structBoundingBox); + placeBlockAtCurrentPosition(world, Blocks.air, 0, 2, 2, 0, structBoundingBox); + placeDoorAtCurrentPosition( + world, structBoundingBox, random, 2, 1, 0, getMetadataWithOffset(Blocks.wooden_door, 1)); + + if (isAirBlockAtCurrentPosition(world, 2, 0, -1, structBoundingBox) + && !isAirBlockAtCurrentPosition(world, 2, -1, -1, structBoundingBox)) { + placeBlockAtCurrentPosition( + world, + Blocks.stone_stairs, + getMetadataWithOffset(Blocks.stone_stairs, 3), + 2, + 0, + -1, + structBoundingBox); + } + + placeBlockAtCurrentPosition(world, Blocks.air, 0, 6, 1, 5, structBoundingBox); + placeBlockAtCurrentPosition(world, Blocks.air, 0, 6, 2, 5, structBoundingBox); + + // Candles / Lighting + placeBlockAtCurrentPosition(world, Blocks.torch, 0, 2, 3, 4, structBoundingBox); + placeBlockAtCurrentPosition(world, Blocks.torch, 0, 6, 3, 4, structBoundingBox); + placeBlockAtCurrentPosition(world, Blocks.torch, 0, 2, 3, 1, structBoundingBox); + placeBlockAtCurrentPosition(world, Blocks.torch, 0, 6, 3, 1, structBoundingBox); + + placeDoorAtCurrentPosition( + world, structBoundingBox, random, 6, 1, 5, getMetadataWithOffset(Blocks.wooden_door, 1)); + + for (int i = 0; i < 5; ++i) { + for (int j = 0; j < 9; ++j) { + clearCurrentPositionBlocksUpwards(world, j, 7, i, structBoundingBox); + func_151554_b(world, Blocks.cobblestone, 0, j, -1, i, structBoundingBox); + } + } + + generateStructureChestContents( + world, + structBoundingBox, + random, + 7, + 1, + 4, + ChestGenHooks.getItems(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, random), + random.nextInt(4) + random.nextInt(4) + 5); + + spawnVillagers(world, boundingBox, 7, 1, 1, 2); + + return true; + } + + private void buildRoof(World world, StructureBoundingBox structBoundingBox) { + for (int i = -1; i <= 2; ++i) { + for (int j = 0; j <= 8; ++j) { + stairs.setDirection(getRotatedDirection(ForgeDirection.NORTH)); + placeBlockAtCurrentPosition(world, stairs, j, 4 + i, i, structBoundingBox); + + stairs.setDirection(getRotatedDirection(ForgeDirection.SOUTH)); + placeBlockAtCurrentPosition(world, stairs, j, 4 + i, 5 - i, structBoundingBox); + } + } + } + + private void buildGarden(World world, StructureBoundingBox box) { + + Block ground = Blocks.dirt; + if (isInDesert) { + ground = Blocks.sand; + } + + for (int i = 1; i <= 8; i++) { + for (int j = 6; j <= 10; j++) { + func_151554_b(world, ground, 0, i, 0, j, box); + } + } + } + + private void plantFlowerGarden( + World world, StructureBoundingBox box, int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + + if (isInDesert) { + placeBlockAtCurrentPosition(world, Blocks.cactus, 0, 4, 1, 7, box); + return; + } + + for (int i = minY; i <= maxY; ++i) { + for (int j = minX; j <= maxX; ++j) { + for (int k = minZ; k <= maxZ; ++k) { + if (world.rand.nextBoolean()) { + int xCoord = getXWithOffset(j, k); + int yCoord = getYWithOffset(i); + int zCoord = getZWithOffset(j, k); + + if (!Blocks.red_flower.canBlockStay(world, xCoord, yCoord, zCoord)) { + continue; + } + + IFlower flower = FlowerManager.flowerRegistry.getRandomPlantableFlower( + FlowerManager.FlowerTypeVanilla, world.rand); + placeBlockAtCurrentPosition(world, flower.getBlock(), flower.getMeta(), j, i, k, box); + } + } + } + } + } + + private void buildApiaries(World world, StructureBoundingBox box) { + populateApiary(world, box, 3, 1, 8); + populateApiary(world, box, 6, 1, 8); + } + + private void populateApiary(World world, StructureBoundingBox box, int x, int y, int z) { + int xCoord = getXWithOffset(x, z); + int yCoord = getYWithOffset(y); + int zCoord = getZWithOffset(x, z); + + if (!box.isVecInside(xCoord, yCoord, zCoord)) { + return; + } + + Block block = world.getBlock(xCoord, yCoord, zCoord); + if (PluginApiculture.blocks.apiculture == block || !world.blockExists(xCoord, yCoord - 1, zCoord)) { + return; + } + + world.setBlock( + xCoord, + yCoord, + zCoord, + PluginApiculture.blocks.apiculture, + BlockApicultureType.APIARY.ordinal(), + Constants.FLAG_BLOCK_SYNCH); + PluginApiculture.blocks.apiculture.onBlockAdded(world, xCoord, yCoord, zCoord); + + TileApiary apiary = TileUtil.getTile(world, xCoord, yCoord, zCoord, TileApiary.class); + if (apiary == null) { + return; + } + + ItemStack randomVillagePrincess = getRandomVillageBeeStack(world, xCoord, yCoord, zCoord, EnumBeeType.PRINCESS); + apiary.getBeeInventory().setQueen(randomVillagePrincess); + + ItemStack randomVillageDrone = getRandomVillageBeeStack(world, xCoord, yCoord, zCoord, EnumBeeType.DRONE); + apiary.getBeeInventory().setDrone(randomVillageDrone); + + for (int i = InventoryApiary.SLOT_FRAMES_1; + i < InventoryApiary.SLOT_FRAMES_1 + InventoryApiary.SLOT_FRAMES_COUNT; + i++) { + ItemStack randomFrame = getRandomFrame(world.rand); + apiary.setInventorySlotContents(i, randomFrame); + } + } + + private static ItemStack getRandomFrame(Random random) { + float roll = random.nextFloat(); + if (roll < 0.2f) { + return PluginApiculture.items.frameUntreated.getItemStack(); + } else if (roll < 0.4f) { + return PluginApiculture.items.frameImpregnated.getItemStack(); + } else if (roll < 0.6) { + return PluginApiculture.items.frameProven.getItemStack(); + } else { + return null; + } + } + + private static ItemStack getRandomVillageBeeStack( + World world, int xCoord, int yCoord, int zCoord, EnumBeeType beeType) { + IBee randomVillageBee = getRandomVillageBee(world, xCoord, yCoord, zCoord); + return BeeManager.beeRoot.getMemberStack(randomVillageBee, beeType.ordinal()); + } + + private static IBee getRandomVillageBee(World world, int xCoord, int yCoord, int zCoord) { + + // Get current biome + BiomeGenBase biome = world.getBiomeGenForCoords(xCoord, zCoord); + + ArrayList candidates; + if (BeeManager.villageBees[1] != null + && BeeManager.villageBees[1].size() > 0 + && world.rand.nextDouble() < 0.2) { + candidates = BeeManager.villageBees[1]; + } else { + candidates = BeeManager.villageBees[0]; + } + + EnumTemperature biomeTemperature = EnumTemperature.getFromBiome(biome, xCoord, yCoord, zCoord); + EnumHumidity biomeHumidity = EnumHumidity.getFromValue(biome.rainfall); + + // Add bees that can live in this environment + List valid = new ArrayList<>(); + for (IBeeGenome genome : candidates) { + if (checkBiomeHazard(genome, biomeTemperature, biomeHumidity)) { + valid.add(genome); + } + } + + // No valid ones found, return any of the common ones. + if (valid.isEmpty()) { + return BeeManager.beeRoot.getBee( + world, BeeManager.villageBees[0].get(world.rand.nextInt(BeeManager.villageBees[0].size()))); + } + + return BeeManager.beeRoot.getBee(world, valid.get(world.rand.nextInt(valid.size()))); + } + + private static boolean checkBiomeHazard( + IBeeGenome genome, EnumTemperature biomeTemperature, EnumHumidity biomeHumidity) { + IAlleleBeeSpecies species = genome.getPrimary(); + return AlleleManager.climateHelper.isWithinLimits( + biomeTemperature, + biomeHumidity, + species.getTemperature(), + genome.getToleranceTemp(), + species.getHumidity(), + genome.getToleranceHumid()); + } + + private void fillBoxWith( + World world, + StructureBoundingBox box, + int par3, + int par4, + int par5, + int par6, + int par7, + int par8, + IBlockType block, + boolean replace) { + + for (int var14 = par4; var14 <= par7; ++var14) { + for (int var15 = par3; var15 <= par6; ++var15) { + for (int var16 = par5; var16 <= par8; ++var16) { + if (!replace || !isAirBlockAtCurrentPosition(world, var15, var14, var16, box)) { + placeBlockAtCurrentPosition(world, block, var15, var14, var16, box); + } + } + } + } + } + + private void placeBlockAtCurrentPosition( + World world, + IBlockType block, + int par4, + int par5, + int par6, + StructureBoundingBox par7StructureBoundingBox) { + int x = getXWithOffset(par4, par6); + int y = getYWithOffset(par5); + int z = getZWithOffset(par4, par6); + + if (par7StructureBoundingBox.isVecInside(x, y, z)) { + block.setBlock(world, x, y, z); + } + } + + @Override + protected int getVillagerType(int villagerCount) { + if (villagerCount <= 0) { + return Constants.ID_VILLAGER_BEEKEEPER; + } else { + return Constants.ID_VILLAGER_LUMBERJACK; + } + } + + private boolean isAirBlockAtCurrentPosition(World world, int x, int y, int z, StructureBoundingBox box) { + return getBlockAtCurrentPosition(world, x, y, z, box).isAir(world, x, y, z); + } + + /** rotates a direction according to the way the structure is facing **/ + private ForgeDirection getRotatedDirection(ForgeDirection direction) { + int stairDirection = 5 - direction.ordinal(); + int meta = getMetadataWithOffset(Blocks.oak_stairs, stairDirection); + return ForgeDirection.getOrientation(5 - meta); + } } diff --git a/src/main/java/forestry/apiculture/worldgen/Hive.java b/src/main/java/forestry/apiculture/worldgen/Hive.java index 122d5dafa..c73312c66 100644 --- a/src/main/java/forestry/apiculture/worldgen/Hive.java +++ b/src/main/java/forestry/apiculture/worldgen/Hive.java @@ -10,75 +10,73 @@ ******************************************************************************/ package forestry.apiculture.worldgen; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - import forestry.api.apiculture.IHiveDrop; import forestry.api.apiculture.hives.IHiveDescription; import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; public final class Hive { - private final IHiveDescription hiveDescription; - private final List drops = new ArrayList<>(); + private final IHiveDescription hiveDescription; + private final List drops = new ArrayList<>(); - public Hive(IHiveDescription hiveDescription) { - if (hiveDescription == null) { - throw new IllegalArgumentException("Tried to create hive with null hive description"); - } - this.hiveDescription = hiveDescription; - } + public Hive(IHiveDescription hiveDescription) { + if (hiveDescription == null) { + throw new IllegalArgumentException("Tried to create hive with null hive description"); + } + this.hiveDescription = hiveDescription; + } - public Block getHiveBlock() { - return hiveDescription.getBlock(); - } + public Block getHiveBlock() { + return hiveDescription.getBlock(); + } - public int getHiveMeta() { - return hiveDescription.getMeta(); - } + public int getHiveMeta() { + return hiveDescription.getMeta(); + } - public void addDrops(List drops) { - this.drops.addAll(drops); - } + public void addDrops(List drops) { + this.drops.addAll(drops); + } - public List getDrops() { - return drops; - } + public List getDrops() { + return drops; + } - public float genChance() { - return hiveDescription.getGenChance(); - } + public float genChance() { + return hiveDescription.getGenChance(); + } - public void postGen(World world, int x, int y, int z) { - hiveDescription.postGen(world, x, y, z); - } + public void postGen(World world, int x, int y, int z) { + hiveDescription.postGen(world, x, y, z); + } - public boolean isGoodBiome(BiomeGenBase biome) { - return hiveDescription.isGoodBiome(biome); - } + public boolean isGoodBiome(BiomeGenBase biome) { + return hiveDescription.isGoodBiome(biome); + } - public boolean isGoodHumidity(EnumHumidity humidity) { - return hiveDescription.isGoodHumidity(humidity); - } + public boolean isGoodHumidity(EnumHumidity humidity) { + return hiveDescription.isGoodHumidity(humidity); + } - public boolean isGoodTemperature(EnumTemperature temperature) { - return hiveDescription.isGoodTemperature(temperature); - } + public boolean isGoodTemperature(EnumTemperature temperature) { + return hiveDescription.isGoodTemperature(temperature); + } - public boolean isValidLocation(World world, int x, int y, int z) { - return hiveDescription.getHiveGen().isValidLocation(world, x, y, z); - } + public boolean isValidLocation(World world, int x, int y, int z) { + return hiveDescription.getHiveGen().isValidLocation(world, x, y, z); + } - public boolean canReplace(World world, int x, int y, int z) { - return hiveDescription.getHiveGen().canReplace(world, x, y, z); - } + public boolean canReplace(World world, int x, int y, int z) { + return hiveDescription.getHiveGen().canReplace(world, x, y, z); + } - public int getYForHive(World world, int x, int z) { - return hiveDescription.getHiveGen().getYForHive(world, x, z); - } + public int getYForHive(World world, int x, int z) { + return hiveDescription.getHiveGen().getYForHive(world, x, z); + } } diff --git a/src/main/java/forestry/apiculture/worldgen/HiveDecorator.java b/src/main/java/forestry/apiculture/worldgen/HiveDecorator.java index da2d7e925..f1e209560 100755 --- a/src/main/java/forestry/apiculture/worldgen/HiveDecorator.java +++ b/src/main/java/forestry/apiculture/worldgen/HiveDecorator.java @@ -10,144 +10,148 @@ ******************************************************************************/ package forestry.apiculture.worldgen; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; -import net.minecraft.world.chunk.IChunkProvider; - -import net.minecraftforge.common.util.EnumHelper; -import net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType; -import net.minecraftforge.event.terraingen.TerrainGen; - import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; import forestry.core.config.Config; import forestry.core.config.Constants; import forestry.plugins.PluginApiculture; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import net.minecraft.block.Block; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; +import net.minecraft.world.chunk.IChunkProvider; +import net.minecraftforge.common.util.EnumHelper; +import net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType; +import net.minecraftforge.event.terraingen.TerrainGen; public abstract class HiveDecorator { - @SuppressWarnings("rawtypes") - private static final EventType EVENT_TYPE = EnumHelper.addEnum(EventType.class, "FORESTRY_HIVES", new Class[0], new Object[0]); + @SuppressWarnings("rawtypes") + private static final EventType EVENT_TYPE = + EnumHelper.addEnum(EventType.class, "FORESTRY_HIVES", new Class[0], new Object[0]); - public static void decorateHives(IChunkProvider chunkProvider, World world, Random rand, int chunkX, int chunkZ, boolean hasVillageGenerated) { - if (!TerrainGen.populate(chunkProvider, world, rand, chunkX, chunkZ, hasVillageGenerated, EVENT_TYPE)) { - return; - } + public static void decorateHives( + IChunkProvider chunkProvider, + World world, + Random rand, + int chunkX, + int chunkZ, + boolean hasVillageGenerated) { + if (!TerrainGen.populate(chunkProvider, world, rand, chunkX, chunkZ, hasVillageGenerated, EVENT_TYPE)) { + return; + } - decorateHives(world, rand, chunkX, chunkZ); - } + decorateHives(world, rand, chunkX, chunkZ); + } - public static void decorateHives(World world, Random rand, int chunkX, int chunkZ) { - List hives = PluginApiculture.hiveRegistry.getHives(); + public static void decorateHives(World world, Random rand, int chunkX, int chunkZ) { + List hives = PluginApiculture.hiveRegistry.getHives(); - if (Config.generateBeehivesDebug) { - decorateHivesDebug(world, chunkX, chunkZ, hives); - return; - } + if (Config.generateBeehivesDebug) { + decorateHivesDebug(world, chunkX, chunkZ, hives); + return; + } - Collections.shuffle(hives, rand); - for (Hive hive : hives) { - if (genHive(world, rand, chunkX, chunkZ, hive)) { - return; - } - } - } + Collections.shuffle(hives, rand); + for (Hive hive : hives) { + if (genHive(world, rand, chunkX, chunkZ, hive)) { + return; + } + } + } - public static boolean genHive(World world, Random rand, int chunkX, int chunkZ, Hive hive) { - if (hive.genChance() * Config.getBeehivesAmount() < rand.nextFloat() * 100.0f) { - return false; - } + public static boolean genHive(World world, Random rand, int chunkX, int chunkZ, Hive hive) { + if (hive.genChance() * Config.getBeehivesAmount() < rand.nextFloat() * 100.0f) { + return false; + } - int worldX = chunkX * 16; - int worldZ = chunkZ * 16; + int worldX = chunkX * 16; + int worldZ = chunkZ * 16; - BiomeGenBase biome = world.getBiomeGenForCoords(worldX, worldZ); - EnumHumidity humidity = EnumHumidity.getFromValue(biome.rainfall); + BiomeGenBase biome = world.getBiomeGenForCoords(worldX, worldZ); + EnumHumidity humidity = EnumHumidity.getFromValue(biome.rainfall); - if (!hive.isGoodBiome(biome) || !hive.isGoodHumidity(humidity)) { - return false; - } + if (!hive.isGoodBiome(biome) || !hive.isGoodHumidity(humidity)) { + return false; + } - for (int tries = 0; tries < 4; tries++) { - int x = worldX + rand.nextInt(16); - int z = worldZ + rand.nextInt(16); + for (int tries = 0; tries < 4; tries++) { + int x = worldX + rand.nextInt(16); + int z = worldZ + rand.nextInt(16); - if (tryGenHive(world, x, z, hive)) { - return true; - } - } + if (tryGenHive(world, x, z, hive)) { + return true; + } + } - return false; - } + return false; + } - private static void decorateHivesDebug(World world, int chunkX, int chunkZ, List hives) { - int worldX = chunkX * 16; - int worldZ = chunkZ * 16; - BiomeGenBase biome = world.getBiomeGenForCoords(worldX, worldZ); - EnumHumidity humidity = EnumHumidity.getFromValue(biome.rainfall); + private static void decorateHivesDebug(World world, int chunkX, int chunkZ, List hives) { + int worldX = chunkX * 16; + int worldZ = chunkZ * 16; + BiomeGenBase biome = world.getBiomeGenForCoords(worldX, worldZ); + EnumHumidity humidity = EnumHumidity.getFromValue(biome.rainfall); - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - Collections.shuffle(hives, world.rand); - for (Hive hive : hives) { - if (!hive.isGoodBiome(biome) || !hive.isGoodHumidity(humidity)) { - continue; - } + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + Collections.shuffle(hives, world.rand); + for (Hive hive : hives) { + if (!hive.isGoodBiome(biome) || !hive.isGoodHumidity(humidity)) { + continue; + } - tryGenHive(world, worldX + x, worldZ + z, hive); - } - } - } - } + tryGenHive(world, worldX + x, worldZ + z, hive); + } + } + } + } - private static boolean tryGenHive(World world, int x, int z, Hive hive) { + private static boolean tryGenHive(World world, int x, int z, Hive hive) { - int y = hive.getYForHive(world, x, z); + int y = hive.getYForHive(world, x, z); - if (y < 0) { - return false; - } + if (y < 0) { + return false; + } - if (!hive.canReplace(world, x, y, z)) { - return false; - } + if (!hive.canReplace(world, x, y, z)) { + return false; + } - BiomeGenBase biome = world.getBiomeGenForCoords(x, z); - EnumTemperature temperature = EnumTemperature.getFromValue(biome.getFloatTemperature(x, y, z)); - if (!hive.isGoodTemperature(temperature)) { - return false; - } + BiomeGenBase biome = world.getBiomeGenForCoords(x, z); + EnumTemperature temperature = EnumTemperature.getFromValue(biome.getFloatTemperature(x, y, z)); + if (!hive.isGoodTemperature(temperature)) { + return false; + } - if (!hive.isValidLocation(world, x, y, z)) { - return false; - } + if (!hive.isValidLocation(world, x, y, z)) { + return false; + } - return setHive(world, x, y, z, hive); - } + return setHive(world, x, y, z, hive); + } - private static boolean setHive(World world, int x, int y, int z, Hive hive) { - Block hiveBlock = hive.getHiveBlock(); - boolean placed = world.setBlock(x, y, z, hiveBlock, hive.getHiveMeta(), Constants.FLAG_BLOCK_SYNCH); - if (!placed) { - return false; - } + private static boolean setHive(World world, int x, int y, int z, Hive hive) { + Block hiveBlock = hive.getHiveBlock(); + boolean placed = world.setBlock(x, y, z, hiveBlock, hive.getHiveMeta(), Constants.FLAG_BLOCK_SYNCH); + if (!placed) { + return false; + } - Block placedBlock = world.getBlock(x, y, z); - if (!Block.isEqualTo(hiveBlock, placedBlock)) { - return false; - } + Block placedBlock = world.getBlock(x, y, z); + if (!Block.isEqualTo(hiveBlock, placedBlock)) { + return false; + } - hiveBlock.onBlockAdded(world, x, y, z); - world.markBlockForUpdate(x, y, z); + hiveBlock.onBlockAdded(world, x, y, z); + world.markBlockForUpdate(x, y, z); - if (!Config.generateBeehivesDebug) { - hive.postGen(world, x, y, z); - } - return true; - } + if (!Config.generateBeehivesDebug) { + hive.postGen(world, x, y, z); + } + return true; + } } diff --git a/src/main/java/forestry/apiculture/worldgen/HiveDescription.java b/src/main/java/forestry/apiculture/worldgen/HiveDescription.java index 57b9355d5..437063d2c 100644 --- a/src/main/java/forestry/apiculture/worldgen/HiveDescription.java +++ b/src/main/java/forestry/apiculture/worldgen/HiveDescription.java @@ -1,109 +1,109 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.worldgen; - -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - -import net.minecraftforge.common.BiomeDictionary; - -import forestry.api.apiculture.IBeeGenome; -import forestry.api.apiculture.hives.HiveManager; -import forestry.api.apiculture.hives.IHiveDescription; -import forestry.api.apiculture.hives.IHiveGen; -import forestry.api.core.BiomeHelper; -import forestry.api.core.EnumHumidity; -import forestry.api.core.EnumTemperature; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.EnumTolerance; -import forestry.apiculture.genetics.BeeDefinition; -import forestry.plugins.PluginApiculture; - -public enum HiveDescription implements IHiveDescription { - - FOREST(1, 3.0f, BeeDefinition.FOREST, HiveManager.genHelper.tree()), - MEADOWS(2, 1.0f, BeeDefinition.MEADOWS, HiveManager.genHelper.ground(Blocks.dirt, Blocks.grass)), - DESERT(3, 1.0f, BeeDefinition.MODEST, HiveManager.genHelper.ground(Blocks.dirt, Blocks.grass, Blocks.sand, Blocks.sandstone)), - JUNGLE(4, 4.0f, BeeDefinition.TROPICAL, HiveManager.genHelper.tree()), - END(5, 4.0f, BeeDefinition.ENDED, HiveManager.genHelper.ground(Blocks.end_stone)) { - @Override - public boolean isGoodBiome(BiomeGenBase biome) { - return BiomeDictionary.isBiomeOfType(biome, BiomeDictionary.Type.END); - } - }, - SNOW(6, 2.0f, BeeDefinition.WINTRY, HiveManager.genHelper.ground(Blocks.dirt, Blocks.grass, Blocks.snow)) { - @Override - public void postGen(World world, int x, int y, int z) { - if (world.isAirBlock(x, y + 1, z)) { - world.setBlock(x, y + 1, z, Blocks.snow_layer, 0, 0); - } - } - }, - SWAMP(7, 2.0f, BeeDefinition.MARSHY, HiveManager.genHelper.ground(Blocks.dirt, Blocks.grass)),; - - private final int meta; - private final float genChance; - private final IBeeGenome beeGenome; - private final IHiveGen hiveGen; - - HiveDescription(int meta, float genChance, BeeDefinition beeTemplate, IHiveGen hiveGen) { - this.meta = meta; - this.genChance = genChance; - this.beeGenome = beeTemplate.getGenome(); - this.hiveGen = hiveGen; - } - - @Override - public IHiveGen getHiveGen() { - return hiveGen; - } - - @Override - public Block getBlock() { - return PluginApiculture.blocks.beehives; - } - - @Override - public int getMeta() { - return meta; - } - - @Override - public boolean isGoodBiome(BiomeGenBase biome) { - return !BiomeHelper.isBiomeHellish(biome); - } - - @Override - public boolean isGoodHumidity(EnumHumidity humidity) { - EnumHumidity idealHumidity = beeGenome.getPrimary().getHumidity(); - EnumTolerance humidityTolerance = beeGenome.getToleranceHumid(); - return AlleleManager.climateHelper.isWithinLimits(humidity, idealHumidity, humidityTolerance); - } - - @Override - public boolean isGoodTemperature(EnumTemperature temperature) { - EnumTemperature idealTemperature = beeGenome.getPrimary().getTemperature(); - EnumTolerance temperatureTolerance = beeGenome.getToleranceTemp(); - return AlleleManager.climateHelper.isWithinLimits(temperature, idealTemperature, temperatureTolerance); - } - - @Override - public float getGenChance() { - return genChance; - } - - @Override - public void postGen(World world, int x, int y, int z) { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.worldgen; + +import forestry.api.apiculture.IBeeGenome; +import forestry.api.apiculture.hives.HiveManager; +import forestry.api.apiculture.hives.IHiveDescription; +import forestry.api.apiculture.hives.IHiveGen; +import forestry.api.core.BiomeHelper; +import forestry.api.core.EnumHumidity; +import forestry.api.core.EnumTemperature; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.EnumTolerance; +import forestry.apiculture.genetics.BeeDefinition; +import forestry.plugins.PluginApiculture; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; +import net.minecraftforge.common.BiomeDictionary; + +public enum HiveDescription implements IHiveDescription { + FOREST(1, 3.0f, BeeDefinition.FOREST, HiveManager.genHelper.tree()), + MEADOWS(2, 1.0f, BeeDefinition.MEADOWS, HiveManager.genHelper.ground(Blocks.dirt, Blocks.grass)), + DESERT( + 3, + 1.0f, + BeeDefinition.MODEST, + HiveManager.genHelper.ground(Blocks.dirt, Blocks.grass, Blocks.sand, Blocks.sandstone)), + JUNGLE(4, 4.0f, BeeDefinition.TROPICAL, HiveManager.genHelper.tree()), + END(5, 4.0f, BeeDefinition.ENDED, HiveManager.genHelper.ground(Blocks.end_stone)) { + @Override + public boolean isGoodBiome(BiomeGenBase biome) { + return BiomeDictionary.isBiomeOfType(biome, BiomeDictionary.Type.END); + } + }, + SNOW(6, 2.0f, BeeDefinition.WINTRY, HiveManager.genHelper.ground(Blocks.dirt, Blocks.grass, Blocks.snow)) { + @Override + public void postGen(World world, int x, int y, int z) { + if (world.isAirBlock(x, y + 1, z)) { + world.setBlock(x, y + 1, z, Blocks.snow_layer, 0, 0); + } + } + }, + SWAMP(7, 2.0f, BeeDefinition.MARSHY, HiveManager.genHelper.ground(Blocks.dirt, Blocks.grass)), + ; + + private final int meta; + private final float genChance; + private final IBeeGenome beeGenome; + private final IHiveGen hiveGen; + + HiveDescription(int meta, float genChance, BeeDefinition beeTemplate, IHiveGen hiveGen) { + this.meta = meta; + this.genChance = genChance; + this.beeGenome = beeTemplate.getGenome(); + this.hiveGen = hiveGen; + } + + @Override + public IHiveGen getHiveGen() { + return hiveGen; + } + + @Override + public Block getBlock() { + return PluginApiculture.blocks.beehives; + } + + @Override + public int getMeta() { + return meta; + } + + @Override + public boolean isGoodBiome(BiomeGenBase biome) { + return !BiomeHelper.isBiomeHellish(biome); + } + + @Override + public boolean isGoodHumidity(EnumHumidity humidity) { + EnumHumidity idealHumidity = beeGenome.getPrimary().getHumidity(); + EnumTolerance humidityTolerance = beeGenome.getToleranceHumid(); + return AlleleManager.climateHelper.isWithinLimits(humidity, idealHumidity, humidityTolerance); + } + + @Override + public boolean isGoodTemperature(EnumTemperature temperature) { + EnumTemperature idealTemperature = beeGenome.getPrimary().getTemperature(); + EnumTolerance temperatureTolerance = beeGenome.getToleranceTemp(); + return AlleleManager.climateHelper.isWithinLimits(temperature, idealTemperature, temperatureTolerance); + } + + @Override + public float getGenChance() { + return genChance; + } + + @Override + public void postGen(World world, int x, int y, int z) {} +} diff --git a/src/main/java/forestry/apiculture/worldgen/HiveDescriptionSwarmer.java b/src/main/java/forestry/apiculture/worldgen/HiveDescriptionSwarmer.java index 08fc5e643..233d635b0 100644 --- a/src/main/java/forestry/apiculture/worldgen/HiveDescriptionSwarmer.java +++ b/src/main/java/forestry/apiculture/worldgen/HiveDescriptionSwarmer.java @@ -10,6 +10,12 @@ ******************************************************************************/ package forestry.apiculture.worldgen; +import forestry.api.apiculture.hives.IHiveDescription; +import forestry.api.apiculture.hives.IHiveGen; +import forestry.api.core.EnumHumidity; +import forestry.api.core.EnumTemperature; +import forestry.apiculture.tiles.TileSwarm; +import forestry.plugins.PluginApiculture; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; @@ -17,61 +23,54 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; -import forestry.api.apiculture.hives.IHiveDescription; -import forestry.api.apiculture.hives.IHiveGen; -import forestry.api.core.EnumHumidity; -import forestry.api.core.EnumTemperature; -import forestry.apiculture.tiles.TileSwarm; -import forestry.plugins.PluginApiculture; - public class HiveDescriptionSwarmer implements IHiveDescription { - private final ItemStack[] bees; + private final ItemStack[] bees; - public HiveDescriptionSwarmer(ItemStack... bees) { - this.bees = bees; - } + public HiveDescriptionSwarmer(ItemStack... bees) { + this.bees = bees; + } - @Override - public IHiveGen getHiveGen() { - return new HiveGenGround(Blocks.dirt, Blocks.grass); - } + @Override + public IHiveGen getHiveGen() { + return new HiveGenGround(Blocks.dirt, Blocks.grass); + } - @Override - public Block getBlock() { - return PluginApiculture.blocks.beehives; - } + @Override + public Block getBlock() { + return PluginApiculture.blocks.beehives; + } - @Override - public int getMeta() { - return 8; - } + @Override + public int getMeta() { + return 8; + } - @Override - public boolean isGoodBiome(BiomeGenBase biome) { - return true; - } + @Override + public boolean isGoodBiome(BiomeGenBase biome) { + return true; + } - @Override - public boolean isGoodHumidity(EnumHumidity humidity) { - return true; - } + @Override + public boolean isGoodHumidity(EnumHumidity humidity) { + return true; + } - @Override - public boolean isGoodTemperature(EnumTemperature temperature) { - return true; - } + @Override + public boolean isGoodTemperature(EnumTemperature temperature) { + return true; + } - @Override - public float getGenChance() { - return 128.0f; - } + @Override + public float getGenChance() { + return 128.0f; + } - @Override - public void postGen(World world, int x, int y, int z) { - TileEntity tile = world.getTileEntity(x, y, z); - if (tile instanceof TileSwarm) { - ((TileSwarm) tile).setContained(bees); - } - } + @Override + public void postGen(World world, int x, int y, int z) { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile instanceof TileSwarm) { + ((TileSwarm) tile).setContained(bees); + } + } } diff --git a/src/main/java/forestry/apiculture/worldgen/HiveGen.java b/src/main/java/forestry/apiculture/worldgen/HiveGen.java index 4eadb38c9..61e67ee3b 100644 --- a/src/main/java/forestry/apiculture/worldgen/HiveGen.java +++ b/src/main/java/forestry/apiculture/worldgen/HiveGen.java @@ -1,29 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.worldgen; - -import net.minecraft.block.Block; -import net.minecraft.block.material.Material; -import net.minecraft.world.World; - -import forestry.api.apiculture.hives.IHiveGen; - -public abstract class HiveGen implements IHiveGen { - - @Override - public boolean canReplace(World world, int x, int y, int z) { - Block block = world.getBlock(x, y, z); - Material material = block.getMaterial(); - return (material.isReplaceable() && !material.isLiquid()) || - material == Material.air || - material == Material.plants; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.worldgen; + +import forestry.api.apiculture.hives.IHiveGen; +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.world.World; + +public abstract class HiveGen implements IHiveGen { + + @Override + public boolean canReplace(World world, int x, int y, int z) { + Block block = world.getBlock(x, y, z); + Material material = block.getMaterial(); + return (material.isReplaceable() && !material.isLiquid()) + || material == Material.air + || material == Material.plants; + } +} diff --git a/src/main/java/forestry/apiculture/worldgen/HiveGenGround.java b/src/main/java/forestry/apiculture/worldgen/HiveGenGround.java index 280f25436..178a9319e 100644 --- a/src/main/java/forestry/apiculture/worldgen/HiveGenGround.java +++ b/src/main/java/forestry/apiculture/worldgen/HiveGenGround.java @@ -1,47 +1,46 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.worldgen; - -import java.util.HashSet; -import java.util.Set; - -import net.minecraft.block.Block; -import net.minecraft.block.material.Material; -import net.minecraft.world.World; - -public class HiveGenGround extends HiveGen { - - private final Set groundMaterials = new HashSet<>(); - - public HiveGenGround(Block... groundBlocks) { - for (Block block : groundBlocks) { - groundMaterials.add(block.getMaterial()); - } - } - - @Override - public boolean isValidLocation(World world, int x, int y, int z) { - Block ground = world.getBlock(x, y - 1, z); - return groundMaterials.contains(ground.getMaterial()); - } - - @Override - public int getYForHive(World world, int x, int z) { - int y = world.getHeightValue(x, z); - - // get to the ground - while (y >= 0 && (world.getBlock(x, y - 1, z).isLeaves(world, x, y - 1, z) || canReplace(world, x, y - 1, z))) { - y--; - } - - return y; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.worldgen; + +import java.util.HashSet; +import java.util.Set; +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.world.World; + +public class HiveGenGround extends HiveGen { + + private final Set groundMaterials = new HashSet<>(); + + public HiveGenGround(Block... groundBlocks) { + for (Block block : groundBlocks) { + groundMaterials.add(block.getMaterial()); + } + } + + @Override + public boolean isValidLocation(World world, int x, int y, int z) { + Block ground = world.getBlock(x, y - 1, z); + return groundMaterials.contains(ground.getMaterial()); + } + + @Override + public int getYForHive(World world, int x, int z) { + int y = world.getHeightValue(x, z); + + // get to the ground + while (y >= 0 && (world.getBlock(x, y - 1, z).isLeaves(world, x, y - 1, z) || canReplace(world, x, y - 1, z))) { + y--; + } + + return y; + } +} diff --git a/src/main/java/forestry/apiculture/worldgen/HiveGenHelper.java b/src/main/java/forestry/apiculture/worldgen/HiveGenHelper.java index a253b3950..cde38a043 100644 --- a/src/main/java/forestry/apiculture/worldgen/HiveGenHelper.java +++ b/src/main/java/forestry/apiculture/worldgen/HiveGenHelper.java @@ -1,31 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.worldgen; - -import net.minecraft.block.Block; - -import forestry.api.apiculture.hives.IHiveGen; -import forestry.api.apiculture.hives.IHiveGenHelper; - -public class HiveGenHelper implements IHiveGenHelper { - - private static final IHiveGen treeGen = new HiveGenTree(); - - @Override - public IHiveGen ground(Block... validGroundBlocks) { - return new HiveGenGround(validGroundBlocks); - } - - @Override - public IHiveGen tree() { - return treeGen; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.worldgen; + +import forestry.api.apiculture.hives.IHiveGen; +import forestry.api.apiculture.hives.IHiveGenHelper; +import net.minecraft.block.Block; + +public class HiveGenHelper implements IHiveGenHelper { + + private static final IHiveGen treeGen = new HiveGenTree(); + + @Override + public IHiveGen ground(Block... validGroundBlocks) { + return new HiveGenGround(validGroundBlocks); + } + + @Override + public IHiveGen tree() { + return treeGen; + } +} diff --git a/src/main/java/forestry/apiculture/worldgen/HiveGenTree.java b/src/main/java/forestry/apiculture/worldgen/HiveGenTree.java index cf3841fd9..aa2781dfe 100644 --- a/src/main/java/forestry/apiculture/worldgen/HiveGenTree.java +++ b/src/main/java/forestry/apiculture/worldgen/HiveGenTree.java @@ -1,44 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.worldgen; - -import net.minecraft.block.Block; -import net.minecraft.world.World; - -public class HiveGenTree extends HiveGen { - - @Override - public boolean isValidLocation(World world, int x, int y, int z) { - Block blockAbove = world.getBlock(x, y + 1, z); - if (!blockAbove.isLeaves(world, x, y + 1, z)) { - return false; - } - - // not a good location if right on top of something - return canReplace(world, x, y - 1, z); - } - - @Override - public int getYForHive(World world, int x, int z) { - // get top leaf block - int y = world.getHeightValue(x, z) - 1; - if (!world.getBlock(x, y, z).isLeaves(world, x, y, z)) { - return -1; - } - - // get to the bottom of the leaves - do { - y--; - } while (world.getBlock(x, y, z).isLeaves(world, x, y, z)); - - return y; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.worldgen; + +import net.minecraft.block.Block; +import net.minecraft.world.World; + +public class HiveGenTree extends HiveGen { + + @Override + public boolean isValidLocation(World world, int x, int y, int z) { + Block blockAbove = world.getBlock(x, y + 1, z); + if (!blockAbove.isLeaves(world, x, y + 1, z)) { + return false; + } + + // not a good location if right on top of something + return canReplace(world, x, y - 1, z); + } + + @Override + public int getYForHive(World world, int x, int z) { + // get top leaf block + int y = world.getHeightValue(x, z) - 1; + if (!world.getBlock(x, y, z).isLeaves(world, x, y, z)) { + return -1; + } + + // get to the bottom of the leaves + do { + y--; + } while (world.getBlock(x, y, z).isLeaves(world, x, y, z)); + + return y; + } +} diff --git a/src/main/java/forestry/apiculture/worldgen/HiveRegistry.java b/src/main/java/forestry/apiculture/worldgen/HiveRegistry.java index 5ec9dceb7..a10213dfa 100644 --- a/src/main/java/forestry/apiculture/worldgen/HiveRegistry.java +++ b/src/main/java/forestry/apiculture/worldgen/HiveRegistry.java @@ -10,55 +10,54 @@ ******************************************************************************/ package forestry.apiculture.worldgen; +import forestry.api.apiculture.IHiveDrop; +import forestry.api.apiculture.hives.IHiveDescription; +import forestry.api.apiculture.hives.IHiveRegistry; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import forestry.api.apiculture.IHiveDrop; -import forestry.api.apiculture.hives.IHiveDescription; -import forestry.api.apiculture.hives.IHiveRegistry; - public class HiveRegistry implements IHiveRegistry { - private final Map hives = new HashMap<>(); + private final Map hives = new HashMap<>(); - @Override - public void registerHive(String hiveName, IHiveDescription hiveDescription) { - if (hives.containsKey(hiveName)) { - throw new IllegalArgumentException("Hive already exists with name: " + hiveName); - } + @Override + public void registerHive(String hiveName, IHiveDescription hiveDescription) { + if (hives.containsKey(hiveName)) { + throw new IllegalArgumentException("Hive already exists with name: " + hiveName); + } - Hive hive = new Hive(hiveDescription); - hives.put(hiveName, hive); - } + Hive hive = new Hive(hiveDescription); + hives.put(hiveName, hive); + } - @Override - public void addDrops(String hiveName, IHiveDrop... drops) { - addDrops(hiveName, Arrays.asList(drops)); - } + @Override + public void addDrops(String hiveName, IHiveDrop... drops) { + addDrops(hiveName, Arrays.asList(drops)); + } - @Override - public void addDrops(String hiveName, List drops) { - Hive hive = hives.get(hiveName); - if (hive == null) { - throw new IllegalArgumentException("No hive registered with name: " + hiveName); - } + @Override + public void addDrops(String hiveName, List drops) { + Hive hive = hives.get(hiveName); + if (hive == null) { + throw new IllegalArgumentException("No hive registered with name: " + hiveName); + } - hive.addDrops(drops); - } + hive.addDrops(drops); + } - public List getHives() { - return new ArrayList<>(hives.values()); - } + public List getHives() { + return new ArrayList<>(hives.values()); + } - public List getDrops(String hiveName) { - Hive hive = hives.get(hiveName); - if (hive == null) { - throw new IllegalArgumentException("No hive registered with name: " + hiveName); - } + public List getDrops(String hiveName) { + Hive hive = hives.get(hiveName); + if (hive == null) { + throw new IllegalArgumentException("No hive registered with name: " + hiveName); + } - return hive.getDrops(); - } + return hive.getDrops(); + } } diff --git a/src/main/java/forestry/arboriculture/FruitProviderNone.java b/src/main/java/forestry/arboriculture/FruitProviderNone.java index 507e865f0..f268d4cb7 100755 --- a/src/main/java/forestry/arboriculture/FruitProviderNone.java +++ b/src/main/java/forestry/arboriculture/FruitProviderNone.java @@ -10,124 +10,122 @@ ******************************************************************************/ package forestry.arboriculture; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.arboriculture.IFruitProvider; +import forestry.api.arboriculture.ITreeGenome; +import forestry.api.genetics.IFruitFamily; +import forestry.core.render.TextureManager; import java.util.HashMap; - import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.arboriculture.IFruitProvider; -import forestry.api.arboriculture.ITreeGenome; -import forestry.api.genetics.IFruitFamily; -import forestry.core.render.TextureManager; - public class FruitProviderNone implements IFruitProvider { - private static class OverlayType { - public final String ident; - public final short texUID; + private static class OverlayType { + public final String ident; + public final short texUID; - public OverlayType(String ident, short texUID) { - this.ident = ident; - this.texUID = texUID; - } - } + public OverlayType(String ident, short texUID) { + this.ident = ident; + this.texUID = texUID; + } + } - private static final HashMap overlayTypes = new HashMap<>(); + private static final HashMap overlayTypes = new HashMap<>(); - static { - overlayTypes.put("berries", new OverlayType("berries", (short) 1000)); - overlayTypes.put("pomes", new OverlayType("pomes", (short) 1001)); - overlayTypes.put("nuts", new OverlayType("nuts", (short) 1002)); - overlayTypes.put("citrus", new OverlayType("citrus", (short) 1003)); - overlayTypes.put("plums", new OverlayType("plums", (short) 1004)); - } + static { + overlayTypes.put("berries", new OverlayType("berries", (short) 1000)); + overlayTypes.put("pomes", new OverlayType("pomes", (short) 1001)); + overlayTypes.put("nuts", new OverlayType("nuts", (short) 1002)); + overlayTypes.put("citrus", new OverlayType("citrus", (short) 1003)); + overlayTypes.put("plums", new OverlayType("plums", (short) 1004)); + } - private final String key; - private final IFruitFamily family; + private final String key; + private final IFruitFamily family; - protected int ripeningPeriod = 10; + protected int ripeningPeriod = 10; - private OverlayType overlay = null; + private OverlayType overlay = null; - public FruitProviderNone(String key, IFruitFamily family) { - this.key = key; - this.family = family; - } + public FruitProviderNone(String key, IFruitFamily family) { + this.key = key; + this.family = family; + } - public IFruitProvider setOverlay(String ident) { - overlay = overlayTypes.get(ident); - return this; - } + public IFruitProvider setOverlay(String ident) { + overlay = overlayTypes.get(ident); + return this; + } - @Override - public IFruitFamily getFamily() { - return family; - } + @Override + public IFruitFamily getFamily() { + return family; + } - @Override - public ItemStack[] getFruits(ITreeGenome genome, World world, int x, int y, int z, int ripeningTime) { - return new ItemStack[0]; - } + @Override + public ItemStack[] getFruits(ITreeGenome genome, World world, int x, int y, int z, int ripeningTime) { + return new ItemStack[0]; + } - @Override - public boolean requiresFruitBlocks() { - return false; - } + @Override + public boolean requiresFruitBlocks() { + return false; + } - @Override - public boolean trySpawnFruitBlock(ITreeGenome genome, World world, int x, int y, int z) { - return false; - } + @Override + public boolean trySpawnFruitBlock(ITreeGenome genome, World world, int x, int y, int z) { + return false; + } - @Override - public int getColour(ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime) { - return 0xffffff; - } + @Override + public int getColour(ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime) { + return 0xffffff; + } - @Override - public boolean markAsFruitLeaf(ITreeGenome genome, World world, int x, int y, int z) { - return false; - } + @Override + public boolean markAsFruitLeaf(ITreeGenome genome, World world, int x, int y, int z) { + return false; + } - @Override - public int getRipeningPeriod() { - return ripeningPeriod; - } + @Override + public int getRipeningPeriod() { + return ripeningPeriod; + } - @Override - public ItemStack[] getProducts() { - return new ItemStack[0]; - } + @Override + public ItemStack[] getProducts() { + return new ItemStack[0]; + } - @Override - public ItemStack[] getSpecialty() { - return new ItemStack[0]; - } + @Override + public ItemStack[] getSpecialty() { + return new ItemStack[0]; + } - @Override - public String getDescription() { - return "fruits." + key; - } + @Override + public String getDescription() { + return "fruits." + key; + } - @Override - public short getIconIndex(ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime, boolean fancy) { - if (overlay != null) { - return overlay.texUID; - } else { - return -1; - } - } + @Override + public short getIconIndex( + ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime, boolean fancy) { + if (overlay != null) { + return overlay.texUID; + } else { + return -1; + } + } - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IIconRegister register) { - if (overlay != null) { - TextureManager.registerTexUID(register, overlay.texUID, "leaves/fruits." + overlay.ident); - } - } + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IIconRegister register) { + if (overlay != null) { + TextureManager.registerTexUID(register, overlay.texUID, "leaves/fruits." + overlay.ident); + } + } } diff --git a/src/main/java/forestry/arboriculture/FruitProviderPod.java b/src/main/java/forestry/arboriculture/FruitProviderPod.java index 7ec9e3de1..5b38ffbb9 100755 --- a/src/main/java/forestry/arboriculture/FruitProviderPod.java +++ b/src/main/java/forestry/arboriculture/FruitProviderPod.java @@ -10,17 +10,8 @@ ******************************************************************************/ package forestry.arboriculture; -import java.util.Locale; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleFruit; import forestry.api.arboriculture.ITreeGenome; @@ -28,89 +19,102 @@ import forestry.api.arboriculture.TreeManager; import forestry.api.genetics.IFruitFamily; import forestry.core.render.TextureManager; import forestry.core.utils.BlockUtil; +import java.util.Locale; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; public class FruitProviderPod extends FruitProviderNone { - public enum EnumPodType { - COCOA((short) 2000, (short) 2001, (short) 2002), DATES((short) 2010, (short) 2011, (short) 2012), - PAPAYA((short) 2013, (short) 2014, (short) 2015);//, COCONUT((short)2016, (short)2017, (short)2018); + public enum EnumPodType { + COCOA((short) 2000, (short) 2001, (short) 2002), + DATES((short) 2010, (short) 2011, (short) 2012), + PAPAYA((short) 2013, (short) 2014, (short) 2015); // , COCONUT((short)2016, (short)2017, (short)2018); - public final short[] uids; + public final short[] uids; - EnumPodType(short stage1, short stage2, short stage3) { - uids = new short[]{stage1, stage2, stage3}; - } + EnumPodType(short stage1, short stage2, short stage3) { + uids = new short[] {stage1, stage2, stage3}; + } - @SideOnly(Side.CLIENT) - public void registerIcons(IIconRegister register) { - if (this == COCOA) { - return; - } + @SideOnly(Side.CLIENT) + public void registerIcons(IIconRegister register) { + if (this == COCOA) { + return; + } - String name = toString().toLowerCase(Locale.ENGLISH); - for (int i = 0; i < 3; i++) { - TextureManager.registerTexUID(register, uids[i], "pods/" + name + "." + i); - } - } - } + String name = toString().toLowerCase(Locale.ENGLISH); + for (int i = 0; i < 3; i++) { + TextureManager.registerTexUID(register, uids[i], "pods/" + name + "." + i); + } + } + } - private static final ItemStack[] DUMMY = new ItemStack[0]; + private static final ItemStack[] DUMMY = new ItemStack[0]; - private final EnumPodType type; - private final ItemStack[] drop; + private final EnumPodType type; + private final ItemStack[] drop; - public FruitProviderPod(String key, IFruitFamily family, EnumPodType type, ItemStack... dropOnMature) { - super(key, family); - this.type = type; - this.drop = dropOnMature; - } + public FruitProviderPod(String key, IFruitFamily family, EnumPodType type, ItemStack... dropOnMature) { + super(key, family); + this.type = type; + this.drop = dropOnMature; + } - @Override - public boolean requiresFruitBlocks() { - return true; - } + @Override + public boolean requiresFruitBlocks() { + return true; + } - @Override - public ItemStack[] getFruits(ITreeGenome genome, World world, int x, int y, int z, int ripeningTime) { - if (drop == null || drop.length == 0) { - return DUMMY; - } + @Override + public ItemStack[] getFruits(ITreeGenome genome, World world, int x, int y, int z, int ripeningTime) { + if (drop == null || drop.length == 0) { + return DUMMY; + } - if (ripeningTime >= 2) { - ItemStack[] dropping = new ItemStack[drop.length]; - for (int i = 0; i < drop.length; i++) { - dropping[i] = drop[i].copy(); - } - return dropping; - } + if (ripeningTime >= 2) { + ItemStack[] dropping = new ItemStack[drop.length]; + for (int i = 0; i < drop.length; i++) { + dropping[i] = drop[i].copy(); + } + return dropping; + } - return DUMMY; - } + return DUMMY; + } - @Override - public boolean trySpawnFruitBlock(ITreeGenome genome, World world, int x, int y, int z) { + @Override + public boolean trySpawnFruitBlock(ITreeGenome genome, World world, int x, int y, int z) { - if (world.rand.nextFloat() > genome.getSappiness()) { - return false; - } + if (world.rand.nextFloat() > genome.getSappiness()) { + return false; + } - if (type == EnumPodType.COCOA) { - return BlockUtil.tryPlantPot(world, x, y, z, Blocks.cocoa); - } else { - return TreeManager.treeRoot.setFruitBlock(world, (IAlleleFruit) genome.getActiveAllele(EnumTreeChromosome.FRUITS), - genome.getSappiness(), type.uids, x, y, z); - } - } + if (type == EnumPodType.COCOA) { + return BlockUtil.tryPlantPot(world, x, y, z, Blocks.cocoa); + } else { + return TreeManager.treeRoot.setFruitBlock( + world, + (IAlleleFruit) genome.getActiveAllele(EnumTreeChromosome.FRUITS), + genome.getSappiness(), + type.uids, + x, + y, + z); + } + } - @Override - public short getIconIndex(ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime, boolean fancy) { - return type.uids[0]; - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IIconRegister register) { - type.registerIcons(register); - } + @Override + public short getIconIndex( + ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime, boolean fancy) { + return type.uids[0]; + } + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IIconRegister register) { + type.registerIcons(register); + } } diff --git a/src/main/java/forestry/arboriculture/FruitProviderRandom.java b/src/main/java/forestry/arboriculture/FruitProviderRandom.java index 31291be08..a7b6ff8cd 100755 --- a/src/main/java/forestry/arboriculture/FruitProviderRandom.java +++ b/src/main/java/forestry/arboriculture/FruitProviderRandom.java @@ -10,71 +10,68 @@ ******************************************************************************/ package forestry.arboriculture; +import forestry.api.arboriculture.ITreeGenome; +import forestry.api.arboriculture.TreeManager; +import forestry.api.genetics.IFruitFamily; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; - import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import forestry.api.arboriculture.ITreeGenome; -import forestry.api.arboriculture.TreeManager; -import forestry.api.genetics.IFruitFamily; - /** * Simple fruit provider which drops from any leaf block according to yield and either marks all leave blocks as fruit leaves or none. */ public class FruitProviderRandom extends FruitProviderNone { - private final Map products = new HashMap<>(); - private int colour = 0xffffff; + private final Map products = new HashMap<>(); + private int colour = 0xffffff; - public FruitProviderRandom(String key, IFruitFamily family, ItemStack product, float modifier) { - super(key, family); - products.put(product, modifier); - } + public FruitProviderRandom(String key, IFruitFamily family, ItemStack product, float modifier) { + super(key, family); + products.put(product, modifier); + } - public FruitProviderRandom setColour(int colour) { - this.colour = colour; - return this; - } + public FruitProviderRandom setColour(int colour) { + this.colour = colour; + return this; + } - @Override - public int getColour(ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime) { - return colour; - } + @Override + public int getColour(ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime) { + return colour; + } - @Override - public ItemStack[] getFruits(ITreeGenome genome, World world, int x, int y, int z, int ripeningTime) { - ArrayList product = new ArrayList<>(); + @Override + public ItemStack[] getFruits(ITreeGenome genome, World world, int x, int y, int z, int ripeningTime) { + ArrayList product = new ArrayList<>(); - float modeYieldMod = TreeManager.treeRoot.getTreekeepingMode(world).getYieldModifier(genome, 1f); + float modeYieldMod = TreeManager.treeRoot.getTreekeepingMode(world).getYieldModifier(genome, 1f); - for (Map.Entry entry : products.entrySet()) { - if (world.rand.nextFloat() <= genome.getYield() * modeYieldMod * entry.getValue()) { - product.add(entry.getKey().copy()); - } - } + for (Map.Entry entry : products.entrySet()) { + if (world.rand.nextFloat() <= genome.getYield() * modeYieldMod * entry.getValue()) { + product.add(entry.getKey().copy()); + } + } - return product.toArray(new ItemStack[product.size()]); - } + return product.toArray(new ItemStack[product.size()]); + } - @Override - public ItemStack[] getProducts() { - Set products = this.products.keySet(); - return products.toArray(new ItemStack[products.size()]); - } + @Override + public ItemStack[] getProducts() { + Set products = this.products.keySet(); + return products.toArray(new ItemStack[products.size()]); + } - @Override - public ItemStack[] getSpecialty() { - return new ItemStack[0]; - } - - @Override - public boolean markAsFruitLeaf(ITreeGenome genome, World world, int x, int y, int z) { - return true; - } + @Override + public ItemStack[] getSpecialty() { + return new ItemStack[0]; + } + @Override + public boolean markAsFruitLeaf(ITreeGenome genome, World world, int x, int y, int z) { + return true; + } } diff --git a/src/main/java/forestry/arboriculture/FruitProviderRipening.java b/src/main/java/forestry/arboriculture/FruitProviderRipening.java index fbd7fe7a7..227b07072 100755 --- a/src/main/java/forestry/arboriculture/FruitProviderRipening.java +++ b/src/main/java/forestry/arboriculture/FruitProviderRipening.java @@ -10,104 +10,101 @@ ******************************************************************************/ package forestry.arboriculture; +import forestry.api.arboriculture.ITreeGenome; +import forestry.api.arboriculture.TreeManager; +import forestry.api.genetics.IFruitFamily; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; - import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import forestry.api.arboriculture.ITreeGenome; -import forestry.api.arboriculture.TreeManager; -import forestry.api.genetics.IFruitFamily; - public class FruitProviderRipening extends FruitProviderNone { - private final Map products = new HashMap<>(); + private final Map products = new HashMap<>(); - private int colourCallow = 0xffffff; + private int colourCallow = 0xffffff; - private int diffR; - private int diffG; - private int diffB; + private int diffR; + private int diffG; + private int diffB; - public FruitProviderRipening(String key, IFruitFamily family, ItemStack product, float modifier) { - super(key, family); - products.put(product, modifier); - } + public FruitProviderRipening(String key, IFruitFamily family, ItemStack product, float modifier) { + super(key, family); + products.put(product, modifier); + } - public FruitProviderRipening setColours(int ripe, int callow) { - colourCallow = callow; + public FruitProviderRipening setColours(int ripe, int callow) { + colourCallow = callow; - diffR = (ripe >> 16 & 255) - (callow >> 16 & 255); - diffG = (ripe >> 8 & 255) - (callow >> 8 & 255); - diffB = (ripe & 255) - (callow & 255); + diffR = (ripe >> 16 & 255) - (callow >> 16 & 255); + diffG = (ripe >> 8 & 255) - (callow >> 8 & 255); + diffB = (ripe & 255) - (callow & 255); - return this; - } + return this; + } - public FruitProviderRipening setRipeningPeriod(int period) { - ripeningPeriod = period; - return this; - } + public FruitProviderRipening setRipeningPeriod(int period) { + ripeningPeriod = period; + return this; + } - private float getRipeningStage(int ripeningTime) { - if (ripeningTime >= ripeningPeriod) { - return 1.0f; - } + private float getRipeningStage(int ripeningTime) { + if (ripeningTime >= ripeningPeriod) { + return 1.0f; + } - return (float) ripeningTime / ripeningPeriod; - } + return (float) ripeningTime / ripeningPeriod; + } - @Override - public ItemStack[] getFruits(ITreeGenome genome, World world, int x, int y, int z, int ripeningTime) { - ArrayList product = new ArrayList<>(); + @Override + public ItemStack[] getFruits(ITreeGenome genome, World world, int x, int y, int z, int ripeningTime) { + ArrayList product = new ArrayList<>(); - float stage = getRipeningStage(ripeningTime); - if (stage < 0.5f) { - return new ItemStack[0]; - } + float stage = getRipeningStage(ripeningTime); + if (stage < 0.5f) { + return new ItemStack[0]; + } - float modeYieldMod = TreeManager.treeRoot.getTreekeepingMode(world).getYieldModifier(genome, 1f); + float modeYieldMod = TreeManager.treeRoot.getTreekeepingMode(world).getYieldModifier(genome, 1f); - for (Map.Entry entry : products.entrySet()) { - if (world.rand.nextFloat() <= genome.getYield() * entry.getValue() * modeYieldMod * 5.0f * stage) { - product.add(entry.getKey().copy()); - } - } + for (Map.Entry entry : products.entrySet()) { + if (world.rand.nextFloat() <= genome.getYield() * entry.getValue() * modeYieldMod * 5.0f * stage) { + product.add(entry.getKey().copy()); + } + } - return product.toArray(new ItemStack[product.size()]); - } + return product.toArray(new ItemStack[product.size()]); + } - @Override - public ItemStack[] getProducts() { - Set products = this.products.keySet(); - return products.toArray(new ItemStack[products.size()]); - } + @Override + public ItemStack[] getProducts() { + Set products = this.products.keySet(); + return products.toArray(new ItemStack[products.size()]); + } - @Override - public ItemStack[] getSpecialty() { - return new ItemStack[0]; - } + @Override + public ItemStack[] getSpecialty() { + return new ItemStack[0]; + } - @Override - public boolean markAsFruitLeaf(ITreeGenome genome, World world, int x, int y, int z) { - return true; - } + @Override + public boolean markAsFruitLeaf(ITreeGenome genome, World world, int x, int y, int z) { + return true; + } - @Override - public int getColour(ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime) { - float stage = getRipeningStage(ripeningTime); + @Override + public int getColour(ITreeGenome genome, IBlockAccess world, int x, int y, int z, int ripeningTime) { + float stage = getRipeningStage(ripeningTime); - int r = (colourCallow >> 16 & 255) + (int) (diffR * stage); - int g = (colourCallow >> 8 & 255) + (int) (diffG * stage); - int b = (colourCallow & 255) + (int) (diffB * stage); - - // System.out.println(String.format("Calcultated rgb %s/%s/%s from %s and %s, resulting in %s", - // r, g, b, colourCallow, stage, (r & 255) << 16 | (g & 255) << 8 | b & 255)); - return (r & 255) << 16 | (g & 255) << 8 | b & 255; - } + int r = (colourCallow >> 16 & 255) + (int) (diffR * stage); + int g = (colourCallow >> 8 & 255) + (int) (diffG * stage); + int b = (colourCallow & 255) + (int) (diffB * stage); + // System.out.println(String.format("Calcultated rgb %s/%s/%s from %s and %s, resulting in %s", + // r, g, b, colourCallow, stage, (r & 255) << 16 | (g & 255) << 8 | b & 255)); + return (r & 255) << 16 | (g & 255) << 8 | b & 255; + } } diff --git a/src/main/java/forestry/arboriculture/IWoodTyped.java b/src/main/java/forestry/arboriculture/IWoodTyped.java index 70b509857..e5d6a1465 100755 --- a/src/main/java/forestry/arboriculture/IWoodTyped.java +++ b/src/main/java/forestry/arboriculture/IWoodTyped.java @@ -11,7 +11,7 @@ package forestry.arboriculture; public interface IWoodTyped { - String getBlockKind(); + String getBlockKind(); - boolean isFireproof(); + boolean isFireproof(); } diff --git a/src/main/java/forestry/arboriculture/LeafDecayHelper.java b/src/main/java/forestry/arboriculture/LeafDecayHelper.java index baefc5d23..689dc481c 100644 --- a/src/main/java/forestry/arboriculture/LeafDecayHelper.java +++ b/src/main/java/forestry/arboriculture/LeafDecayHelper.java @@ -1,96 +1,167 @@ -package forestry.arboriculture; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockLeaves; -import net.minecraft.world.World; - -/** Based on vanilla leaf decay, but accepts leaves that are connected further from a trunk */ -public abstract class LeafDecayHelper { - private static final short SUSTAINS_LEAVES = 0; - private static final short NOT_SUSTAINS_LEAVES = -1; - private static final short IS_LEAVES = -2; - private static int[] leafDecayValues; - - public static void leafDecay(BlockLeaves leaves, World world, int x, int y, int z) { - if (world.isRemote) { - return; - } - - int leafMeta = world.getBlockMetadata(x, y, z); - - if ((leafMeta & 8) != 0 && (leafMeta & 4) == 0) { - byte radius = 4; - byte yArrayMult = 32; - int xArrayMult = yArrayMult * yArrayMult; - int arrayOffset = yArrayMult / 2; - - if (leafDecayValues == null) { - leafDecayValues = new int[yArrayMult * yArrayMult * yArrayMult]; - } - - int radius1 = radius + 1; - if (world.checkChunksExist(x - radius1, y - radius1, z - radius1, x + radius1, y + radius1, z + radius1)) { - for (int xOffset = -radius; xOffset <= radius; ++xOffset) { - for (int yOffset = -radius; yOffset <= radius; ++yOffset) { - for (int zOffset = -radius; zOffset <= radius; ++zOffset) { - Block block = world.getBlock(x + xOffset, y + yOffset, z + zOffset); - - if (!block.canSustainLeaves(world, x + xOffset, y + yOffset, z + zOffset)) { - if (block.isLeaves(world, x + xOffset, y + yOffset, z + zOffset)) { - leafDecayValues[(xOffset + arrayOffset) * xArrayMult + (yOffset + arrayOffset) * yArrayMult + zOffset + arrayOffset] = IS_LEAVES; - } else { - leafDecayValues[(xOffset + arrayOffset) * xArrayMult + (yOffset + arrayOffset) * yArrayMult + zOffset + arrayOffset] = NOT_SUSTAINS_LEAVES; - } - } else { - leafDecayValues[(xOffset + arrayOffset) * xArrayMult + (yOffset + arrayOffset) * yArrayMult + zOffset + arrayOffset] = SUSTAINS_LEAVES; - } - } - } - } - - for (int sustainedValue = 1; sustainedValue <= 8; ++sustainedValue) { - for (int xOffset = -radius; xOffset <= radius; ++xOffset) { - for (int yOffset = -radius; yOffset <= radius; ++yOffset) { - for (int zOffset = -radius; zOffset <= radius; ++zOffset) { - if (leafDecayValues[(xOffset + arrayOffset) * xArrayMult + (yOffset + arrayOffset) * yArrayMult + zOffset + arrayOffset] == sustainedValue - 1) { - if (leafDecayValues[(xOffset + arrayOffset - 1) * xArrayMult + (yOffset + arrayOffset) * yArrayMult + zOffset + arrayOffset] == IS_LEAVES) { - leafDecayValues[(xOffset + arrayOffset - 1) * xArrayMult + (yOffset + arrayOffset) * yArrayMult + zOffset + arrayOffset] = sustainedValue; - } - - if (leafDecayValues[(xOffset + arrayOffset + 1) * xArrayMult + (yOffset + arrayOffset) * yArrayMult + zOffset + arrayOffset] == IS_LEAVES) { - leafDecayValues[(xOffset + arrayOffset + 1) * xArrayMult + (yOffset + arrayOffset) * yArrayMult + zOffset + arrayOffset] = sustainedValue; - } - - if (leafDecayValues[(xOffset + arrayOffset) * xArrayMult + (yOffset + arrayOffset - 1) * yArrayMult + zOffset + arrayOffset] == IS_LEAVES) { - leafDecayValues[(xOffset + arrayOffset) * xArrayMult + (yOffset + arrayOffset - 1) * yArrayMult + zOffset + arrayOffset] = sustainedValue; - } - - if (leafDecayValues[(xOffset + arrayOffset) * xArrayMult + (yOffset + arrayOffset + 1) * yArrayMult + zOffset + arrayOffset] == IS_LEAVES) { - leafDecayValues[(xOffset + arrayOffset) * xArrayMult + (yOffset + arrayOffset + 1) * yArrayMult + zOffset + arrayOffset] = sustainedValue; - } - - if (leafDecayValues[(xOffset + arrayOffset) * xArrayMult + (yOffset + arrayOffset) * yArrayMult + (zOffset + arrayOffset - 1)] == IS_LEAVES) { - leafDecayValues[(xOffset + arrayOffset) * xArrayMult + (yOffset + arrayOffset) * yArrayMult + (zOffset + arrayOffset - 1)] = sustainedValue; - } - - if (leafDecayValues[(xOffset + arrayOffset) * xArrayMult + (yOffset + arrayOffset) * yArrayMult + zOffset + arrayOffset + 1] == IS_LEAVES) { - leafDecayValues[(xOffset + arrayOffset) * xArrayMult + (yOffset + arrayOffset) * yArrayMult + zOffset + arrayOffset + 1] = sustainedValue; - } - } - } - } - } - } - } - - int sustainValue = leafDecayValues[(arrayOffset * xArrayMult) + (arrayOffset * yArrayMult) + arrayOffset]; - - if (sustainValue >= 0) { - world.setBlockMetadataWithNotify(x, y, z, leafMeta & -9, 4); // stop trying to decay - } else { - leaves.dropBlockAsItem(world, x, y, z, world.getBlockMetadata(x, y, z), 0); - world.setBlockToAir(x, y, z); - } - } - } -} +package forestry.arboriculture; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockLeaves; +import net.minecraft.world.World; + +/** Based on vanilla leaf decay, but accepts leaves that are connected further from a trunk */ +public abstract class LeafDecayHelper { + private static final short SUSTAINS_LEAVES = 0; + private static final short NOT_SUSTAINS_LEAVES = -1; + private static final short IS_LEAVES = -2; + private static int[] leafDecayValues; + + public static void leafDecay(BlockLeaves leaves, World world, int x, int y, int z) { + if (world.isRemote) { + return; + } + + int leafMeta = world.getBlockMetadata(x, y, z); + + if ((leafMeta & 8) != 0 && (leafMeta & 4) == 0) { + byte radius = 4; + byte yArrayMult = 32; + int xArrayMult = yArrayMult * yArrayMult; + int arrayOffset = yArrayMult / 2; + + if (leafDecayValues == null) { + leafDecayValues = new int[yArrayMult * yArrayMult * yArrayMult]; + } + + int radius1 = radius + 1; + if (world.checkChunksExist(x - radius1, y - radius1, z - radius1, x + radius1, y + radius1, z + radius1)) { + for (int xOffset = -radius; xOffset <= radius; ++xOffset) { + for (int yOffset = -radius; yOffset <= radius; ++yOffset) { + for (int zOffset = -radius; zOffset <= radius; ++zOffset) { + Block block = world.getBlock(x + xOffset, y + yOffset, z + zOffset); + + if (!block.canSustainLeaves(world, x + xOffset, y + yOffset, z + zOffset)) { + if (block.isLeaves(world, x + xOffset, y + yOffset, z + zOffset)) { + leafDecayValues[ + (xOffset + arrayOffset) * xArrayMult + + (yOffset + arrayOffset) * yArrayMult + + zOffset + + arrayOffset] = IS_LEAVES; + } else { + leafDecayValues[ + (xOffset + arrayOffset) * xArrayMult + + (yOffset + arrayOffset) * yArrayMult + + zOffset + + arrayOffset] = NOT_SUSTAINS_LEAVES; + } + } else { + leafDecayValues[ + (xOffset + arrayOffset) * xArrayMult + + (yOffset + arrayOffset) * yArrayMult + + zOffset + + arrayOffset] = SUSTAINS_LEAVES; + } + } + } + } + + for (int sustainedValue = 1; sustainedValue <= 8; ++sustainedValue) { + for (int xOffset = -radius; xOffset <= radius; ++xOffset) { + for (int yOffset = -radius; yOffset <= radius; ++yOffset) { + for (int zOffset = -radius; zOffset <= radius; ++zOffset) { + if (leafDecayValues[ + (xOffset + arrayOffset) * xArrayMult + + (yOffset + arrayOffset) * yArrayMult + + zOffset + + arrayOffset] + == sustainedValue - 1) { + if (leafDecayValues[ + (xOffset + arrayOffset - 1) * xArrayMult + + (yOffset + arrayOffset) * yArrayMult + + zOffset + + arrayOffset] + == IS_LEAVES) { + leafDecayValues[ + (xOffset + arrayOffset - 1) * xArrayMult + + (yOffset + arrayOffset) * yArrayMult + + zOffset + + arrayOffset] = sustainedValue; + } + + if (leafDecayValues[ + (xOffset + arrayOffset + 1) * xArrayMult + + (yOffset + arrayOffset) * yArrayMult + + zOffset + + arrayOffset] + == IS_LEAVES) { + leafDecayValues[ + (xOffset + arrayOffset + 1) * xArrayMult + + (yOffset + arrayOffset) * yArrayMult + + zOffset + + arrayOffset] = sustainedValue; + } + + if (leafDecayValues[ + (xOffset + arrayOffset) * xArrayMult + + (yOffset + arrayOffset - 1) * yArrayMult + + zOffset + + arrayOffset] + == IS_LEAVES) { + leafDecayValues[ + (xOffset + arrayOffset) * xArrayMult + + (yOffset + arrayOffset - 1) * yArrayMult + + zOffset + + arrayOffset] = sustainedValue; + } + + if (leafDecayValues[ + (xOffset + arrayOffset) * xArrayMult + + (yOffset + arrayOffset + 1) * yArrayMult + + zOffset + + arrayOffset] + == IS_LEAVES) { + leafDecayValues[ + (xOffset + arrayOffset) * xArrayMult + + (yOffset + arrayOffset + 1) * yArrayMult + + zOffset + + arrayOffset] = sustainedValue; + } + + if (leafDecayValues[ + (xOffset + arrayOffset) * xArrayMult + + (yOffset + arrayOffset) * yArrayMult + + (zOffset + arrayOffset - 1)] + == IS_LEAVES) { + leafDecayValues[ + (xOffset + arrayOffset) * xArrayMult + + (yOffset + arrayOffset) * yArrayMult + + (zOffset + arrayOffset - 1)] = sustainedValue; + } + + if (leafDecayValues[ + (xOffset + arrayOffset) * xArrayMult + + (yOffset + arrayOffset) * yArrayMult + + zOffset + + arrayOffset + + 1] + == IS_LEAVES) { + leafDecayValues[ + (xOffset + arrayOffset) * xArrayMult + + (yOffset + arrayOffset) * yArrayMult + + zOffset + + arrayOffset + + 1] = sustainedValue; + } + } + } + } + } + } + } + + int sustainValue = leafDecayValues[(arrayOffset * xArrayMult) + (arrayOffset * yArrayMult) + arrayOffset]; + + if (sustainValue >= 0) { + world.setBlockMetadataWithNotify(x, y, z, leafMeta & -9, 4); // stop trying to decay + } else { + leaves.dropBlockAsItem(world, x, y, z, world.getBlockMetadata(x, y, z), 0); + world.setBlockToAir(x, y, z); + } + } + } +} diff --git a/src/main/java/forestry/arboriculture/VillageHandlerArboriculture.java b/src/main/java/forestry/arboriculture/VillageHandlerArboriculture.java index 2ccb69a2c..51e5e54f1 100755 --- a/src/main/java/forestry/arboriculture/VillageHandlerArboriculture.java +++ b/src/main/java/forestry/arboriculture/VillageHandlerArboriculture.java @@ -10,16 +10,7 @@ ******************************************************************************/ package forestry.arboriculture; -import java.util.Random; - -import net.minecraft.entity.passive.EntityVillager; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.village.MerchantRecipe; -import net.minecraft.village.MerchantRecipeList; - import cpw.mods.fml.common.registry.VillagerRegistry.IVillageTradeHandler; - import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.EnumWoodType; import forestry.api.arboriculture.ITree; @@ -27,25 +18,31 @@ import forestry.api.arboriculture.ITreeGenome; import forestry.api.arboriculture.TreeManager; import forestry.api.genetics.IAllele; import forestry.plugins.PluginArboriculture; +import java.util.Random; +import net.minecraft.entity.passive.EntityVillager; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.village.MerchantRecipe; +import net.minecraft.village.MerchantRecipeList; public class VillageHandlerArboriculture implements IVillageTradeHandler { - @SuppressWarnings("unchecked") - @Override - public void manipulateTradesForVillager(EntityVillager villager, MerchantRecipeList recipeList, Random random) { - IAllele[] randomTemplate = TreeManager.treeRoot.getRandomTemplate(random); - ITreeGenome randomGenome = TreeManager.treeRoot.templateAsGenome(randomTemplate); - ITree randomTree = TreeManager.treeRoot.getTree(villager.worldObj, randomGenome); - ItemStack randomTreeStack = TreeManager.treeRoot.getMemberStack(randomTree, EnumGermlingType.SAPLING.ordinal()); + @SuppressWarnings("unchecked") + @Override + public void manipulateTradesForVillager(EntityVillager villager, MerchantRecipeList recipeList, Random random) { + IAllele[] randomTemplate = TreeManager.treeRoot.getRandomTemplate(random); + ITreeGenome randomGenome = TreeManager.treeRoot.templateAsGenome(randomTemplate); + ITree randomTree = TreeManager.treeRoot.getTree(villager.worldObj, randomGenome); + ItemStack randomTreeStack = TreeManager.treeRoot.getMemberStack(randomTree, EnumGermlingType.SAPLING.ordinal()); - recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 8), randomTreeStack)); - recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 2), PluginArboriculture.items.grafterProven.getItemStack())); + recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 8), randomTreeStack)); + recipeList.add(new MerchantRecipe( + new ItemStack(Items.emerald, 2), PluginArboriculture.items.grafterProven.getItemStack())); - EnumWoodType randomWoodType = EnumWoodType.getRandom(random); - ItemStack planks = TreeManager.woodItemAccess.getPlanks(randomWoodType, false); - planks.stackSize = 32; - - recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 1), planks)); - } + EnumWoodType randomWoodType = EnumWoodType.getRandom(random); + ItemStack planks = TreeManager.woodItemAccess.getPlanks(randomWoodType, false); + planks.stackSize = 32; + recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 1), planks)); + } } diff --git a/src/main/java/forestry/arboriculture/WoodItemAccess.java b/src/main/java/forestry/arboriculture/WoodItemAccess.java index fd9ef7135..e19fe8cb1 100644 --- a/src/main/java/forestry/arboriculture/WoodItemAccess.java +++ b/src/main/java/forestry/arboriculture/WoodItemAccess.java @@ -10,121 +10,118 @@ ******************************************************************************/ package forestry.arboriculture; -import java.util.EnumMap; - -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; - import forestry.api.arboriculture.EnumWoodType; import forestry.api.arboriculture.IWoodItemAccess; import forestry.arboriculture.items.ItemBlockWood; +import java.util.EnumMap; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; public class WoodItemAccess implements IWoodItemAccess { - private static final EnumMap logs = new EnumMap<>(EnumWoodType.class); - private static final EnumMap logsFireproof = new EnumMap<>(EnumWoodType.class); - private static final EnumMap planks = new EnumMap<>(EnumWoodType.class); - private static final EnumMap planksFireproof = new EnumMap<>(EnumWoodType.class); - private static final EnumMap slabs = new EnumMap<>(EnumWoodType.class); - private static final EnumMap slabsFireproof = new EnumMap<>(EnumWoodType.class); - private static final EnumMap fences = new EnumMap<>(EnumWoodType.class); - private static final EnumMap fencesFireproof = new EnumMap<>(EnumWoodType.class); - private static final EnumMap stairs = new EnumMap<>(EnumWoodType.class); - private static final EnumMap stairsFireproof = new EnumMap<>(EnumWoodType.class); + private static final EnumMap logs = new EnumMap<>(EnumWoodType.class); + private static final EnumMap logsFireproof = new EnumMap<>(EnumWoodType.class); + private static final EnumMap planks = new EnumMap<>(EnumWoodType.class); + private static final EnumMap planksFireproof = new EnumMap<>(EnumWoodType.class); + private static final EnumMap slabs = new EnumMap<>(EnumWoodType.class); + private static final EnumMap slabsFireproof = new EnumMap<>(EnumWoodType.class); + private static final EnumMap fences = new EnumMap<>(EnumWoodType.class); + private static final EnumMap fencesFireproof = new EnumMap<>(EnumWoodType.class); + private static final EnumMap stairs = new EnumMap<>(EnumWoodType.class); + private static final EnumMap stairsFireproof = new EnumMap<>(EnumWoodType.class); - private static ItemStack getStack(EnumWoodType woodType, Block block) { - ItemStack itemStack = new ItemStack(block); - ItemBlockWood.saveToItemStack(woodType, itemStack); - return itemStack; - } + private static ItemStack getStack(EnumWoodType woodType, Block block) { + ItemStack itemStack = new ItemStack(block); + ItemBlockWood.saveToItemStack(woodType, itemStack); + return itemStack; + } - public static void registerLog(Block block, EnumWoodType woodType, boolean fireproof) { - ItemStack itemStack = getStack(woodType, block); - if (fireproof) { - logsFireproof.put(woodType, itemStack); - } else { - logs.put(woodType, itemStack); - } - } + public static void registerLog(Block block, EnumWoodType woodType, boolean fireproof) { + ItemStack itemStack = getStack(woodType, block); + if (fireproof) { + logsFireproof.put(woodType, itemStack); + } else { + logs.put(woodType, itemStack); + } + } - public static void registerPlanks(Block block, EnumWoodType woodType, boolean fireproof) { - ItemStack itemStack = getStack(woodType, block); - if (fireproof) { - planksFireproof.put(woodType, itemStack); - } else { - planks.put(woodType, itemStack); - } - } + public static void registerPlanks(Block block, EnumWoodType woodType, boolean fireproof) { + ItemStack itemStack = getStack(woodType, block); + if (fireproof) { + planksFireproof.put(woodType, itemStack); + } else { + planks.put(woodType, itemStack); + } + } - public static void registerSlab(Block block, EnumWoodType woodType, boolean fireproof) { - ItemStack itemStack = getStack(woodType, block); - if (fireproof) { - slabsFireproof.put(woodType, itemStack); - } else { - slabs.put(woodType, itemStack); - } - } + public static void registerSlab(Block block, EnumWoodType woodType, boolean fireproof) { + ItemStack itemStack = getStack(woodType, block); + if (fireproof) { + slabsFireproof.put(woodType, itemStack); + } else { + slabs.put(woodType, itemStack); + } + } - public static void registerFence(Block block, EnumWoodType woodType, boolean fireproof) { - ItemStack itemStack = getStack(woodType, block); - if (fireproof) { - fencesFireproof.put(woodType, itemStack); - } else { - fences.put(woodType, itemStack); - } - } + public static void registerFence(Block block, EnumWoodType woodType, boolean fireproof) { + ItemStack itemStack = getStack(woodType, block); + if (fireproof) { + fencesFireproof.put(woodType, itemStack); + } else { + fences.put(woodType, itemStack); + } + } - public static void registerStairs(Block block, EnumWoodType woodType, boolean fireproof) { - ItemStack itemStack = getStack(woodType, block); - if (fireproof) { - stairsFireproof.put(woodType, itemStack); - } else { - stairs.put(woodType, itemStack); - } - } + public static void registerStairs(Block block, EnumWoodType woodType, boolean fireproof) { + ItemStack itemStack = getStack(woodType, block); + if (fireproof) { + stairsFireproof.put(woodType, itemStack); + } else { + stairs.put(woodType, itemStack); + } + } - @Override - public ItemStack getPlanks(EnumWoodType woodType, boolean fireproof) { - if (fireproof) { - return planksFireproof.get(woodType).copy(); - } else { - return planks.get(woodType).copy(); - } - } + @Override + public ItemStack getPlanks(EnumWoodType woodType, boolean fireproof) { + if (fireproof) { + return planksFireproof.get(woodType).copy(); + } else { + return planks.get(woodType).copy(); + } + } - @Override - public ItemStack getLog(EnumWoodType woodType, boolean fireproof) { - if (fireproof) { - return logsFireproof.get(woodType).copy(); - } else { - return logs.get(woodType).copy(); - } - } + @Override + public ItemStack getLog(EnumWoodType woodType, boolean fireproof) { + if (fireproof) { + return logsFireproof.get(woodType).copy(); + } else { + return logs.get(woodType).copy(); + } + } - @Override - public ItemStack getSlab(EnumWoodType woodType, boolean fireproof) { - if (fireproof) { - return slabsFireproof.get(woodType).copy(); - } else { - return slabs.get(woodType).copy(); - } - } + @Override + public ItemStack getSlab(EnumWoodType woodType, boolean fireproof) { + if (fireproof) { + return slabsFireproof.get(woodType).copy(); + } else { + return slabs.get(woodType).copy(); + } + } - @Override - public ItemStack getFence(EnumWoodType woodType, boolean fireproof) { - if (fireproof) { - return fencesFireproof.get(woodType).copy(); - } else { - return fences.get(woodType).copy(); - } - } - - @Override - public ItemStack getStairs(EnumWoodType woodType, boolean fireproof) { - if (fireproof) { - return stairsFireproof.get(woodType).copy(); - } else { - return stairs.get(woodType).copy(); - } - } + @Override + public ItemStack getFence(EnumWoodType woodType, boolean fireproof) { + if (fireproof) { + return fencesFireproof.get(woodType).copy(); + } else { + return fences.get(woodType).copy(); + } + } + @Override + public ItemStack getStairs(EnumWoodType woodType, boolean fireproof) { + if (fireproof) { + return stairsFireproof.get(woodType).copy(); + } else { + return stairs.get(woodType).copy(); + } + } } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockArbFence.java b/src/main/java/forestry/arboriculture/blocks/BlockArbFence.java index cfd3e2ac0..f716b56ca 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockArbFence.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockArbFence.java @@ -10,9 +10,18 @@ ******************************************************************************/ package forestry.arboriculture.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.arboriculture.EnumWoodType; +import forestry.api.arboriculture.TreeManager; +import forestry.api.core.Tabs; +import forestry.arboriculture.IWoodTyped; +import forestry.arboriculture.render.IconProviderWood; +import forestry.arboriculture.tiles.TileWood; +import forestry.core.render.ParticleHelper; +import forestry.plugins.PluginArboriculture; import java.util.ArrayList; import java.util.List; - import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.block.BlockFenceGate; @@ -29,170 +38,159 @@ import net.minecraft.util.IIcon; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.common.util.ForgeDirection; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.api.arboriculture.TreeManager; -import forestry.api.core.Tabs; -import forestry.arboriculture.IWoodTyped; -import forestry.arboriculture.render.IconProviderWood; -import forestry.arboriculture.tiles.TileWood; -import forestry.core.render.ParticleHelper; -import forestry.plugins.PluginArboriculture; - public class BlockArbFence extends BlockFence implements IWoodTyped, ITileEntityProvider { - private final ParticleHelper.Callback particleCallback; - private final boolean fireproof; + private final ParticleHelper.Callback particleCallback; + private final boolean fireproof; - public BlockArbFence(boolean fireproof) { - super("", Material.wood); + public BlockArbFence(boolean fireproof) { + super("", Material.wood); - this.fireproof = fireproof; + this.fireproof = fireproof; - setHardness(2.0F); - setResistance(5.0F); - setHarvestLevel("axe", 0); - setStepSound(soundTypeWood); - setCreativeTab(Tabs.tabArboriculture); + setHardness(2.0F); + setResistance(5.0F); + setHarvestLevel("axe", 0); + setStepSound(soundTypeWood); + setCreativeTab(Tabs.tabArboriculture); - this.particleCallback = new ParticleHelper.DefaultCallback(this); - } + this.particleCallback = new ParticleHelper.DefaultCallback(this); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List list) { - for (EnumWoodType woodType : EnumWoodType.VALUES) { - list.add(TreeManager.woodItemAccess.getFence(woodType, fireproof)); - } - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List list) { + for (EnumWoodType woodType : EnumWoodType.VALUES) { + list.add(TreeManager.woodItemAccess.getFence(woodType, fireproof)); + } + } - @Override - public boolean canPlaceTorchOnTop(World world, int x, int y, int z) { - return true; - } + @Override + public boolean canPlaceTorchOnTop(World world, int x, int y, int z) { + return true; + } - @Override - public boolean canConnectFenceTo(IBlockAccess world, int x, int y, int z) { - if (!isFence(world, x, y, z)) { - Block block = world.getBlock(x, y, z); - if (block == this || block instanceof BlockFenceGate) { - return true; - } + @Override + public boolean canConnectFenceTo(IBlockAccess world, int x, int y, int z) { + if (!isFence(world, x, y, z)) { + Block block = world.getBlock(x, y, z); + if (block == this || block instanceof BlockFenceGate) { + return true; + } - return block.getMaterial().isOpaque() && block.renderAsNormalBlock() && block.getMaterial() != Material.gourd; - } else { - return true; - } - } + return block.getMaterial().isOpaque() + && block.renderAsNormalBlock() + && block.getMaterial() != Material.gourd; + } else { + return true; + } + } - /* ICONS */ - @SideOnly(Side.CLIENT) - @Override - public void registerBlockIcons(IIconRegister register) { - IconProviderWood.registerIcons(register); - } + /* ICONS */ + @SideOnly(Side.CLIENT) + @Override + public void registerBlockIcons(IIconRegister register) { + IconProviderWood.registerIcons(register); + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(int side, int meta) { - return IconProviderWood.getPlankIcon(EnumWoodType.LARCH); - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(int side, int meta) { + return IconProviderWood.getPlankIcon(EnumWoodType.LARCH); + } - @Override - public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { - TileWood wood = TileWood.getWoodTile(world, x, y, z); - EnumWoodType woodType = wood.getWoodType(); - return IconProviderWood.getPlankIcon(woodType); - } + @Override + public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { + TileWood wood = TileWood.getWoodTile(world, x, y, z); + EnumWoodType woodType = wood.getWoodType(); + return IconProviderWood.getPlankIcon(woodType); + } - private static boolean isFence(IBlockAccess world, int x, int y, int z) { - Block block = world.getBlock(x, y, z); - return PluginArboriculture.validFences.contains(block); - } + private static boolean isFence(IBlockAccess world, int x, int y, int z) { + Block block = world.getBlock(x, y, z); + return PluginArboriculture.validFences.contains(block); + } - @Override - public final TileEntity createNewTileEntity(World world, int meta) { - return new TileWood(); - } + @Override + public final TileEntity createNewTileEntity(World world, int meta) { + return new TileWood(); + } - /* PROPERTIES */ - @Override - public final ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { - return TileWood.getPickBlock(this, world, x, y, z); - } + /* PROPERTIES */ + @Override + public final ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { + return TileWood.getPickBlock(this, world, x, y, z); + } - /* DROP HANDLING */ - // Hack: When harvesting we need to get the drops in onBlockHarvested, - // because Mojang destroys the block and tile before calling getDrops. - private final ThreadLocal> drops = new ThreadLocal<>(); + /* DROP HANDLING */ + // Hack: When harvesting we need to get the drops in onBlockHarvested, + // because Mojang destroys the block and tile before calling getDrops. + private final ThreadLocal> drops = new ThreadLocal<>(); - @Override - public void onBlockHarvested(World world, int x, int y, int z, int meta, EntityPlayer playerProfile) { - drops.set(TileWood.getDrops(this, world, x, y, z)); - } + @Override + public void onBlockHarvested(World world, int x, int y, int z, int meta, EntityPlayer playerProfile) { + drops.set(TileWood.getDrops(this, world, x, y, z)); + } - @Override - public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - ArrayList ret = drops.get(); - drops.remove(); + @Override + public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + ArrayList ret = drops.get(); + drops.remove(); - // not harvested, get drops normally - if (ret == null) { - ret = TileWood.getDrops(this, world, x, y, z); - } + // not harvested, get drops normally + if (ret == null) { + ret = TileWood.getDrops(this, world, x, y, z); + } - return ret; - } + return ret; + } - @Override - public final float getBlockHardness(World world, int x, int y, int z) { - TileWood wood = TileWood.getWoodTile(world, x, y, z); - if (wood == null) { - return EnumWoodType.DEFAULT_HARDNESS; - } - return wood.getWoodType().getHardness(); - } + @Override + public final float getBlockHardness(World world, int x, int y, int z) { + TileWood wood = TileWood.getWoodTile(world, x, y, z); + if (wood == null) { + return EnumWoodType.DEFAULT_HARDNESS; + } + return wood.getWoodType().getHardness(); + } - @Override - public final boolean isFlammable(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return !isFireproof(); - } + @Override + public final boolean isFlammable(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return !isFireproof(); + } - @Override - public int getFlammability(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return isFireproof() ? 0 : 20; - } + @Override + public int getFlammability(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return isFireproof() ? 0 : 20; + } - @Override - public int getFireSpreadSpeed(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return isFireproof() ? 0 : 5; - } + @Override + public int getFireSpreadSpeed(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return isFireproof() ? 0 : 5; + } - @Override - public String getBlockKind() { - return "fences"; - } + @Override + public String getBlockKind() { + return "fences"; + } - @Override - public boolean isFireproof() { - return fireproof; - } + @Override + public boolean isFireproof() { + return fireproof; + } - /* Particles */ - @SideOnly(Side.CLIENT) - @Override - public boolean addHitEffects(World worldObj, MovingObjectPosition target, EffectRenderer effectRenderer) { - return ParticleHelper.addHitEffects(worldObj, this, target, effectRenderer, particleCallback); - } + /* Particles */ + @SideOnly(Side.CLIENT) + @Override + public boolean addHitEffects(World worldObj, MovingObjectPosition target, EffectRenderer effectRenderer) { + return ParticleHelper.addHitEffects(worldObj, this, target, effectRenderer, particleCallback); + } - @SideOnly(Side.CLIENT) - @Override - public boolean addDestroyEffects(World worldObj, int x, int y, int z, int meta, EffectRenderer effectRenderer) { - return ParticleHelper.addDestroyEffects(worldObj, this, x, y, z, meta, effectRenderer, particleCallback); - } + @SideOnly(Side.CLIENT) + @Override + public boolean addDestroyEffects(World worldObj, int x, int y, int z, int meta, EffectRenderer effectRenderer) { + return ParticleHelper.addDestroyEffects(worldObj, this, x, y, z, meta, effectRenderer, particleCallback); + } } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockArbStairs.java b/src/main/java/forestry/arboriculture/blocks/BlockArbStairs.java index 8d259872d..060832a2a 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockArbStairs.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockArbStairs.java @@ -10,9 +10,17 @@ ******************************************************************************/ package forestry.arboriculture.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.arboriculture.EnumWoodType; +import forestry.api.arboriculture.TreeManager; +import forestry.api.core.Tabs; +import forestry.arboriculture.IWoodTyped; +import forestry.arboriculture.render.IconProviderWood; +import forestry.arboriculture.tiles.TileWood; +import forestry.core.render.ParticleHelper; import java.util.ArrayList; import java.util.List; - import net.minecraft.block.Block; import net.minecraft.block.BlockStairs; import net.minecraft.block.ITileEntityProvider; @@ -28,123 +36,112 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.api.arboriculture.TreeManager; -import forestry.api.core.Tabs; -import forestry.arboriculture.IWoodTyped; -import forestry.arboriculture.render.IconProviderWood; -import forestry.arboriculture.tiles.TileWood; -import forestry.core.render.ParticleHelper; - public class BlockArbStairs extends BlockStairs implements IWoodTyped, ITileEntityProvider { - private final ParticleHelper.Callback particleCallback; - private final boolean fireproof; + private final ParticleHelper.Callback particleCallback; + private final boolean fireproof; - public BlockArbStairs(Block par2Block, boolean fireproof) { - super(par2Block, 0); + public BlockArbStairs(Block par2Block, boolean fireproof) { + super(par2Block, 0); - this.fireproof = fireproof; + this.fireproof = fireproof; - setCreativeTab(Tabs.tabArboriculture); - setHardness(2.0F); - setResistance(5.0F); - setHarvestLevel("axe", 0); + setCreativeTab(Tabs.tabArboriculture); + setHardness(2.0F); + setResistance(5.0F); + setHarvestLevel("axe", 0); - this.particleCallback = new ParticleHelper.DefaultCallback(this); - } + this.particleCallback = new ParticleHelper.DefaultCallback(this); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - @SideOnly(Side.CLIENT) - public void getSubBlocks(Item item, CreativeTabs tab, List list) { - for (EnumWoodType woodType : EnumWoodType.VALUES) { - list.add(TreeManager.woodItemAccess.getStairs(woodType, fireproof)); - } - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + @SideOnly(Side.CLIENT) + public void getSubBlocks(Item item, CreativeTabs tab, List list) { + for (EnumWoodType woodType : EnumWoodType.VALUES) { + list.add(TreeManager.woodItemAccess.getStairs(woodType, fireproof)); + } + } - /* DROP HANDLING */ - // Hack: When harvesting we need to get the drops in onBlockHarvested, - // because Mojang destroys the block and tile before calling getDrops. - private final ThreadLocal> drops = new ThreadLocal<>(); + /* DROP HANDLING */ + // Hack: When harvesting we need to get the drops in onBlockHarvested, + // because Mojang destroys the block and tile before calling getDrops. + private final ThreadLocal> drops = new ThreadLocal<>(); - @Override - public void onBlockHarvested(World world, int x, int y, int z, int meta, EntityPlayer playerProfile) { - drops.set(TileWood.getDrops(this, world, x, y, z)); - } + @Override + public void onBlockHarvested(World world, int x, int y, int z, int meta, EntityPlayer playerProfile) { + drops.set(TileWood.getDrops(this, world, x, y, z)); + } - @Override - public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - ArrayList ret = drops.get(); - drops.remove(); + @Override + public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + ArrayList ret = drops.get(); + drops.remove(); - // not harvested, get drops normally - if (ret == null) { - ret = TileWood.getDrops(this, world, x, y, z); - } + // not harvested, get drops normally + if (ret == null) { + ret = TileWood.getDrops(this, world, x, y, z); + } - return ret; - } + return ret; + } - @Override - public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { - return TileWood.getPickBlock(this, world, x, y, z); - } + @Override + public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { + return TileWood.getPickBlock(this, world, x, y, z); + } - /* ICONS */ - @SideOnly(Side.CLIENT) - @Override - public void registerBlockIcons(IIconRegister register) { - IconProviderWood.registerIcons(register); - } + /* ICONS */ + @SideOnly(Side.CLIENT) + @Override + public void registerBlockIcons(IIconRegister register) { + IconProviderWood.registerIcons(register); + } - /* ICONS */ - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(int side, int meta) { - return IconProviderWood.getPlankIcon(EnumWoodType.LARCH); - } + /* ICONS */ + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(int side, int meta) { + return IconProviderWood.getPlankIcon(EnumWoodType.LARCH); + } - @Override - public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { - TileWood wood = TileWood.getWoodTile(world, x, y, z); - EnumWoodType woodType = wood.getWoodType(); - return IconProviderWood.getPlankIcon(woodType); - } + @Override + public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { + TileWood wood = TileWood.getWoodTile(world, x, y, z); + EnumWoodType woodType = wood.getWoodType(); + return IconProviderWood.getPlankIcon(woodType); + } - @Override - public boolean getUseNeighborBrightness() { - return true; - } + @Override + public boolean getUseNeighborBrightness() { + return true; + } - @Override - public String getBlockKind() { - return "stairs"; - } + @Override + public String getBlockKind() { + return "stairs"; + } - @Override - public boolean isFireproof() { - return fireproof; - } + @Override + public boolean isFireproof() { + return fireproof; + } - @Override - public TileEntity createNewTileEntity(World p_149915_1_, int p_149915_2_) { - return new TileWood(); - } + @Override + public TileEntity createNewTileEntity(World p_149915_1_, int p_149915_2_) { + return new TileWood(); + } - /* Particles */ - @SideOnly(Side.CLIENT) - @Override - public boolean addHitEffects(World worldObj, MovingObjectPosition target, EffectRenderer effectRenderer) { - return ParticleHelper.addHitEffects(worldObj, this, target, effectRenderer, particleCallback); - } + /* Particles */ + @SideOnly(Side.CLIENT) + @Override + public boolean addHitEffects(World worldObj, MovingObjectPosition target, EffectRenderer effectRenderer) { + return ParticleHelper.addHitEffects(worldObj, this, target, effectRenderer, particleCallback); + } - @SideOnly(Side.CLIENT) - @Override - public boolean addDestroyEffects(World worldObj, int x, int y, int z, int meta, EffectRenderer effectRenderer) { - return ParticleHelper.addDestroyEffects(worldObj, this, x, y, z, meta, effectRenderer, particleCallback); - } + @SideOnly(Side.CLIENT) + @Override + public boolean addDestroyEffects(World worldObj, int x, int y, int z, int meta, EffectRenderer effectRenderer) { + return ParticleHelper.addDestroyEffects(worldObj, this, x, y, z, meta, effectRenderer, particleCallback); + } } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockArboriculture.java b/src/main/java/forestry/arboriculture/blocks/BlockArboriculture.java index 7ff4af2ad..500d73969 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockArboriculture.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockArboriculture.java @@ -1,21 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.blocks; - -import forestry.api.core.Tabs; -import forestry.core.blocks.BlockBase; - -public class BlockArboriculture extends BlockBase { - public BlockArboriculture() { - super(true); - setCreativeTab(Tabs.tabArboriculture); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.blocks; + +import forestry.api.core.Tabs; +import forestry.core.blocks.BlockBase; + +public class BlockArboriculture extends BlockBase { + public BlockArboriculture() { + super(true); + setCreativeTab(Tabs.tabArboriculture); + } +} diff --git a/src/main/java/forestry/arboriculture/blocks/BlockArboricultureType.java b/src/main/java/forestry/arboriculture/blocks/BlockArboricultureType.java index e728b556f..946a32b7d 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockArboricultureType.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockArboricultureType.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.blocks; - -import forestry.arboriculture.tiles.TileArboristChest; -import forestry.core.blocks.IMachinePropertiesTESR; -import forestry.core.proxy.Proxies; -import forestry.core.render.IBlockRenderer; -import forestry.core.tiles.TileForestry; - -public enum BlockArboricultureType implements IMachinePropertiesTESR { - ARBCHEST(TileArboristChest.class, "ArbChest") { - @Override - public IBlockRenderer getRenderer() { - return Proxies.render.getRenderChest("arbchest"); - } - }; - - public static final BlockArboricultureType[] VALUES = values(); - - private final String teIdent; - private final Class teClass; - - BlockArboricultureType(Class teClass, String teName) { - this.teIdent = "forestry." + teName; - this.teClass = teClass; - } - - @Override - public int getMeta() { - return ordinal(); - } - - @Override - public String getTeIdent() { - return teIdent; - } - - @Override - public Class getTeClass() { - return teClass; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.blocks; + +import forestry.arboriculture.tiles.TileArboristChest; +import forestry.core.blocks.IMachinePropertiesTESR; +import forestry.core.proxy.Proxies; +import forestry.core.render.IBlockRenderer; +import forestry.core.tiles.TileForestry; + +public enum BlockArboricultureType implements IMachinePropertiesTESR { + ARBCHEST(TileArboristChest.class, "ArbChest") { + @Override + public IBlockRenderer getRenderer() { + return Proxies.render.getRenderChest("arbchest"); + } + }; + + public static final BlockArboricultureType[] VALUES = values(); + + private final String teIdent; + private final Class teClass; + + BlockArboricultureType(Class teClass, String teName) { + this.teIdent = "forestry." + teName; + this.teClass = teClass; + } + + @Override + public int getMeta() { + return ordinal(); + } + + @Override + public String getTeIdent() { + return teIdent; + } + + @Override + public Class getTeClass() { + return teClass; + } +} diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryLeaves.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryLeaves.java index 86f1cef09..dee0dc964 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryLeaves.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryLeaves.java @@ -10,37 +10,9 @@ ******************************************************************************/ package forestry.arboriculture.blocks; -import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -import net.minecraft.block.BlockNewLeaf; -import net.minecraft.block.IGrowable; -import net.minecraft.block.ITileEntityProvider; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.enchantment.EnchantmentHelper; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.IIcon; -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.util.ForgeDirection; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.EnumLeafType; import forestry.api.arboriculture.IToolGrafter; @@ -59,320 +31,346 @@ import forestry.arboriculture.tiles.TileLeaves; import forestry.core.proxy.Proxies; import forestry.core.utils.ItemStackUtil; import forestry.plugins.PluginArboriculture; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import javax.annotation.Nullable; +import net.minecraft.block.BlockNewLeaf; +import net.minecraft.block.IGrowable; +import net.minecraft.block.ITileEntityProvider; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.enchantment.EnchantmentHelper; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.IIcon; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; public class BlockForestryLeaves extends BlockNewLeaf implements ITileEntityProvider, IGrowable { - public BlockForestryLeaves() { - this.setCreativeTab(Tabs.tabArboriculture); - } + public BlockForestryLeaves() { + this.setCreativeTab(Tabs.tabArboriculture); + } - /* TILE ENTITY */ - @Override - public TileEntity createNewTileEntity(World world, int meta) { - return new TileLeaves(); - } + /* TILE ENTITY */ + @Override + public TileEntity createNewTileEntity(World world, int meta) { + return new TileLeaves(); + } - public static TileLeaves getLeafTile(IBlockAccess world, int x, int y, int z) { - TileEntity tile = world.getTileEntity(x, y, z); - if (tile instanceof TileLeaves) { - return (TileLeaves) tile; - } - return null; - } + public static TileLeaves getLeafTile(IBlockAccess world, int x, int y, int z) { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile instanceof TileLeaves) { + return (TileLeaves) tile; + } + return null; + } - @SideOnly(Side.CLIENT) - @Override - @SuppressWarnings({"unchecked", "rawtypes"}) - public void getSubBlocks(Item item, CreativeTabs tab, List list) { + @SideOnly(Side.CLIENT) + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public void getSubBlocks(Item item, CreativeTabs tab, List list) { - for (ITree tree : TreeManager.treeRoot.getIndividualTemplates()) { - TileLeaves leaves = new TileLeaves(); - leaves.setDecorative(); - leaves.setTree(tree); + for (ITree tree : TreeManager.treeRoot.getIndividualTemplates()) { + TileLeaves leaves = new TileLeaves(); + leaves.setDecorative(); + leaves.setTree(tree); - NBTTagCompound leavesNBT = new NBTTagCompound(); - leaves.writeToNBTDecorative(leavesNBT); + NBTTagCompound leavesNBT = new NBTTagCompound(); + leaves.writeToNBTDecorative(leavesNBT); - ItemStack itemStack = new ItemStack(item, 1, 0); - itemStack.setTagCompound(leavesNBT); + ItemStack itemStack = new ItemStack(item, 1, 0); + itemStack.setTagCompound(leavesNBT); - list.add(itemStack); - } - } + list.add(itemStack); + } + } - /* DROP HANDLING */ - // Hack: When harvesting leaves we need to get the drops in onBlockHarvested, - // because Mojang destroys the block and tile before calling getDrops. - private final ThreadLocal> drops = new ThreadLocal<>(); + /* DROP HANDLING */ + // Hack: When harvesting leaves we need to get the drops in onBlockHarvested, + // because Mojang destroys the block and tile before calling getDrops. + private final ThreadLocal> drops = new ThreadLocal<>(); - @Override - public void onBlockHarvested(World world, int x, int y, int z, int metadata, EntityPlayer player) { - TileLeaves leafTile = getLeafTile(world, x, y, z); - if (leafTile == null || leafTile.isDecorative()) { - return; - } + @Override + public void onBlockHarvested(World world, int x, int y, int z, int metadata, EntityPlayer player) { + TileLeaves leafTile = getLeafTile(world, x, y, z); + if (leafTile == null || leafTile.isDecorative()) { + return; + } - int fortune = EnchantmentHelper.getFortuneModifier(player); - float saplingModifier = 1.0f; + int fortune = EnchantmentHelper.getFortuneModifier(player); + float saplingModifier = 1.0f; - if (!world.isRemote) { - ItemStack held = player.inventory.getCurrentItem(); - if (held != null && held.getItem() instanceof IToolGrafter) { - saplingModifier = ((IToolGrafter) held.getItem()).getSaplingModifier(held, world, player, x, y, z); - held.damageItem(1, player); - if (held.stackSize <= 0) { - player.destroyCurrentEquippedItem(); - } - } - } - GameProfile playerProfile = player.getGameProfile(); - ArrayList leafDrops = getLeafDrop(world, playerProfile, x, y, z, saplingModifier, fortune); - drops.set(leafDrops); - } + if (!world.isRemote) { + ItemStack held = player.inventory.getCurrentItem(); + if (held != null && held.getItem() instanceof IToolGrafter) { + saplingModifier = ((IToolGrafter) held.getItem()).getSaplingModifier(held, world, player, x, y, z); + held.damageItem(1, player); + if (held.stackSize <= 0) { + player.destroyCurrentEquippedItem(); + } + } + } + GameProfile playerProfile = player.getGameProfile(); + ArrayList leafDrops = getLeafDrop(world, playerProfile, x, y, z, saplingModifier, fortune); + drops.set(leafDrops); + } - @Override - public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - ArrayList ret = drops.get(); - drops.remove(); + @Override + public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + ArrayList ret = drops.get(); + drops.remove(); - // leaves not harvested, get drops normally - if (ret == null) { - ret = getLeafDrop(world, null, x, y, z, 1.0f, fortune); - } + // leaves not harvested, get drops normally + if (ret == null) { + ret = getLeafDrop(world, null, x, y, z, 1.0f, fortune); + } - return ret; - } + return ret; + } - private static ArrayList getLeafDrop(World world, @Nullable GameProfile playerProfile, int x, int y, int z, float saplingModifier, int fortune) { - ArrayList prod = new ArrayList<>(); + private static ArrayList getLeafDrop( + World world, @Nullable GameProfile playerProfile, int x, int y, int z, float saplingModifier, int fortune) { + ArrayList prod = new ArrayList<>(); - TileLeaves tile = getLeafTile(world, x, y, z); - if (tile == null || tile.getTree() == null || tile.isDecorative()) { - return prod; - } + TileLeaves tile = getLeafTile(world, x, y, z); + if (tile == null || tile.getTree() == null || tile.isDecorative()) { + return prod; + } - // Add saplings - ITree[] saplings = tile.getTree().getSaplings(world, playerProfile, x, y, z, saplingModifier); + // Add saplings + ITree[] saplings = tile.getTree().getSaplings(world, playerProfile, x, y, z, saplingModifier); - for (ITree sapling : saplings) { - if (sapling != null) { - prod.add(TreeManager.treeRoot.getMemberStack(sapling, EnumGermlingType.SAPLING.ordinal())); - } - } + for (ITree sapling : saplings) { + if (sapling != null) { + prod.add(TreeManager.treeRoot.getMemberStack(sapling, EnumGermlingType.SAPLING.ordinal())); + } + } - // Add fruits - if (tile.hasFruit()) { - Collections.addAll(prod, tile.getTree().produceStacks(world, x, y, z, tile.getRipeningTime())); - } + // Add fruits + if (tile.hasFruit()) { + Collections.addAll(prod, tile.getTree().produceStacks(world, x, y, z, tile.getRipeningTime())); + } - return prod; - } + return prod; + } - @Override - public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { - ItemStack itemStack = super.getPickBlock(target, world, x, y, z); - TileLeaves leaves = getLeafTile(world, x, y, z); - NBTTagCompound leavesNBT = new NBTTagCompound(); - leaves.writeToNBTDecorative(leavesNBT); - itemStack.setTagCompound(leavesNBT); - return itemStack; - } + @Override + public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { + ItemStack itemStack = super.getPickBlock(target, world, x, y, z); + TileLeaves leaves = getLeafTile(world, x, y, z); + NBTTagCompound leavesNBT = new NBTTagCompound(); + leaves.writeToNBTDecorative(leavesNBT); + itemStack.setTagCompound(leavesNBT); + return itemStack; + } - @Override - public boolean isShearable(ItemStack item, IBlockAccess world, int x, int y, int z) { - return true; - } + @Override + public boolean isShearable(ItemStack item, IBlockAccess world, int x, int y, int z) { + return true; + } - @Override - public ArrayList onSheared(ItemStack item, IBlockAccess world, int x, int y, int z, int fortune) { - ArrayList ret = super.onSheared(item, world, x, y, z, fortune); + @Override + public ArrayList onSheared(ItemStack item, IBlockAccess world, int x, int y, int z, int fortune) { + ArrayList ret = super.onSheared(item, world, x, y, z, fortune); - TileLeaves leaves = getLeafTile(world, x, y, z); - NBTTagCompound shearedLeavesNBT = new NBTTagCompound(); - leaves.writeToNBTDecorative(shearedLeavesNBT); + TileLeaves leaves = getLeafTile(world, x, y, z); + NBTTagCompound shearedLeavesNBT = new NBTTagCompound(); + leaves.writeToNBTDecorative(shearedLeavesNBT); - for (ItemStack stack : ret) { - if (stack.getItem() instanceof ItemBlockLeaves) { - stack.setTagCompound(shearedLeavesNBT); - } - } + for (ItemStack stack : ret) { + if (stack.getItem() instanceof ItemBlockLeaves) { + stack.setTagCompound(shearedLeavesNBT); + } + } - return ret; - } + return ret; + } - @Override - public void beginLeavesDecay(World world, int x, int y, int z) { - TileLeaves tile = getLeafTile(world, x, y, z); - if (tile == null || tile.isDecorative()) { - return; - } - super.beginLeavesDecay(world, x, y, z); - } + @Override + public void beginLeavesDecay(World world, int x, int y, int z) { + TileLeaves tile = getLeafTile(world, x, y, z); + if (tile == null || tile.isDecorative()) { + return; + } + super.beginLeavesDecay(world, x, y, z); + } - @Override - public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z) { - TileLeaves tileLeaves = getLeafTile(world, x, y, z); - if (tileLeaves != null && TreeDefinition.Willow.getUID().equals(tileLeaves.getSpeciesUID())) { - return null; - } - return super.getCollisionBoundingBoxFromPool(world, x, y, z); - } + @Override + public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z) { + TileLeaves tileLeaves = getLeafTile(world, x, y, z); + if (tileLeaves != null && TreeDefinition.Willow.getUID().equals(tileLeaves.getSpeciesUID())) { + return null; + } + return super.getCollisionBoundingBoxFromPool(world, x, y, z); + } - @Override - public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity) { - entity.motionX *= 0.4D; - entity.motionZ *= 0.4D; - } + @Override + public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity) { + entity.motionX *= 0.4D; + entity.motionZ *= 0.4D; + } - @Override - public void updateTick(World world, int x, int y, int z, Random random) { - TileLeaves tileLeaves = getLeafTile(world, x, y, z); - if (tileLeaves == null || tileLeaves.isDecorative()) { - return; - } + @Override + public void updateTick(World world, int x, int y, int z, Random random) { + TileLeaves tileLeaves = getLeafTile(world, x, y, z); + if (tileLeaves == null || tileLeaves.isDecorative()) { + return; + } - LeafDecayHelper.leafDecay(this, world, x, y, z); + LeafDecayHelper.leafDecay(this, world, x, y, z); - // check leaves tile again because they can decay in super.updateTick - if (tileLeaves.isInvalid()) { - return; - } + // check leaves tile again because they can decay in super.updateTick + if (tileLeaves.isInvalid()) { + return; + } - if (world.rand.nextFloat() > 0.1) { - return; - } - tileLeaves.onBlockTick(); - } + if (world.rand.nextFloat() > 0.1) { + return; + } + tileLeaves.onBlockTick(); + } - /* RENDERING */ - @Override - public boolean isOpaqueCube() { - return !Proxies.render.fancyGraphicsEnabled(); - } + /* RENDERING */ + @Override + public boolean isOpaqueCube() { + return !Proxies.render.fancyGraphicsEnabled(); + } - @Override - public int getRenderType() { - return PluginArboriculture.modelIdLeaves; - } + @Override + public int getRenderType() { + return PluginArboriculture.modelIdLeaves; + } - @Override - @SideOnly(Side.CLIENT) - public int colorMultiplier(IBlockAccess world, int x, int y, int z) { + @Override + @SideOnly(Side.CLIENT) + public int colorMultiplier(IBlockAccess world, int x, int y, int z) { - TileLeaves leaves = getLeafTile(world, x, y, z); - if (leaves == null) { - return super.colorMultiplier(world, x, y, z); - } + TileLeaves leaves = getLeafTile(world, x, y, z); + if (leaves == null) { + return super.colorMultiplier(world, x, y, z); + } - int colour = leaves.getFoliageColour(Proxies.common.getClientInstance().thePlayer); - if (colour == PluginArboriculture.proxy.getFoliageColorBasic()) { - colour = super.colorMultiplier(world, x, y, z); - } + int colour = leaves.getFoliageColour(Proxies.common.getClientInstance().thePlayer); + if (colour == PluginArboriculture.proxy.getFoliageColorBasic()) { + colour = super.colorMultiplier(world, x, y, z); + } - return colour; - } + return colour; + } - @Override - public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int side) { - return true; - } + @Override + public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int side) { + return true; + } - /* ICONS */ - @SideOnly(Side.CLIENT) - private static IIcon defaultIcon; + /* ICONS */ + @SideOnly(Side.CLIENT) + private static IIcon defaultIcon; - @SideOnly(Side.CLIENT) - @Override - public void registerBlockIcons(IIconRegister register) { - TextureLeaves.registerAllIcons(register); - defaultIcon = TextureLeaves.get(EnumLeafType.DECIDUOUS).getFancy(); - } + @SideOnly(Side.CLIENT) + @Override + public void registerBlockIcons(IIconRegister register) { + TextureLeaves.registerAllIcons(register); + defaultIcon = TextureLeaves.get(EnumLeafType.DECIDUOUS).getFancy(); + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(int side, int metadata) { - return defaultIcon; - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(int side, int metadata) { + return defaultIcon; + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { - TileLeaves leaves = getLeafTile(world, x, y, z); - if (leaves != null) { - return leaves.getIcon(Proxies.render.fancyGraphicsEnabled()); - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { + TileLeaves leaves = getLeafTile(world, x, y, z); + if (leaves != null) { + return leaves.getIcon(Proxies.render.fancyGraphicsEnabled()); + } - return defaultIcon; - } + return defaultIcon; + } - /* LOCALIZATION */ - @Override - public String[] func_150125_e() { - return new String[0]; - } + /* LOCALIZATION */ + @Override + public String[] func_150125_e() { + return new String[0]; + } - /* PROPERTIES */ - @Override - public int getFlammability(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return 60; - } + /* PROPERTIES */ + @Override + public int getFlammability(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return 60; + } - @Override - public boolean isFlammable(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return true; - } + @Override + public boolean isFlammable(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return true; + } - @Override - public int getFireSpreadSpeed(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - if (face == ForgeDirection.DOWN) { - return 20; - } else if (face != ForgeDirection.UP) { - return 10; - } else { - return 5; - } - } + @Override + public int getFireSpreadSpeed(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + if (face == ForgeDirection.DOWN) { + return 20; + } else if (face != ForgeDirection.UP) { + return 10; + } else { + return 5; + } + } - @Override - public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) { + @Override + public boolean onBlockActivated( + World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) { - ItemStack heldItem = player.getHeldItem(); - TileEntity tile = world.getTileEntity(x, y, z); - IButterfly caterpillar = tile instanceof TileLeaves ? ((TileLeaves) tile).getCaterpillar() : null; - if (heldItem != null && (heldItem.getItem() instanceof IToolScoop) && caterpillar != null) { - ItemStack butterfly = ButterflyManager.butterflyRoot.getMemberStack(caterpillar, EnumFlutterType.CATERPILLAR.ordinal()); - ItemStackUtil.dropItemStackAsEntity(butterfly, world, x, y, z); - ((TileLeaves) tile).setCaterpillar(null); - return true; - } + ItemStack heldItem = player.getHeldItem(); + TileEntity tile = world.getTileEntity(x, y, z); + IButterfly caterpillar = tile instanceof TileLeaves ? ((TileLeaves) tile).getCaterpillar() : null; + if (heldItem != null && (heldItem.getItem() instanceof IToolScoop) && caterpillar != null) { + ItemStack butterfly = + ButterflyManager.butterflyRoot.getMemberStack(caterpillar, EnumFlutterType.CATERPILLAR.ordinal()); + ItemStackUtil.dropItemStackAsEntity(butterfly, world, x, y, z); + ((TileLeaves) tile).setCaterpillar(null); + return true; + } - return super.onBlockActivated(world, x, y, z, player, par6, par7, par8, par9); - } + return super.onBlockActivated(world, x, y, z, player, par6, par7, par8, par9); + } - /* IGrowable */ + /* IGrowable */ - @Override - // canFertilize - public boolean func_149851_a(World world, int x, int y, int z, boolean isClient) { - TileLeaves leafTile = getLeafTile(world, x, y, z); - if (leafTile != null) { - return leafTile.hasFruit() && leafTile.getRipeness() < 1.0f; - } - return false; - } + @Override + // canFertilize + public boolean func_149851_a(World world, int x, int y, int z, boolean isClient) { + TileLeaves leafTile = getLeafTile(world, x, y, z); + if (leafTile != null) { + return leafTile.hasFruit() && leafTile.getRipeness() < 1.0f; + } + return false; + } - @Override - // shouldFertilize - public boolean func_149852_a(World world, Random random, int x, int y, int z) { - return true; - } + @Override + // shouldFertilize + public boolean func_149852_a(World world, Random random, int x, int y, int z) { + return true; + } - @Override - // fertilize - public void func_149853_b(World world, Random random, int x, int y, int z) { - TileLeaves leafTile = getLeafTile(world, x, y, z); - if (leafTile != null) { - leafTile.addRipeness(1.0f); - } - } + @Override + // fertilize + public void func_149853_b(World world, Random random, int x, int y, int z) { + TileLeaves leafTile = getLeafTile(world, x, y, z); + if (leafTile != null) { + leafTile.addRipeness(1.0f); + } + } } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockFruitPod.java b/src/main/java/forestry/arboriculture/blocks/BlockFruitPod.java index 056f0f834..14d67fdfb 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockFruitPod.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockFruitPod.java @@ -10,9 +10,15 @@ ******************************************************************************/ package forestry.arboriculture.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.arboriculture.tiles.TileFruitPod; +import forestry.core.render.TextureManager; +import forestry.core.utils.BlockUtil; +import forestry.core.utils.ItemStackUtil; +import forestry.plugins.PluginArboriculture; import java.util.ArrayList; import java.util.Random; - import net.minecraft.block.Block; import net.minecraft.block.BlockCocoa; import net.minecraft.client.renderer.texture.IIconRegister; @@ -23,146 +29,137 @@ import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.arboriculture.tiles.TileFruitPod; -import forestry.core.render.TextureManager; -import forestry.core.utils.BlockUtil; -import forestry.core.utils.ItemStackUtil; -import forestry.plugins.PluginArboriculture; - public class BlockFruitPod extends BlockCocoa { - public BlockFruitPod() { - super(); - } + public BlockFruitPod() { + super(); + } - public static TileFruitPod getPodTile(IBlockAccess world, int x, int y, int z) { - TileEntity tile = world.getTileEntity(x, y, z); - if (!(tile instanceof TileFruitPod)) { - return null; - } + public static TileFruitPod getPodTile(IBlockAccess world, int x, int y, int z) { + TileEntity tile = world.getTileEntity(x, y, z); + if (!(tile instanceof TileFruitPod)) { + return null; + } - return (TileFruitPod) tile; - } + return (TileFruitPod) tile; + } - @Override - public void updateTick(World world, int x, int y, int z, Random rand) { + @Override + public void updateTick(World world, int x, int y, int z, Random rand) { - if (!canBlockStay(world, x, y, z)) { - dropBlockAsItem(world, x, y, z, world.getBlockMetadata(x, y, z), 0); - world.setBlockToAir(x, y, z); - return; - } + if (!canBlockStay(world, x, y, z)) { + dropBlockAsItem(world, x, y, z, world.getBlockMetadata(x, y, z), 0); + world.setBlockToAir(x, y, z); + return; + } - TileFruitPod tile = getPodTile(world, x, y, z); - if (tile == null) { - return; - } + TileFruitPod tile = getPodTile(world, x, y, z); + if (tile == null) { + return; + } - tile.onBlockTick(); - } + tile.onBlockTick(); + } - @Override - public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) { - if (!world.isRemote) { - TileFruitPod tile = getPodTile(world, x, y, z); - if (tile != null) { - for (ItemStack drop : tile.getDrop()) { - ItemStackUtil.dropItemStackAsEntity(drop, world, x, y, z); - } - } - } + @Override + public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) { + if (!world.isRemote) { + TileFruitPod tile = getPodTile(world, x, y, z); + if (tile != null) { + for (ItemStack drop : tile.getDrop()) { + ItemStackUtil.dropItemStackAsEntity(drop, world, x, y, z); + } + } + } - return super.removedByPlayer(world, player, x, y, z); - } + return super.removedByPlayer(world, player, x, y, z); + } - @Override - public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - return new ArrayList<>(); - } + @Override + public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + return new ArrayList<>(); + } - @Override - public boolean canBlockStay(World world, int x, int y, int z) { - return BlockUtil.getDirectionalMetadata(world, x, y, z) >= 0; - } + @Override + public boolean canBlockStay(World world, int x, int y, int z) { + return BlockUtil.getDirectionalMetadata(world, x, y, z) >= 0; + } - @Override - public void breakBlock(World world, int x, int y, int z, Block block, int meta) { - world.removeTileEntity(x, y, z); - super.breakBlock(world, x, y, z, block, meta); - } + @Override + public void breakBlock(World world, int x, int y, int z, Block block, int meta) { + world.removeTileEntity(x, y, z); + super.breakBlock(world, x, y, z, block, meta); + } - @Override - public boolean hasTileEntity(int meta) { - return true; - } + @Override + public boolean hasTileEntity(int meta) { + return true; + } - @Override - public TileEntity createTileEntity(World world, int meta) { - return new TileFruitPod(); - } + @Override + public TileEntity createTileEntity(World world, int meta) { + return new TileFruitPod(); + } - /* ICONS */ - @SideOnly(Side.CLIENT) - private static IIcon defaultIcon; + /* ICONS */ + @SideOnly(Side.CLIENT) + private static IIcon defaultIcon; - @SideOnly(Side.CLIENT) - @Override - public void registerBlockIcons(IIconRegister register) { - defaultIcon = TextureManager.registerTex(register, "pods/papaya.2"); - } + @SideOnly(Side.CLIENT) + @Override + public void registerBlockIcons(IIconRegister register) { + defaultIcon = TextureManager.registerTex(register, "pods/papaya.2"); + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(int par1, int par2) { - return defaultIcon; - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(int par1, int par2) { + return defaultIcon; + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { - TileFruitPod pod = getPodTile(world, x, y, z); - if (pod != null) { - IIcon podIcon = pod.getIcon(); - if (podIcon != null) { - return podIcon; - } - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { + TileFruitPod pod = getPodTile(world, x, y, z); + if (pod != null) { + IIcon podIcon = pod.getIcon(); + if (podIcon != null) { + return podIcon; + } + } - return defaultIcon; - } + return defaultIcon; + } - @Override - public int getRenderType() { - return PluginArboriculture.modelIdPods; - } + @Override + public int getRenderType() { + return PluginArboriculture.modelIdPods; + } - /* IGrowable */ + /* IGrowable */ - @Override - // canFertilize - public boolean func_149851_a(World world, int x, int y, int z, boolean isClient) { - TileFruitPod podTile = getPodTile(world, x, y, z); - if (podTile != null) { - return podTile.canMature(); - } - return false; - } + @Override + // canFertilize + public boolean func_149851_a(World world, int x, int y, int z, boolean isClient) { + TileFruitPod podTile = getPodTile(world, x, y, z); + if (podTile != null) { + return podTile.canMature(); + } + return false; + } - @Override - // shouldFertilize - public boolean func_149852_a(World world, Random random, int x, int y, int z) { - return true; - } + @Override + // shouldFertilize + public boolean func_149852_a(World world, Random random, int x, int y, int z) { + return true; + } - @Override - // fertilize - public void func_149853_b(World world, Random random, int x, int y, int z) { - TileFruitPod podTile = getPodTile(world, x, y, z); - if (podTile != null) { - podTile.mature(); - } - } + @Override + // fertilize + public void func_149853_b(World world, Random random, int x, int y, int z) { + TileFruitPod podTile = getPodTile(world, x, y, z); + if (podTile != null) { + podTile.mature(); + } + } } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockLog.java b/src/main/java/forestry/arboriculture/blocks/BlockLog.java index 2fc3bb4fe..b129dfdc4 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockLog.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockLog.java @@ -10,8 +10,13 @@ ******************************************************************************/ package forestry.arboriculture.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.arboriculture.EnumWoodType; +import forestry.api.arboriculture.TreeManager; +import forestry.arboriculture.render.IconProviderWood; +import forestry.arboriculture.tiles.TileWood; import java.util.List; - import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; @@ -19,119 +24,110 @@ import net.minecraft.item.Item; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.common.util.ForgeDirection; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.api.arboriculture.TreeManager; -import forestry.arboriculture.render.IconProviderWood; -import forestry.arboriculture.tiles.TileWood; - public class BlockLog extends BlockWood { - public BlockLog(boolean fireproof) { - super("log", fireproof); - setResistance(5.0F); - setHarvestLevel("axe", 0); - } + public BlockLog(boolean fireproof) { + super("log", fireproof); + setResistance(5.0F); + setHarvestLevel("axe", 0); + } - @Override - public int getRenderType() { - return Blocks.log.getRenderType(); - } + @Override + public int getRenderType() { + return Blocks.log.getRenderType(); + } - @Override - public void breakBlock(World world, int x, int y, int z, Block block, int meta) { - super.breakBlock(world, x, y, z, block, meta); + @Override + public void breakBlock(World world, int x, int y, int z, Block block, int meta) { + super.breakBlock(world, x, y, z, block, meta); - byte radius = 4; - int boundary = radius + 1; + byte radius = 4; + int boundary = radius + 1; - if (world.checkChunksExist(x - boundary, y - boundary, z - boundary, x + boundary, y + boundary, z + boundary)) { - for (int i = -radius; i <= radius; ++i) { - for (int j = -radius; j <= radius; ++j) { - for (int k = -radius; k <= radius; ++k) { - Block neighbor = world.getBlock(x + i, y + j, z + k); + if (world.checkChunksExist( + x - boundary, y - boundary, z - boundary, x + boundary, y + boundary, z + boundary)) { + for (int i = -radius; i <= radius; ++i) { + for (int j = -radius; j <= radius; ++j) { + for (int k = -radius; k <= radius; ++k) { + Block neighbor = world.getBlock(x + i, y + j, z + k); - neighbor.beginLeavesDecay(world, x + i, y + j, z + k); - } - } - } - } - } + neighbor.beginLeavesDecay(world, x + i, y + j, z + k); + } + } + } + } + } - @Override - public int onBlockPlaced(World world, int x, int y, int z, int side, float par6, float par7, float par8, int meta) { - byte b0 = 0; + @Override + public int onBlockPlaced(World world, int x, int y, int z, int side, float par6, float par7, float par8, int meta) { + byte b0 = 0; - switch (side) { - case 0: - case 1: - b0 = 0; - break; - case 2: - case 3: - b0 = 8; - break; - case 4: - case 5: - b0 = 4; - } + switch (side) { + case 0: + case 1: + b0 = 0; + break; + case 2: + case 3: + b0 = 8; + break; + case 4: + case 5: + b0 = 4; + } - return meta | b0; - } + return meta | b0; + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubBlocks(Item item, CreativeTabs tab, List list) { - for (EnumWoodType woodType : EnumWoodType.VALUES) { - list.add(TreeManager.woodItemAccess.getLog(woodType, isFireproof())); - } - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubBlocks(Item item, CreativeTabs tab, List list) { + for (EnumWoodType woodType : EnumWoodType.VALUES) { + list.add(TreeManager.woodItemAccess.getLog(woodType, isFireproof())); + } + } - /* ICONS */ - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(int side, int meta) { - return IconProviderWood.getLogIcon(EnumWoodType.LARCH, meta, side); - } + /* ICONS */ + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(int side, int meta) { + return IconProviderWood.getLogIcon(EnumWoodType.LARCH, meta, side); + } - @Override - public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { - int meta = world.getBlockMetadata(x, y, z); - TileWood wood = TileWood.getWoodTile(world, x, y, z); - EnumWoodType type = wood.getWoodType(); - if (type == null) { - return getIcon(side, meta); - } - return IconProviderWood.getLogIcon(type, meta, side); - } + @Override + public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { + int meta = world.getBlockMetadata(x, y, z); + TileWood wood = TileWood.getWoodTile(world, x, y, z); + EnumWoodType type = wood.getWoodType(); + if (type == null) { + return getIcon(side, meta); + } + return IconProviderWood.getLogIcon(type, meta, side); + } - /* PROPERTIES */ - @Override - public int getFireSpreadSpeed(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - if (isFireproof()) { - return 0; - } else if (face == ForgeDirection.DOWN) { - return 20; - } else if (face != ForgeDirection.UP) { - return 10; - } else { - return 5; - } - } + /* PROPERTIES */ + @Override + public int getFireSpreadSpeed(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + if (isFireproof()) { + return 0; + } else if (face == ForgeDirection.DOWN) { + return 20; + } else if (face != ForgeDirection.UP) { + return 10; + } else { + return 5; + } + } - @Override - public boolean canSustainLeaves(IBlockAccess world, int x, int y, int z) { - return true; - } - - @Override - public boolean isWood(IBlockAccess world, int x, int y, int z) { - return true; - } + @Override + public boolean canSustainLeaves(IBlockAccess world, int x, int y, int z) { + return true; + } + @Override + public boolean isWood(IBlockAccess world, int x, int y, int z) { + return true; + } } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockPlanks.java b/src/main/java/forestry/arboriculture/blocks/BlockPlanks.java index c51e264bb..f5972ad08 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockPlanks.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockPlanks.java @@ -10,53 +10,49 @@ ******************************************************************************/ package forestry.arboriculture.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.arboriculture.EnumWoodType; +import forestry.api.arboriculture.TreeManager; +import forestry.arboriculture.render.IconProviderWood; +import forestry.arboriculture.tiles.TileWood; import java.util.List; - import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.api.arboriculture.TreeManager; -import forestry.arboriculture.render.IconProviderWood; -import forestry.arboriculture.tiles.TileWood; - public class BlockPlanks extends BlockWood { - public BlockPlanks(boolean fireproof) { - super("planks", fireproof); - setResistance(5.0F); - setHarvestLevel("axe", 0); - } + public BlockPlanks(boolean fireproof) { + super("planks", fireproof); + setResistance(5.0F); + setHarvestLevel("axe", 0); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List list) { - for (EnumWoodType woodType : EnumWoodType.VALUES) { - list.add(TreeManager.woodItemAccess.getPlanks(woodType, isFireproof())); - } - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List list) { + for (EnumWoodType woodType : EnumWoodType.VALUES) { + list.add(TreeManager.woodItemAccess.getPlanks(woodType, isFireproof())); + } + } - /* ICONS */ - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(int side, int meta) { - EnumWoodType woodType = EnumWoodType.LARCH; - if (meta > 0 && meta < EnumWoodType.VALUES.length) { - woodType = EnumWoodType.VALUES[meta]; - } - return IconProviderWood.getPlankIcon(woodType); - } - - @Override - public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { - TileWood wood = TileWood.getWoodTile(world, x, y, z); - EnumWoodType woodType = wood.getWoodType(); - return IconProviderWood.getPlankIcon(woodType); - } + /* ICONS */ + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(int side, int meta) { + EnumWoodType woodType = EnumWoodType.LARCH; + if (meta > 0 && meta < EnumWoodType.VALUES.length) { + woodType = EnumWoodType.VALUES[meta]; + } + return IconProviderWood.getPlankIcon(woodType); + } + @Override + public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { + TileWood wood = TileWood.getWoodTile(world, x, y, z); + EnumWoodType woodType = wood.getWoodType(); + return IconProviderWood.getPlankIcon(woodType); + } } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockRegistryArboriculture.java b/src/main/java/forestry/arboriculture/blocks/BlockRegistryArboriculture.java index f44eb61ff..5ee583a87 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockRegistryArboriculture.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockRegistryArboriculture.java @@ -1,93 +1,105 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.blocks; - -import forestry.arboriculture.items.ItemBlockLeaves; -import forestry.arboriculture.items.ItemBlockWood; -import forestry.arboriculture.items.ItemBlockWoodSlab; -import forestry.core.blocks.BlockRegistry; -import forestry.core.items.ItemBlockForestry; - -public class BlockRegistryArboriculture extends BlockRegistry { - public final BlockLog logs; - public final BlockPlanks planks; - public final BlockSlab slabs; - public final BlockSlab slabsDouble; - public final BlockArbFence fences; - public final BlockArbStairs stairs; - public final BlockLog logsFireproof; - public final BlockPlanks planksFireproof; - public final BlockSlab slabsFireproof; - public final BlockSlab slabsDoubleFireproof; - public final BlockArbFence fencesFireproof; - public final BlockArbStairs stairsFireproof; - - public final BlockSapling saplingGE; - public final BlockForestryLeaves leaves; - public final BlockFruitPod pods; - - public final BlockArboriculture arboriculture; - - public BlockRegistryArboriculture() { - // Wood blocks - logs = registerBlock(new BlockLog(false), ItemBlockWood.class, "logs"); - registerOreDictWildcard("logWood", logs); - - planks = registerBlock(new BlockPlanks(false), ItemBlockWood.class, "planks"); - registerOreDictWildcard("plankWood", planks); - - BlockSlab blockSlab = new BlockSlab(false, false); - BlockSlab blockSlabDouble = new BlockSlab(true, false); - slabs = registerBlock(blockSlab, ItemBlockWoodSlab.class, "slabs", blockSlabDouble, blockSlab); - registerOreDictWildcard("slabWood", slabs); - - slabsDouble = registerBlock(blockSlabDouble, ItemBlockWoodSlab.class, "slabsDouble", blockSlabDouble, blockSlab); - - fences = registerBlock(new BlockArbFence(false), ItemBlockWood.class, "fences"); - registerOreDictWildcard("fenceWood", fences); - - stairs = registerBlock(new BlockArbStairs(planks, false), ItemBlockWood.class, "stairs"); - registerOreDictWildcard("stairWood", stairs); - - logsFireproof = registerBlock(new BlockLog(true), ItemBlockWood.class, "logsFireproof"); - registerOreDictWildcard("logWood", logsFireproof); - - planksFireproof = registerBlock(new BlockPlanks(true), ItemBlockWood.class, "planksFireproof"); - registerOreDictWildcard("plankWood", planksFireproof); - - BlockSlab blockSlabFireproof = new BlockSlab(false, true); - BlockSlab blockSlabDoubleFireproof = new BlockSlab(true, true); - slabsFireproof = registerBlock(blockSlabFireproof, ItemBlockWoodSlab.class, "slabsFireproof", blockSlabDoubleFireproof, blockSlabFireproof); - registerOreDictWildcard("slabWood", slabsFireproof); - - slabsDoubleFireproof = registerBlock(blockSlabDoubleFireproof, ItemBlockWoodSlab.class, "slabsDoubleFireproof", blockSlabDoubleFireproof, blockSlabFireproof); - - fencesFireproof = registerBlock(new BlockArbFence(true), ItemBlockWood.class, "fencesFireproof"); - registerOreDictWildcard("fenceWood", fencesFireproof); - - stairsFireproof = registerBlock(new BlockArbStairs(planksFireproof, true), ItemBlockWood.class, "stairsFireproof"); - registerOreDictWildcard("stairWood", stairsFireproof); - - // Saplings - saplingGE = registerBlock(new BlockSapling(), ItemBlockForestry.class, "saplingGE"); - registerOreDictWildcard("treeSapling", saplingGE); - - // Leaves - leaves = registerBlock(new BlockForestryLeaves(), ItemBlockLeaves.class, "leaves"); - registerOreDictWildcard("treeLeaves", leaves); - - // Pods - pods = registerBlock(new BlockFruitPod(), ItemBlockForestry.class, "pods"); - - // Machines - arboriculture = registerBlock(new BlockArboriculture(), ItemBlockForestry.class, "arboriculture"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.blocks; + +import forestry.arboriculture.items.ItemBlockLeaves; +import forestry.arboriculture.items.ItemBlockWood; +import forestry.arboriculture.items.ItemBlockWoodSlab; +import forestry.core.blocks.BlockRegistry; +import forestry.core.items.ItemBlockForestry; + +public class BlockRegistryArboriculture extends BlockRegistry { + public final BlockLog logs; + public final BlockPlanks planks; + public final BlockSlab slabs; + public final BlockSlab slabsDouble; + public final BlockArbFence fences; + public final BlockArbStairs stairs; + public final BlockLog logsFireproof; + public final BlockPlanks planksFireproof; + public final BlockSlab slabsFireproof; + public final BlockSlab slabsDoubleFireproof; + public final BlockArbFence fencesFireproof; + public final BlockArbStairs stairsFireproof; + + public final BlockSapling saplingGE; + public final BlockForestryLeaves leaves; + public final BlockFruitPod pods; + + public final BlockArboriculture arboriculture; + + public BlockRegistryArboriculture() { + // Wood blocks + logs = registerBlock(new BlockLog(false), ItemBlockWood.class, "logs"); + registerOreDictWildcard("logWood", logs); + + planks = registerBlock(new BlockPlanks(false), ItemBlockWood.class, "planks"); + registerOreDictWildcard("plankWood", planks); + + BlockSlab blockSlab = new BlockSlab(false, false); + BlockSlab blockSlabDouble = new BlockSlab(true, false); + slabs = registerBlock(blockSlab, ItemBlockWoodSlab.class, "slabs", blockSlabDouble, blockSlab); + registerOreDictWildcard("slabWood", slabs); + + slabsDouble = + registerBlock(blockSlabDouble, ItemBlockWoodSlab.class, "slabsDouble", blockSlabDouble, blockSlab); + + fences = registerBlock(new BlockArbFence(false), ItemBlockWood.class, "fences"); + registerOreDictWildcard("fenceWood", fences); + + stairs = registerBlock(new BlockArbStairs(planks, false), ItemBlockWood.class, "stairs"); + registerOreDictWildcard("stairWood", stairs); + + logsFireproof = registerBlock(new BlockLog(true), ItemBlockWood.class, "logsFireproof"); + registerOreDictWildcard("logWood", logsFireproof); + + planksFireproof = registerBlock(new BlockPlanks(true), ItemBlockWood.class, "planksFireproof"); + registerOreDictWildcard("plankWood", planksFireproof); + + BlockSlab blockSlabFireproof = new BlockSlab(false, true); + BlockSlab blockSlabDoubleFireproof = new BlockSlab(true, true); + slabsFireproof = registerBlock( + blockSlabFireproof, + ItemBlockWoodSlab.class, + "slabsFireproof", + blockSlabDoubleFireproof, + blockSlabFireproof); + registerOreDictWildcard("slabWood", slabsFireproof); + + slabsDoubleFireproof = registerBlock( + blockSlabDoubleFireproof, + ItemBlockWoodSlab.class, + "slabsDoubleFireproof", + blockSlabDoubleFireproof, + blockSlabFireproof); + + fencesFireproof = registerBlock(new BlockArbFence(true), ItemBlockWood.class, "fencesFireproof"); + registerOreDictWildcard("fenceWood", fencesFireproof); + + stairsFireproof = + registerBlock(new BlockArbStairs(planksFireproof, true), ItemBlockWood.class, "stairsFireproof"); + registerOreDictWildcard("stairWood", stairsFireproof); + + // Saplings + saplingGE = registerBlock(new BlockSapling(), ItemBlockForestry.class, "saplingGE"); + registerOreDictWildcard("treeSapling", saplingGE); + + // Leaves + leaves = registerBlock(new BlockForestryLeaves(), ItemBlockLeaves.class, "leaves"); + registerOreDictWildcard("treeLeaves", leaves); + + // Pods + pods = registerBlock(new BlockFruitPod(), ItemBlockForestry.class, "pods"); + + // Machines + arboriculture = registerBlock(new BlockArboriculture(), ItemBlockForestry.class, "arboriculture"); + } +} diff --git a/src/main/java/forestry/arboriculture/blocks/BlockSapling.java b/src/main/java/forestry/arboriculture/blocks/BlockSapling.java index e657e55e0..604978a79 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockSapling.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockSapling.java @@ -10,9 +10,21 @@ ******************************************************************************/ package forestry.arboriculture.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.arboriculture.EnumGermlingType; +import forestry.api.arboriculture.IAlleleFruit; +import forestry.api.arboriculture.IAlleleTreeSpecies; +import forestry.api.arboriculture.TreeManager; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllele; +import forestry.arboriculture.tiles.TileSapling; +import forestry.core.render.TextureManager; +import forestry.core.tiles.TileUtil; +import forestry.core.utils.ItemStackUtil; +import forestry.plugins.PluginArboriculture; import java.util.ArrayList; import java.util.Random; - import net.minecraft.block.Block; import net.minecraft.block.IGrowable; import net.minecraft.block.material.Material; @@ -26,188 +38,172 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.arboriculture.EnumGermlingType; -import forestry.api.arboriculture.IAlleleFruit; -import forestry.api.arboriculture.IAlleleTreeSpecies; -import forestry.api.arboriculture.TreeManager; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAllele; -import forestry.arboriculture.tiles.TileSapling; -import forestry.core.render.TextureManager; -import forestry.core.tiles.TileUtil; -import forestry.core.utils.ItemStackUtil; -import forestry.plugins.PluginArboriculture; - public class BlockSapling extends BlockTreeContainer implements IGrowable { - public static TileSapling getSaplingTile(IBlockAccess world, int x, int y, int z) { - return TileUtil.getTile(world, x, y, z, TileSapling.class); - } + public static TileSapling getSaplingTile(IBlockAccess world, int x, int y, int z) { + return TileUtil.getTile(world, x, y, z, TileSapling.class); + } - public BlockSapling() { - super(Material.plants); + public BlockSapling() { + super(Material.plants); - float factor = 0.4F; - setBlockBounds(0.5F - factor, 0.0F, 0.5F - factor, 0.5F + factor, factor * 2.0F, 0.5F + factor); - setStepSound(soundTypeGrass); - } + float factor = 0.4F; + setBlockBounds(0.5F - factor, 0.0F, 0.5F - factor, 0.5F + factor, factor * 2.0F, 0.5F + factor); + setStepSound(soundTypeGrass); + } - @Override - public TileEntity createNewTileEntity(World var1, int meta) { - return new TileSapling(); - } + @Override + public TileEntity createNewTileEntity(World var1, int meta) { + return new TileSapling(); + } - /* COLLISION BOX */ - @Override - public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z) { - return null; - } + /* COLLISION BOX */ + @Override + public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z) { + return null; + } - /* RENDERING */ - @Override - public boolean isOpaqueCube() { - return false; - } + /* RENDERING */ + @Override + public boolean isOpaqueCube() { + return false; + } - @Override - public boolean renderAsNormalBlock() { - return false; - } + @Override + public boolean renderAsNormalBlock() { + return false; + } - @Override - public int getRenderType() { - return PluginArboriculture.modelIdSaplings; - } + @Override + public int getRenderType() { + return PluginArboriculture.modelIdSaplings; + } - /* ICONS */ - @SideOnly(Side.CLIENT) - private static IIcon defaultIcon; + /* ICONS */ + @SideOnly(Side.CLIENT) + private static IIcon defaultIcon; - @SideOnly(Side.CLIENT) - @Override - public void registerBlockIcons(IIconRegister register) { - defaultIcon = TextureManager.registerTex(register, "germlings/sapling.treeBalsa"); + @SideOnly(Side.CLIENT) + @Override + public void registerBlockIcons(IIconRegister register) { + defaultIcon = TextureManager.registerTex(register, "germlings/sapling.treeBalsa"); - for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { - if (allele instanceof IAlleleTreeSpecies) { - ((IAlleleTreeSpecies) allele).getIconProvider().registerIcons(register); - } - if (allele instanceof IAlleleFruit) { - ((IAlleleFruit) allele).getProvider().registerIcons(register); - } - } + for (IAllele allele : + AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleTreeSpecies) { + ((IAlleleTreeSpecies) allele).getIconProvider().registerIcons(register); + } + if (allele instanceof IAlleleFruit) { + ((IAlleleFruit) allele).getProvider().registerIcons(register); + } + } + } - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(int side, int metadata) { + return defaultIcon; + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(int side, int metadata) { - return defaultIcon; - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { + TileSapling sapling = getSaplingTile(world, x, y, z); + if (sapling == null) { + return defaultIcon; + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { - TileSapling sapling = getSaplingTile(world, x, y, z); - if (sapling == null) { - return defaultIcon; - } + if (sapling.getTree() == null) { + return defaultIcon; + } - if (sapling.getTree() == null) { - return defaultIcon; - } + return sapling.getTree().getGenome().getPrimary().getGermlingIcon(EnumGermlingType.SAPLING, 0); + } - return sapling.getTree().getGenome().getPrimary().getGermlingIcon(EnumGermlingType.SAPLING, 0); - } + /* PLANTING */ + @Override + public boolean canBlockStay(World world, int x, int y, int z) { + TileSapling tile = getSaplingTile(world, x, y, z); + if (tile == null) { + return false; + } + if (tile.getTree() == null) { + return false; + } - /* PLANTING */ - @Override - public boolean canBlockStay(World world, int x, int y, int z) { - TileSapling tile = getSaplingTile(world, x, y, z); - if (tile == null) { - return false; - } - if (tile.getTree() == null) { - return false; - } + return tile.getTree().canStay(world, x, y, z); + } - return tile.getTree().canStay(world, x, y, z); - } + @Override + public void onNeighborBlockChange(World world, int x, int y, int z, Block neighbour) { + super.onNeighborBlockChange(world, x, y, z, neighbour); + if (!world.isRemote && !this.canBlockStay(world, x, y, z)) { + dropAsSapling(world, x, y, z); + world.setBlockToAir(x, y, z); + } + } - @Override - public void onNeighborBlockChange(World world, int x, int y, int z, Block neighbour) { - super.onNeighborBlockChange(world, x, y, z, neighbour); - if (!world.isRemote && !this.canBlockStay(world, x, y, z)) { - dropAsSapling(world, x, y, z); - world.setBlockToAir(x, y, z); - } + /* REMOVING */ + @Override + public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + return new ArrayList<>(); + } - } + @Override + public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { + TileSapling sapling = getSaplingTile(world, x, y, z); + if (sapling == null || sapling.getTree() == null) { + return null; + } + return TreeManager.treeRoot.getMemberStack(sapling.getTree(), EnumGermlingType.SAPLING.ordinal()); + } - /* REMOVING */ - @Override - public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - return new ArrayList<>(); - } + @Override + public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) { + if (!world.isRemote && canHarvestBlock(player, world.getBlockMetadata(x, y, z))) { + if (!player.capabilities.isCreativeMode) { + dropAsSapling(world, x, y, z); + } + } - @Override - public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { - TileSapling sapling = getSaplingTile(world, x, y, z); - if (sapling == null || sapling.getTree() == null) { - return null; - } - return TreeManager.treeRoot.getMemberStack(sapling.getTree(), EnumGermlingType.SAPLING.ordinal()); - } + return world.setBlockToAir(x, y, z); + } - @Override - public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) { - if (!world.isRemote && canHarvestBlock(player, world.getBlockMetadata(x, y, z))) { - if (!player.capabilities.isCreativeMode) { - dropAsSapling(world, x, y, z); - } - } + private static void dropAsSapling(World world, int x, int y, int z) { + if (world.isRemote) { + return; + } - return world.setBlockToAir(x, y, z); - } + TileSapling sapling = getSaplingTile(world, x, y, z); + if (sapling != null && sapling.getTree() != null) { + ItemStack saplingStack = + TreeManager.treeRoot.getMemberStack(sapling.getTree(), EnumGermlingType.SAPLING.ordinal()); + ItemStackUtil.dropItemStackAsEntity(saplingStack, world, x, y, z); + } + } - private static void dropAsSapling(World world, int x, int y, int z) { - if (world.isRemote) { - return; - } + @Override + /** canFertilize */ + public boolean func_149851_a(World world, int x, int y, int z, boolean isClient) { + TileSapling saplingTile = getSaplingTile(world, x, y, z); + if (saplingTile != null) { + return saplingTile.canAcceptBoneMeal(); + } + return true; + } - TileSapling sapling = getSaplingTile(world, x, y, z); - if (sapling != null && sapling.getTree() != null) { - ItemStack saplingStack = TreeManager.treeRoot.getMemberStack(sapling.getTree(), EnumGermlingType.SAPLING.ordinal()); - ItemStackUtil.dropItemStackAsEntity(saplingStack, world, x, y, z); - } + @Override + /** shouldFertilize */ + public boolean func_149852_a(World world, Random random, int x, int y, int z) { + return world.rand.nextFloat() < 0.45F; + } - } - - @Override - /** canFertilize */ - public boolean func_149851_a(World world, int x, int y, int z, boolean isClient) { - TileSapling saplingTile = getSaplingTile(world, x, y, z); - if (saplingTile != null) { - return saplingTile.canAcceptBoneMeal(); - } - return true; - } - - @Override - /** shouldFertilize */ - public boolean func_149852_a(World world, Random random, int x, int y, int z) { - return world.rand.nextFloat() < 0.45F; - } - - @Override - /** fertilize */ - public void func_149853_b(World world, Random random, int x, int y, int z) { - TileSapling saplingTile = getSaplingTile(world, x, y, z); - if (saplingTile != null) { - saplingTile.tryGrow(true); - } - } + @Override + /** fertilize */ + public void func_149853_b(World world, Random random, int x, int y, int z) { + TileSapling saplingTile = getSaplingTile(world, x, y, z); + if (saplingTile != null) { + saplingTile.tryGrow(true); + } + } } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockSlab.java b/src/main/java/forestry/arboriculture/blocks/BlockSlab.java index b11c31f08..d957ef3e5 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockSlab.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockSlab.java @@ -10,9 +10,17 @@ ******************************************************************************/ package forestry.arboriculture.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.arboriculture.EnumWoodType; +import forestry.api.arboriculture.TreeManager; +import forestry.api.core.Tabs; +import forestry.arboriculture.IWoodTyped; +import forestry.arboriculture.render.IconProviderWood; +import forestry.arboriculture.tiles.TileWood; +import forestry.core.render.ParticleHelper; import java.util.ArrayList; import java.util.List; - import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.Material; import net.minecraft.client.particle.EffectRenderer; @@ -27,175 +35,163 @@ import net.minecraft.util.IIcon; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.common.util.ForgeDirection; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.api.arboriculture.TreeManager; -import forestry.api.core.Tabs; -import forestry.arboriculture.IWoodTyped; -import forestry.arboriculture.render.IconProviderWood; -import forestry.arboriculture.tiles.TileWood; -import forestry.core.render.ParticleHelper; - public class BlockSlab extends net.minecraft.block.BlockSlab implements IWoodTyped, ITileEntityProvider { - private final ParticleHelper.Callback particleCallback; - private final boolean fireproof; + private final ParticleHelper.Callback particleCallback; + private final boolean fireproof; - public BlockSlab(boolean doubleSlab, boolean fireproof) { - super(doubleSlab, Material.wood); + public BlockSlab(boolean doubleSlab, boolean fireproof) { + super(doubleSlab, Material.wood); - this.fireproof = fireproof; + this.fireproof = fireproof; - setCreativeTab(Tabs.tabArboriculture); - setLightOpacity(0); - setHardness(2.0F); - setResistance(5.0F); - setStepSound(soundTypeWood); - setHarvestLevel("axe", 0); + setCreativeTab(Tabs.tabArboriculture); + setLightOpacity(0); + setHardness(2.0F); + setResistance(5.0F); + setStepSound(soundTypeWood); + setHarvestLevel("axe", 0); - this.particleCallback = new ParticleHelper.DefaultCallback(this); - } + this.particleCallback = new ParticleHelper.DefaultCallback(this); + } - public boolean isDoubleSlab() { - return field_150004_a; - } + public boolean isDoubleSlab() { + return field_150004_a; + } - /* ICONS */ - @SideOnly(Side.CLIENT) - @Override - public void registerBlockIcons(IIconRegister register) { - IconProviderWood.registerIcons(register); - } + /* ICONS */ + @SideOnly(Side.CLIENT) + @Override + public void registerBlockIcons(IIconRegister register) { + IconProviderWood.registerIcons(register); + } - /* ICONS */ - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(int side, int meta) { - return IconProviderWood.getPlankIcon(EnumWoodType.LARCH); - } + /* ICONS */ + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(int side, int meta) { + return IconProviderWood.getPlankIcon(EnumWoodType.LARCH); + } - @Override - public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { - TileWood wood = TileWood.getWoodTile(world, x, y, z); - EnumWoodType woodType = wood.getWoodType(); - return IconProviderWood.getPlankIcon(woodType); - } + @Override + public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { + TileWood wood = TileWood.getWoodTile(world, x, y, z); + EnumWoodType woodType = wood.getWoodType(); + return IconProviderWood.getPlankIcon(woodType); + } - @Override - protected ItemStack createStackedBlock(int meta) { - return new ItemStack(Blocks.wooden_slab, 2, meta & 7); - } + @Override + protected ItemStack createStackedBlock(int meta) { + return new ItemStack(Blocks.wooden_slab, 2, meta & 7); + } - @Override - public String func_150002_b(int var1) { - return "SomeSlab"; - } + @Override + public String func_150002_b(int var1) { + return "SomeSlab"; + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List list) { - if (!isDoubleSlab()) { - for (EnumWoodType woodType : EnumWoodType.VALUES) { - list.add(TreeManager.woodItemAccess.getSlab(woodType, fireproof)); - } - } - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List list) { + if (!isDoubleSlab()) { + for (EnumWoodType woodType : EnumWoodType.VALUES) { + list.add(TreeManager.woodItemAccess.getSlab(woodType, fireproof)); + } + } + } - @Override - public final TileEntity createNewTileEntity(World world, int meta) { - return new TileWood(); - } + @Override + public final TileEntity createNewTileEntity(World world, int meta) { + return new TileWood(); + } - /* PROPERTIES */ - @Override - public final ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { - return TileWood.getPickBlock(this, world, x, y, z); - } + /* PROPERTIES */ + @Override + public final ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { + return TileWood.getPickBlock(this, world, x, y, z); + } - /* DROP HANDLING */ - // Hack: When harvesting we need to get the drops in onBlockHarvested, - // because Mojang destroys the block and tile before calling getDrops. - private final ThreadLocal> drops = new ThreadLocal<>(); + /* DROP HANDLING */ + // Hack: When harvesting we need to get the drops in onBlockHarvested, + // because Mojang destroys the block and tile before calling getDrops. + private final ThreadLocal> drops = new ThreadLocal<>(); - @Override - public void onBlockHarvested(World world, int x, int y, int z, int meta, EntityPlayer playerProfile) { - drops.set(TileWood.getDrops(this, world, x, y, z)); - } + @Override + public void onBlockHarvested(World world, int x, int y, int z, int meta, EntityPlayer playerProfile) { + drops.set(TileWood.getDrops(this, world, x, y, z)); + } - @Override - public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - ArrayList ret = drops.get(); - drops.remove(); + @Override + public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + ArrayList ret = drops.get(); + drops.remove(); - // not harvested, get drops normally - if (ret == null) { - ret = TileWood.getDrops(this, world, x, y, z); - } + // not harvested, get drops normally + if (ret == null) { + ret = TileWood.getDrops(this, world, x, y, z); + } - return ret; - } + return ret; + } - @Override - public final float getBlockHardness(World world, int x, int y, int z) { - TileWood wood = TileWood.getWoodTile(world, x, y, z); - if (wood == null) { - return EnumWoodType.DEFAULT_HARDNESS; - } - return wood.getWoodType().getHardness(); - } + @Override + public final float getBlockHardness(World world, int x, int y, int z) { + TileWood wood = TileWood.getWoodTile(world, x, y, z); + if (wood == null) { + return EnumWoodType.DEFAULT_HARDNESS; + } + return wood.getWoodType().getHardness(); + } - @Override - public final boolean isFlammable(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return !isFireproof(); - } + @Override + public final boolean isFlammable(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return !isFireproof(); + } - @Override - public int getFlammability(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return isFireproof() ? 0 : 20; - } + @Override + public int getFlammability(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return isFireproof() ? 0 : 20; + } - @Override - public int getFireSpreadSpeed(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return isFireproof() ? 0 : 5; - } + @Override + public int getFireSpreadSpeed(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return isFireproof() ? 0 : 5; + } - @Override - public String getBlockKind() { - return "slab"; - } + @Override + public String getBlockKind() { + return "slab"; + } - @Override - public boolean isFireproof() { - return fireproof; - } + @Override + public boolean isFireproof() { + return fireproof; + } - @Override - public boolean getUseNeighborBrightness() { - return true; - } + @Override + public boolean getUseNeighborBrightness() { + return true; + } - // Minecraft's BlockSlab overrides this for their slabs, so we change it back to normal here - @Override - @SideOnly(Side.CLIENT) - public Item getItem(World world, int x, int y, int z) { - return Item.getItemFromBlock(this); - } + // Minecraft's BlockSlab overrides this for their slabs, so we change it back to normal here + @Override + @SideOnly(Side.CLIENT) + public Item getItem(World world, int x, int y, int z) { + return Item.getItemFromBlock(this); + } - /* Particles */ - @SideOnly(Side.CLIENT) - @Override - public boolean addHitEffects(World worldObj, MovingObjectPosition target, EffectRenderer effectRenderer) { - return ParticleHelper.addHitEffects(worldObj, this, target, effectRenderer, particleCallback); - } + /* Particles */ + @SideOnly(Side.CLIENT) + @Override + public boolean addHitEffects(World worldObj, MovingObjectPosition target, EffectRenderer effectRenderer) { + return ParticleHelper.addHitEffects(worldObj, this, target, effectRenderer, particleCallback); + } - @SideOnly(Side.CLIENT) - @Override - public boolean addDestroyEffects(World worldObj, int x, int y, int z, int meta, EffectRenderer effectRenderer) { - return ParticleHelper.addDestroyEffects(worldObj, this, x, y, z, meta, effectRenderer, particleCallback); - } + @SideOnly(Side.CLIENT) + @Override + public boolean addDestroyEffects(World worldObj, int x, int y, int z, int meta, EffectRenderer effectRenderer) { + return ParticleHelper.addDestroyEffects(worldObj, this, x, y, z, meta, effectRenderer, particleCallback); + } } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockTreeContainer.java b/src/main/java/forestry/arboriculture/blocks/BlockTreeContainer.java index 4c0aae430..03c82e867 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockTreeContainer.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockTreeContainer.java @@ -10,40 +10,37 @@ ******************************************************************************/ package forestry.arboriculture.blocks; +import forestry.arboriculture.tiles.TileTreeContainer; import java.util.Random; - import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import forestry.arboriculture.tiles.TileTreeContainer; - public abstract class BlockTreeContainer extends BlockContainer { - protected BlockTreeContainer(Material material) { - super(material); - setTickRandomly(true); - } + protected BlockTreeContainer(Material material) { + super(material); + setTickRandomly(true); + } - @Override - public void updateTick(World world, int x, int y, int z, Random rand) { + @Override + public void updateTick(World world, int x, int y, int z, Random rand) { - if (world.rand.nextFloat() > 0.1) { - return; - } + if (world.rand.nextFloat() > 0.1) { + return; + } - TileEntity tile = world.getTileEntity(x, y, z); - if (!(tile instanceof TileTreeContainer)) { - return; - } + TileEntity tile = world.getTileEntity(x, y, z); + if (!(tile instanceof TileTreeContainer)) { + return; + } - ((TileTreeContainer) tile).onBlockTick(); - } - - @Override - public boolean hasTileEntity(int metadata) { - return true; - } + ((TileTreeContainer) tile).onBlockTick(); + } + @Override + public boolean hasTileEntity(int metadata) { + return true; + } } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockWood.java b/src/main/java/forestry/arboriculture/blocks/BlockWood.java index baf06bb37..655eb4551 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockWood.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockWood.java @@ -1,145 +1,141 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.blocks; - -import java.util.ArrayList; - -import net.minecraft.block.Block; -import net.minecraft.block.ITileEntityProvider; -import net.minecraft.block.material.Material; -import net.minecraft.client.particle.EffectRenderer; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.IIcon; -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.api.core.Tabs; -import forestry.arboriculture.IWoodTyped; -import forestry.arboriculture.render.IconProviderWood; -import forestry.arboriculture.tiles.TileWood; -import forestry.core.render.ParticleHelper; - -public abstract class BlockWood extends Block implements ITileEntityProvider, IWoodTyped { - - private final ParticleHelper.Callback particleCallback; - private final String blockKind; - private final boolean fireproof; - - protected BlockWood(String blockKind, boolean fireproof) { - super(Material.wood); - this.blockKind = blockKind; - this.fireproof = fireproof; - - setStepSound(soundTypeWood); - setCreativeTab(Tabs.tabArboriculture); - - particleCallback = new ParticleHelper.DefaultCallback(this); - } - - @Override - public final String getBlockKind() { - return blockKind; - } - - @Override - public boolean isFireproof() { - return fireproof; - } - - @SideOnly(Side.CLIENT) - @Override - public final void registerBlockIcons(IIconRegister register) { - IconProviderWood.registerIcons(register); - } - - @Override - public final TileEntity createNewTileEntity(World world, int meta) { - return new TileWood(); - } - - @Override - public final ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { - return TileWood.getPickBlock(this, world, x, y, z); - } - - /* DROP HANDLING */ - // Hack: When harvesting we need to get the drops in onBlockHarvested, - // because Mojang destroys the block and tile before calling getDrops. - private final ThreadLocal> drops = new ThreadLocal<>(); - - @Override - public void onBlockHarvested(World world, int x, int y, int z, int meta, EntityPlayer playerProfile) { - drops.set(TileWood.getDrops(this, world, x, y, z)); - } - - @Override - public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - ArrayList ret = drops.get(); - drops.remove(); - - // not harvested, get drops normally - if (ret == null) { - ret = TileWood.getDrops(this, world, x, y, z); - } - - return ret; - } - - @Override - public final float getBlockHardness(World world, int x, int y, int z) { - TileWood wood = TileWood.getWoodTile(world, x, y, z); - if (wood == null) { - return EnumWoodType.DEFAULT_HARDNESS; - } - return wood.getWoodType().getHardness(); - } - - @Override - public final boolean isFlammable(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return !isFireproof(); - } - - @Override - public int getFlammability(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return isFireproof() ? 0 : 20; - } - - @Override - public int getFireSpreadSpeed(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return isFireproof() ? 0 : 5; - } - - @SideOnly(Side.CLIENT) - public abstract IIcon getIcon(IBlockAccess world, int x, int y, int z, int side); - - /* Particles */ - @SideOnly(Side.CLIENT) - @Override - public boolean addHitEffects(World worldObj, MovingObjectPosition target, EffectRenderer effectRenderer) { - return ParticleHelper.addHitEffects(worldObj, this, target, effectRenderer, particleCallback); - } - - @SideOnly(Side.CLIENT) - @Override - public boolean addDestroyEffects(World worldObj, int x, int y, int z, int meta, EffectRenderer effectRenderer) { - return ParticleHelper.addDestroyEffects(worldObj, this, x, y, z, meta, effectRenderer, particleCallback); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.blocks; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.arboriculture.EnumWoodType; +import forestry.api.core.Tabs; +import forestry.arboriculture.IWoodTyped; +import forestry.arboriculture.render.IconProviderWood; +import forestry.arboriculture.tiles.TileWood; +import forestry.core.render.ParticleHelper; +import java.util.ArrayList; +import net.minecraft.block.Block; +import net.minecraft.block.ITileEntityProvider; +import net.minecraft.block.material.Material; +import net.minecraft.client.particle.EffectRenderer; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +public abstract class BlockWood extends Block implements ITileEntityProvider, IWoodTyped { + + private final ParticleHelper.Callback particleCallback; + private final String blockKind; + private final boolean fireproof; + + protected BlockWood(String blockKind, boolean fireproof) { + super(Material.wood); + this.blockKind = blockKind; + this.fireproof = fireproof; + + setStepSound(soundTypeWood); + setCreativeTab(Tabs.tabArboriculture); + + particleCallback = new ParticleHelper.DefaultCallback(this); + } + + @Override + public final String getBlockKind() { + return blockKind; + } + + @Override + public boolean isFireproof() { + return fireproof; + } + + @SideOnly(Side.CLIENT) + @Override + public final void registerBlockIcons(IIconRegister register) { + IconProviderWood.registerIcons(register); + } + + @Override + public final TileEntity createNewTileEntity(World world, int meta) { + return new TileWood(); + } + + @Override + public final ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { + return TileWood.getPickBlock(this, world, x, y, z); + } + + /* DROP HANDLING */ + // Hack: When harvesting we need to get the drops in onBlockHarvested, + // because Mojang destroys the block and tile before calling getDrops. + private final ThreadLocal> drops = new ThreadLocal<>(); + + @Override + public void onBlockHarvested(World world, int x, int y, int z, int meta, EntityPlayer playerProfile) { + drops.set(TileWood.getDrops(this, world, x, y, z)); + } + + @Override + public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + ArrayList ret = drops.get(); + drops.remove(); + + // not harvested, get drops normally + if (ret == null) { + ret = TileWood.getDrops(this, world, x, y, z); + } + + return ret; + } + + @Override + public final float getBlockHardness(World world, int x, int y, int z) { + TileWood wood = TileWood.getWoodTile(world, x, y, z); + if (wood == null) { + return EnumWoodType.DEFAULT_HARDNESS; + } + return wood.getWoodType().getHardness(); + } + + @Override + public final boolean isFlammable(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return !isFireproof(); + } + + @Override + public int getFlammability(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return isFireproof() ? 0 : 20; + } + + @Override + public int getFireSpreadSpeed(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return isFireproof() ? 0 : 5; + } + + @SideOnly(Side.CLIENT) + public abstract IIcon getIcon(IBlockAccess world, int x, int y, int z, int side); + + /* Particles */ + @SideOnly(Side.CLIENT) + @Override + public boolean addHitEffects(World worldObj, MovingObjectPosition target, EffectRenderer effectRenderer) { + return ParticleHelper.addHitEffects(worldObj, this, target, effectRenderer, particleCallback); + } + + @SideOnly(Side.CLIENT) + @Override + public boolean addDestroyEffects(World worldObj, int x, int y, int z, int meta, EffectRenderer effectRenderer) { + return ParticleHelper.addDestroyEffects(worldObj, this, x, y, z, meta, effectRenderer, particleCallback); + } +} diff --git a/src/main/java/forestry/arboriculture/commands/CommandTree.java b/src/main/java/forestry/arboriculture/commands/CommandTree.java index f15d86448..5712bb3cc 100644 --- a/src/main/java/forestry/arboriculture/commands/CommandTree.java +++ b/src/main/java/forestry/arboriculture/commands/CommandTree.java @@ -18,16 +18,15 @@ import forestry.core.commands.SubCommand; public class CommandTree extends SubCommand { - public CommandTree() { - super("tree"); + public CommandTree() { + super("tree"); - IStatsSaveHelper saveHelper = new TreeStatsSaveHelper(); - ICommandModeHelper modeHelper = new TreeModeHelper(); - - addChildCommand(new CommandTreeSpawn("spawnTree", new TreeSpawner())); - addChildCommand(new CommandTreeSpawn("spawnForest", new ForestSpawner())); - addChildCommand(new CommandMode(modeHelper)); - addChildCommand(new CommandSaveStats(saveHelper, modeHelper)); - } + IStatsSaveHelper saveHelper = new TreeStatsSaveHelper(); + ICommandModeHelper modeHelper = new TreeModeHelper(); + addChildCommand(new CommandTreeSpawn("spawnTree", new TreeSpawner())); + addChildCommand(new CommandTreeSpawn("spawnForest", new ForestSpawner())); + addChildCommand(new CommandMode(modeHelper)); + addChildCommand(new CommandSaveStats(saveHelper, modeHelper)); + } } diff --git a/src/main/java/forestry/arboriculture/commands/CommandTreeSpawn.java b/src/main/java/forestry/arboriculture/commands/CommandTreeSpawn.java index 00988755a..a236f02e1 100644 --- a/src/main/java/forestry/arboriculture/commands/CommandTreeSpawn.java +++ b/src/main/java/forestry/arboriculture/commands/CommandTreeSpawn.java @@ -10,78 +10,75 @@ ******************************************************************************/ package forestry.arboriculture.commands; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; - -import net.minecraft.command.ICommandSender; -import net.minecraft.command.PlayerNotFoundException; -import net.minecraft.entity.player.EntityPlayer; - import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; import forestry.core.commands.CommandHelpers; import forestry.core.commands.SubCommand; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.command.ICommandSender; +import net.minecraft.command.PlayerNotFoundException; +import net.minecraft.entity.player.EntityPlayer; +import org.apache.commons.lang3.StringUtils; public final class CommandTreeSpawn extends SubCommand { - private final ITreeSpawner treeSpawner; + private final ITreeSpawner treeSpawner; - public CommandTreeSpawn(String name, ITreeSpawner treeSpawner) { - super(name); - setPermLevel(PermLevel.ADMIN); - this.treeSpawner = treeSpawner; - } + public CommandTreeSpawn(String name, ITreeSpawner treeSpawner) { + super(name); + setPermLevel(PermLevel.ADMIN); + this.treeSpawner = treeSpawner; + } - @Override - public final void processSubCommand(ICommandSender sender, String[] arguments) { - if (arguments.length < 1 || arguments.length > 2) { - printHelp(sender); - return; - } + @Override + public final void processSubCommand(ICommandSender sender, String[] arguments) { + if (arguments.length < 1 || arguments.length > 2) { + printHelp(sender); + return; + } - EntityPlayer player; - String treeName; - try { - player = CommandHelpers.getPlayer(sender, arguments[arguments.length - 1]); - String[] argumentsWithoutPlayer = new String[arguments.length - 1]; - System.arraycopy(arguments, 0, argumentsWithoutPlayer, 0, arguments.length - 1); - treeName = StringUtils.join(argumentsWithoutPlayer, " "); - } catch (PlayerNotFoundException e) { - player = CommandHelpers.getPlayer(sender, sender.getCommandSenderName()); - treeName = StringUtils.join(arguments, " "); - } + EntityPlayer player; + String treeName; + try { + player = CommandHelpers.getPlayer(sender, arguments[arguments.length - 1]); + String[] argumentsWithoutPlayer = new String[arguments.length - 1]; + System.arraycopy(arguments, 0, argumentsWithoutPlayer, 0, arguments.length - 1); + treeName = StringUtils.join(argumentsWithoutPlayer, " "); + } catch (PlayerNotFoundException e) { + player = CommandHelpers.getPlayer(sender, sender.getCommandSenderName()); + treeName = StringUtils.join(arguments, " "); + } - boolean success = treeSpawner.spawn(sender, treeName, player); - if (!success) { - printHelp(sender); - } - } + boolean success = treeSpawner.spawn(sender, treeName, player); + if (!success) { + printHelp(sender); + } + } - @Override - public List addTabCompletionOptions(ICommandSender sender, String[] parameters) { - if (parameters.length == 1) { - List tabCompletion = CommandHelpers.getListOfStringsMatchingLastWord(parameters, getSpecies()); - tabCompletion.add("help"); - return tabCompletion; - } else if (parameters.length == 2) { - return CommandHelpers.getListOfStringsMatchingLastWord(parameters, CommandHelpers.getPlayers()); - } - return null; - } + @Override + public List addTabCompletionOptions(ICommandSender sender, String[] parameters) { + if (parameters.length == 1) { + List tabCompletion = CommandHelpers.getListOfStringsMatchingLastWord(parameters, getSpecies()); + tabCompletion.add("help"); + return tabCompletion; + } else if (parameters.length == 2) { + return CommandHelpers.getListOfStringsMatchingLastWord(parameters, CommandHelpers.getPlayers()); + } + return null; + } - private static String[] getSpecies() { - List species = new ArrayList<>(); + private static String[] getSpecies() { + List species = new ArrayList<>(); - for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { - if (allele instanceof IAlleleTreeSpecies) { - species.add(allele.getName().replaceAll("\\s", "")); - } - } - - return species.toArray(new String[species.size()]); - } + for (IAllele allele : + AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleTreeSpecies) { + species.add(allele.getName().replaceAll("\\s", "")); + } + } + return species.toArray(new String[species.size()]); + } } diff --git a/src/main/java/forestry/arboriculture/commands/ForestSpawner.java b/src/main/java/forestry/arboriculture/commands/ForestSpawner.java index c13c89e32..09148f726 100644 --- a/src/main/java/forestry/arboriculture/commands/ForestSpawner.java +++ b/src/main/java/forestry/arboriculture/commands/ForestSpawner.java @@ -17,24 +17,23 @@ import net.minecraft.world.gen.feature.WorldGenerator; public class ForestSpawner implements ITreeSpawner { - public boolean spawn(ICommandSender sender, String treeName, EntityPlayer player) { - Vec3 look = player.getLookVec(); + public boolean spawn(ICommandSender sender, String treeName, EntityPlayer player) { + Vec3 look = player.getLookVec(); - int x = (int) Math.round(player.posX + (16 * look.xCoord)); - int y = (int) Math.round(player.posY); - int z = (int) Math.round(player.posZ + (16 * look.zCoord)); + int x = (int) Math.round(player.posX + (16 * look.xCoord)); + int y = (int) Math.round(player.posY); + int z = (int) Math.round(player.posZ + (16 * look.zCoord)); - for (int i = 0; i < 16; i++) { - int spawnX = x + player.worldObj.rand.nextInt(32) - 16; - int spawnZ = z + player.worldObj.rand.nextInt(32) - 16; - - WorldGenerator gen = TreeGenHelper.getWorldGen(treeName, player, spawnX, y, spawnZ); - if (gen == null) { - return false; - } - TreeGenHelper.generateTree(gen, player, spawnX, y, spawnZ); - } - return true; - } + for (int i = 0; i < 16; i++) { + int spawnX = x + player.worldObj.rand.nextInt(32) - 16; + int spawnZ = z + player.worldObj.rand.nextInt(32) - 16; + WorldGenerator gen = TreeGenHelper.getWorldGen(treeName, player, spawnX, y, spawnZ); + if (gen == null) { + return false; + } + TreeGenHelper.generateTree(gen, player, spawnX, y, spawnZ); + } + return true; + } } diff --git a/src/main/java/forestry/arboriculture/commands/ITreeSpawner.java b/src/main/java/forestry/arboriculture/commands/ITreeSpawner.java index ddeec9b99..7c25b1949 100644 --- a/src/main/java/forestry/arboriculture/commands/ITreeSpawner.java +++ b/src/main/java/forestry/arboriculture/commands/ITreeSpawner.java @@ -15,6 +15,5 @@ import net.minecraft.entity.player.EntityPlayer; public interface ITreeSpawner { - boolean spawn(ICommandSender sender, String treeName, EntityPlayer player); - + boolean spawn(ICommandSender sender, String treeName, EntityPlayer player); } diff --git a/src/main/java/forestry/arboriculture/commands/TreeGenHelper.java b/src/main/java/forestry/arboriculture/commands/TreeGenHelper.java index 0d3390739..59c3ec438 100644 --- a/src/main/java/forestry/arboriculture/commands/TreeGenHelper.java +++ b/src/main/java/forestry/arboriculture/commands/TreeGenHelper.java @@ -10,9 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.commands; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.gen.feature.WorldGenerator; - import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.arboriculture.ITree; import forestry.api.arboriculture.ITreeGenome; @@ -22,62 +19,66 @@ import forestry.api.genetics.IAllele; import forestry.core.commands.SpeciesNotFoundException; import forestry.core.commands.TemplateNotFoundException; import forestry.core.worldgen.WorldGenBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.gen.feature.WorldGenerator; public final class TreeGenHelper { - public static WorldGenerator getWorldGen(String treeName, EntityPlayer player, int x, int y, int z) { - ITreeGenome treeGenome = getTreeGenome(treeName); - if (treeGenome == null) { - return null; - } + public static WorldGenerator getWorldGen(String treeName, EntityPlayer player, int x, int y, int z) { + ITreeGenome treeGenome = getTreeGenome(treeName); + if (treeGenome == null) { + return null; + } - ITree tree = TreeManager.treeRoot.getTree(player.worldObj, treeGenome); - return tree.getTreeGenerator(player.worldObj, x, y, z, true); - } + ITree tree = TreeManager.treeRoot.getTree(player.worldObj, treeGenome); + return tree.getTreeGenerator(player.worldObj, x, y, z, true); + } - public static void generateTree(WorldGenerator gen, EntityPlayer player, int x, int y, int z) { - if (gen instanceof WorldGenBase) { - ((WorldGenBase) gen).generate(player.worldObj, x, y, z, true); - } else { - gen.generate(player.worldObj, player.worldObj.rand, x, y, z); - } - } + public static void generateTree(WorldGenerator gen, EntityPlayer player, int x, int y, int z) { + if (gen instanceof WorldGenBase) { + ((WorldGenBase) gen).generate(player.worldObj, x, y, z, true); + } else { + gen.generate(player.worldObj, player.worldObj.rand, x, y, z); + } + } - private static ITreeGenome getTreeGenome(String speciesName) { - IAlleleTreeSpecies species = null; + private static ITreeGenome getTreeGenome(String speciesName) { + IAlleleTreeSpecies species = null; - for (String uid : AlleleManager.alleleRegistry.getRegisteredAlleles().keySet()) { + for (String uid : AlleleManager.alleleRegistry.getRegisteredAlleles().keySet()) { - if (!uid.equals(speciesName)) { - continue; - } + if (!uid.equals(speciesName)) { + continue; + } - IAllele allele = AlleleManager.alleleRegistry.getAllele(uid); - if (allele instanceof IAlleleTreeSpecies) { - species = (IAlleleTreeSpecies) allele; - break; - } - } + IAllele allele = AlleleManager.alleleRegistry.getAllele(uid); + if (allele instanceof IAlleleTreeSpecies) { + species = (IAlleleTreeSpecies) allele; + break; + } + } - if (species == null) { - for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { - if (allele instanceof IAlleleTreeSpecies && allele.getName().replaceAll("\\s", "").equals(speciesName)) { - species = (IAlleleTreeSpecies) allele; - break; - } - } - } + if (species == null) { + for (IAllele allele : + AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleTreeSpecies + && allele.getName().replaceAll("\\s", "").equals(speciesName)) { + species = (IAlleleTreeSpecies) allele; + break; + } + } + } - if (species == null) { - throw new SpeciesNotFoundException(speciesName); - } + if (species == null) { + throw new SpeciesNotFoundException(speciesName); + } - IAllele[] template = TreeManager.treeRoot.getTemplate(species.getUID()); + IAllele[] template = TreeManager.treeRoot.getTemplate(species.getUID()); - if (template == null) { - throw new TemplateNotFoundException(species); - } + if (template == null) { + throw new TemplateNotFoundException(species); + } - return TreeManager.treeRoot.templateAsGenome(template); - } + return TreeManager.treeRoot.templateAsGenome(template); + } } diff --git a/src/main/java/forestry/arboriculture/commands/TreeModeHelper.java b/src/main/java/forestry/arboriculture/commands/TreeModeHelper.java index 8443e1af7..afb173690 100644 --- a/src/main/java/forestry/arboriculture/commands/TreeModeHelper.java +++ b/src/main/java/forestry/arboriculture/commands/TreeModeHelper.java @@ -10,52 +10,49 @@ ******************************************************************************/ package forestry.arboriculture.commands; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.world.World; - import forestry.api.arboriculture.ITreekeepingMode; import forestry.api.arboriculture.TreeManager; import forestry.core.commands.ICommandModeHelper; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.world.World; public class TreeModeHelper implements ICommandModeHelper { - @Override - public String[] getModeNames() { - ArrayList treekeepingModes = TreeManager.treeRoot.getTreekeepingModes(); - int modeStringCount = treekeepingModes.size(); - List modeStrings = new ArrayList<>(modeStringCount); - for (ITreekeepingMode mode : treekeepingModes) { - modeStrings.add(mode.getName()); - } + @Override + public String[] getModeNames() { + ArrayList treekeepingModes = TreeManager.treeRoot.getTreekeepingModes(); + int modeStringCount = treekeepingModes.size(); + List modeStrings = new ArrayList<>(modeStringCount); + for (ITreekeepingMode mode : treekeepingModes) { + modeStrings.add(mode.getName()); + } - return modeStrings.toArray(new String[modeStringCount]); - } + return modeStrings.toArray(new String[modeStringCount]); + } - @Override - public String getModeNameMatching(String desired) { - ITreekeepingMode mode = TreeManager.treeRoot.getTreekeepingMode(desired); - if (mode == null) { - return null; - } - return mode.getName(); - } + @Override + public String getModeNameMatching(String desired) { + ITreekeepingMode mode = TreeManager.treeRoot.getTreekeepingMode(desired); + if (mode == null) { + return null; + } + return mode.getName(); + } - @Override - public String getModeName(World world) { - return TreeManager.treeRoot.getTreekeepingMode(world).getName(); - } + @Override + public String getModeName(World world) { + return TreeManager.treeRoot.getTreekeepingMode(world).getName(); + } - @Override - public void setMode(World world, String modeName) { - TreeManager.treeRoot.setTreekeepingMode(world, modeName); - } - - @Override - public Iterable getDescription(String modeName) { - ITreekeepingMode mode = TreeManager.treeRoot.getTreekeepingMode(modeName); - return mode.getDescription(); - } + @Override + public void setMode(World world, String modeName) { + TreeManager.treeRoot.setTreekeepingMode(world, modeName); + } + @Override + public Iterable getDescription(String modeName) { + ITreekeepingMode mode = TreeManager.treeRoot.getTreekeepingMode(modeName); + return mode.getDescription(); + } } diff --git a/src/main/java/forestry/arboriculture/commands/TreeSpawner.java b/src/main/java/forestry/arboriculture/commands/TreeSpawner.java index 3bf02f05d..e32000656 100644 --- a/src/main/java/forestry/arboriculture/commands/TreeSpawner.java +++ b/src/main/java/forestry/arboriculture/commands/TreeSpawner.java @@ -17,21 +17,20 @@ import net.minecraft.world.gen.feature.WorldGenerator; public class TreeSpawner implements ITreeSpawner { - @Override - public boolean spawn(ICommandSender sender, String treeName, EntityPlayer player) { - Vec3 look = player.getLookVec(); + @Override + public boolean spawn(ICommandSender sender, String treeName, EntityPlayer player) { + Vec3 look = player.getLookVec(); - int x = (int) Math.round(player.posX + (3 * look.xCoord)); - int y = (int) Math.round(player.posY); - int z = (int) Math.round(player.posZ + (3 * look.zCoord)); + int x = (int) Math.round(player.posX + (3 * look.xCoord)); + int y = (int) Math.round(player.posY); + int z = (int) Math.round(player.posZ + (3 * look.zCoord)); - WorldGenerator gen = TreeGenHelper.getWorldGen(treeName, player, x, y, z); - if (gen == null) { - return false; - } - - TreeGenHelper.generateTree(gen, player, x, y, z); - return true; - } + WorldGenerator gen = TreeGenHelper.getWorldGen(treeName, player, x, y, z); + if (gen == null) { + return false; + } + TreeGenHelper.generateTree(gen, player, x, y, z); + return true; + } } diff --git a/src/main/java/forestry/arboriculture/commands/TreeStatsSaveHelper.java b/src/main/java/forestry/arboriculture/commands/TreeStatsSaveHelper.java index 7424a66e5..90f59fa1e 100644 --- a/src/main/java/forestry/arboriculture/commands/TreeStatsSaveHelper.java +++ b/src/main/java/forestry/arboriculture/commands/TreeStatsSaveHelper.java @@ -10,13 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.commands; -import java.util.ArrayList; -import java.util.Collection; - -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.arboriculture.TreeManager; import forestry.api.genetics.AlleleManager; @@ -24,37 +18,39 @@ import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IBreedingTracker; import forestry.core.commands.IStatsSaveHelper; +import java.util.ArrayList; +import java.util.Collection; +import net.minecraft.world.World; public class TreeStatsSaveHelper implements IStatsSaveHelper { - @Override - public String getUnlocalizedSaveStatsString() { - return "for.chat.command.forestry.tree.save.stats"; - } + @Override + public String getUnlocalizedSaveStatsString() { + return "for.chat.command.forestry.tree.save.stats"; + } - @Override - public void addExtraInfo(Collection statistics, IBreedingTracker breedingTracker) { - } + @Override + public void addExtraInfo(Collection statistics, IBreedingTracker breedingTracker) {} - @Override - public Collection getSpecies() { - Collection species = new ArrayList<>(); - for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { - if (allele instanceof IAlleleTreeSpecies) { - species.add((IAlleleTreeSpecies) allele); - } - } - return species; - } + @Override + public Collection getSpecies() { + Collection species = new ArrayList<>(); + for (IAllele allele : + AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleTreeSpecies) { + species.add((IAlleleTreeSpecies) allele); + } + } + return species; + } - @Override - public String getFileSuffix() { - return "trees"; - } - - @Override - public IBreedingTracker getBreedingTracker(World world, GameProfile gameProfile) { - return TreeManager.treeRoot.getBreedingTracker(world, gameProfile); - } + @Override + public String getFileSuffix() { + return "trees"; + } + @Override + public IBreedingTracker getBreedingTracker(World world, GameProfile gameProfile) { + return TreeManager.treeRoot.getBreedingTracker(world, gameProfile); + } } diff --git a/src/main/java/forestry/arboriculture/genetics/ArboristTracker.java b/src/main/java/forestry/arboriculture/genetics/ArboristTracker.java index bcf05c96d..84209483a 100755 --- a/src/main/java/forestry/arboriculture/genetics/ArboristTracker.java +++ b/src/main/java/forestry/arboriculture/genetics/ArboristTracker.java @@ -10,33 +10,30 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import net.minecraft.entity.player.EntityPlayer; - import forestry.api.arboriculture.IArboristTracker; import forestry.api.arboriculture.TreeManager; import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.IIndividual; import forestry.core.genetics.BreedingTracker; +import net.minecraft.entity.player.EntityPlayer; public class ArboristTracker extends BreedingTracker implements IArboristTracker { - /** Required for creation from map storage */ - public ArboristTracker(String s) { - super(s); - } + /** Required for creation from map storage */ + public ArboristTracker(String s) { + super(s); + } - @Override - protected IBreedingTracker getBreedingTracker(EntityPlayer player) { - return TreeManager.treeRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); - } + @Override + protected IBreedingTracker getBreedingTracker(EntityPlayer player) { + return TreeManager.treeRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); + } - @Override - protected String speciesRootUID() { - return TreeHelper.UID; - } - - @Override - public void registerPickup(IIndividual individual) { - } + @Override + protected String speciesRootUID() { + return TreeHelper.UID; + } + @Override + public void registerPickup(IIndividual individual) {} } diff --git a/src/main/java/forestry/arboriculture/genetics/BranchTrees.java b/src/main/java/forestry/arboriculture/genetics/BranchTrees.java index adefe33ea..da246f04a 100755 --- a/src/main/java/forestry/arboriculture/genetics/BranchTrees.java +++ b/src/main/java/forestry/arboriculture/genetics/BranchTrees.java @@ -14,8 +14,7 @@ import forestry.core.genetics.Branch; public class BranchTrees extends Branch { - public BranchTrees(String uid, String scientific) { - super("trees." + uid, scientific); - } - + public BranchTrees(String uid, String scientific) { + super("trees." + uid, scientific); + } } diff --git a/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java b/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java index 24de32a2e..610108e4f 100755 --- a/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java +++ b/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java @@ -10,10 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - import forestry.api.arboriculture.EnumGrowthConditions; import forestry.api.arboriculture.IGrowthProvider; import forestry.api.arboriculture.ITree; @@ -22,126 +18,136 @@ import forestry.arboriculture.tiles.TileSapling; import forestry.core.utils.BlockUtil; import forestry.core.utils.StringUtil; import forestry.core.utils.vect.Vect; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; public class GrowthProvider implements IGrowthProvider { - @Override - public boolean canGrow(ITreeGenome genome, World world, int xPos, int yPos, int zPos, int expectedGirth, int expectedHeight) { - if (!hasRoom(world, xPos, yPos, zPos, expectedGirth, expectedHeight)) { - return false; - } + @Override + public boolean canGrow( + ITreeGenome genome, World world, int xPos, int yPos, int zPos, int expectedGirth, int expectedHeight) { + if (!hasRoom(world, xPos, yPos, zPos, expectedGirth, expectedHeight)) { + return false; + } - if (getGrowthConditions(genome, world, xPos, yPos, zPos) == EnumGrowthConditions.HOSTILE) { - return false; - } + if (getGrowthConditions(genome, world, xPos, yPos, zPos) == EnumGrowthConditions.HOSTILE) { + return false; + } - return hasSufficientSaplings(genome, world, xPos, yPos, zPos, expectedGirth); - } + return hasSufficientSaplings(genome, world, xPos, yPos, zPos, expectedGirth); + } - @Override - public EnumGrowthConditions getGrowthConditions(ITreeGenome genome, World world, int xPos, int yPos, int zPos) { - return getConditionFromLight(world, xPos, yPos, zPos); - } + @Override + public EnumGrowthConditions getGrowthConditions(ITreeGenome genome, World world, int xPos, int yPos, int zPos) { + return getConditionFromLight(world, xPos, yPos, zPos); + } - @Override - public String getDescription() { - return StringUtil.localize("growth.normal"); - } + @Override + public String getDescription() { + return StringUtil.localize("growth.normal"); + } - @Override - public String[] getInfo() { - return new String[0]; - } + @Override + public String[] getInfo() { + return new String[0]; + } - protected static EnumGrowthConditions getConditionsFromRainfall(World world, int xPos, int yPos, int zPos, float min, float max) { + protected static EnumGrowthConditions getConditionsFromRainfall( + World world, int xPos, int yPos, int zPos, float min, float max) { - BiomeGenBase biome = world.getWorldChunkManager().getBiomeGenAt(xPos, zPos); - if (biome.rainfall < min || biome.rainfall > max) { - return EnumGrowthConditions.HOSTILE; - } + BiomeGenBase biome = world.getWorldChunkManager().getBiomeGenAt(xPos, zPos); + if (biome.rainfall < min || biome.rainfall > max) { + return EnumGrowthConditions.HOSTILE; + } - return EnumGrowthConditions.EXCELLENT; - } + return EnumGrowthConditions.EXCELLENT; + } - protected static EnumGrowthConditions getConditionsFromTemperature(World world, int xPos, int yPos, int zPos, float min, float max) { + protected static EnumGrowthConditions getConditionsFromTemperature( + World world, int xPos, int yPos, int zPos, float min, float max) { - BiomeGenBase biome = world.getWorldChunkManager().getBiomeGenAt(xPos, zPos); - float biomeTemperature = biome.getFloatTemperature(xPos, yPos, zPos); - if (biomeTemperature < min || biomeTemperature > max) { - return EnumGrowthConditions.HOSTILE; - } + BiomeGenBase biome = world.getWorldChunkManager().getBiomeGenAt(xPos, zPos); + float biomeTemperature = biome.getFloatTemperature(xPos, yPos, zPos); + if (biomeTemperature < min || biomeTemperature > max) { + return EnumGrowthConditions.HOSTILE; + } - return EnumGrowthConditions.EXCELLENT; - } + return EnumGrowthConditions.EXCELLENT; + } - protected static EnumGrowthConditions getConditionFromLight(World world, int xPos, int yPos, int zPos) { - int lightvalue = world.getBlockLightValue(xPos, yPos + 1, zPos); + protected static EnumGrowthConditions getConditionFromLight(World world, int xPos, int yPos, int zPos) { + int lightvalue = world.getBlockLightValue(xPos, yPos + 1, zPos); - if (lightvalue > 13) { - return EnumGrowthConditions.EXCELLENT; - } else if (lightvalue > 11) { - return EnumGrowthConditions.GOOD; - } else if (lightvalue > 8) { - return EnumGrowthConditions.NORMAL; - } else if (lightvalue > 6) { - return EnumGrowthConditions.PALTRY; - } else { - return EnumGrowthConditions.HOSTILE; - } - } + if (lightvalue > 13) { + return EnumGrowthConditions.EXCELLENT; + } else if (lightvalue > 11) { + return EnumGrowthConditions.GOOD; + } else if (lightvalue > 8) { + return EnumGrowthConditions.NORMAL; + } else if (lightvalue > 6) { + return EnumGrowthConditions.PALTRY; + } else { + return EnumGrowthConditions.HOSTILE; + } + } - private static boolean hasRoom(World world, int xPos, int yPos, int zPos, int expectedGirth, int expectedHeight) { + private static boolean hasRoom(World world, int xPos, int yPos, int zPos, int expectedGirth, int expectedHeight) { - int offset = (expectedGirth - 1) / 2; - // if(offset <= 0) - // offset = 1; - Vect start = new Vect(xPos - offset, yPos + 1, zPos + offset); - Vect area = new Vect(-offset + expectedGirth, expectedHeight + 1, -offset + expectedGirth); + int offset = (expectedGirth - 1) / 2; + // if(offset <= 0) + // offset = 1; + Vect start = new Vect(xPos - offset, yPos + 1, zPos + offset); + Vect area = new Vect(-offset + expectedGirth, expectedHeight + 1, -offset + expectedGirth); - return checkArea(world, start, area); - } + return checkArea(world, start, area); + } - private static boolean checkArea(World world, Vect start, Vect area) { - for (int x = start.x; x < start.x + area.x; x++) { - for (int y = start.y; y < start.y + area.y; y++) { - for (int z = start.z; z < start.z + area.z; z++) { - if (!world.isAirBlock(x, y, z) && !BlockUtil.isReplaceableBlock(world, x, y, z)) { - return false; - } - } - } - } - return true; - } + private static boolean checkArea(World world, Vect start, Vect area) { + for (int x = start.x; x < start.x + area.x; x++) { + for (int y = start.y; y < start.y + area.y; y++) { + for (int z = start.z; z < start.z + area.z; z++) { + if (!world.isAirBlock(x, y, z) && !BlockUtil.isReplaceableBlock(world, x, y, z)) { + return false; + } + } + } + } + return true; + } - private static boolean hasSufficientSaplings(ITreeGenome genome, World world, int xPos, int yPos, int zPos, int expectedGirth) { + private static boolean hasSufficientSaplings( + ITreeGenome genome, World world, int xPos, int yPos, int zPos, int expectedGirth) { - if (expectedGirth == 1) { - return true; - } + if (expectedGirth == 1) { + return true; + } - int offset = (expectedGirth - 1) / 2; + int offset = (expectedGirth - 1) / 2; - for (int x = xPos - offset; x < xPos - offset + expectedGirth; x++) { - for (int z = zPos - offset; z < zPos - offset + expectedGirth; z++) { + for (int x = xPos - offset; x < xPos - offset + expectedGirth; x++) { + for (int z = zPos - offset; z < zPos - offset + expectedGirth; z++) { - if (world.isAirBlock(x, yPos, z)) { - return false; - } + if (world.isAirBlock(x, yPos, z)) { + return false; + } - TileEntity tile = world.getTileEntity(x, yPos, z); - if (!(tile instanceof TileSapling)) { - return false; - } + TileEntity tile = world.getTileEntity(x, yPos, z); + if (!(tile instanceof TileSapling)) { + return false; + } - ITree tree = ((TileSapling) tile).getTree(); - if (tree == null || !tree.getGenome().getPrimary().getUID().equals(genome.getPrimary().getUID())) { - return false; - } - } - } - - return true; - } + ITree tree = ((TileSapling) tile).getTree(); + if (tree == null + || !tree.getGenome() + .getPrimary() + .getUID() + .equals(genome.getPrimary().getUID())) { + return false; + } + } + } + return true; + } } diff --git a/src/main/java/forestry/arboriculture/genetics/GrowthProviderTropical.java b/src/main/java/forestry/arboriculture/genetics/GrowthProviderTropical.java index 2e02d6c01..f41a6c814 100755 --- a/src/main/java/forestry/arboriculture/genetics/GrowthProviderTropical.java +++ b/src/main/java/forestry/arboriculture/genetics/GrowthProviderTropical.java @@ -10,45 +10,44 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import java.util.EnumSet; - -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - import forestry.api.arboriculture.EnumGrowthConditions; import forestry.api.arboriculture.ITreeGenome; import forestry.core.utils.StringUtil; +import java.util.EnumSet; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; public class GrowthProviderTropical extends GrowthProvider { - @Override - public EnumGrowthConditions getGrowthConditions(ITreeGenome genome, World world, int xPos, int yPos, int zPos) { - EnumGrowthConditions light = getConditionFromLight(world, xPos, yPos, zPos); - EnumGrowthConditions moisture = getConditionsFromRainfall(world, xPos, yPos, zPos, BiomeGenBase.jungle.rainfall, 2.0f); + @Override + public EnumGrowthConditions getGrowthConditions(ITreeGenome genome, World world, int xPos, int yPos, int zPos) { + EnumGrowthConditions light = getConditionFromLight(world, xPos, yPos, zPos); + EnumGrowthConditions moisture = + getConditionsFromRainfall(world, xPos, yPos, zPos, BiomeGenBase.jungle.rainfall, 2.0f); - float jungleTemperature = BiomeGenBase.jungle.getFloatTemperature(xPos, yPos, zPos); - float desertTemperature = BiomeGenBase.desert.getFloatTemperature(xPos, yPos, zPos); - EnumGrowthConditions temperature = getConditionsFromTemperature(world, xPos, yPos, zPos, jungleTemperature, desertTemperature - 0.1f); + float jungleTemperature = BiomeGenBase.jungle.getFloatTemperature(xPos, yPos, zPos); + float desertTemperature = BiomeGenBase.desert.getFloatTemperature(xPos, yPos, zPos); + EnumGrowthConditions temperature = + getConditionsFromTemperature(world, xPos, yPos, zPos, jungleTemperature, desertTemperature - 0.1f); - EnumSet conditions = EnumSet.of(light, moisture, temperature); + EnumSet conditions = EnumSet.of(light, moisture, temperature); - EnumGrowthConditions result = EnumGrowthConditions.HOSTILE; - for (EnumGrowthConditions cond : conditions) { - if (cond == EnumGrowthConditions.HOSTILE) { - return EnumGrowthConditions.HOSTILE; - } + EnumGrowthConditions result = EnumGrowthConditions.HOSTILE; + for (EnumGrowthConditions cond : conditions) { + if (cond == EnumGrowthConditions.HOSTILE) { + return EnumGrowthConditions.HOSTILE; + } - if (cond.ordinal() > result.ordinal()) { - result = cond; - } - } + if (cond.ordinal() > result.ordinal()) { + result = cond; + } + } - return result; - } - - @Override - public String getDescription() { - return StringUtil.localize("growth.tropical"); - } + return result; + } + @Override + public String getDescription() { + return StringUtil.localize("growth.tropical"); + } } diff --git a/src/main/java/forestry/arboriculture/genetics/ITreeDefinition.java b/src/main/java/forestry/arboriculture/genetics/ITreeDefinition.java index 85e54654e..625bfd3c0 100644 --- a/src/main/java/forestry/arboriculture/genetics/ITreeDefinition.java +++ b/src/main/java/forestry/arboriculture/genetics/ITreeDefinition.java @@ -1,28 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.genetics; - -import net.minecraft.item.ItemStack; - -import forestry.api.arboriculture.EnumGermlingType; -import forestry.api.arboriculture.ITree; -import forestry.api.arboriculture.ITreeGenome; -import forestry.core.genetics.IGeneticDefinition; - -public interface ITreeDefinition extends IGeneticDefinition { - @Override - ITreeGenome getGenome(); - - @Override - ITree getIndividual(); - - ItemStack getMemberStack(EnumGermlingType treeType); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.genetics; + +import forestry.api.arboriculture.EnumGermlingType; +import forestry.api.arboriculture.ITree; +import forestry.api.arboriculture.ITreeGenome; +import forestry.core.genetics.IGeneticDefinition; +import net.minecraft.item.ItemStack; + +public interface ITreeDefinition extends IGeneticDefinition { + @Override + ITreeGenome getGenome(); + + @Override + ITree getIndividual(); + + ItemStack getMemberStack(EnumGermlingType treeType); +} diff --git a/src/main/java/forestry/arboriculture/genetics/Tree.java b/src/main/java/forestry/arboriculture/genetics/Tree.java index 43f874817..cd622ec23 100755 --- a/src/main/java/forestry/arboriculture/genetics/Tree.java +++ b/src/main/java/forestry/arboriculture/genetics/Tree.java @@ -10,27 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumSet; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.StatCollector; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; -import net.minecraft.world.gen.feature.WorldGenerator; - import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.EnumPlantType; -import net.minecraftforge.common.IPlantable; -import net.minecraftforge.common.util.ForgeDirection; - import forestry.api.arboriculture.EnumGrowthConditions; import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleLeafEffect; @@ -53,417 +33,449 @@ import forestry.core.config.Config; import forestry.core.genetics.Chromosome; import forestry.core.genetics.Individual; import forestry.core.utils.StringUtil; +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumSet; +import java.util.List; +import javax.annotation.Nullable; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.StatCollector; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraft.world.gen.feature.WorldGenerator; +import net.minecraftforge.common.EnumPlantType; +import net.minecraftforge.common.IPlantable; +import net.minecraftforge.common.util.ForgeDirection; public class Tree extends Individual implements ITree, IPlantable { - private ITreeGenome genome; - private ITreeGenome mate; - - private EnumSet plantTypes; - private EnumPlantType plantType; - - /* CONSTRUCTOR */ - public Tree(NBTTagCompound nbttagcompound) { - readFromNBT(nbttagcompound); - } - - public Tree(ITreeGenome genome) { - setGenome(genome); - } - - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - - super.readFromNBT(nbttagcompound); - - if (nbttagcompound.hasKey("Genome")) { - setGenome(new TreeGenome(nbttagcompound.getCompoundTag("Genome"))); - } else { - setGenome(TreeDefinition.Oak.getGenome()); - } - - if (nbttagcompound.hasKey("Mate")) { - mate = new TreeGenome(nbttagcompound.getCompoundTag("Mate")); - } - - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - - super.writeToNBT(nbttagcompound); - - if (genome != null) { - NBTTagCompound nbtGenome = new NBTTagCompound(); - genome.writeToNBT(nbtGenome); - nbttagcompound.setTag("Genome", nbtGenome); - } - if (mate != null) { - NBTTagCompound nbtMate = new NBTTagCompound(); - mate.writeToNBT(nbtMate); - nbttagcompound.setTag("Mate", nbtMate); - } - - } - - /* INTERACTION */ - @Override - public void mate(ITree other) { - mate = new TreeGenome(other.getGenome().getChromosomes()); - } - - /* EFFECTS */ - @Override - public IEffectData[] doEffect(IEffectData[] storedData, World world, int x, int y, int z) { - IAlleleLeafEffect effect = (IAlleleLeafEffect) getGenome().getActiveAllele(EnumTreeChromosome.EFFECT); - - if (effect == null) { - return null; - } - - storedData[0] = doEffect(effect, storedData[0], world, x, y, z); - - // Return here if the primary can already not be combined - if (!effect.isCombinable()) { - return storedData; - } - - IAlleleLeafEffect secondary = (IAlleleLeafEffect) getGenome().getInactiveAllele(EnumTreeChromosome.EFFECT); - if (!secondary.isCombinable()) { - return storedData; - } - - storedData[1] = doEffect(secondary, storedData[1], world, x, y, z); - - return storedData; - } - - private IEffectData doEffect(IAlleleLeafEffect effect, IEffectData storedData, World world, int x, int y, int z) { - storedData = effect.validateStorage(storedData); - return effect.doEffect(getGenome(), storedData, world, x, y, z); - } - - @Override - public IEffectData[] doFX(IEffectData[] storedData, World world, int x, int y, int z) { - return null; - } - - /* GROWTH */ - @Override - public WorldGenerator getTreeGenerator(World world, int x, int y, int z, boolean wasBonemealed) { - return genome.getPrimary().getGenerator().getWorldGenerator(this); - } - - @Override - public boolean canStay(World world, int x, int y, int z) { - Block block = world.getBlock(x, y - 1, z); - if (block == null) { - return false; - } - - for (EnumPlantType type : getPlantTypes()) { - this.plantType = type; - if (block.canSustainPlant(world, x, y - 1, z, ForgeDirection.UP, this)) { - return true; - } - } - - return false; - } - - @Override - public EnumPlantType getPlantType(IBlockAccess world, int x, int y, int z) { - return plantType; - } - - @Override - public Block getPlant(IBlockAccess world, int x, int y, int z) { - return null; - } - - @Override - public int getPlantMetadata(IBlockAccess world, int x, int y, int z) { - return 0; - } - - @Override - public boolean canGrow(World world, int x, int y, int z, int expectedGirth, int expectedHeight) { - IGrowthProvider growthProvider = genome.getGrowthProvider(); - return growthProvider.canGrow(genome, world, x, y, z, expectedGirth, expectedHeight); - } - - @Override - public int getRequiredMaturity() { - return genome.getMaturationTime(); - } - - @Override - public EnumGrowthConditions getGrowthCondition(World world, int x, int y, int z) { - return genome.getGrowthProvider().getGrowthConditions(getGenome(), world, x, y, z); - } - - @Override - public int getGirth(World world, int x, int y, int z) { - return genome.getGirth(); - } - - @Override - public int getResilience() { - int base = (int) (getGenome().getFertility() * getGenome().getSappiness() * 100); - return (base > 1 ? base : 1) * 10; - } - - @Override - public float getHeightModifier() { - return genome.getHeight(); - } - - @Override - public void setLeaves(World world, GameProfile owner, int x, int y, int z) { - try { - genome.getPrimary().getGenerator().setLeaves(genome, world, owner, x, y, z, false); - } catch (Throwable ignored) { - genome.getPrimary().getGenerator().setLeaves(world, owner, x, y, z, false); - } - } - - @Override - public void setLeavesDecorative(World world, GameProfile owner, int x, int y, int z) { - try { - genome.getPrimary().getGenerator().setLeaves(genome, world, owner, x, y, z, true); - } catch (Throwable ignored) { - genome.getPrimary().getGenerator().setLeaves(world, owner, x, y, z, true); - } - } - - @Override - public void setLogBlock(World world, int x, int y, int z, ForgeDirection facing) { - try { - genome.getPrimary().getGenerator().setLogBlock(genome, world, x, y, z, facing); - } catch (Throwable ignored) { - genome.getPrimary().getGenerator().setLogBlock(world, x, y, z, facing); - } - } - - @Override - public boolean allowsFruitBlocks() { - IFruitProvider provider = getGenome().getFruitProvider(); - if (!provider.requiresFruitBlocks()) { - return false; - } - - Collection suitable = genome.getPrimary().getSuitableFruit(); - return suitable.contains(provider.getFamily()); - } - - @Override - public boolean trySpawnFruitBlock(World world, int x, int y, int z) { - IFruitProvider provider = getGenome().getFruitProvider(); - Collection suitable = genome.getPrimary().getSuitableFruit(); - if (!suitable.contains(provider.getFamily())) { - return false; - } - - return provider.trySpawnFruitBlock(getGenome(), world, x, y, z); - } - - /* INFORMATION */ - @Override - public ITreeGenome getGenome() { - return genome; - } - - private void setGenome(ITreeGenome genome) { - this.genome = genome; - plantTypes = genome.getPlantTypes(); - plantTypes.add(genome.getPrimary().getPlantType()); - } - - @Override - public ITree copy() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - this.writeToNBT(nbttagcompound); - return new Tree(nbttagcompound); - } - - @Override - public ITreeGenome getMate() { - return this.mate; - } - - @Override - public boolean isPureBred(EnumTreeChromosome chromosome) { - return genome.getActiveAllele(chromosome).getUID().equals(genome.getInactiveAllele(chromosome).getUID()); - } - - @Override - public EnumSet getPlantTypes() { - return plantTypes; - } - - @Override - public void addTooltip(List list) { - - // No info 4 u! - if (!isAnalyzed) { - list.add("<" + StringUtil.localize("gui.unknown") + ">"); - return; - } - - // You analyzed it? Juicy tooltip coming up! - IAlleleTreeSpecies primary = genome.getPrimary(); - IAlleleTreeSpecies secondary = genome.getSecondary(); - if (!isPureBred(EnumTreeChromosome.SPECIES)) { - list.add(EnumChatFormatting.BLUE + StringUtil.localize("trees.hybrid").replaceAll("%PRIMARY", primary.getName()).replaceAll("%SECONDARY", secondary.getName())); - } - - String sappiness = EnumChatFormatting.GOLD + "S: " + genome.getActiveAllele(EnumTreeChromosome.SAPPINESS).getName(); - String maturation = EnumChatFormatting.RED + "M: " + genome.getActiveAllele(EnumTreeChromosome.MATURATION).getName(); - String height = EnumChatFormatting.LIGHT_PURPLE + "H: " + genome.getActiveAllele(EnumTreeChromosome.HEIGHT).getName(); - String girth = EnumChatFormatting.AQUA + "G: " + String.format("%sx%s", genome.getGirth(), genome.getGirth()); - String saplings = EnumChatFormatting.YELLOW + "S: " + genome.getActiveAllele(EnumTreeChromosome.FERTILITY).getName(); - String yield = EnumChatFormatting.WHITE + "Y: " + genome.getActiveAllele(EnumTreeChromosome.YIELD).getName(); - list.add(String.format("%s, %s", saplings, maturation)); - list.add(String.format("%s, %s", height, girth)); - list.add(String.format("%s, %s", yield, sappiness)); - - IAlleleBoolean primaryFireproof = (IAlleleBoolean) genome.getActiveAllele(EnumTreeChromosome.FIREPROOF); - if (primaryFireproof.getValue()) { - list.add(EnumChatFormatting.RED + StatCollector.translateToLocal("for.gui.fireresist")); - } - - IAllele fruit = getGenome().getActiveAllele(EnumTreeChromosome.FRUITS); - if (fruit != AlleleFruit.fruitNone) { - String strike = ""; - if (!canBearFruit()) { - strike = EnumChatFormatting.STRIKETHROUGH.toString(); - } - list.add(strike + EnumChatFormatting.GREEN + "F: " + StringUtil.localize(genome.getFruitProvider().getDescription())); - } - - } - - /* REPRODUCTION */ - @Override - public ITree[] getSaplings(World world, GameProfile playerProfile, int x, int y, int z, float modifier) { - ArrayList prod = new ArrayList<>(); - - float chance = genome.getFertility() * modifier; - - if (world.rand.nextFloat() <= chance) { - if (this.getMate() == null) { - prod.add(TreeManager.treeRoot.getTree(world, new TreeGenome(genome.getChromosomes()))); - } else { - prod.add(createOffspring(world, playerProfile, x, y, z)); - } - } - - return prod.toArray(new ITree[prod.size()]); - } - - private ITree createOffspring(World world, GameProfile playerProfile, int x, int y, int z) { - - IChromosome[] chromosomes = new IChromosome[genome.getChromosomes().length]; - IChromosome[] parent1 = genome.getChromosomes(); - IChromosome[] parent2 = mate.getChromosomes(); - - // Check for mutation. Replace one of the parents with the mutation - // template if mutation occured. - IChromosome[] mutated = mutateSpecies(world, playerProfile, x, y, z, genome, mate); - if (mutated == null) { - mutated = mutateSpecies(world, playerProfile, x, y, z, mate, genome); - } - - if (mutated != null) { - return new Tree(new TreeGenome(mutated)); - } - - for (int i = 0; i < parent1.length; i++) { - if (parent1[i] != null && parent2[i] != null) { - chromosomes[i] = Chromosome.inheritChromosome(world.rand, parent1[i], parent2[i]); - } - } - - return new Tree(new TreeGenome(chromosomes)); - } - - private static IChromosome[] mutateSpecies(World world, @Nullable GameProfile playerProfile, int x, int y, int z, ITreeGenome genomeOne, ITreeGenome genomeTwo) { - - IChromosome[] parent1 = genomeOne.getChromosomes(); - IChromosome[] parent2 = genomeTwo.getChromosomes(); - - ITreeGenome genome0; - ITreeGenome genome1; - IAlleleTreeSpecies allele0; - IAlleleTreeSpecies allele1; - - if (world.rand.nextBoolean()) { - allele0 = (IAlleleTreeSpecies) parent1[EnumTreeChromosome.SPECIES.ordinal()].getPrimaryAllele(); - allele1 = (IAlleleTreeSpecies) parent2[EnumTreeChromosome.SPECIES.ordinal()].getSecondaryAllele(); - - genome0 = genomeOne; - genome1 = genomeTwo; - } else { - allele0 = (IAlleleTreeSpecies) parent2[EnumTreeChromosome.SPECIES.ordinal()].getPrimaryAllele(); - allele1 = (IAlleleTreeSpecies) parent1[EnumTreeChromosome.SPECIES.ordinal()].getSecondaryAllele(); - - genome0 = genomeTwo; - genome1 = genomeOne; - } - - IArboristTracker breedingTracker = null; - if (playerProfile != null) { - breedingTracker = TreeManager.treeRoot.getBreedingTracker(world, playerProfile); - } - - List combinations = TreeManager.treeRoot.getCombinations(allele0, allele1, true); - for (IMutation mutation : combinations) { - ITreeMutation treeMutation = (ITreeMutation) mutation; - // Stop blacklisted species. - // if (BeeManager.breedingManager.isBlacklisted(mutation.getTemplate()[0].getUID())) { - // continue; - // } - - float chance = treeMutation.getChance(world, x, y, z, allele0, allele1, genome0, genome1); - if (chance <= 0) { - continue; - } - - // boost chance for researched mutations - if (breedingTracker != null && breedingTracker.isResearched(treeMutation)) { - float mutationBoost = chance * (Config.researchMutationBoostMultiplier - 1.0f); - mutationBoost = Math.min(Config.maxResearchMutationBoostPercent, mutationBoost); - chance += mutationBoost; - } - - if (chance > world.rand.nextFloat() * 100) { - return TreeManager.treeRoot.templateAsChromosomes(treeMutation.getTemplate()); - } - } - - return null; - } - - /* PRODUCTION */ - @Override - public boolean canBearFruit() { - return genome.getPrimary().getSuitableFruit().contains(genome.getFruitProvider().getFamily()); - } - - @Override - public ItemStack[] getProduceList() { - return genome.getFruitProvider().getProducts(); - } - - @Override - public ItemStack[] getSpecialtyList() { - return genome.getFruitProvider().getSpecialty(); - } - - @Override - public ItemStack[] produceStacks(World world, int x, int y, int z, int ripeningTime) { - return genome.getFruitProvider().getFruits(genome, world, x, y, z, ripeningTime); - } - + private ITreeGenome genome; + private ITreeGenome mate; + + private EnumSet plantTypes; + private EnumPlantType plantType; + + /* CONSTRUCTOR */ + public Tree(NBTTagCompound nbttagcompound) { + readFromNBT(nbttagcompound); + } + + public Tree(ITreeGenome genome) { + setGenome(genome); + } + + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + + super.readFromNBT(nbttagcompound); + + if (nbttagcompound.hasKey("Genome")) { + setGenome(new TreeGenome(nbttagcompound.getCompoundTag("Genome"))); + } else { + setGenome(TreeDefinition.Oak.getGenome()); + } + + if (nbttagcompound.hasKey("Mate")) { + mate = new TreeGenome(nbttagcompound.getCompoundTag("Mate")); + } + } + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + + super.writeToNBT(nbttagcompound); + + if (genome != null) { + NBTTagCompound nbtGenome = new NBTTagCompound(); + genome.writeToNBT(nbtGenome); + nbttagcompound.setTag("Genome", nbtGenome); + } + if (mate != null) { + NBTTagCompound nbtMate = new NBTTagCompound(); + mate.writeToNBT(nbtMate); + nbttagcompound.setTag("Mate", nbtMate); + } + } + + /* INTERACTION */ + @Override + public void mate(ITree other) { + mate = new TreeGenome(other.getGenome().getChromosomes()); + } + + /* EFFECTS */ + @Override + public IEffectData[] doEffect(IEffectData[] storedData, World world, int x, int y, int z) { + IAlleleLeafEffect effect = (IAlleleLeafEffect) getGenome().getActiveAllele(EnumTreeChromosome.EFFECT); + + if (effect == null) { + return null; + } + + storedData[0] = doEffect(effect, storedData[0], world, x, y, z); + + // Return here if the primary can already not be combined + if (!effect.isCombinable()) { + return storedData; + } + + IAlleleLeafEffect secondary = (IAlleleLeafEffect) getGenome().getInactiveAllele(EnumTreeChromosome.EFFECT); + if (!secondary.isCombinable()) { + return storedData; + } + + storedData[1] = doEffect(secondary, storedData[1], world, x, y, z); + + return storedData; + } + + private IEffectData doEffect(IAlleleLeafEffect effect, IEffectData storedData, World world, int x, int y, int z) { + storedData = effect.validateStorage(storedData); + return effect.doEffect(getGenome(), storedData, world, x, y, z); + } + + @Override + public IEffectData[] doFX(IEffectData[] storedData, World world, int x, int y, int z) { + return null; + } + + /* GROWTH */ + @Override + public WorldGenerator getTreeGenerator(World world, int x, int y, int z, boolean wasBonemealed) { + return genome.getPrimary().getGenerator().getWorldGenerator(this); + } + + @Override + public boolean canStay(World world, int x, int y, int z) { + Block block = world.getBlock(x, y - 1, z); + if (block == null) { + return false; + } + + for (EnumPlantType type : getPlantTypes()) { + this.plantType = type; + if (block.canSustainPlant(world, x, y - 1, z, ForgeDirection.UP, this)) { + return true; + } + } + + return false; + } + + @Override + public EnumPlantType getPlantType(IBlockAccess world, int x, int y, int z) { + return plantType; + } + + @Override + public Block getPlant(IBlockAccess world, int x, int y, int z) { + return null; + } + + @Override + public int getPlantMetadata(IBlockAccess world, int x, int y, int z) { + return 0; + } + + @Override + public boolean canGrow(World world, int x, int y, int z, int expectedGirth, int expectedHeight) { + IGrowthProvider growthProvider = genome.getGrowthProvider(); + return growthProvider.canGrow(genome, world, x, y, z, expectedGirth, expectedHeight); + } + + @Override + public int getRequiredMaturity() { + return genome.getMaturationTime(); + } + + @Override + public EnumGrowthConditions getGrowthCondition(World world, int x, int y, int z) { + return genome.getGrowthProvider().getGrowthConditions(getGenome(), world, x, y, z); + } + + @Override + public int getGirth(World world, int x, int y, int z) { + return genome.getGirth(); + } + + @Override + public int getResilience() { + int base = (int) (getGenome().getFertility() * getGenome().getSappiness() * 100); + return (base > 1 ? base : 1) * 10; + } + + @Override + public float getHeightModifier() { + return genome.getHeight(); + } + + @Override + public void setLeaves(World world, GameProfile owner, int x, int y, int z) { + try { + genome.getPrimary().getGenerator().setLeaves(genome, world, owner, x, y, z, false); + } catch (Throwable ignored) { + genome.getPrimary().getGenerator().setLeaves(world, owner, x, y, z, false); + } + } + + @Override + public void setLeavesDecorative(World world, GameProfile owner, int x, int y, int z) { + try { + genome.getPrimary().getGenerator().setLeaves(genome, world, owner, x, y, z, true); + } catch (Throwable ignored) { + genome.getPrimary().getGenerator().setLeaves(world, owner, x, y, z, true); + } + } + + @Override + public void setLogBlock(World world, int x, int y, int z, ForgeDirection facing) { + try { + genome.getPrimary().getGenerator().setLogBlock(genome, world, x, y, z, facing); + } catch (Throwable ignored) { + genome.getPrimary().getGenerator().setLogBlock(world, x, y, z, facing); + } + } + + @Override + public boolean allowsFruitBlocks() { + IFruitProvider provider = getGenome().getFruitProvider(); + if (!provider.requiresFruitBlocks()) { + return false; + } + + Collection suitable = genome.getPrimary().getSuitableFruit(); + return suitable.contains(provider.getFamily()); + } + + @Override + public boolean trySpawnFruitBlock(World world, int x, int y, int z) { + IFruitProvider provider = getGenome().getFruitProvider(); + Collection suitable = genome.getPrimary().getSuitableFruit(); + if (!suitable.contains(provider.getFamily())) { + return false; + } + + return provider.trySpawnFruitBlock(getGenome(), world, x, y, z); + } + + /* INFORMATION */ + @Override + public ITreeGenome getGenome() { + return genome; + } + + private void setGenome(ITreeGenome genome) { + this.genome = genome; + plantTypes = genome.getPlantTypes(); + plantTypes.add(genome.getPrimary().getPlantType()); + } + + @Override + public ITree copy() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + this.writeToNBT(nbttagcompound); + return new Tree(nbttagcompound); + } + + @Override + public ITreeGenome getMate() { + return this.mate; + } + + @Override + public boolean isPureBred(EnumTreeChromosome chromosome) { + return genome.getActiveAllele(chromosome) + .getUID() + .equals(genome.getInactiveAllele(chromosome).getUID()); + } + + @Override + public EnumSet getPlantTypes() { + return plantTypes; + } + + @Override + public void addTooltip(List list) { + + // No info 4 u! + if (!isAnalyzed) { + list.add("<" + StringUtil.localize("gui.unknown") + ">"); + return; + } + + // You analyzed it? Juicy tooltip coming up! + IAlleleTreeSpecies primary = genome.getPrimary(); + IAlleleTreeSpecies secondary = genome.getSecondary(); + if (!isPureBred(EnumTreeChromosome.SPECIES)) { + list.add(EnumChatFormatting.BLUE + + StringUtil.localize("trees.hybrid") + .replaceAll("%PRIMARY", primary.getName()) + .replaceAll("%SECONDARY", secondary.getName())); + } + + String sappiness = EnumChatFormatting.GOLD + "S: " + + genome.getActiveAllele(EnumTreeChromosome.SAPPINESS).getName(); + String maturation = EnumChatFormatting.RED + "M: " + + genome.getActiveAllele(EnumTreeChromosome.MATURATION).getName(); + String height = EnumChatFormatting.LIGHT_PURPLE + "H: " + + genome.getActiveAllele(EnumTreeChromosome.HEIGHT).getName(); + String girth = EnumChatFormatting.AQUA + "G: " + String.format("%sx%s", genome.getGirth(), genome.getGirth()); + String saplings = EnumChatFormatting.YELLOW + "S: " + + genome.getActiveAllele(EnumTreeChromosome.FERTILITY).getName(); + String yield = EnumChatFormatting.WHITE + "Y: " + + genome.getActiveAllele(EnumTreeChromosome.YIELD).getName(); + list.add(String.format("%s, %s", saplings, maturation)); + list.add(String.format("%s, %s", height, girth)); + list.add(String.format("%s, %s", yield, sappiness)); + + IAlleleBoolean primaryFireproof = (IAlleleBoolean) genome.getActiveAllele(EnumTreeChromosome.FIREPROOF); + if (primaryFireproof.getValue()) { + list.add(EnumChatFormatting.RED + StatCollector.translateToLocal("for.gui.fireresist")); + } + + IAllele fruit = getGenome().getActiveAllele(EnumTreeChromosome.FRUITS); + if (fruit != AlleleFruit.fruitNone) { + String strike = ""; + if (!canBearFruit()) { + strike = EnumChatFormatting.STRIKETHROUGH.toString(); + } + list.add(strike + EnumChatFormatting.GREEN + "F: " + + StringUtil.localize(genome.getFruitProvider().getDescription())); + } + } + + /* REPRODUCTION */ + @Override + public ITree[] getSaplings(World world, GameProfile playerProfile, int x, int y, int z, float modifier) { + ArrayList prod = new ArrayList<>(); + + float chance = genome.getFertility() * modifier; + + if (world.rand.nextFloat() <= chance) { + if (this.getMate() == null) { + prod.add(TreeManager.treeRoot.getTree(world, new TreeGenome(genome.getChromosomes()))); + } else { + prod.add(createOffspring(world, playerProfile, x, y, z)); + } + } + + return prod.toArray(new ITree[prod.size()]); + } + + private ITree createOffspring(World world, GameProfile playerProfile, int x, int y, int z) { + + IChromosome[] chromosomes = new IChromosome[genome.getChromosomes().length]; + IChromosome[] parent1 = genome.getChromosomes(); + IChromosome[] parent2 = mate.getChromosomes(); + + // Check for mutation. Replace one of the parents with the mutation + // template if mutation occured. + IChromosome[] mutated = mutateSpecies(world, playerProfile, x, y, z, genome, mate); + if (mutated == null) { + mutated = mutateSpecies(world, playerProfile, x, y, z, mate, genome); + } + + if (mutated != null) { + return new Tree(new TreeGenome(mutated)); + } + + for (int i = 0; i < parent1.length; i++) { + if (parent1[i] != null && parent2[i] != null) { + chromosomes[i] = Chromosome.inheritChromosome(world.rand, parent1[i], parent2[i]); + } + } + + return new Tree(new TreeGenome(chromosomes)); + } + + private static IChromosome[] mutateSpecies( + World world, + @Nullable GameProfile playerProfile, + int x, + int y, + int z, + ITreeGenome genomeOne, + ITreeGenome genomeTwo) { + + IChromosome[] parent1 = genomeOne.getChromosomes(); + IChromosome[] parent2 = genomeTwo.getChromosomes(); + + ITreeGenome genome0; + ITreeGenome genome1; + IAlleleTreeSpecies allele0; + IAlleleTreeSpecies allele1; + + if (world.rand.nextBoolean()) { + allele0 = (IAlleleTreeSpecies) parent1[EnumTreeChromosome.SPECIES.ordinal()].getPrimaryAllele(); + allele1 = (IAlleleTreeSpecies) parent2[EnumTreeChromosome.SPECIES.ordinal()].getSecondaryAllele(); + + genome0 = genomeOne; + genome1 = genomeTwo; + } else { + allele0 = (IAlleleTreeSpecies) parent2[EnumTreeChromosome.SPECIES.ordinal()].getPrimaryAllele(); + allele1 = (IAlleleTreeSpecies) parent1[EnumTreeChromosome.SPECIES.ordinal()].getSecondaryAllele(); + + genome0 = genomeTwo; + genome1 = genomeOne; + } + + IArboristTracker breedingTracker = null; + if (playerProfile != null) { + breedingTracker = TreeManager.treeRoot.getBreedingTracker(world, playerProfile); + } + + List combinations = TreeManager.treeRoot.getCombinations(allele0, allele1, true); + for (IMutation mutation : combinations) { + ITreeMutation treeMutation = (ITreeMutation) mutation; + // Stop blacklisted species. + // if (BeeManager.breedingManager.isBlacklisted(mutation.getTemplate()[0].getUID())) { + // continue; + // } + + float chance = treeMutation.getChance(world, x, y, z, allele0, allele1, genome0, genome1); + if (chance <= 0) { + continue; + } + + // boost chance for researched mutations + if (breedingTracker != null && breedingTracker.isResearched(treeMutation)) { + float mutationBoost = chance * (Config.researchMutationBoostMultiplier - 1.0f); + mutationBoost = Math.min(Config.maxResearchMutationBoostPercent, mutationBoost); + chance += mutationBoost; + } + + if (chance > world.rand.nextFloat() * 100) { + return TreeManager.treeRoot.templateAsChromosomes(treeMutation.getTemplate()); + } + } + + return null; + } + + /* PRODUCTION */ + @Override + public boolean canBearFruit() { + return genome.getPrimary() + .getSuitableFruit() + .contains(genome.getFruitProvider().getFamily()); + } + + @Override + public ItemStack[] getProduceList() { + return genome.getFruitProvider().getProducts(); + } + + @Override + public ItemStack[] getSpecialtyList() { + return genome.getFruitProvider().getSpecialty(); + } + + @Override + public ItemStack[] produceStacks(World world, int x, int y, int z, int ripeningTime) { + return genome.getFruitProvider().getFruits(genome, world, x, y, z, ripeningTime); + } } diff --git a/src/main/java/forestry/arboriculture/genetics/TreeBranchDefinition.java b/src/main/java/forestry/arboriculture/genetics/TreeBranchDefinition.java index 43ca3e2a1..176c99ade 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeBranchDefinition.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeBranchDefinition.java @@ -1,226 +1,262 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.genetics; - -import java.util.Arrays; -import java.util.Locale; - -import org.apache.commons.lang3.text.WordUtils; - -import forestry.api.arboriculture.EnumTreeChromosome; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IAlleleRegistry; -import forestry.api.genetics.IClassification; -import forestry.api.genetics.IClassification.EnumClassLevel; -import forestry.arboriculture.genetics.alleles.AlleleFruit; -import forestry.arboriculture.genetics.alleles.AlleleGrowth; -import forestry.arboriculture.genetics.alleles.AlleleLeafEffect; -import forestry.core.genetics.IBranchDefinition; -import forestry.core.genetics.alleles.AlleleHelper; -import forestry.core.genetics.alleles.AllelePlantType; -import forestry.core.genetics.alleles.EnumAllele; - -public enum TreeBranchDefinition implements IBranchDefinition { - ACACIA, - ACER, - ADANSONIA, - ASTRONIUM, - BETULA, - CASTANEA, - CEIBA, - CHLOROCARDIUM, - CITRUS, - DALBERGIA, - EBONY("Diospyros"), - JUGLANS, - LARIX, - MAHOGANY("Shorea"), - MILLETTIA, - OCHROMA, - PHOENIX, - PICEA, - PINUS, - POPULUS, - PRUNUS, - PTEROCARPUS, - QUERCUS, - SALIX, - SEQUOIA, - SEQUOIADENDRON, - TABEBUIA, - TALIPARITI, - TECTONA, - TILIA, - - // unclassified - CARICA, - TROPICAL(""),; - - private final IClassification branch; - - TreeBranchDefinition() { - String name = this.name().toLowerCase(Locale.ENGLISH); - String scientific = WordUtils.capitalize(name); - branch = new BranchTrees(name, scientific); - } - - TreeBranchDefinition(String scientific) { - String name = this.name().toLowerCase(Locale.ENGLISH); - branch = new BranchTrees(name, scientific); - } - - private static IAllele[] defaultTemplate; - - @Override - public IAllele[] getTemplate() { - if (defaultTemplate == null) { - defaultTemplate = new IAllele[EnumTreeChromosome.values().length]; - - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.FRUITS, AlleleFruit.fruitNone); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.GROWTH, AlleleGrowth.growthLightLevel); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALL); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOWER); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOWEST); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.PLANT, AllelePlantType.plantTypeNone); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWEST); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.TERRITORY, EnumAllele.Territory.AVERAGE); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.EFFECT, AlleleLeafEffect.leavesNone); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.AVERAGE); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.GIRTH, 1); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.FIREPROOF, EnumAllele.Fireproof.FALSE); - } - return Arrays.copyOf(defaultTemplate, defaultTemplate.length); - } - - @Override - public IClassification getBranch() { - return branch; - } - - public static void createAlleles() { - - IAlleleRegistry alleleRegistry = AlleleManager.alleleRegistry; - - IClassification plantae = alleleRegistry.getClassification("kingdom.plantae"); - - plantae.addMemberGroup( - alleleRegistry.createAndRegisterClassification(EnumClassLevel.DIVISION, "angiosperms", "Angiosperms", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.CLASS, "asterids", "Asterids", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "ericales", "Ericales", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "ebenaceae", "Ebenaceae", - EBONY.getBranch() - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "fabaceae", "Fabaceae", - ACACIA.getBranch(), - DALBERGIA.getBranch(), - MILLETTIA.getBranch(), - PTEROCARPUS.getBranch() - ) - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "lamiales", "Lamiales", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "bignoniaceae", "Bignoniaceae", - TABEBUIA.getBranch() - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "lamiaceae", "Lamiaceae", - TECTONA.getBranch() - ) - ) - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.CLASS, "commelinids", "Commelinids", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "arecales", "Arecales", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "arecaceae", "Arecaceae", - PHOENIX.getBranch() - ) - ) - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.CLASS, "rosids", "Rosids", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "brassicales", "Brassicales", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "caricaceae", "Caricaceae") - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "fabales", "Fabales"), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "fagales", "Fagales", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "betulaceae", "Betulaceae", - BETULA.getBranch() - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "fagaceae", "Fagaceae", - CASTANEA.getBranch(), - QUERCUS.getBranch() - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "juglandaceae", "Juglandaceae", - JUGLANS.getBranch() - ) - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "rosales", "Rosales", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "rosaceae", "Rosaceae", - PRUNUS.getBranch() - ) - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "malvales", "Malvales", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "dipterocarpaceae", "Dipterocarpaceae", - MAHOGANY.getBranch() - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "malvaceae", "Malvaceae", - ADANSONIA.getBranch(), - CEIBA.getBranch(), - OCHROMA.getBranch(), - TALIPARITI.getBranch(), - TILIA.getBranch() - ) - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "laurales", "Laurales"), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "malpighiales", "Malpighiales", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "salicaceae", "Salicaceae", - CHLOROCARDIUM.getBranch(), - POPULUS.getBranch(), - SALIX.getBranch() - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "lauraceae", "Lauraceae") - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "sapindales", "Sapindales", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "rutaceae", "Rutaceae", - CITRUS.getBranch() - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "sapindaceae", "Sapindaceae", - ACER.getBranch() - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "anacardiaceae", "Anacardiaceae", - ASTRONIUM.getBranch() - ) - ) - ) - ) - ); - - plantae.addMemberGroup( - alleleRegistry.createAndRegisterClassification(EnumClassLevel.DIVISION, "pinophyta", "Pinophyta", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.CLASS, "pinopsida", "Pinopsida", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "pinales", "Pinales", - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "pinaceae", "Pinaceae", - PICEA.getBranch(), - PINUS.getBranch(), - LARIX.getBranch() - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "cupressaceae", "Cupressaceae", - SEQUOIA.getBranch(), - SEQUOIADENDRON.getBranch() - ) - ) - ), - alleleRegistry.createAndRegisterClassification(EnumClassLevel.CLASS, "magnoliopsida", "Magnoliopsida") - ) - ); - - plantae.addMemberGroup( - alleleRegistry.createAndRegisterClassification(EnumClassLevel.DIVISION, "magnoliophyta", "Magnoliophyta") - ); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.genetics; + +import forestry.api.arboriculture.EnumTreeChromosome; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IAlleleRegistry; +import forestry.api.genetics.IClassification; +import forestry.api.genetics.IClassification.EnumClassLevel; +import forestry.arboriculture.genetics.alleles.AlleleFruit; +import forestry.arboriculture.genetics.alleles.AlleleGrowth; +import forestry.arboriculture.genetics.alleles.AlleleLeafEffect; +import forestry.core.genetics.IBranchDefinition; +import forestry.core.genetics.alleles.AlleleHelper; +import forestry.core.genetics.alleles.AllelePlantType; +import forestry.core.genetics.alleles.EnumAllele; +import java.util.Arrays; +import java.util.Locale; +import org.apache.commons.lang3.text.WordUtils; + +public enum TreeBranchDefinition implements IBranchDefinition { + ACACIA, + ACER, + ADANSONIA, + ASTRONIUM, + BETULA, + CASTANEA, + CEIBA, + CHLOROCARDIUM, + CITRUS, + DALBERGIA, + EBONY("Diospyros"), + JUGLANS, + LARIX, + MAHOGANY("Shorea"), + MILLETTIA, + OCHROMA, + PHOENIX, + PICEA, + PINUS, + POPULUS, + PRUNUS, + PTEROCARPUS, + QUERCUS, + SALIX, + SEQUOIA, + SEQUOIADENDRON, + TABEBUIA, + TALIPARITI, + TECTONA, + TILIA, + + // unclassified + CARICA, + TROPICAL(""), + ; + + private final IClassification branch; + + TreeBranchDefinition() { + String name = this.name().toLowerCase(Locale.ENGLISH); + String scientific = WordUtils.capitalize(name); + branch = new BranchTrees(name, scientific); + } + + TreeBranchDefinition(String scientific) { + String name = this.name().toLowerCase(Locale.ENGLISH); + branch = new BranchTrees(name, scientific); + } + + private static IAllele[] defaultTemplate; + + @Override + public IAllele[] getTemplate() { + if (defaultTemplate == null) { + defaultTemplate = new IAllele[EnumTreeChromosome.values().length]; + + AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.FRUITS, AlleleFruit.fruitNone); + AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.GROWTH, AlleleGrowth.growthLightLevel); + AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALL); + AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOWER); + AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOWEST); + AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.PLANT, AllelePlantType.plantTypeNone); + AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWEST); + AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.TERRITORY, EnumAllele.Territory.AVERAGE); + AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.EFFECT, AlleleLeafEffect.leavesNone); + AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.AVERAGE); + AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.GIRTH, 1); + AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.FIREPROOF, EnumAllele.Fireproof.FALSE); + } + return Arrays.copyOf(defaultTemplate, defaultTemplate.length); + } + + @Override + public IClassification getBranch() { + return branch; + } + + public static void createAlleles() { + + IAlleleRegistry alleleRegistry = AlleleManager.alleleRegistry; + + IClassification plantae = alleleRegistry.getClassification("kingdom.plantae"); + + plantae.addMemberGroup(alleleRegistry.createAndRegisterClassification( + EnumClassLevel.DIVISION, + "angiosperms", + "Angiosperms", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.CLASS, + "asterids", + "Asterids", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.ORDER, + "ericales", + "Ericales", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, "ebenaceae", "Ebenaceae", EBONY.getBranch()), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, + "fabaceae", + "Fabaceae", + ACACIA.getBranch(), + DALBERGIA.getBranch(), + MILLETTIA.getBranch(), + PTEROCARPUS.getBranch())), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.ORDER, + "lamiales", + "Lamiales", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, "bignoniaceae", "Bignoniaceae", TABEBUIA.getBranch()), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, "lamiaceae", "Lamiaceae", TECTONA.getBranch()))), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.CLASS, + "commelinids", + "Commelinids", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.ORDER, + "arecales", + "Arecales", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, "arecaceae", "Arecaceae", PHOENIX.getBranch()))), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.CLASS, + "rosids", + "Rosids", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.ORDER, + "brassicales", + "Brassicales", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, "caricaceae", "Caricaceae")), + alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "fabales", "Fabales"), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.ORDER, + "fagales", + "Fagales", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, "betulaceae", "Betulaceae", BETULA.getBranch()), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, + "fagaceae", + "Fagaceae", + CASTANEA.getBranch(), + QUERCUS.getBranch()), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, "juglandaceae", "Juglandaceae", JUGLANS.getBranch())), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.ORDER, + "rosales", + "Rosales", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, "rosaceae", "Rosaceae", PRUNUS.getBranch())), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.ORDER, + "malvales", + "Malvales", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, + "dipterocarpaceae", + "Dipterocarpaceae", + MAHOGANY.getBranch()), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, + "malvaceae", + "Malvaceae", + ADANSONIA.getBranch(), + CEIBA.getBranch(), + OCHROMA.getBranch(), + TALIPARITI.getBranch(), + TILIA.getBranch())), + alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "laurales", "Laurales"), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.ORDER, + "malpighiales", + "Malpighiales", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, + "salicaceae", + "Salicaceae", + CHLOROCARDIUM.getBranch(), + POPULUS.getBranch(), + SALIX.getBranch()), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, "lauraceae", "Lauraceae")), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.ORDER, + "sapindales", + "Sapindales", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, "rutaceae", "Rutaceae", CITRUS.getBranch()), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, "sapindaceae", "Sapindaceae", ACER.getBranch()), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, + "anacardiaceae", + "Anacardiaceae", + ASTRONIUM.getBranch()))))); + + plantae.addMemberGroup(alleleRegistry.createAndRegisterClassification( + EnumClassLevel.DIVISION, + "pinophyta", + "Pinophyta", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.CLASS, + "pinopsida", + "Pinopsida", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.ORDER, + "pinales", + "Pinales", + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, + "pinaceae", + "Pinaceae", + PICEA.getBranch(), + PINUS.getBranch(), + LARIX.getBranch()), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.FAMILY, + "cupressaceae", + "Cupressaceae", + SEQUOIA.getBranch(), + SEQUOIADENDRON.getBranch()))), + alleleRegistry.createAndRegisterClassification( + EnumClassLevel.CLASS, "magnoliopsida", "Magnoliopsida"))); + + plantae.addMemberGroup(alleleRegistry.createAndRegisterClassification( + EnumClassLevel.DIVISION, "magnoliophyta", "Magnoliophyta")); + } +} diff --git a/src/main/java/forestry/arboriculture/genetics/TreeDefinition.java b/src/main/java/forestry/arboriculture/genetics/TreeDefinition.java index 1d0fce417..6fadd043c 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeDefinition.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeDefinition.java @@ -1,1111 +1,1408 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.genetics; - -import java.awt.Color; -import java.util.Arrays; - -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; -import net.minecraft.world.gen.feature.WorldGenerator; - -import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.BiomeDictionary; -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.api.arboriculture.EnumFruitFamily; -import forestry.api.arboriculture.EnumGermlingType; -import forestry.api.arboriculture.EnumLeafType; -import forestry.api.arboriculture.EnumTreeChromosome; -import forestry.api.arboriculture.EnumWoodType; -import forestry.api.arboriculture.IAlleleTreeSpeciesCustom; -import forestry.api.arboriculture.IGermlingIconProvider; -import forestry.api.arboriculture.ILeafIconProvider; -import forestry.api.arboriculture.ITree; -import forestry.api.arboriculture.ITreeGenerator; -import forestry.api.arboriculture.ITreeGenome; -import forestry.api.arboriculture.ITreeMutationCustom; -import forestry.api.arboriculture.TreeManager; -import forestry.api.core.EnumHumidity; -import forestry.api.core.EnumTemperature; -import forestry.api.genetics.IAllele; -import forestry.api.world.ITreeGenData; -import forestry.arboriculture.blocks.BlockForestryLeaves; -import forestry.arboriculture.genetics.alleles.AlleleFruit; -import forestry.arboriculture.genetics.alleles.AlleleGrowth; -import forestry.arboriculture.render.IconProviderGermling; -import forestry.arboriculture.render.IconProviderGermlingVanilla; -import forestry.arboriculture.tiles.TileLeaves; -import forestry.arboriculture.worldgen.BlockTypeLog; -import forestry.arboriculture.worldgen.WorldGenAcacia; -import forestry.arboriculture.worldgen.WorldGenAcaciaVanilla; -import forestry.arboriculture.worldgen.WorldGenBalsa; -import forestry.arboriculture.worldgen.WorldGenBaobab; -import forestry.arboriculture.worldgen.WorldGenBirch; -import forestry.arboriculture.worldgen.WorldGenCherry; -import forestry.arboriculture.worldgen.WorldGenChestnut; -import forestry.arboriculture.worldgen.WorldGenCocobolo; -import forestry.arboriculture.worldgen.WorldGenDarkOak; -import forestry.arboriculture.worldgen.WorldGenDate; -import forestry.arboriculture.worldgen.WorldGenEbony; -import forestry.arboriculture.worldgen.WorldGenGiganteum; -import forestry.arboriculture.worldgen.WorldGenGreenheart; -import forestry.arboriculture.worldgen.WorldGenIpe; -import forestry.arboriculture.worldgen.WorldGenJungle; -import forestry.arboriculture.worldgen.WorldGenKapok; -import forestry.arboriculture.worldgen.WorldGenLarch; -import forestry.arboriculture.worldgen.WorldGenLemon; -import forestry.arboriculture.worldgen.WorldGenMahoe; -import forestry.arboriculture.worldgen.WorldGenMahogany; -import forestry.arboriculture.worldgen.WorldGenMaple; -import forestry.arboriculture.worldgen.WorldGenOak; -import forestry.arboriculture.worldgen.WorldGenPadauk; -import forestry.arboriculture.worldgen.WorldGenPapaya; -import forestry.arboriculture.worldgen.WorldGenPine; -import forestry.arboriculture.worldgen.WorldGenPlum; -import forestry.arboriculture.worldgen.WorldGenPoplar; -import forestry.arboriculture.worldgen.WorldGenSequoia; -import forestry.arboriculture.worldgen.WorldGenSilverLime; -import forestry.arboriculture.worldgen.WorldGenSpruce; -import forestry.arboriculture.worldgen.WorldGenTeak; -import forestry.arboriculture.worldgen.WorldGenWalnut; -import forestry.arboriculture.worldgen.WorldGenWenge; -import forestry.arboriculture.worldgen.WorldGenWillow; -import forestry.arboriculture.worldgen.WorldGenZebrawood; -import forestry.core.config.Constants; -import forestry.core.genetics.alleles.AlleleBoolean; -import forestry.core.genetics.alleles.AlleleHelper; -import forestry.core.genetics.alleles.AllelePlantType; -import forestry.core.genetics.alleles.EnumAllele; -import forestry.plugins.PluginArboriculture; - -public enum TreeDefinition implements ITreeDefinition, ITreeGenerator { - Oak(TreeBranchDefinition.QUERCUS, "appleOak", "robur", false, EnumLeafType.DECIDUOUS, new Color(4764952), new Color(4764952).brighter(), 0, new ItemStack(Blocks.log, 1, 0)) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenOak(tree); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitApple); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.POMES); - } - - @Override - protected void registerMutations() { - // vanilla - } - }, - DarkOak(TreeBranchDefinition.QUERCUS, "darkOak", "velutina", false, EnumLeafType.DECIDUOUS, new Color(4764952), new Color(4764952).brighter(), 5, new ItemStack(Blocks.log2, 1, 1)) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenDarkOak(tree); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.POMES); - } - - @Override - protected void registerMutations() { - // vanilla - } - }, - Birch(TreeBranchDefinition.BETULA, "silverBirch", "pendula", false, EnumLeafType.DECIDUOUS, new Color(8431445), new Color(0xb0c648), 2, new ItemStack(Blocks.log, 1, 2)) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenBirch(tree); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - - } - - @Override - protected void registerMutations() { - // vanilla - } - }, - Lime(TreeBranchDefinition.TILIA, "silverLime", "pendula", true, EnumLeafType.DECIDUOUS, new Color(0x5ea107), new Color(0x5ea107).brighter(), EnumWoodType.LIME) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenSilverLime(tree); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOWER); - //Allele.helper.set(alleles, EnumTreeChromosome.EFFECT, Allele.leavesBrimstone); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.NUX) - .addFruitFamily(EnumFruitFamily.PRUNES) - .addFruitFamily(EnumFruitFamily.POMES); - } - - @Override - protected void registerMutations() { - registerMutation(Birch, Oak, 15); - } - }, - Walnut(TreeBranchDefinition.JUGLANS, "commonWalnut", "regia", true, EnumLeafType.DECIDUOUS, new Color(0x798c55), new Color(0xb0c648), EnumWoodType.WALNUT) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenWalnut(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.NUX) - .addFruitFamily(EnumFruitFamily.PRUNES) - .addFruitFamily(EnumFruitFamily.POMES); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitWalnut); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); - } - - @Override - protected void registerMutations() { - registerMutation(Lime, Cherry, 10); - } - }, - Chestnut(TreeBranchDefinition.CASTANEA, "sweetChestnut", "sativa", true, EnumLeafType.DECIDUOUS, new Color(0x5ea107), new Color(0xb0c648), EnumWoodType.CHESTNUT) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenChestnut(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.NUX) - .addFruitFamily(EnumFruitFamily.PRUNES) - .addFruitFamily(EnumFruitFamily.POMES); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitChestnut); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); - } - - @Override - protected void registerMutations() { - registerMutation(Walnut, Lime, 10); - registerMutation(Walnut, Cherry, 10); - } - }, - Cherry(TreeBranchDefinition.PRUNUS, "hillCherry", "serrulata", true, EnumLeafType.DECIDUOUS, new Color(0xe691da), new Color(0xe63e59), EnumWoodType.CHERRY) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenCherry(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.PRUNES) - .addFruitFamily(EnumFruitFamily.POMES); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitCherry); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALLER); - } - - @Override - protected void registerMutations() { - registerMutation(Lime, Oak, 10); - registerMutation(Lime, Birch, 10); - } - }, - Lemon(TreeBranchDefinition.CITRUS, "lemon", "limon", true, EnumLeafType.DECIDUOUS, new Color(0x88af54), new Color(0xa3b850), EnumWoodType.CITRUS) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenLemon(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.PRUNES) - .addFruitFamily(EnumFruitFamily.POMES); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitLemon); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALLEST); - } - - @Override - protected void registerMutations() { - registerMutation(Lime, Cherry, 5); - } - }, - Plum(TreeBranchDefinition.PRUNUS, "plum", "domestica", true, EnumLeafType.DECIDUOUS, new Color(0x589246), new Color(0xa3b850), EnumWoodType.PLUM) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenPlum(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.PRUNES) - .addFruitFamily(EnumFruitFamily.POMES); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitPlum); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.HIGH); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALLEST); - } - - @Override - protected void registerMutations() { - registerMutation(Lemon, Cherry, 5); - } - }, - Maple(TreeBranchDefinition.ACER, "sugarMaple", "saccharum", true, EnumLeafType.MAPLE, new Color(0xd4f425), new Color(0x619a3c), EnumWoodType.MAPLE) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenMaple(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.PRUNES) - .addFruitFamily(EnumFruitFamily.POMES); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); - } - - @Override - protected void registerMutations() { - registerMutation(Spruce, Larch, 5); - } - }, - Spruce(TreeBranchDefinition.PICEA, "redSpruce", "abies", false, EnumLeafType.CONIFERS, new Color(6396257), new Color(0x539d12), 1, new ItemStack(Blocks.log, 1, 1)) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenSpruce(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); - } - - @Override - protected void registerMutations() { - // vanilla - } - }, - Larch(TreeBranchDefinition.LARIX, "mundaneLarch", "decidua", true, EnumLeafType.CONIFERS, new Color(0x698f90), new Color(0x569896), EnumWoodType.LARCH) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenLarch(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); - } - - @Override - protected void registerMutations() { - registerMutation(Spruce, Birch, 10); - registerMutation(Spruce, Oak, 10); - } - }, - Pine(TreeBranchDefinition.PINUS, "bullPine", "sabiniana", true, EnumLeafType.CONIFERS, new Color(0xfeff8f), new Color(0xffd98f), EnumWoodType.PINE) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenPine(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); - } - - @Override - protected void registerMutations() { - registerMutation(Spruce, Larch, 10); - } - }, - Sequioa(TreeBranchDefinition.SEQUOIA, "coastSequoia", "sempervirens", false, EnumLeafType.CONIFERS, new Color(0x418e71), new Color(0x569896), EnumWoodType.SEQUOIA) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenSequoia(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGEST); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 3); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FIREPROOF, EnumAllele.Fireproof.TRUE); - } - - @Override - protected void registerMutations() { - registerMutation(Larch, Pine, 5); - } - }, - Gigant(TreeBranchDefinition.SEQUOIADENDRON, "giantSequoia", "giganteum", false, EnumLeafType.CONIFERS, new Color(0x738434), new Color(0x738434).brighter(), EnumWoodType.GIGANTEUM) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenGiganteum(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.GIGANTIC); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWEST); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWEST); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 4); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FIREPROOF, EnumAllele.Fireproof.TRUE); - } - - @Override - protected void registerMutations() { - registerMutation(Sequioa,Baobab,1).requireNight().restrictBiomeType(BiomeDictionary.Type.FOREST); - } - }, - Jungle(TreeBranchDefinition.TROPICAL, "jungle", "tectona", false, EnumLeafType.JUNGLE, new Color(4764952), new Color(0x658917), 3, new ItemStack(Blocks.log, 1, 3)) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenJungle(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitCocoa); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FAST); - } - - @Override - protected void registerMutations() { - // vanilla - } - }, - Teak(TreeBranchDefinition.TECTONA, "teak", "grandis", true, EnumLeafType.JUNGLE, new Color(0xfeff8f), new Color(0xffd98f), EnumWoodType.TEAK) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenTeak(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - } - - @Override - protected void registerMutations() { - registerMutation(DarkOak, Jungle, 10); - } - }, - Ipe(TreeBranchDefinition.TABEBUIA, "ipe", "serratifolia", true, EnumLeafType.JUNGLE, new Color(0xfdd207), new Color(0xad8f04), EnumWoodType.IPE) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenIpe(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); - } - - @Override - protected void registerMutations() { - registerMutation(Teak, DarkOak, 10); - } - }, - Kapok(TreeBranchDefinition.CEIBA, "kapok", "pentandra", true, EnumLeafType.JUNGLE, new Color(0x89987b), new Color(0x89aa9e), EnumWoodType.KAPOK) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenKapok(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE) - .addFruitFamily(EnumFruitFamily.PRUNES); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); - } - - @Override - protected void registerMutations() { - registerMutation(Jungle, Teak, 10); - } - }, - Ebony(TreeBranchDefinition.EBONY, "myrtleEbony", "pentamera", true, EnumLeafType.JUNGLE, new Color(0xa2d24a), new Color(0xc4d24a), EnumWoodType.EBONY) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenEbony(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE) - .addFruitFamily(EnumFruitFamily.PRUNES); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 3); - } - - @Override - protected void registerMutations() { - registerMutation(DarkOak, Kapok, 10); - } - }, - Zebrawood(TreeBranchDefinition.ASTRONIUM, "zebrawood", "graveolens", false, EnumLeafType.JUNGLE, new Color(0xa2d24a), new Color(0xc4d24a), EnumWoodType.ZEBRAWOOD) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenZebrawood(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.NUX); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); - } - - @Override - protected void registerMutations() { - registerMutation(Ebony, Poplar, 5); - } - }, - Mahogony(TreeBranchDefinition.MAHOGANY, "yellowMeranti", "gibbosa", true, EnumLeafType.JUNGLE, new Color(0x8ab154), new Color(0xa9b154), EnumWoodType.MAHOGANY) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenMahogany(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); - } - - @Override - protected void registerMutations() { - registerMutation(Kapok, Ebony, 10); - } - }, - AcaciaVanilla(TreeBranchDefinition.ACACIA, "acacia", "aneura", true, EnumLeafType.DECIDUOUS, new Color(0x616101), new Color(0xb3b302), 4, new ItemStack(Blocks.log2, 1, 0)) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenAcaciaVanilla(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE) - .addFruitFamily(EnumFruitFamily.NUX); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - - } - - @Override - protected void registerMutations() { - // vanilla - } - }, - Acacia(TreeBranchDefinition.ACACIA, "desertAcacia", "erioloba", true, EnumLeafType.DECIDUOUS, new Color(0x748C1C), new Color(0xb3b302), EnumWoodType.ACACIA) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenAcacia(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE) - .addFruitFamily(EnumFruitFamily.NUX); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.PLANT, AllelePlantType.plantTypeDesert); - } - - @Override - protected void registerMutations() { - registerMutation(Teak, Balsa, 10); - } - }, - Padauk(TreeBranchDefinition.PTEROCARPUS, "padauk", "soyauxii", true, EnumLeafType.DECIDUOUS, new Color(0xd0df8c), new Color(0x435c32), EnumWoodType.PADAUK) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenPadauk(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - } - - @Override - protected void registerMutations() { - registerMutation(AcaciaVanilla, Jungle, 10); - } - }, - Balsa(TreeBranchDefinition.OCHROMA, "balsa", "pyramidale", true, EnumLeafType.DECIDUOUS, new Color(0x59ac00), new Color(0xfeff8f), EnumWoodType.BALSA) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenBalsa(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE) - .addFruitFamily(EnumFruitFamily.NUX); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.HIGH); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - } - - @Override - protected void registerMutations() { - registerMutation(Teak, AcaciaVanilla, 10); - } - }, - Cocobolo(TreeBranchDefinition.DALBERGIA, "cocobolo", "retusa", false, EnumLeafType.DECIDUOUS, new Color(0x6aa17a), new Color(0x487d4c), EnumWoodType.COCOBOLO) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenCocobolo(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGEST); - } - - @Override - protected void registerMutations() { - registerMutation(Acacia, DarkOak, 10); - } - }, - Wenge(TreeBranchDefinition.MILLETTIA, "wenge", "laurentii", true, EnumLeafType.DECIDUOUS, new Color(0xada157), new Color(0xad8a57), EnumWoodType.WENGE) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenWenge(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE) - .addFruitFamily(EnumFruitFamily.NUX); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOWEST); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); - } - - @Override - protected void registerMutations() { - registerMutation(Cocobolo, Balsa, 10); - } - }, - Baobab(TreeBranchDefinition.ADANSONIA, "grandidierBaobab", "digitata", true, EnumLeafType.DECIDUOUS, new Color(0xfeff8f), new Color(0xffd98f), EnumWoodType.BAOBAB) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenBaobab(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE) - .addFruitFamily(EnumFruitFamily.NUX); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.PLANT, AllelePlantType.plantTypeDesert); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 3); - } - - @Override - protected void registerMutations() { - registerMutation(Balsa, Wenge, 10); - } - }, - Mahoe(TreeBranchDefinition.TALIPARITI, "blueMahoe", "elatum", true, EnumLeafType.DECIDUOUS, new Color(0xa0ba1b), new Color(0x79a175), EnumWoodType.MAHOE) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenMahoe(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE) - .addFruitFamily(EnumFruitFamily.POMES) - .addFruitFamily(EnumFruitFamily.PRUNES); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALL); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.HIGH); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWEST); - } - - @Override - protected void registerMutations() { - registerMutation(Balsa, Acacia, 5); - } - }, - Willow(TreeBranchDefinition.SALIX, "whiteWillow", "alba", true, EnumLeafType.WILLOW, new Color(0xa3b8a5), new Color(0xa3b850), EnumWoodType.WILLOW) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenWillow(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.NUX) - .addFruitFamily(EnumFruitFamily.PRUNES) - .addFruitFamily(EnumFruitFamily.POMES); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); - } - - @Override - protected void registerMutations() { - registerMutation(Oak, Birch, 10) - .restrictTemperature(EnumTemperature.WARM, EnumTemperature.HOT) - .restrictHumidity(EnumHumidity.DAMP); - registerMutation(Oak, Lime, 10) - .restrictTemperature(EnumTemperature.WARM, EnumTemperature.HOT) - .restrictHumidity(EnumHumidity.DAMP); - registerMutation(Lime, Birch, 10) - .restrictTemperature(EnumTemperature.WARM, EnumTemperature.HOT) - .restrictHumidity(EnumHumidity.DAMP); - } - }, - Sipiri(TreeBranchDefinition.CHLOROCARDIUM, "sipiri", "rodiei", true, EnumLeafType.DECIDUOUS, new Color(0x678911), new Color(0x79a175), EnumWoodType.GREENHEART) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenGreenheart(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GROWTH, AlleleGrowth.growthTropical); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); - } - - @Override - protected void registerMutations() { - registerMutation(Kapok, Mahogony, 10) - .restrictTemperature(EnumTemperature.WARM, EnumTemperature.HOT) - .restrictHumidity(EnumHumidity.DAMP); - } - }, - Papaya(TreeBranchDefinition.CARICA, "papaya", "papaya", true, EnumLeafType.PALM, new Color(0x6d9f58), new Color(0x75E675), EnumWoodType.PAPAYA) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenPapaya(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE) - .addFruitFamily(EnumFruitFamily.NUX); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitPapaya); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); - } - - @Override - protected void registerMutations() { - registerMutation(Jungle, Cherry, 5); - } - }, - Date(TreeBranchDefinition.PHOENIX, "datePalm", "dactylifera", true, EnumLeafType.PALM, new Color(0xcbcd79), new Color(0xB3F370), EnumWoodType.PALM) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenDate(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE) - .addFruitFamily(EnumFruitFamily.NUX); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitDates); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); - } - - @Override - protected void registerMutations() { - registerMutation(Jungle, Papaya, 5); - } - }, - Poplar(TreeBranchDefinition.POPULUS, "whitePoplar", "alba", true, EnumLeafType.DECIDUOUS, new Color(0xa3b8a5), new Color(0x539d12), EnumWoodType.POPLAR) { - @Override - public WorldGenerator getWorldGenerator(ITreeGenData tree) { - return new WorldGenPoplar(tree); - } - - @Override - protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { - treeSpecies.addFruitFamily(EnumFruitFamily.PRUNES) - .addFruitFamily(EnumFruitFamily.POMES); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALL); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWER); - } - - @Override - protected void registerMutations() { - registerMutation(Birch, Willow, 5); - registerMutation(Oak, Willow, 5); - registerMutation(Lime, Willow, 5); - } - }; - - private final TreeBranchDefinition branch; - private final IAlleleTreeSpeciesCustom species; - - private final EnumWoodType woodType; // for forestry trees - private final ItemStack vanillaWood; // for vanilla trees - - private IAllele[] template; - private ITreeGenome genome; - - // vanilla tree constructor - TreeDefinition(TreeBranchDefinition branch, String speciesName, String binomial, boolean dominant, EnumLeafType leafType, Color primary, Color secondary, int vanillaMeta, ItemStack vanillaWood) { - String uid = "forestry.tree" + this; - String unlocalizedDescription = "for.description.tree" + this; - String unlocalizedName = "for.trees.species." + speciesName; - - this.branch = branch; - - ILeafIconProvider leafIconProvider = TreeManager.treeFactory.getLeafIconProvider(leafType, primary, secondary); - IGermlingIconProvider germlingIconProvider = new IconProviderGermlingVanilla(vanillaMeta); - - this.species = TreeManager.treeFactory.createSpecies(uid, unlocalizedName, "Sengir", unlocalizedDescription, dominant, branch.getBranch(), binomial, leafIconProvider, germlingIconProvider, this); - this.woodType = null; - this.vanillaWood = vanillaWood; - } - - // forestry tree constructor - TreeDefinition(TreeBranchDefinition branch, String speciesName, String binomial, boolean dominant, EnumLeafType leafType, Color primary, Color secondary, EnumWoodType woodType) { - String uid = "forestry.tree" + this; - String unlocalizedDescription = "for.description.tree" + this; - String unlocalizedName = "for.trees.species." + speciesName; - - this.branch = branch; - - ILeafIconProvider leafIconProvider = TreeManager.treeFactory.getLeafIconProvider(leafType, primary, secondary); - IGermlingIconProvider germlingIconProvider = new IconProviderGermling(uid); - - this.species = TreeManager.treeFactory.createSpecies(uid, unlocalizedName, "Sengir", unlocalizedDescription, dominant, branch.getBranch(), binomial, leafIconProvider, germlingIconProvider, this); - this.woodType = woodType; - this.vanillaWood = null; - } - - protected abstract void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies); - - protected abstract void setAlleles(IAllele[] alleles); - - protected abstract void registerMutations(); - - @Override - public void setLogBlock(ITreeGenome genome, World world, int x, int y, int z, ForgeDirection facing) { - if (woodType == null) { - Block vanillaWoodBlock = Block.getBlockFromItem(vanillaWood.getItem()); - int vanillaWoodMeta = vanillaWood.getItemDamage(); - switch (facing) { - case NORTH: - case SOUTH: - vanillaWoodMeta |= 2 << 2; - break; - case EAST: - case WEST: - vanillaWoodMeta |= 1 << 2; - break; - } - - world.setBlock(x, y, z, vanillaWoodBlock, vanillaWoodMeta, Constants.FLAG_BLOCK_SYNCH); - } else { - AlleleBoolean fireproofAllele = (AlleleBoolean) genome.getActiveAllele(EnumTreeChromosome.FIREPROOF); - boolean fireproof = fireproofAllele.getValue(); - ItemStack log = TreeManager.woodItemAccess.getLog(woodType, fireproof); - - BlockTypeLog logBlock = new BlockTypeLog(log); - logBlock.setDirection(facing); - logBlock.setBlock(world, x, y, z); - } - } - - @Override - public void setLogBlock(World world, int x, int y, int z, ForgeDirection facing) { - setLogBlock(genome, world, x, y, z, facing); - } - - @Override - public void setLeaves(ITreeGenome genome, World world, GameProfile owner, int x, int y, int z, boolean decorative) { - boolean placed = world.setBlock(x, y, z, PluginArboriculture.blocks.leaves, 0, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); - if (!placed) { - return; - } - - Block block = world.getBlock(x, y, z); - if (PluginArboriculture.blocks.leaves != block) { - world.setBlockToAir(x, y, z); - return; - } - - TileLeaves tileLeaves = BlockForestryLeaves.getLeafTile(world, x, y, z); - if (tileLeaves == null) { - world.setBlockToAir(x, y, z); - return; - } - - tileLeaves.setOwner(owner); - if (decorative) { - tileLeaves.setDecorative(); - } - tileLeaves.setTree(new Tree(genome)); - - world.markBlockForUpdate(x, y, z); - } - - @Override - public void setLeaves(World world, GameProfile owner, int x, int y, int z, boolean decorative) { - setLeaves(genome, world, owner, x, y, z, decorative); - } - - public static void initTrees() { - for (TreeDefinition tree : values()) { - tree.init(); - } - for (TreeDefinition tree : values()) { - tree.registerMutations(); - } - } - - private void init() { - setSpeciesProperties(species); - - template = branch.getTemplate(); - AlleleHelper.instance.set(template, EnumTreeChromosome.SPECIES, species); - setAlleles(template); - - genome = TreeManager.treeRoot.templateAsGenome(template); - - TreeManager.treeRoot.registerTemplate(template); - } - - protected final ITreeMutationCustom registerMutation(TreeDefinition parent1, TreeDefinition parent2, int chance) { - return TreeManager.treeMutationFactory.createMutation(parent1.species, parent2.species, getTemplate(), chance); - } - - @Override - public final IAllele[] getTemplate() { - return Arrays.copyOf(template, template.length); - } - - public final String getUID() { - return species.getUID(); - } - - @Override - public final ITreeGenome getGenome() { - return genome; - } - - @Override - public final ITree getIndividual() { - return new Tree(genome); - } - - @Override - public final ItemStack getMemberStack(EnumGermlingType treeType) { - ITree tree = getIndividual(); - return TreeManager.treeRoot.getMemberStack(tree, treeType.ordinal()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.genetics; + +import com.mojang.authlib.GameProfile; +import forestry.api.arboriculture.EnumFruitFamily; +import forestry.api.arboriculture.EnumGermlingType; +import forestry.api.arboriculture.EnumLeafType; +import forestry.api.arboriculture.EnumTreeChromosome; +import forestry.api.arboriculture.EnumWoodType; +import forestry.api.arboriculture.IAlleleTreeSpeciesCustom; +import forestry.api.arboriculture.IGermlingIconProvider; +import forestry.api.arboriculture.ILeafIconProvider; +import forestry.api.arboriculture.ITree; +import forestry.api.arboriculture.ITreeGenerator; +import forestry.api.arboriculture.ITreeGenome; +import forestry.api.arboriculture.ITreeMutationCustom; +import forestry.api.arboriculture.TreeManager; +import forestry.api.core.EnumHumidity; +import forestry.api.core.EnumTemperature; +import forestry.api.genetics.IAllele; +import forestry.api.world.ITreeGenData; +import forestry.arboriculture.blocks.BlockForestryLeaves; +import forestry.arboriculture.genetics.alleles.AlleleFruit; +import forestry.arboriculture.genetics.alleles.AlleleGrowth; +import forestry.arboriculture.render.IconProviderGermling; +import forestry.arboriculture.render.IconProviderGermlingVanilla; +import forestry.arboriculture.tiles.TileLeaves; +import forestry.arboriculture.worldgen.BlockTypeLog; +import forestry.arboriculture.worldgen.WorldGenAcacia; +import forestry.arboriculture.worldgen.WorldGenAcaciaVanilla; +import forestry.arboriculture.worldgen.WorldGenBalsa; +import forestry.arboriculture.worldgen.WorldGenBaobab; +import forestry.arboriculture.worldgen.WorldGenBirch; +import forestry.arboriculture.worldgen.WorldGenCherry; +import forestry.arboriculture.worldgen.WorldGenChestnut; +import forestry.arboriculture.worldgen.WorldGenCocobolo; +import forestry.arboriculture.worldgen.WorldGenDarkOak; +import forestry.arboriculture.worldgen.WorldGenDate; +import forestry.arboriculture.worldgen.WorldGenEbony; +import forestry.arboriculture.worldgen.WorldGenGiganteum; +import forestry.arboriculture.worldgen.WorldGenGreenheart; +import forestry.arboriculture.worldgen.WorldGenIpe; +import forestry.arboriculture.worldgen.WorldGenJungle; +import forestry.arboriculture.worldgen.WorldGenKapok; +import forestry.arboriculture.worldgen.WorldGenLarch; +import forestry.arboriculture.worldgen.WorldGenLemon; +import forestry.arboriculture.worldgen.WorldGenMahoe; +import forestry.arboriculture.worldgen.WorldGenMahogany; +import forestry.arboriculture.worldgen.WorldGenMaple; +import forestry.arboriculture.worldgen.WorldGenOak; +import forestry.arboriculture.worldgen.WorldGenPadauk; +import forestry.arboriculture.worldgen.WorldGenPapaya; +import forestry.arboriculture.worldgen.WorldGenPine; +import forestry.arboriculture.worldgen.WorldGenPlum; +import forestry.arboriculture.worldgen.WorldGenPoplar; +import forestry.arboriculture.worldgen.WorldGenSequoia; +import forestry.arboriculture.worldgen.WorldGenSilverLime; +import forestry.arboriculture.worldgen.WorldGenSpruce; +import forestry.arboriculture.worldgen.WorldGenTeak; +import forestry.arboriculture.worldgen.WorldGenWalnut; +import forestry.arboriculture.worldgen.WorldGenWenge; +import forestry.arboriculture.worldgen.WorldGenWillow; +import forestry.arboriculture.worldgen.WorldGenZebrawood; +import forestry.core.config.Constants; +import forestry.core.genetics.alleles.AlleleBoolean; +import forestry.core.genetics.alleles.AlleleHelper; +import forestry.core.genetics.alleles.AllelePlantType; +import forestry.core.genetics.alleles.EnumAllele; +import forestry.plugins.PluginArboriculture; +import java.awt.Color; +import java.util.Arrays; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraft.world.gen.feature.WorldGenerator; +import net.minecraftforge.common.BiomeDictionary; +import net.minecraftforge.common.util.ForgeDirection; + +public enum TreeDefinition implements ITreeDefinition, ITreeGenerator { + Oak( + TreeBranchDefinition.QUERCUS, + "appleOak", + "robur", + false, + EnumLeafType.DECIDUOUS, + new Color(4764952), + new Color(4764952).brighter(), + 0, + new ItemStack(Blocks.log, 1, 0)) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenOak(tree); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitApple); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.POMES); + } + + @Override + protected void registerMutations() { + // vanilla + } + }, + DarkOak( + TreeBranchDefinition.QUERCUS, + "darkOak", + "velutina", + false, + EnumLeafType.DECIDUOUS, + new Color(4764952), + new Color(4764952).brighter(), + 5, + new ItemStack(Blocks.log2, 1, 1)) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenDarkOak(tree); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.POMES); + } + + @Override + protected void registerMutations() { + // vanilla + } + }, + Birch( + TreeBranchDefinition.BETULA, + "silverBirch", + "pendula", + false, + EnumLeafType.DECIDUOUS, + new Color(8431445), + new Color(0xb0c648), + 2, + new ItemStack(Blocks.log, 1, 2)) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenBirch(tree); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) {} + + @Override + protected void registerMutations() { + // vanilla + } + }, + Lime( + TreeBranchDefinition.TILIA, + "silverLime", + "pendula", + true, + EnumLeafType.DECIDUOUS, + new Color(0x5ea107), + new Color(0x5ea107).brighter(), + EnumWoodType.LIME) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenSilverLime(tree); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOWER); + // Allele.helper.set(alleles, EnumTreeChromosome.EFFECT, Allele.leavesBrimstone); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies + .addFruitFamily(EnumFruitFamily.NUX) + .addFruitFamily(EnumFruitFamily.PRUNES) + .addFruitFamily(EnumFruitFamily.POMES); + } + + @Override + protected void registerMutations() { + registerMutation(Birch, Oak, 15); + } + }, + Walnut( + TreeBranchDefinition.JUGLANS, + "commonWalnut", + "regia", + true, + EnumLeafType.DECIDUOUS, + new Color(0x798c55), + new Color(0xb0c648), + EnumWoodType.WALNUT) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenWalnut(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies + .addFruitFamily(EnumFruitFamily.NUX) + .addFruitFamily(EnumFruitFamily.PRUNES) + .addFruitFamily(EnumFruitFamily.POMES); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitWalnut); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.AVERAGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + } + + @Override + protected void registerMutations() { + registerMutation(Lime, Cherry, 10); + } + }, + Chestnut( + TreeBranchDefinition.CASTANEA, + "sweetChestnut", + "sativa", + true, + EnumLeafType.DECIDUOUS, + new Color(0x5ea107), + new Color(0xb0c648), + EnumWoodType.CHESTNUT) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenChestnut(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies + .addFruitFamily(EnumFruitFamily.NUX) + .addFruitFamily(EnumFruitFamily.PRUNES) + .addFruitFamily(EnumFruitFamily.POMES); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitChestnut); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.AVERAGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + } + + @Override + protected void registerMutations() { + registerMutation(Walnut, Lime, 10); + registerMutation(Walnut, Cherry, 10); + } + }, + Cherry( + TreeBranchDefinition.PRUNUS, + "hillCherry", + "serrulata", + true, + EnumLeafType.DECIDUOUS, + new Color(0xe691da), + new Color(0xe63e59), + EnumWoodType.CHERRY) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenCherry(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.PRUNES).addFruitFamily(EnumFruitFamily.POMES); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitCherry); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.AVERAGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALLER); + } + + @Override + protected void registerMutations() { + registerMutation(Lime, Oak, 10); + registerMutation(Lime, Birch, 10); + } + }, + Lemon( + TreeBranchDefinition.CITRUS, + "lemon", + "limon", + true, + EnumLeafType.DECIDUOUS, + new Color(0x88af54), + new Color(0xa3b850), + EnumWoodType.CITRUS) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenLemon(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.PRUNES).addFruitFamily(EnumFruitFamily.POMES); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitLemon); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.AVERAGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALLEST); + } + + @Override + protected void registerMutations() { + registerMutation(Lime, Cherry, 5); + } + }, + Plum( + TreeBranchDefinition.PRUNUS, + "plum", + "domestica", + true, + EnumLeafType.DECIDUOUS, + new Color(0x589246), + new Color(0xa3b850), + EnumWoodType.PLUM) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenPlum(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.PRUNES).addFruitFamily(EnumFruitFamily.POMES); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitPlum); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.HIGH); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.AVERAGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALLEST); + } + + @Override + protected void registerMutations() { + registerMutation(Lemon, Cherry, 5); + } + }, + Maple( + TreeBranchDefinition.ACER, + "sugarMaple", + "saccharum", + true, + EnumLeafType.MAPLE, + new Color(0xd4f425), + new Color(0x619a3c), + EnumWoodType.MAPLE) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenMaple(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.PRUNES).addFruitFamily(EnumFruitFamily.POMES); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + } + + @Override + protected void registerMutations() { + registerMutation(Spruce, Larch, 5); + } + }, + Spruce( + TreeBranchDefinition.PICEA, + "redSpruce", + "abies", + false, + EnumLeafType.CONIFERS, + new Color(6396257), + new Color(0x539d12), + 1, + new ItemStack(Blocks.log, 1, 1)) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenSpruce(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) {} + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); + } + + @Override + protected void registerMutations() { + // vanilla + } + }, + Larch( + TreeBranchDefinition.LARIX, + "mundaneLarch", + "decidua", + true, + EnumLeafType.CONIFERS, + new Color(0x698f90), + new Color(0x569896), + EnumWoodType.LARCH) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenLarch(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) {} + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + } + + @Override + protected void registerMutations() { + registerMutation(Spruce, Birch, 10); + registerMutation(Spruce, Oak, 10); + } + }, + Pine( + TreeBranchDefinition.PINUS, + "bullPine", + "sabiniana", + true, + EnumLeafType.CONIFERS, + new Color(0xfeff8f), + new Color(0xffd98f), + EnumWoodType.PINE) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenPine(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) {} + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + } + + @Override + protected void registerMutations() { + registerMutation(Spruce, Larch, 10); + } + }, + Sequioa( + TreeBranchDefinition.SEQUOIA, + "coastSequoia", + "sempervirens", + false, + EnumLeafType.CONIFERS, + new Color(0x418e71), + new Color(0x569896), + EnumWoodType.SEQUOIA) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenSequoia(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) {} + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGEST); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 3); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FIREPROOF, EnumAllele.Fireproof.TRUE); + } + + @Override + protected void registerMutations() { + registerMutation(Larch, Pine, 5); + } + }, + Gigant( + TreeBranchDefinition.SEQUOIADENDRON, + "giantSequoia", + "giganteum", + false, + EnumLeafType.CONIFERS, + new Color(0x738434), + new Color(0x738434).brighter(), + EnumWoodType.GIGANTEUM) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenGiganteum(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) {} + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.GIGANTIC); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWEST); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWEST); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 4); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FIREPROOF, EnumAllele.Fireproof.TRUE); + } + + @Override + protected void registerMutations() { + registerMutation(Sequioa, Baobab, 1).requireNight().restrictBiomeType(BiomeDictionary.Type.FOREST); + } + }, + Jungle( + TreeBranchDefinition.TROPICAL, + "jungle", + "tectona", + false, + EnumLeafType.JUNGLE, + new Color(4764952), + new Color(0x658917), + 3, + new ItemStack(Blocks.log, 1, 3)) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenJungle(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitCocoa); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FAST); + } + + @Override + protected void registerMutations() { + // vanilla + } + }, + Teak( + TreeBranchDefinition.TECTONA, + "teak", + "grandis", + true, + EnumLeafType.JUNGLE, + new Color(0xfeff8f), + new Color(0xffd98f), + EnumWoodType.TEAK) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenTeak(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + } + + @Override + protected void registerMutations() { + registerMutation(DarkOak, Jungle, 10); + } + }, + Ipe( + TreeBranchDefinition.TABEBUIA, + "ipe", + "serratifolia", + true, + EnumLeafType.JUNGLE, + new Color(0xfdd207), + new Color(0xad8f04), + EnumWoodType.IPE) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenIpe(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + } + + @Override + protected void registerMutations() { + registerMutation(Teak, DarkOak, 10); + } + }, + Kapok( + TreeBranchDefinition.CEIBA, + "kapok", + "pentandra", + true, + EnumLeafType.JUNGLE, + new Color(0x89987b), + new Color(0x89aa9e), + EnumWoodType.KAPOK) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenKapok(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE).addFruitFamily(EnumFruitFamily.PRUNES); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); + } + + @Override + protected void registerMutations() { + registerMutation(Jungle, Teak, 10); + } + }, + Ebony( + TreeBranchDefinition.EBONY, + "myrtleEbony", + "pentamera", + true, + EnumLeafType.JUNGLE, + new Color(0xa2d24a), + new Color(0xc4d24a), + EnumWoodType.EBONY) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenEbony(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE).addFruitFamily(EnumFruitFamily.PRUNES); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 3); + } + + @Override + protected void registerMutations() { + registerMutation(DarkOak, Kapok, 10); + } + }, + Zebrawood( + TreeBranchDefinition.ASTRONIUM, + "zebrawood", + "graveolens", + false, + EnumLeafType.JUNGLE, + new Color(0xa2d24a), + new Color(0xc4d24a), + EnumWoodType.ZEBRAWOOD) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenZebrawood(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.NUX); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + } + + @Override + protected void registerMutations() { + registerMutation(Ebony, Poplar, 5); + } + }, + Mahogony( + TreeBranchDefinition.MAHOGANY, + "yellowMeranti", + "gibbosa", + true, + EnumLeafType.JUNGLE, + new Color(0x8ab154), + new Color(0xa9b154), + EnumWoodType.MAHOGANY) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenMahogany(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + } + + @Override + protected void registerMutations() { + registerMutation(Kapok, Ebony, 10); + } + }, + AcaciaVanilla( + TreeBranchDefinition.ACACIA, + "acacia", + "aneura", + true, + EnumLeafType.DECIDUOUS, + new Color(0x616101), + new Color(0xb3b302), + 4, + new ItemStack(Blocks.log2, 1, 0)) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenAcaciaVanilla(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE).addFruitFamily(EnumFruitFamily.NUX); + } + + @Override + protected void setAlleles(IAllele[] alleles) {} + + @Override + protected void registerMutations() { + // vanilla + } + }, + Acacia( + TreeBranchDefinition.ACACIA, + "desertAcacia", + "erioloba", + true, + EnumLeafType.DECIDUOUS, + new Color(0x748C1C), + new Color(0xb3b302), + EnumWoodType.ACACIA) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenAcacia(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE).addFruitFamily(EnumFruitFamily.NUX); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.PLANT, AllelePlantType.plantTypeDesert); + } + + @Override + protected void registerMutations() { + registerMutation(Teak, Balsa, 10); + } + }, + Padauk( + TreeBranchDefinition.PTEROCARPUS, + "padauk", + "soyauxii", + true, + EnumLeafType.DECIDUOUS, + new Color(0xd0df8c), + new Color(0x435c32), + EnumWoodType.PADAUK) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenPadauk(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + } + + @Override + protected void registerMutations() { + registerMutation(AcaciaVanilla, Jungle, 10); + } + }, + Balsa( + TreeBranchDefinition.OCHROMA, + "balsa", + "pyramidale", + true, + EnumLeafType.DECIDUOUS, + new Color(0x59ac00), + new Color(0xfeff8f), + EnumWoodType.BALSA) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenBalsa(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE).addFruitFamily(EnumFruitFamily.NUX); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.HIGH); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + } + + @Override + protected void registerMutations() { + registerMutation(Teak, AcaciaVanilla, 10); + } + }, + Cocobolo( + TreeBranchDefinition.DALBERGIA, + "cocobolo", + "retusa", + false, + EnumLeafType.DECIDUOUS, + new Color(0x6aa17a), + new Color(0x487d4c), + EnumWoodType.COCOBOLO) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenCocobolo(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGEST); + } + + @Override + protected void registerMutations() { + registerMutation(Acacia, DarkOak, 10); + } + }, + Wenge( + TreeBranchDefinition.MILLETTIA, + "wenge", + "laurentii", + true, + EnumLeafType.DECIDUOUS, + new Color(0xada157), + new Color(0xad8a57), + EnumWoodType.WENGE) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenWenge(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE).addFruitFamily(EnumFruitFamily.NUX); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOWEST); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + } + + @Override + protected void registerMutations() { + registerMutation(Cocobolo, Balsa, 10); + } + }, + Baobab( + TreeBranchDefinition.ADANSONIA, + "grandidierBaobab", + "digitata", + true, + EnumLeafType.DECIDUOUS, + new Color(0xfeff8f), + new Color(0xffd98f), + EnumWoodType.BAOBAB) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenBaobab(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE).addFruitFamily(EnumFruitFamily.NUX); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.PLANT, AllelePlantType.plantTypeDesert); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 3); + } + + @Override + protected void registerMutations() { + registerMutation(Balsa, Wenge, 10); + } + }, + Mahoe( + TreeBranchDefinition.TALIPARITI, + "blueMahoe", + "elatum", + true, + EnumLeafType.DECIDUOUS, + new Color(0xa0ba1b), + new Color(0x79a175), + EnumWoodType.MAHOE) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenMahoe(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies + .addFruitFamily(EnumFruitFamily.JUNGLE) + .addFruitFamily(EnumFruitFamily.POMES) + .addFruitFamily(EnumFruitFamily.PRUNES); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALL); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.HIGH); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWEST); + } + + @Override + protected void registerMutations() { + registerMutation(Balsa, Acacia, 5); + } + }, + Willow( + TreeBranchDefinition.SALIX, + "whiteWillow", + "alba", + true, + EnumLeafType.WILLOW, + new Color(0xa3b8a5), + new Color(0xa3b850), + EnumWoodType.WILLOW) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenWillow(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies + .addFruitFamily(EnumFruitFamily.NUX) + .addFruitFamily(EnumFruitFamily.PRUNES) + .addFruitFamily(EnumFruitFamily.POMES); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); + } + + @Override + protected void registerMutations() { + registerMutation(Oak, Birch, 10) + .restrictTemperature(EnumTemperature.WARM, EnumTemperature.HOT) + .restrictHumidity(EnumHumidity.DAMP); + registerMutation(Oak, Lime, 10) + .restrictTemperature(EnumTemperature.WARM, EnumTemperature.HOT) + .restrictHumidity(EnumHumidity.DAMP); + registerMutation(Lime, Birch, 10) + .restrictTemperature(EnumTemperature.WARM, EnumTemperature.HOT) + .restrictHumidity(EnumHumidity.DAMP); + } + }, + Sipiri( + TreeBranchDefinition.CHLOROCARDIUM, + "sipiri", + "rodiei", + true, + EnumLeafType.DECIDUOUS, + new Color(0x678911), + new Color(0x79a175), + EnumWoodType.GREENHEART) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenGreenheart(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.GROWTH, AlleleGrowth.growthTropical); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); + } + + @Override + protected void registerMutations() { + registerMutation(Kapok, Mahogony, 10) + .restrictTemperature(EnumTemperature.WARM, EnumTemperature.HOT) + .restrictHumidity(EnumHumidity.DAMP); + } + }, + Papaya( + TreeBranchDefinition.CARICA, + "papaya", + "papaya", + true, + EnumLeafType.PALM, + new Color(0x6d9f58), + new Color(0x75E675), + EnumWoodType.PAPAYA) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenPapaya(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE).addFruitFamily(EnumFruitFamily.NUX); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitPapaya); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + } + + @Override + protected void registerMutations() { + registerMutation(Jungle, Cherry, 5); + } + }, + Date( + TreeBranchDefinition.PHOENIX, + "datePalm", + "dactylifera", + true, + EnumLeafType.PALM, + new Color(0xcbcd79), + new Color(0xB3F370), + EnumWoodType.PALM) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenDate(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.JUNGLE).addFruitFamily(EnumFruitFamily.NUX); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitDates); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + } + + @Override + protected void registerMutations() { + registerMutation(Jungle, Papaya, 5); + } + }, + Poplar( + TreeBranchDefinition.POPULUS, + "whitePoplar", + "alba", + true, + EnumLeafType.DECIDUOUS, + new Color(0xa3b8a5), + new Color(0x539d12), + EnumWoodType.POPLAR) { + @Override + public WorldGenerator getWorldGenerator(ITreeGenData tree) { + return new WorldGenPoplar(tree); + } + + @Override + protected void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies) { + treeSpecies.addFruitFamily(EnumFruitFamily.PRUNES).addFruitFamily(EnumFruitFamily.POMES); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALL); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWER); + } + + @Override + protected void registerMutations() { + registerMutation(Birch, Willow, 5); + registerMutation(Oak, Willow, 5); + registerMutation(Lime, Willow, 5); + } + }; + + private final TreeBranchDefinition branch; + private final IAlleleTreeSpeciesCustom species; + + private final EnumWoodType woodType; // for forestry trees + private final ItemStack vanillaWood; // for vanilla trees + + private IAllele[] template; + private ITreeGenome genome; + + // vanilla tree constructor + TreeDefinition( + TreeBranchDefinition branch, + String speciesName, + String binomial, + boolean dominant, + EnumLeafType leafType, + Color primary, + Color secondary, + int vanillaMeta, + ItemStack vanillaWood) { + String uid = "forestry.tree" + this; + String unlocalizedDescription = "for.description.tree" + this; + String unlocalizedName = "for.trees.species." + speciesName; + + this.branch = branch; + + ILeafIconProvider leafIconProvider = TreeManager.treeFactory.getLeafIconProvider(leafType, primary, secondary); + IGermlingIconProvider germlingIconProvider = new IconProviderGermlingVanilla(vanillaMeta); + + this.species = TreeManager.treeFactory.createSpecies( + uid, + unlocalizedName, + "Sengir", + unlocalizedDescription, + dominant, + branch.getBranch(), + binomial, + leafIconProvider, + germlingIconProvider, + this); + this.woodType = null; + this.vanillaWood = vanillaWood; + } + + // forestry tree constructor + TreeDefinition( + TreeBranchDefinition branch, + String speciesName, + String binomial, + boolean dominant, + EnumLeafType leafType, + Color primary, + Color secondary, + EnumWoodType woodType) { + String uid = "forestry.tree" + this; + String unlocalizedDescription = "for.description.tree" + this; + String unlocalizedName = "for.trees.species." + speciesName; + + this.branch = branch; + + ILeafIconProvider leafIconProvider = TreeManager.treeFactory.getLeafIconProvider(leafType, primary, secondary); + IGermlingIconProvider germlingIconProvider = new IconProviderGermling(uid); + + this.species = TreeManager.treeFactory.createSpecies( + uid, + unlocalizedName, + "Sengir", + unlocalizedDescription, + dominant, + branch.getBranch(), + binomial, + leafIconProvider, + germlingIconProvider, + this); + this.woodType = woodType; + this.vanillaWood = null; + } + + protected abstract void setSpeciesProperties(IAlleleTreeSpeciesCustom treeSpecies); + + protected abstract void setAlleles(IAllele[] alleles); + + protected abstract void registerMutations(); + + @Override + public void setLogBlock(ITreeGenome genome, World world, int x, int y, int z, ForgeDirection facing) { + if (woodType == null) { + Block vanillaWoodBlock = Block.getBlockFromItem(vanillaWood.getItem()); + int vanillaWoodMeta = vanillaWood.getItemDamage(); + switch (facing) { + case NORTH: + case SOUTH: + vanillaWoodMeta |= 2 << 2; + break; + case EAST: + case WEST: + vanillaWoodMeta |= 1 << 2; + break; + } + + world.setBlock(x, y, z, vanillaWoodBlock, vanillaWoodMeta, Constants.FLAG_BLOCK_SYNCH); + } else { + AlleleBoolean fireproofAllele = (AlleleBoolean) genome.getActiveAllele(EnumTreeChromosome.FIREPROOF); + boolean fireproof = fireproofAllele.getValue(); + ItemStack log = TreeManager.woodItemAccess.getLog(woodType, fireproof); + + BlockTypeLog logBlock = new BlockTypeLog(log); + logBlock.setDirection(facing); + logBlock.setBlock(world, x, y, z); + } + } + + @Override + public void setLogBlock(World world, int x, int y, int z, ForgeDirection facing) { + setLogBlock(genome, world, x, y, z, facing); + } + + @Override + public void setLeaves(ITreeGenome genome, World world, GameProfile owner, int x, int y, int z, boolean decorative) { + boolean placed = + world.setBlock(x, y, z, PluginArboriculture.blocks.leaves, 0, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); + if (!placed) { + return; + } + + Block block = world.getBlock(x, y, z); + if (PluginArboriculture.blocks.leaves != block) { + world.setBlockToAir(x, y, z); + return; + } + + TileLeaves tileLeaves = BlockForestryLeaves.getLeafTile(world, x, y, z); + if (tileLeaves == null) { + world.setBlockToAir(x, y, z); + return; + } + + tileLeaves.setOwner(owner); + if (decorative) { + tileLeaves.setDecorative(); + } + tileLeaves.setTree(new Tree(genome)); + + world.markBlockForUpdate(x, y, z); + } + + @Override + public void setLeaves(World world, GameProfile owner, int x, int y, int z, boolean decorative) { + setLeaves(genome, world, owner, x, y, z, decorative); + } + + public static void initTrees() { + for (TreeDefinition tree : values()) { + tree.init(); + } + for (TreeDefinition tree : values()) { + tree.registerMutations(); + } + } + + private void init() { + setSpeciesProperties(species); + + template = branch.getTemplate(); + AlleleHelper.instance.set(template, EnumTreeChromosome.SPECIES, species); + setAlleles(template); + + genome = TreeManager.treeRoot.templateAsGenome(template); + + TreeManager.treeRoot.registerTemplate(template); + } + + protected final ITreeMutationCustom registerMutation(TreeDefinition parent1, TreeDefinition parent2, int chance) { + return TreeManager.treeMutationFactory.createMutation(parent1.species, parent2.species, getTemplate(), chance); + } + + @Override + public final IAllele[] getTemplate() { + return Arrays.copyOf(template, template.length); + } + + public final String getUID() { + return species.getUID(); + } + + @Override + public final ITreeGenome getGenome() { + return genome; + } + + @Override + public final ITree getIndividual() { + return new Tree(genome); + } + + @Override + public final ItemStack getMemberStack(EnumGermlingType treeType) { + ITree tree = getIndividual(); + return TreeManager.treeRoot.getMemberStack(tree, treeType.ordinal()); + } +} diff --git a/src/main/java/forestry/arboriculture/genetics/TreeFactory.java b/src/main/java/forestry/arboriculture/genetics/TreeFactory.java index ad1cdba10..4a97e5ef7 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeFactory.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeFactory.java @@ -1,39 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.genetics; - -import java.awt.Color; - -import forestry.api.arboriculture.EnumLeafType; -import forestry.api.arboriculture.EnumTreeChromosome; -import forestry.api.arboriculture.IAlleleTreeSpeciesCustom; -import forestry.api.arboriculture.IGermlingIconProvider; -import forestry.api.arboriculture.ILeafIconProvider; -import forestry.api.arboriculture.ITreeFactory; -import forestry.api.arboriculture.ITreeGenerator; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IClassification; -import forestry.arboriculture.genetics.alleles.AlleleTreeSpecies; -import forestry.arboriculture.render.IconProviderLeaves; - -public class TreeFactory implements ITreeFactory { - @Override - public IAlleleTreeSpeciesCustom createSpecies(String uid, String unlocalizedName, String authority, String unlocalizedDescription, boolean dominant, IClassification branch, String binomial, ILeafIconProvider leafIconProvider, IGermlingIconProvider germlingIconProvider, ITreeGenerator generator) { - IAlleleTreeSpeciesCustom treeSpecies = new AlleleTreeSpecies(uid, unlocalizedName, authority, unlocalizedDescription, dominant, branch, binomial, leafIconProvider, germlingIconProvider, generator); - AlleleManager.alleleRegistry.registerAllele(treeSpecies, EnumTreeChromosome.SPECIES); - return treeSpecies; - } - - @Override - public ILeafIconProvider getLeafIconProvider(EnumLeafType enumLeafType, Color color, Color colorPollinated) { - return new IconProviderLeaves(enumLeafType, color, colorPollinated); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.genetics; + +import forestry.api.arboriculture.EnumLeafType; +import forestry.api.arboriculture.EnumTreeChromosome; +import forestry.api.arboriculture.IAlleleTreeSpeciesCustom; +import forestry.api.arboriculture.IGermlingIconProvider; +import forestry.api.arboriculture.ILeafIconProvider; +import forestry.api.arboriculture.ITreeFactory; +import forestry.api.arboriculture.ITreeGenerator; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IClassification; +import forestry.arboriculture.genetics.alleles.AlleleTreeSpecies; +import forestry.arboriculture.render.IconProviderLeaves; +import java.awt.Color; + +public class TreeFactory implements ITreeFactory { + @Override + public IAlleleTreeSpeciesCustom createSpecies( + String uid, + String unlocalizedName, + String authority, + String unlocalizedDescription, + boolean dominant, + IClassification branch, + String binomial, + ILeafIconProvider leafIconProvider, + IGermlingIconProvider germlingIconProvider, + ITreeGenerator generator) { + IAlleleTreeSpeciesCustom treeSpecies = new AlleleTreeSpecies( + uid, + unlocalizedName, + authority, + unlocalizedDescription, + dominant, + branch, + binomial, + leafIconProvider, + germlingIconProvider, + generator); + AlleleManager.alleleRegistry.registerAllele(treeSpecies, EnumTreeChromosome.SPECIES); + return treeSpecies; + } + + @Override + public ILeafIconProvider getLeafIconProvider(EnumLeafType enumLeafType, Color color, Color colorPollinated) { + return new IconProviderLeaves(enumLeafType, color, colorPollinated); + } +} diff --git a/src/main/java/forestry/arboriculture/genetics/TreeGenome.java b/src/main/java/forestry/arboriculture/genetics/TreeGenome.java index 6743839c5..05c48ff63 100755 --- a/src/main/java/forestry/arboriculture/genetics/TreeGenome.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeGenome.java @@ -10,13 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import java.util.EnumSet; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.EnumPlantType; - import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleFruit; import forestry.api.arboriculture.IAlleleGrowth; @@ -33,94 +26,97 @@ import forestry.api.genetics.IChromosome; import forestry.api.genetics.ISpeciesRoot; import forestry.core.genetics.Genome; import forestry.core.genetics.alleles.AllelePlantType; +import java.util.EnumSet; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.EnumPlantType; public class TreeGenome extends Genome implements ITreeGenome { - public TreeGenome(IChromosome[] chromosomes) { - super(chromosomes); - } + public TreeGenome(IChromosome[] chromosomes) { + super(chromosomes); + } - public TreeGenome(NBTTagCompound nbttagcompound) { - super(nbttagcompound); - } + public TreeGenome(NBTTagCompound nbttagcompound) { + super(nbttagcompound); + } - // NBT RETRIEVAL - public static IAlleleTreeSpecies getSpecies(ItemStack itemStack) { - if (!TreeManager.treeRoot.isMember(itemStack)) { - return null; - } + // NBT RETRIEVAL + public static IAlleleTreeSpecies getSpecies(ItemStack itemStack) { + if (!TreeManager.treeRoot.isMember(itemStack)) { + return null; + } - IAlleleSpecies species = getSpeciesDirectly(itemStack); - if (species instanceof IAlleleTreeSpecies) { - return (IAlleleTreeSpecies) species; - } + IAlleleSpecies species = getSpeciesDirectly(itemStack); + if (species instanceof IAlleleTreeSpecies) { + return (IAlleleTreeSpecies) species; + } - return (IAlleleTreeSpecies) getActiveAllele(itemStack, EnumTreeChromosome.SPECIES, TreeManager.treeRoot); - } + return (IAlleleTreeSpecies) getActiveAllele(itemStack, EnumTreeChromosome.SPECIES, TreeManager.treeRoot); + } - @Override - public IAlleleTreeSpecies getPrimary() { - return (IAlleleTreeSpecies) getActiveAllele(EnumTreeChromosome.SPECIES); - } + @Override + public IAlleleTreeSpecies getPrimary() { + return (IAlleleTreeSpecies) getActiveAllele(EnumTreeChromosome.SPECIES); + } - @Override - public IAlleleTreeSpecies getSecondary() { - return (IAlleleTreeSpecies) getInactiveAllele(EnumTreeChromosome.SPECIES); - } + @Override + public IAlleleTreeSpecies getSecondary() { + return (IAlleleTreeSpecies) getInactiveAllele(EnumTreeChromosome.SPECIES); + } - @Override - public IFruitProvider getFruitProvider() { - return ((IAlleleFruit) getActiveAllele(EnumTreeChromosome.FRUITS)).getProvider(); - } + @Override + public IFruitProvider getFruitProvider() { + return ((IAlleleFruit) getActiveAllele(EnumTreeChromosome.FRUITS)).getProvider(); + } - @Override - public IGrowthProvider getGrowthProvider() { - return ((IAlleleGrowth) getActiveAllele(EnumTreeChromosome.GROWTH)).getProvider(); - } + @Override + public IGrowthProvider getGrowthProvider() { + return ((IAlleleGrowth) getActiveAllele(EnumTreeChromosome.GROWTH)).getProvider(); + } - @Override - public float getHeight() { - return ((IAlleleFloat) getActiveAllele(EnumTreeChromosome.HEIGHT)).getValue(); - } + @Override + public float getHeight() { + return ((IAlleleFloat) getActiveAllele(EnumTreeChromosome.HEIGHT)).getValue(); + } - @Override - public float getFertility() { - return ((IAlleleFloat) getActiveAllele(EnumTreeChromosome.FERTILITY)).getValue(); - } + @Override + public float getFertility() { + return ((IAlleleFloat) getActiveAllele(EnumTreeChromosome.FERTILITY)).getValue(); + } - @Override - public float getYield() { - return ((IAlleleFloat) getActiveAllele(EnumTreeChromosome.YIELD)).getValue(); - } + @Override + public float getYield() { + return ((IAlleleFloat) getActiveAllele(EnumTreeChromosome.YIELD)).getValue(); + } - @Override - public float getSappiness() { - return ((IAlleleFloat) getActiveAllele(EnumTreeChromosome.SAPPINESS)).getValue(); - } + @Override + public float getSappiness() { + return ((IAlleleFloat) getActiveAllele(EnumTreeChromosome.SAPPINESS)).getValue(); + } - @Override - public EnumSet getPlantTypes() { - return ((AllelePlantType) getActiveAllele(EnumTreeChromosome.PLANT)).getPlantTypes(); - } + @Override + public EnumSet getPlantTypes() { + return ((AllelePlantType) getActiveAllele(EnumTreeChromosome.PLANT)).getPlantTypes(); + } - @Override - public int getMaturationTime() { - return ((IAlleleInteger) getActiveAllele(EnumTreeChromosome.MATURATION)).getValue(); - } + @Override + public int getMaturationTime() { + return ((IAlleleInteger) getActiveAllele(EnumTreeChromosome.MATURATION)).getValue(); + } - @Override - public int getGirth() { - return ((IAlleleInteger) getActiveAllele(EnumTreeChromosome.GIRTH)).getValue(); - } - - @Override - public IAlleleLeafEffect getEffect() { - return (IAlleleLeafEffect) getActiveAllele(EnumTreeChromosome.EFFECT); - } + @Override + public int getGirth() { + return ((IAlleleInteger) getActiveAllele(EnumTreeChromosome.GIRTH)).getValue(); + } - @Override - public ISpeciesRoot getSpeciesRoot() { - return TreeManager.treeRoot; - } + @Override + public IAlleleLeafEffect getEffect() { + return (IAlleleLeafEffect) getActiveAllele(EnumTreeChromosome.EFFECT); + } + @Override + public ISpeciesRoot getSpeciesRoot() { + return TreeManager.treeRoot; + } } diff --git a/src/main/java/forestry/arboriculture/genetics/TreeHelper.java b/src/main/java/forestry/arboriculture/genetics/TreeHelper.java index e65af385b..de7083a83 100755 --- a/src/main/java/forestry/arboriculture/genetics/TreeHelper.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeHelper.java @@ -10,28 +10,8 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map.Entry; - -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - -import net.minecraftforge.oredict.OreDictionary; - import cpw.mods.fml.common.FMLCommonHandler; - import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleFruit; @@ -56,346 +36,365 @@ import forestry.core.config.Constants; import forestry.core.genetics.SpeciesRoot; import forestry.core.utils.BlockUtil; import forestry.plugins.PluginArboriculture; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Map.Entry; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.oredict.OreDictionary; public class TreeHelper extends SpeciesRoot implements ITreeRoot { - public static final String UID = "rootTrees"; - private static int treeSpeciesCount = -1; - private static ITreekeepingMode activeTreekeepingMode; - public static final ArrayList treeTemplates = new ArrayList<>(); - - private final ArrayList treekeepingModes = new ArrayList<>(); - - public TreeHelper() { - setResearchSuitability(new ItemStack(Blocks.sapling, 1, OreDictionary.WILDCARD_VALUE), 1.0f); - } - - @Override - public String getUID() { - return UID; - } - - @Override - public Class getMemberClass() { - return ITree.class; - } - - @Override - public int getSpeciesCount() { - if (treeSpeciesCount < 0) { - treeSpeciesCount = 0; - for (Entry entry : AlleleManager.alleleRegistry.getRegisteredAlleles().entrySet()) { - if (entry.getValue() instanceof IAlleleTreeSpecies) { - if (((IAlleleTreeSpecies) entry.getValue()).isCounted()) { - treeSpeciesCount++; - } - } - } - } - - return treeSpeciesCount; - } - - @Override - public boolean isMember(ItemStack itemstack) { - return getType(itemstack) != EnumGermlingType.NONE; - } - - @Override - public boolean isMember(ItemStack stack, int type) { - return getType(stack).ordinal() == type; - } - - @Override - public boolean isMember(IIndividual individual) { - return individual instanceof ITree; - } - - /* TREE SPECIFIC */ - @Override - public EnumGermlingType getType(ItemStack stack) { - if (stack == null) { - return EnumGermlingType.NONE; - } - - Item item = stack.getItem(); - - if (PluginArboriculture.items.sapling == item) { - return EnumGermlingType.SAPLING; - } else if (PluginArboriculture.items.pollenFertile == item) { - return EnumGermlingType.POLLEN; - } - - return EnumGermlingType.NONE; - } - - @Override - public ITree getTree(World world, int x, int y, int z) { - TileEntity tile = world.getTileEntity(x, y, z); - if (!(tile instanceof TileSapling)) { - return null; - } - - return ((TileSapling) tile).getTree(); - } - - @Override - public ITree getMember(ItemStack itemstack) { - if (!isMember(itemstack)) { - return null; - } - if (itemstack.getTagCompound() == null) { - return null; - } - - return new Tree(itemstack.getTagCompound()); - } - - @Override - public ITree getMember(NBTTagCompound compound) { - return new Tree(compound); - } - - @Override - public ITree getTree(World world, ITreeGenome genome) { - return new Tree(genome); - } - - @Override - public ItemStack getMemberStack(IIndividual tree, int type) { - if (!isMember(tree)) { - return null; - } - - Item germlingItem; - switch (EnumGermlingType.VALUES[type]) { - case SAPLING: - germlingItem = PluginArboriculture.items.sapling; - break; - case POLLEN: - germlingItem = PluginArboriculture.items.pollenFertile; - break; - default: - throw new RuntimeException("Cannot instantiate a tree of type " + type); - } - - NBTTagCompound nbttagcompound = new NBTTagCompound(); - tree.writeToNBT(nbttagcompound); - - ItemStack treeStack = new ItemStack(germlingItem); - treeStack.setTagCompound(nbttagcompound); - - return treeStack; - - } - - @Override - public boolean plantSapling(World world, ITree tree, GameProfile owner, int x, int y, int z) { - - boolean placed = world.setBlock(x, y, z, PluginArboriculture.blocks.saplingGE, 0, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); - if (!placed) { - return false; - } - - Block block = world.getBlock(x, y, z); - if (PluginArboriculture.blocks.saplingGE != block) { - return false; - } - - TileEntity tile = world.getTileEntity(x, y, z); - if (!(tile instanceof TileSapling)) { - world.setBlockToAir(x, y, z); - return false; - } - - TileSapling sapling = (TileSapling) tile; - sapling.setTree(tree.copy()); - sapling.setOwner(owner); - - return true; - } - - @Override - public boolean setFruitBlock(World world, IAlleleFruit allele, float sappiness, short[] indices, int x, int y, int z) { - - int direction = BlockUtil.getDirectionalMetadata(world, x, y, z); - if (direction < 0) { - return false; - } - - boolean placed = world.setBlock(x, y, z, PluginArboriculture.blocks.pods, direction, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); - if (!placed) { - return false; - } - - Block block = world.getBlock(x, y, z); - if (PluginArboriculture.blocks.pods != block) { - return false; - } - - TileFruitPod pod = BlockFruitPod.getPodTile(world, x, y, z); - if (pod == null) { - world.setBlockToAir(x, y, z); - return false; - } - pod.setFruit(allele, sappiness, indices); - world.markBlockForUpdate(x, y, z); - return true; - } - - /* GENOME CONVERSIONS */ - @Override - public ITreeGenome templateAsGenome(IAllele[] template) { - return new TreeGenome(templateAsChromosomes(template)); - } - - @Override - public ITreeGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive) { - return new TreeGenome(templateAsChromosomes(templateActive, templateInactive)); - } - - @Override - public ITree templateAsIndividual(IAllele[] template) { - return new Tree(templateAsGenome(template)); - } - - @Override - public ITree templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive) { - return new Tree(templateAsGenome(templateActive, templateInactive)); - } - - /* BREEDING TRACKER */ - @Override - public IArboristTracker getBreedingTracker(World world, GameProfile player) { - String filename = "ArboristTracker." + (player == null ? "common" : player.getId()); - ArboristTracker tracker = (ArboristTracker) world.loadItemData(ArboristTracker.class, filename); - - // Create a tracker if there is none yet. - if (tracker == null) { - tracker = new ArboristTracker(filename); - world.setItemData(filename, tracker); - } - - tracker.setUsername(player); - tracker.setWorld(world); - - return tracker; - } - - /* BREEDING MODES */ - - @Override - public ArrayList getTreekeepingModes() { - return this.treekeepingModes; - } - - @Override - public ITreekeepingMode getTreekeepingMode(World world) { - if (activeTreekeepingMode != null) { - return activeTreekeepingMode; - } - - // No Treekeeping mode yet, item it. - IArboristTracker tracker = getBreedingTracker(world, null); - String mode = tracker.getModeName(); - if (mode == null || mode.isEmpty()) { - mode = PluginArboriculture.treekeepingMode; - } - - setTreekeepingMode(world, mode); - FMLCommonHandler.instance().getFMLLogger().debug("Set Treekeeping mode for a world to " + mode); - - return activeTreekeepingMode; - } - - @Override - public void registerTreekeepingMode(ITreekeepingMode mode) { - treekeepingModes.add(mode); - } - - @Override - public void setTreekeepingMode(World world, String name) { - activeTreekeepingMode = getTreekeepingMode(name); - getBreedingTracker(world, null).setModeName(name); - } - - @Override - public ITreekeepingMode getTreekeepingMode(String name) { - for (ITreekeepingMode mode : treekeepingModes) { - if (mode.getName().equals(name) || mode.getName().equals(name.toLowerCase(Locale.ENGLISH))) { - return mode; - } - } - - FMLCommonHandler.instance().getFMLLogger().debug("Failed to find a Treekeeping mode called '%s', reverting to fallback."); - return treekeepingModes.get(0); - } - - /* TEMPLATES */ - - @Override - public ArrayList getIndividualTemplates() { - return treeTemplates; - } - - @Override - public void registerTemplate(String identifier, IAllele[] template) { - treeTemplates.add(new Tree(TreeManager.treeRoot.templateAsGenome(template))); - speciesTemplates.put(identifier, template); - } - - @Override - public IAllele[] getDefaultTemplate() { - return TreeDefinition.Oak.getTemplate(); - } - - /* MUTATIONS */ - private static final List treeMutations = new ArrayList<>(); - - @Override - public List getMutations(boolean shuffle) { - if (shuffle) { - Collections.shuffle(treeMutations); - } - return treeMutations; - } - - @Override - public void registerMutation(IMutation mutation) { - if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getTemplate()[0].getUID())) { - return; - } - if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getAllele0().getUID())) { - return; - } - if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getAllele1().getUID())) { - return; - } - - treeMutations.add((ITreeMutation) mutation); - } - - /* ILEAFTICKHANDLER */ - private final LinkedList leafTickHandlers = new LinkedList<>(); - - @Override - public void registerLeafTickHandler(ILeafTickHandler handler) { - leafTickHandlers.add(handler); - } - - @Override - public Collection getLeafTickHandlers() { - return leafTickHandlers; - } - - @Override - public IChromosomeType[] getKaryotype() { - return EnumTreeChromosome.values(); - } - - @Override - public IChromosomeType getKaryotypeKey() { - return EnumTreeChromosome.SPECIES; - } - + public static final String UID = "rootTrees"; + private static int treeSpeciesCount = -1; + private static ITreekeepingMode activeTreekeepingMode; + public static final ArrayList treeTemplates = new ArrayList<>(); + + private final ArrayList treekeepingModes = new ArrayList<>(); + + public TreeHelper() { + setResearchSuitability(new ItemStack(Blocks.sapling, 1, OreDictionary.WILDCARD_VALUE), 1.0f); + } + + @Override + public String getUID() { + return UID; + } + + @Override + public Class getMemberClass() { + return ITree.class; + } + + @Override + public int getSpeciesCount() { + if (treeSpeciesCount < 0) { + treeSpeciesCount = 0; + for (Entry entry : + AlleleManager.alleleRegistry.getRegisteredAlleles().entrySet()) { + if (entry.getValue() instanceof IAlleleTreeSpecies) { + if (((IAlleleTreeSpecies) entry.getValue()).isCounted()) { + treeSpeciesCount++; + } + } + } + } + + return treeSpeciesCount; + } + + @Override + public boolean isMember(ItemStack itemstack) { + return getType(itemstack) != EnumGermlingType.NONE; + } + + @Override + public boolean isMember(ItemStack stack, int type) { + return getType(stack).ordinal() == type; + } + + @Override + public boolean isMember(IIndividual individual) { + return individual instanceof ITree; + } + + /* TREE SPECIFIC */ + @Override + public EnumGermlingType getType(ItemStack stack) { + if (stack == null) { + return EnumGermlingType.NONE; + } + + Item item = stack.getItem(); + + if (PluginArboriculture.items.sapling == item) { + return EnumGermlingType.SAPLING; + } else if (PluginArboriculture.items.pollenFertile == item) { + return EnumGermlingType.POLLEN; + } + + return EnumGermlingType.NONE; + } + + @Override + public ITree getTree(World world, int x, int y, int z) { + TileEntity tile = world.getTileEntity(x, y, z); + if (!(tile instanceof TileSapling)) { + return null; + } + + return ((TileSapling) tile).getTree(); + } + + @Override + public ITree getMember(ItemStack itemstack) { + if (!isMember(itemstack)) { + return null; + } + if (itemstack.getTagCompound() == null) { + return null; + } + + return new Tree(itemstack.getTagCompound()); + } + + @Override + public ITree getMember(NBTTagCompound compound) { + return new Tree(compound); + } + + @Override + public ITree getTree(World world, ITreeGenome genome) { + return new Tree(genome); + } + + @Override + public ItemStack getMemberStack(IIndividual tree, int type) { + if (!isMember(tree)) { + return null; + } + + Item germlingItem; + switch (EnumGermlingType.VALUES[type]) { + case SAPLING: + germlingItem = PluginArboriculture.items.sapling; + break; + case POLLEN: + germlingItem = PluginArboriculture.items.pollenFertile; + break; + default: + throw new RuntimeException("Cannot instantiate a tree of type " + type); + } + + NBTTagCompound nbttagcompound = new NBTTagCompound(); + tree.writeToNBT(nbttagcompound); + + ItemStack treeStack = new ItemStack(germlingItem); + treeStack.setTagCompound(nbttagcompound); + + return treeStack; + } + + @Override + public boolean plantSapling(World world, ITree tree, GameProfile owner, int x, int y, int z) { + + boolean placed = + world.setBlock(x, y, z, PluginArboriculture.blocks.saplingGE, 0, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); + if (!placed) { + return false; + } + + Block block = world.getBlock(x, y, z); + if (PluginArboriculture.blocks.saplingGE != block) { + return false; + } + + TileEntity tile = world.getTileEntity(x, y, z); + if (!(tile instanceof TileSapling)) { + world.setBlockToAir(x, y, z); + return false; + } + + TileSapling sapling = (TileSapling) tile; + sapling.setTree(tree.copy()); + sapling.setOwner(owner); + + return true; + } + + @Override + public boolean setFruitBlock( + World world, IAlleleFruit allele, float sappiness, short[] indices, int x, int y, int z) { + + int direction = BlockUtil.getDirectionalMetadata(world, x, y, z); + if (direction < 0) { + return false; + } + + boolean placed = world.setBlock( + x, y, z, PluginArboriculture.blocks.pods, direction, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); + if (!placed) { + return false; + } + + Block block = world.getBlock(x, y, z); + if (PluginArboriculture.blocks.pods != block) { + return false; + } + + TileFruitPod pod = BlockFruitPod.getPodTile(world, x, y, z); + if (pod == null) { + world.setBlockToAir(x, y, z); + return false; + } + pod.setFruit(allele, sappiness, indices); + world.markBlockForUpdate(x, y, z); + return true; + } + + /* GENOME CONVERSIONS */ + @Override + public ITreeGenome templateAsGenome(IAllele[] template) { + return new TreeGenome(templateAsChromosomes(template)); + } + + @Override + public ITreeGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive) { + return new TreeGenome(templateAsChromosomes(templateActive, templateInactive)); + } + + @Override + public ITree templateAsIndividual(IAllele[] template) { + return new Tree(templateAsGenome(template)); + } + + @Override + public ITree templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive) { + return new Tree(templateAsGenome(templateActive, templateInactive)); + } + + /* BREEDING TRACKER */ + @Override + public IArboristTracker getBreedingTracker(World world, GameProfile player) { + String filename = "ArboristTracker." + (player == null ? "common" : player.getId()); + ArboristTracker tracker = (ArboristTracker) world.loadItemData(ArboristTracker.class, filename); + + // Create a tracker if there is none yet. + if (tracker == null) { + tracker = new ArboristTracker(filename); + world.setItemData(filename, tracker); + } + + tracker.setUsername(player); + tracker.setWorld(world); + + return tracker; + } + + /* BREEDING MODES */ + + @Override + public ArrayList getTreekeepingModes() { + return this.treekeepingModes; + } + + @Override + public ITreekeepingMode getTreekeepingMode(World world) { + if (activeTreekeepingMode != null) { + return activeTreekeepingMode; + } + + // No Treekeeping mode yet, item it. + IArboristTracker tracker = getBreedingTracker(world, null); + String mode = tracker.getModeName(); + if (mode == null || mode.isEmpty()) { + mode = PluginArboriculture.treekeepingMode; + } + + setTreekeepingMode(world, mode); + FMLCommonHandler.instance().getFMLLogger().debug("Set Treekeeping mode for a world to " + mode); + + return activeTreekeepingMode; + } + + @Override + public void registerTreekeepingMode(ITreekeepingMode mode) { + treekeepingModes.add(mode); + } + + @Override + public void setTreekeepingMode(World world, String name) { + activeTreekeepingMode = getTreekeepingMode(name); + getBreedingTracker(world, null).setModeName(name); + } + + @Override + public ITreekeepingMode getTreekeepingMode(String name) { + for (ITreekeepingMode mode : treekeepingModes) { + if (mode.getName().equals(name) || mode.getName().equals(name.toLowerCase(Locale.ENGLISH))) { + return mode; + } + } + + FMLCommonHandler.instance() + .getFMLLogger() + .debug("Failed to find a Treekeeping mode called '%s', reverting to fallback."); + return treekeepingModes.get(0); + } + + /* TEMPLATES */ + + @Override + public ArrayList getIndividualTemplates() { + return treeTemplates; + } + + @Override + public void registerTemplate(String identifier, IAllele[] template) { + treeTemplates.add(new Tree(TreeManager.treeRoot.templateAsGenome(template))); + speciesTemplates.put(identifier, template); + } + + @Override + public IAllele[] getDefaultTemplate() { + return TreeDefinition.Oak.getTemplate(); + } + + /* MUTATIONS */ + private static final List treeMutations = new ArrayList<>(); + + @Override + public List getMutations(boolean shuffle) { + if (shuffle) { + Collections.shuffle(treeMutations); + } + return treeMutations; + } + + @Override + public void registerMutation(IMutation mutation) { + if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getTemplate()[0].getUID())) { + return; + } + if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getAllele0().getUID())) { + return; + } + if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getAllele1().getUID())) { + return; + } + + treeMutations.add((ITreeMutation) mutation); + } + + /* ILEAFTICKHANDLER */ + private final LinkedList leafTickHandlers = new LinkedList<>(); + + @Override + public void registerLeafTickHandler(ILeafTickHandler handler) { + leafTickHandlers.add(handler); + } + + @Override + public Collection getLeafTickHandlers() { + return leafTickHandlers; + } + + @Override + public IChromosomeType[] getKaryotype() { + return EnumTreeChromosome.values(); + } + + @Override + public IChromosomeType getKaryotypeKey() { + return EnumTreeChromosome.SPECIES; + } } diff --git a/src/main/java/forestry/arboriculture/genetics/TreeMutation.java b/src/main/java/forestry/arboriculture/genetics/TreeMutation.java index 8889afabc..d7fee7e1d 100755 --- a/src/main/java/forestry/arboriculture/genetics/TreeMutation.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeMutation.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import net.minecraft.world.World; - import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.arboriculture.ITreeGenome; import forestry.api.arboriculture.ITreeMutationCustom; @@ -20,28 +18,45 @@ import forestry.api.arboriculture.TreeManager; import forestry.api.core.ForestryAPI; import forestry.api.genetics.IAllele; import forestry.core.genetics.mutations.Mutation; +import net.minecraft.world.World; public class TreeMutation extends Mutation implements ITreeMutationCustom { - public TreeMutation(IAlleleTreeSpecies allele0, IAlleleTreeSpecies allele1, IAllele[] template, int chance) { - super(allele0, allele1, template, chance); - } + public TreeMutation(IAlleleTreeSpecies allele0, IAlleleTreeSpecies allele1, IAllele[] template, int chance) { + super(allele0, allele1, template, chance); + } - @Override - public ITreeRoot getRoot() { - return TreeManager.treeRoot; - } + @Override + public ITreeRoot getRoot() { + return TreeManager.treeRoot; + } - @Override - public float getChance(World world, int x, int y, int z, IAlleleTreeSpecies allele0, IAlleleTreeSpecies allele1, ITreeGenome genome0, ITreeGenome genome1) { - float processedChance = super.getChance(world, x, y, z, allele0, allele1, genome0, genome1, ForestryAPI.climateManager.getDefaultClimate(world, x, y, z)); - if (processedChance <= 0) { - return 0; - } + @Override + public float getChance( + World world, + int x, + int y, + int z, + IAlleleTreeSpecies allele0, + IAlleleTreeSpecies allele1, + ITreeGenome genome0, + ITreeGenome genome1) { + float processedChance = super.getChance( + world, + x, + y, + z, + allele0, + allele1, + genome0, + genome1, + ForestryAPI.climateManager.getDefaultClimate(world, x, y, z)); + if (processedChance <= 0) { + return 0; + } - processedChance *= getRoot().getTreekeepingMode(world).getMutationModifier(genome0, genome1, 1f); - - return processedChance; - } + processedChance *= getRoot().getTreekeepingMode(world).getMutationModifier(genome0, genome1, 1f); + return processedChance; + } } diff --git a/src/main/java/forestry/arboriculture/genetics/TreeMutationFactory.java b/src/main/java/forestry/arboriculture/genetics/TreeMutationFactory.java index 23af72f92..dd58d0966 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeMutationFactory.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeMutationFactory.java @@ -1,27 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.genetics; - -import forestry.api.arboriculture.IAlleleTreeSpecies; -import forestry.api.arboriculture.ITreeMutationCustom; -import forestry.api.arboriculture.ITreeMutationFactory; -import forestry.api.arboriculture.TreeManager; -import forestry.api.genetics.IAllele; - -public class TreeMutationFactory implements ITreeMutationFactory { - - @Override - public ITreeMutationCustom createMutation(IAlleleTreeSpecies parent0, IAlleleTreeSpecies parent1, IAllele[] result, int chance) { - ITreeMutationCustom mutation = new TreeMutation(parent0, parent1, result, chance); - TreeManager.treeRoot.registerMutation(mutation); - return mutation; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.genetics; + +import forestry.api.arboriculture.IAlleleTreeSpecies; +import forestry.api.arboriculture.ITreeMutationCustom; +import forestry.api.arboriculture.ITreeMutationFactory; +import forestry.api.arboriculture.TreeManager; +import forestry.api.genetics.IAllele; + +public class TreeMutationFactory implements ITreeMutationFactory { + + @Override + public ITreeMutationCustom createMutation( + IAlleleTreeSpecies parent0, IAlleleTreeSpecies parent1, IAllele[] result, int chance) { + ITreeMutationCustom mutation = new TreeMutation(parent0, parent1, result, chance); + TreeManager.treeRoot.registerMutation(mutation); + return mutation; + } +} diff --git a/src/main/java/forestry/arboriculture/genetics/TreekeepingMode.java b/src/main/java/forestry/arboriculture/genetics/TreekeepingMode.java index 39c955156..9fa66024f 100755 --- a/src/main/java/forestry/arboriculture/genetics/TreekeepingMode.java +++ b/src/main/java/forestry/arboriculture/genetics/TreekeepingMode.java @@ -10,68 +10,72 @@ ******************************************************************************/ package forestry.arboriculture.genetics; +import forestry.api.arboriculture.ITreeGenome; +import forestry.api.arboriculture.ITreekeepingMode; import java.util.ArrayList; import java.util.Locale; -import forestry.api.arboriculture.ITreeGenome; -import forestry.api.arboriculture.ITreekeepingMode; - public class TreekeepingMode implements ITreekeepingMode { - public static final ITreekeepingMode easy = new TreekeepingMode("EASY", 1.4f, 1.3f, 1.2f, 1.2f); - public static final ITreekeepingMode normal = new TreekeepingMode("NORMAL", 1f, 1f, 1f, 1f); - public static final ITreekeepingMode hard = new TreekeepingMode("HARD", 0.9f, 0.9f, 0.9f, 0.9f); - public static final ITreekeepingMode hardcore = new TreekeepingMode("HARDCORE", 0.7f, 0.7f, 0.5f, 0.5f); - public static final ITreekeepingMode insane = new TreekeepingMode("INSANE", 0.5f, 0.5f, 0.2f, 0.1f); + public static final ITreekeepingMode easy = new TreekeepingMode("EASY", 1.4f, 1.3f, 1.2f, 1.2f); + public static final ITreekeepingMode normal = new TreekeepingMode("NORMAL", 1f, 1f, 1f, 1f); + public static final ITreekeepingMode hard = new TreekeepingMode("HARD", 0.9f, 0.9f, 0.9f, 0.9f); + public static final ITreekeepingMode hardcore = new TreekeepingMode("HARDCORE", 0.7f, 0.7f, 0.5f, 0.5f); + public static final ITreekeepingMode insane = new TreekeepingMode("INSANE", 0.5f, 0.5f, 0.2f, 0.1f); - private final String name; - private final float yieldModifier; - private final float sappinessModifier; - private final float maturationModifier; - private final float mutationModifier; + private final String name; + private final float yieldModifier; + private final float sappinessModifier; + private final float maturationModifier; + private final float mutationModifier; - public TreekeepingMode(String name, float yieldModifier, float sappinessModifier, float maturationModifier, float mutationModifier) { - this.name = name; - this.yieldModifier = yieldModifier; - this.sappinessModifier = sappinessModifier; - this.maturationModifier = maturationModifier; - this.mutationModifier = mutationModifier; - } + public TreekeepingMode( + String name, + float yieldModifier, + float sappinessModifier, + float maturationModifier, + float mutationModifier) { + this.name = name; + this.yieldModifier = yieldModifier; + this.sappinessModifier = sappinessModifier; + this.maturationModifier = maturationModifier; + this.mutationModifier = mutationModifier; + } - @Override - public String getName() { - return this.name; - } + @Override + public String getName() { + return this.name; + } - @Override - public ArrayList getDescription() { - ArrayList ret = new ArrayList<>(); - ret.add("treemode." + name.toLowerCase(Locale.ENGLISH) + ".desc"); - return ret; - } + @Override + public ArrayList getDescription() { + ArrayList ret = new ArrayList<>(); + ret.add("treemode." + name.toLowerCase(Locale.ENGLISH) + ".desc"); + return ret; + } - @Override - public float getHeightModifier(ITreeGenome genome, float currentModifier) { - return 1f; - } + @Override + public float getHeightModifier(ITreeGenome genome, float currentModifier) { + return 1f; + } - @Override - public float getYieldModifier(ITreeGenome genome, float currentModifier) { - return yieldModifier; - } + @Override + public float getYieldModifier(ITreeGenome genome, float currentModifier) { + return yieldModifier; + } - @Override - public float getSappinessModifier(ITreeGenome genome, float currentModifier) { - return sappinessModifier; - } + @Override + public float getSappinessModifier(ITreeGenome genome, float currentModifier) { + return sappinessModifier; + } - @Override - public float getMaturationModifier(ITreeGenome genome, float currentModifier) { - return maturationModifier; - } + @Override + public float getMaturationModifier(ITreeGenome genome, float currentModifier) { + return maturationModifier; + } - @Override - public float getMutationModifier(ITreeGenome genome, ITreeGenome mate, float currentModifier) { - return mutationModifier; - } + @Override + public float getMutationModifier(ITreeGenome genome, ITreeGenome mate, float currentModifier) { + return mutationModifier; + } } diff --git a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleFruit.java b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleFruit.java index 1b2c6683e..5aa4fc16e 100644 --- a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleFruit.java +++ b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleFruit.java @@ -10,12 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.genetics.alleles; -import java.util.Arrays; -import java.util.List; - -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - import forestry.api.arboriculture.EnumFruitFamily; import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleFruit; @@ -27,61 +21,113 @@ import forestry.arboriculture.FruitProviderRandom; import forestry.arboriculture.FruitProviderRipening; import forestry.core.genetics.alleles.AlleleCategorized; import forestry.core.items.ItemFruit; +import java.util.Arrays; +import java.util.List; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; public class AlleleFruit extends AlleleCategorized implements IAlleleFruit { - public static IAlleleFruit fruitNone; - public static IAlleleFruit fruitApple; - public static IAlleleFruit fruitCocoa; - public static IAlleleFruit fruitChestnut; - public static IAlleleFruit fruitCoconut; - public static IAlleleFruit fruitWalnut; - public static IAlleleFruit fruitCherry; - public static IAlleleFruit fruitDates; - public static IAlleleFruit fruitPapaya; - public static IAlleleFruit fruitLemon; - public static IAlleleFruit fruitPlum; - public static IAlleleFruit fruitJujube; + public static IAlleleFruit fruitNone; + public static IAlleleFruit fruitApple; + public static IAlleleFruit fruitCocoa; + public static IAlleleFruit fruitChestnut; + public static IAlleleFruit fruitCoconut; + public static IAlleleFruit fruitWalnut; + public static IAlleleFruit fruitCherry; + public static IAlleleFruit fruitDates; + public static IAlleleFruit fruitPapaya; + public static IAlleleFruit fruitLemon; + public static IAlleleFruit fruitPlum; + public static IAlleleFruit fruitJujube; - public static void createAlleles() { - List fruitAlleles = Arrays.asList( - fruitNone = new AlleleFruit("none", new FruitProviderNone("none", null)), - fruitApple = new AlleleFruit("apple", new FruitProviderRandom("apple", EnumFruitFamily.POMES, new ItemStack(Items.apple), 1.0f).setColour(0xff2e2e).setOverlay("pomes")), - fruitCocoa = new AlleleFruit("cocoa", new FruitProviderPod("cocoa", EnumFruitFamily.JUNGLE, FruitProviderPod.EnumPodType.COCOA)), - // .setColours(0xecdca5, 0xc4d24a), true); - fruitChestnut = new AlleleFruit("chestnut", new FruitProviderRipening("chestnut", EnumFruitFamily.NUX, ItemFruit.EnumFruit.CHESTNUT.getStack(), 1.0f).setRipeningPeriod(6).setColours(0x7f333d, 0xc4d24a).setOverlay("nuts"), true), - fruitWalnut = new AlleleFruit("walnut", new FruitProviderRipening("walnut", EnumFruitFamily.NUX, ItemFruit.EnumFruit.WALNUT.getStack(), 1.0f).setRipeningPeriod(8).setColours(0xfba248, 0xc4d24a).setOverlay("nuts"), true), - fruitCherry = new AlleleFruit("cherry", new FruitProviderRipening("cherry", EnumFruitFamily.PRUNES, ItemFruit.EnumFruit.CHERRY.getStack(), 1.0f).setColours(0xff2e2e, 0xc4d24a).setOverlay("berries"), true), - fruitDates = new AlleleFruit("dates", new FruitProviderPod("dates", EnumFruitFamily.JUNGLE, FruitProviderPod.EnumPodType.DATES, ItemFruit.EnumFruit.DATES.getStack(4))), - fruitPapaya = new AlleleFruit("papaya", new FruitProviderPod("papaya", EnumFruitFamily.JUNGLE, FruitProviderPod.EnumPodType.PAPAYA, ItemFruit.EnumFruit.PAPAYA.getStack())), - fruitLemon = new AlleleFruit("lemon", new FruitProviderRipening("lemon", EnumFruitFamily.PRUNES, ItemFruit.EnumFruit.LEMON.getStack(), 1.0f).setColours(0xeeee00, 0x99ff00).setOverlay("citrus"), true), - fruitPlum = new AlleleFruit("plum", new FruitProviderRipening("plum", EnumFruitFamily.PRUNES, ItemFruit.EnumFruit.PLUM.getStack(), 1.0f).setColours(0x663446, 0xeeff1a).setOverlay("plums"), true) - ); + public static void createAlleles() { + List fruitAlleles = Arrays.asList( + fruitNone = new AlleleFruit("none", new FruitProviderNone("none", null)), + fruitApple = new AlleleFruit( + "apple", + new FruitProviderRandom("apple", EnumFruitFamily.POMES, new ItemStack(Items.apple), 1.0f) + .setColour(0xff2e2e) + .setOverlay("pomes")), + fruitCocoa = new AlleleFruit( + "cocoa", + new FruitProviderPod("cocoa", EnumFruitFamily.JUNGLE, FruitProviderPod.EnumPodType.COCOA)), + // .setColours(0xecdca5, 0xc4d24a), true); + fruitChestnut = new AlleleFruit( + "chestnut", + new FruitProviderRipening( + "chestnut", EnumFruitFamily.NUX, ItemFruit.EnumFruit.CHESTNUT.getStack(), 1.0f) + .setRipeningPeriod(6) + .setColours(0x7f333d, 0xc4d24a) + .setOverlay("nuts"), + true), + fruitWalnut = new AlleleFruit( + "walnut", + new FruitProviderRipening( + "walnut", EnumFruitFamily.NUX, ItemFruit.EnumFruit.WALNUT.getStack(), 1.0f) + .setRipeningPeriod(8) + .setColours(0xfba248, 0xc4d24a) + .setOverlay("nuts"), + true), + fruitCherry = new AlleleFruit( + "cherry", + new FruitProviderRipening( + "cherry", EnumFruitFamily.PRUNES, ItemFruit.EnumFruit.CHERRY.getStack(), 1.0f) + .setColours(0xff2e2e, 0xc4d24a) + .setOverlay("berries"), + true), + fruitDates = new AlleleFruit( + "dates", + new FruitProviderPod( + "dates", + EnumFruitFamily.JUNGLE, + FruitProviderPod.EnumPodType.DATES, + ItemFruit.EnumFruit.DATES.getStack(4))), + fruitPapaya = new AlleleFruit( + "papaya", + new FruitProviderPod( + "papaya", + EnumFruitFamily.JUNGLE, + FruitProviderPod.EnumPodType.PAPAYA, + ItemFruit.EnumFruit.PAPAYA.getStack())), + fruitLemon = new AlleleFruit( + "lemon", + new FruitProviderRipening( + "lemon", EnumFruitFamily.PRUNES, ItemFruit.EnumFruit.LEMON.getStack(), 1.0f) + .setColours(0xeeee00, 0x99ff00) + .setOverlay("citrus"), + true), + fruitPlum = new AlleleFruit( + "plum", + new FruitProviderRipening( + "plum", EnumFruitFamily.PRUNES, ItemFruit.EnumFruit.PLUM.getStack(), 1.0f) + .setColours(0x663446, 0xeeff1a) + .setOverlay("plums"), + true)); - for (IAlleleFruit fruitAllele : fruitAlleles) { - AlleleManager.alleleRegistry.registerAllele(fruitAllele, EnumTreeChromosome.FRUITS); - } - } + for (IAlleleFruit fruitAllele : fruitAlleles) { + AlleleManager.alleleRegistry.registerAllele(fruitAllele, EnumTreeChromosome.FRUITS); + } + } - private final IFruitProvider provider; + private final IFruitProvider provider; - public AlleleFruit(String name, IFruitProvider provider) { - this(name, provider, false); - } + public AlleleFruit(String name, IFruitProvider provider) { + this(name, provider, false); + } - public AlleleFruit(String name, IFruitProvider provider, boolean isDominant) { - super("forestry", "fruit", name, isDominant); - this.provider = provider; - } + public AlleleFruit(String name, IFruitProvider provider, boolean isDominant) { + super("forestry", "fruit", name, isDominant); + this.provider = provider; + } - @Override - public IFruitProvider getProvider() { - return this.provider; - } - - @Override - public String getName() { - return getProvider().getDescription(); - } + @Override + public IFruitProvider getProvider() { + return this.provider; + } + @Override + public String getName() { + return getProvider().getDescription(); + } } diff --git a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleGrowth.java b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleGrowth.java index 4f98efd27..db2d3bd55 100644 --- a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleGrowth.java +++ b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleGrowth.java @@ -10,9 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.genetics.alleles; -import java.util.Arrays; -import java.util.List; - import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleGrowth; import forestry.api.arboriculture.IGrowthProvider; @@ -20,39 +17,39 @@ import forestry.api.genetics.AlleleManager; import forestry.arboriculture.genetics.GrowthProvider; import forestry.arboriculture.genetics.GrowthProviderTropical; import forestry.core.genetics.alleles.AlleleCategorized; +import java.util.Arrays; +import java.util.List; public class AlleleGrowth extends AlleleCategorized implements IAlleleGrowth { - public static IAlleleGrowth growthLightLevel; - public static IAlleleGrowth growthAcacia; - public static IAlleleGrowth growthTropical; + public static IAlleleGrowth growthLightLevel; + public static IAlleleGrowth growthAcacia; + public static IAlleleGrowth growthTropical; - public static void createAlleles() { - List growthAlleles = Arrays.asList( - growthLightLevel = new AlleleGrowth("lightlevel", new GrowthProvider()), - growthAcacia = new AlleleGrowth("acacia", new GrowthProvider()), - growthTropical = new AlleleGrowth("tropical", new GrowthProviderTropical()) - ); + public static void createAlleles() { + List growthAlleles = Arrays.asList( + growthLightLevel = new AlleleGrowth("lightlevel", new GrowthProvider()), + growthAcacia = new AlleleGrowth("acacia", new GrowthProvider()), + growthTropical = new AlleleGrowth("tropical", new GrowthProviderTropical())); - for (IAlleleGrowth alleleGrowth : growthAlleles) { - AlleleManager.alleleRegistry.registerAllele(alleleGrowth, EnumTreeChromosome.GROWTH); - } - } + for (IAlleleGrowth alleleGrowth : growthAlleles) { + AlleleManager.alleleRegistry.registerAllele(alleleGrowth, EnumTreeChromosome.GROWTH); + } + } - private final IGrowthProvider provider; + private final IGrowthProvider provider; - public AlleleGrowth(String name, IGrowthProvider provider) { - this(name, provider, false); - } + public AlleleGrowth(String name, IGrowthProvider provider) { + this(name, provider, false); + } - public AlleleGrowth(String name, IGrowthProvider provider, boolean isDominant) { - super("forestry", "growth", name, isDominant); - this.provider = provider; - } - - @Override - public IGrowthProvider getProvider() { - return provider; - } + public AlleleGrowth(String name, IGrowthProvider provider, boolean isDominant) { + super("forestry", "growth", name, isDominant); + this.provider = provider; + } + @Override + public IGrowthProvider getProvider() { + return provider; + } } diff --git a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffect.java b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffect.java index 79c3b0425..7f47dddc4 100644 --- a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffect.java +++ b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffect.java @@ -1,64 +1,63 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.genetics.alleles; - -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.world.World; - -import forestry.api.arboriculture.EnumTreeChromosome; -import forestry.api.arboriculture.IAlleleLeafEffect; -import forestry.api.arboriculture.ITreeGenome; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IEffectData; -import forestry.core.genetics.alleles.Allele; -import forestry.core.genetics.alleles.AlleleCategorized; -import forestry.core.utils.vect.Vect; - -public class AlleleLeafEffect extends AlleleCategorized implements IAlleleLeafEffect { - private static final int[] DEFAULT_EFFECT_AREA = new int[]{12, 12, 12}; - - public static Allele leavesNone; - - public static void createAlleles() { - leavesNone = new AlleleLeafEffectNone(); - AlleleManager.alleleRegistry.registerAllele(leavesNone, EnumTreeChromosome.EFFECT); - } - - protected AlleleLeafEffect(String valueName, boolean isDominant) { - super("forestry", "leaves", valueName, isDominant); - } - - @Override - public boolean isCombinable() { - return true; - } - - @Override - public IEffectData validateStorage(IEffectData storedData) { - return storedData; - } - - @Override - public IEffectData doEffect(ITreeGenome genome, IEffectData storedData, World world, int x, int y, int z) { - return storedData; - } - - protected static AxisAlignedBB getBounding(int x, int y, int z, float modifier) { - int[] areaAr = DEFAULT_EFFECT_AREA; - Vect area = new Vect(areaAr).multiply(modifier); - Vect offset = area.multiply(-1 / 2.0f); - - Vect min = offset.add(x, y, z); - Vect max = min.add(area); - - return AxisAlignedBB.getBoundingBox(min.x, min.y, min.z, max.x, max.y, max.z); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.genetics.alleles; + +import forestry.api.arboriculture.EnumTreeChromosome; +import forestry.api.arboriculture.IAlleleLeafEffect; +import forestry.api.arboriculture.ITreeGenome; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IEffectData; +import forestry.core.genetics.alleles.Allele; +import forestry.core.genetics.alleles.AlleleCategorized; +import forestry.core.utils.vect.Vect; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.world.World; + +public class AlleleLeafEffect extends AlleleCategorized implements IAlleleLeafEffect { + private static final int[] DEFAULT_EFFECT_AREA = new int[] {12, 12, 12}; + + public static Allele leavesNone; + + public static void createAlleles() { + leavesNone = new AlleleLeafEffectNone(); + AlleleManager.alleleRegistry.registerAllele(leavesNone, EnumTreeChromosome.EFFECT); + } + + protected AlleleLeafEffect(String valueName, boolean isDominant) { + super("forestry", "leaves", valueName, isDominant); + } + + @Override + public boolean isCombinable() { + return true; + } + + @Override + public IEffectData validateStorage(IEffectData storedData) { + return storedData; + } + + @Override + public IEffectData doEffect(ITreeGenome genome, IEffectData storedData, World world, int x, int y, int z) { + return storedData; + } + + protected static AxisAlignedBB getBounding(int x, int y, int z, float modifier) { + int[] areaAr = DEFAULT_EFFECT_AREA; + Vect area = new Vect(areaAr).multiply(modifier); + Vect offset = area.multiply(-1 / 2.0f); + + Vect min = offset.add(x, y, z); + Vect max = min.add(area); + + return AxisAlignedBB.getBoundingBox(min.x, min.y, min.z, max.x, max.y, max.z); + } +} diff --git a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffectNone.java b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffectNone.java index ee2eeff6a..f086507a4 100644 --- a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffectNone.java +++ b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffectNone.java @@ -11,12 +11,12 @@ package forestry.arboriculture.genetics.alleles; public class AlleleLeafEffectNone extends AlleleLeafEffect { - public AlleleLeafEffectNone() { - super("none", true); - } + public AlleleLeafEffectNone() { + super("none", true); + } - @Override - public String getUnlocalizedName() { - return "for.arboriculture.effect.none"; - } + @Override + public String getUnlocalizedName() { + return "for.arboriculture.effect.none"; + } } diff --git a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleTreeSpecies.java b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleTreeSpecies.java index 26bdeb4e2..2278146b1 100644 --- a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleTreeSpecies.java +++ b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleTreeSpecies.java @@ -10,17 +10,8 @@ ******************************************************************************/ package forestry.arboriculture.genetics.alleles; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.util.IIcon; - -import net.minecraftforge.common.EnumPlantType; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.IAlleleTreeSpeciesCustom; import forestry.api.arboriculture.IGermlingIconProvider; @@ -33,102 +24,116 @@ import forestry.api.genetics.IClassification; import forestry.api.genetics.IFruitFamily; import forestry.core.genetics.alleles.AlleleSpecies; import forestry.core.render.TextureManager; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.util.IIcon; +import net.minecraftforge.common.EnumPlantType; public class AlleleTreeSpecies extends AlleleSpecies implements IAlleleTreeSpeciesCustom, IIconProvider { - private final ITreeGenerator generator; - private final IGermlingIconProvider germlingIconProvider; - private final ILeafIconProvider leafIconProvider; - private final List fruits = new ArrayList<>(); + private final ITreeGenerator generator; + private final IGermlingIconProvider germlingIconProvider; + private final ILeafIconProvider leafIconProvider; + private final List fruits = new ArrayList<>(); - private EnumPlantType nativeType = EnumPlantType.Plains; + private EnumPlantType nativeType = EnumPlantType.Plains; - public AlleleTreeSpecies(String uid, String unlocalizedName, String authority, String unlocalizedDescription, boolean isDominant, IClassification branch, String binomial, ILeafIconProvider leafIconProvider, IGermlingIconProvider germlingIconProvider, ITreeGenerator generator) { - super(uid, unlocalizedName, authority, unlocalizedDescription, isDominant, branch, binomial); + public AlleleTreeSpecies( + String uid, + String unlocalizedName, + String authority, + String unlocalizedDescription, + boolean isDominant, + IClassification branch, + String binomial, + ILeafIconProvider leafIconProvider, + IGermlingIconProvider germlingIconProvider, + ITreeGenerator generator) { + super(uid, unlocalizedName, authority, unlocalizedDescription, isDominant, branch, binomial); - this.generator = generator; - this.germlingIconProvider = germlingIconProvider; - this.leafIconProvider = leafIconProvider; - } + this.generator = generator; + this.germlingIconProvider = germlingIconProvider; + this.leafIconProvider = leafIconProvider; + } - @Override - public ITreeRoot getRoot() { - return TreeManager.treeRoot; - } + @Override + public ITreeRoot getRoot() { + return TreeManager.treeRoot; + } - @Override - public AlleleTreeSpecies setPlantType(EnumPlantType type) { - nativeType = type; - return this; - } + @Override + public AlleleTreeSpecies setPlantType(EnumPlantType type) { + nativeType = type; + return this; + } - @Override - public AlleleTreeSpecies addFruitFamily(IFruitFamily family) { - fruits.add(family); - return this; - } + @Override + public AlleleTreeSpecies addFruitFamily(IFruitFamily family) { + fruits.add(family); + return this; + } - /* OTHER */ - @Override - public EnumPlantType getPlantType() { - return nativeType; - } + /* OTHER */ + @Override + public EnumPlantType getPlantType() { + return nativeType; + } - @Override - public List getSuitableFruit() { - return fruits; - } + @Override + public List getSuitableFruit() { + return fruits; + } - @Override - public ITreeGenerator getGenerator() { - return generator; - } + @Override + public ITreeGenerator getGenerator() { + return generator; + } - @Override - public IIcon getLeafIcon(boolean pollinated, boolean fancy) { - return leafIconProvider.getIcon(pollinated, fancy); - } + @Override + public IIcon getLeafIcon(boolean pollinated, boolean fancy) { + return leafIconProvider.getIcon(pollinated, fancy); + } - @Override - public int getLeafColour(boolean pollinated) { - return leafIconProvider.getColor(pollinated); - } + @Override + public int getLeafColour(boolean pollinated) { + return leafIconProvider.getColor(pollinated); + } - @Override - public int getIconColour(int renderPass) { - return leafIconProvider.getColor(false); - } + @Override + public int getIconColour(int renderPass) { + return leafIconProvider.getColor(false); + } - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IIconRegister register) { - germlingIconProvider.registerIcons(register); - } + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IIconRegister register) { + germlingIconProvider.registerIcons(register); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getGermlingIcon(EnumGermlingType type, int renderPass) { - return germlingIconProvider.getIcon(type, renderPass); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getGermlingIcon(EnumGermlingType type, int renderPass) { + return germlingIconProvider.getIcon(type, renderPass); + } - @Override - @SideOnly(Side.CLIENT) - public int getGermlingColour(EnumGermlingType type, int renderPass) { - if (type == EnumGermlingType.SAPLING) { - return 0xFFFFFF; - } - return getLeafColour(false); - } + @Override + @SideOnly(Side.CLIENT) + public int getGermlingColour(EnumGermlingType type, int renderPass) { + if (type == EnumGermlingType.SAPLING) { + return 0xFFFFFF; + } + return getLeafColour(false); + } - @Override - @SideOnly(Side.CLIENT) - public IIconProvider getIconProvider() { - return this; - } - - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(short texUID) { - return TextureManager.getInstance().getIcon(texUID); - } + @Override + @SideOnly(Side.CLIENT) + public IIconProvider getIconProvider() { + return this; + } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(short texUID) { + return TextureManager.getInstance().getIcon(texUID); + } } diff --git a/src/main/java/forestry/arboriculture/genetics/pollination/CheckPollinatable.java b/src/main/java/forestry/arboriculture/genetics/pollination/CheckPollinatable.java index 3054b7983..4ededf226 100644 --- a/src/main/java/forestry/arboriculture/genetics/pollination/CheckPollinatable.java +++ b/src/main/java/forestry/arboriculture/genetics/pollination/CheckPollinatable.java @@ -1,47 +1,45 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.genetics.pollination; - -import java.util.EnumSet; - -import net.minecraftforge.common.EnumPlantType; - -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.IPollinatable; - -public class CheckPollinatable implements ICheckPollinatable { - - private final IPollinatable pollinatable; - - public CheckPollinatable(IPollinatable pollinatable) { - this.pollinatable = pollinatable; - } - - @Override - public EnumSet getPlantType() { - return pollinatable.getPlantType(); - } - - @Override - public IIndividual getPollen() { - return pollinatable.getPollen(); - } - - @Override - public boolean canMateWith(IIndividual pollen) { - return pollinatable.canMateWith(pollen); - } - - @Override - public boolean isPollinated() { - return pollinatable.isPollinated(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.genetics.pollination; + +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.IPollinatable; +import java.util.EnumSet; +import net.minecraftforge.common.EnumPlantType; + +public class CheckPollinatable implements ICheckPollinatable { + + private final IPollinatable pollinatable; + + public CheckPollinatable(IPollinatable pollinatable) { + this.pollinatable = pollinatable; + } + + @Override + public EnumSet getPlantType() { + return pollinatable.getPlantType(); + } + + @Override + public IIndividual getPollen() { + return pollinatable.getPollen(); + } + + @Override + public boolean canMateWith(IIndividual pollen) { + return pollinatable.canMateWith(pollen); + } + + @Override + public boolean isPollinated() { + return pollinatable.isPollinated(); + } +} diff --git a/src/main/java/forestry/arboriculture/genetics/pollination/CheckPollinatableTree.java b/src/main/java/forestry/arboriculture/genetics/pollination/CheckPollinatableTree.java index c9f541b8f..1daceedb9 100644 --- a/src/main/java/forestry/arboriculture/genetics/pollination/CheckPollinatableTree.java +++ b/src/main/java/forestry/arboriculture/genetics/pollination/CheckPollinatableTree.java @@ -1,54 +1,52 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.genetics.pollination; - -import java.util.EnumSet; - -import net.minecraftforge.common.EnumPlantType; - -import forestry.api.arboriculture.ITree; -import forestry.api.genetics.IIndividual; - -public class CheckPollinatableTree implements ICheckPollinatable { - - private final ITree tree; - - public CheckPollinatableTree(ITree tree) { - this.tree = tree; - } - - @Override - public EnumSet getPlantType() { - return tree.getPlantTypes(); - } - - @Override - public IIndividual getPollen() { - return tree; - } - - @Override - public boolean canMateWith(IIndividual pollen) { - if (tree.getMate() != null) { - return false; - } - if (!(pollen instanceof ITree)) { - return false; - } - - return !tree.isGeneticEqual(pollen); - } - - @Override - public boolean isPollinated() { - return tree.getMate() != null; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.genetics.pollination; + +import forestry.api.arboriculture.ITree; +import forestry.api.genetics.IIndividual; +import java.util.EnumSet; +import net.minecraftforge.common.EnumPlantType; + +public class CheckPollinatableTree implements ICheckPollinatable { + + private final ITree tree; + + public CheckPollinatableTree(ITree tree) { + this.tree = tree; + } + + @Override + public EnumSet getPlantType() { + return tree.getPlantTypes(); + } + + @Override + public IIndividual getPollen() { + return tree; + } + + @Override + public boolean canMateWith(IIndividual pollen) { + if (tree.getMate() != null) { + return false; + } + if (!(pollen instanceof ITree)) { + return false; + } + + return !tree.isGeneticEqual(pollen); + } + + @Override + public boolean isPollinated() { + return tree.getMate() != null; + } +} diff --git a/src/main/java/forestry/arboriculture/genetics/pollination/FakePollinatable.java b/src/main/java/forestry/arboriculture/genetics/pollination/FakePollinatable.java index b8dd0871c..80ab2bf8b 100644 --- a/src/main/java/forestry/arboriculture/genetics/pollination/FakePollinatable.java +++ b/src/main/java/forestry/arboriculture/genetics/pollination/FakePollinatable.java @@ -1,42 +1,38 @@ -package forestry.arboriculture.genetics.pollination; - -import java.util.EnumSet; - -import net.minecraftforge.common.EnumPlantType; - -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.IPollinatable; - -public class FakePollinatable implements IPollinatable { - - private final ICheckPollinatable checkPollinatable; - - public FakePollinatable(ICheckPollinatable checkPollinatable) { - this.checkPollinatable = checkPollinatable; - } - - @Override - public EnumSet getPlantType() { - return checkPollinatable.getPlantType(); - } - - @Override - public IIndividual getPollen() { - return checkPollinatable.getPollen(); - } - - @Override - public boolean canMateWith(IIndividual pollen) { - return checkPollinatable.canMateWith(pollen); - } - - @Override - public void mateWith(IIndividual pollen) { - - } - - @Override - public boolean isPollinated() { - return checkPollinatable.isPollinated(); - } -} +package forestry.arboriculture.genetics.pollination; + +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.IPollinatable; +import java.util.EnumSet; +import net.minecraftforge.common.EnumPlantType; + +public class FakePollinatable implements IPollinatable { + + private final ICheckPollinatable checkPollinatable; + + public FakePollinatable(ICheckPollinatable checkPollinatable) { + this.checkPollinatable = checkPollinatable; + } + + @Override + public EnumSet getPlantType() { + return checkPollinatable.getPlantType(); + } + + @Override + public IIndividual getPollen() { + return checkPollinatable.getPollen(); + } + + @Override + public boolean canMateWith(IIndividual pollen) { + return checkPollinatable.canMateWith(pollen); + } + + @Override + public void mateWith(IIndividual pollen) {} + + @Override + public boolean isPollinated() { + return checkPollinatable.isPollinated(); + } +} diff --git a/src/main/java/forestry/arboriculture/genetics/pollination/ICheckPollinatable.java b/src/main/java/forestry/arboriculture/genetics/pollination/ICheckPollinatable.java index c1aeaab6b..ac2cd99ac 100644 --- a/src/main/java/forestry/arboriculture/genetics/pollination/ICheckPollinatable.java +++ b/src/main/java/forestry/arboriculture/genetics/pollination/ICheckPollinatable.java @@ -1,43 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.genetics.pollination; - -import java.util.EnumSet; - -import net.minecraftforge.common.EnumPlantType; - -import forestry.api.genetics.IIndividual; - -/** Just like IPollinatible but for checking only, it can't be mated */ -public interface ICheckPollinatable { - - /** - * @return plant types this pollinatable is classified as. (Can be used by bees to determine whether to interact or not. - */ - EnumSet getPlantType(); - - /** - * @return IIndividual containing the genetic information of this IPollinatable - */ - IIndividual getPollen(); - - /** - * Checks whether this can mate with the given pollen. - * - * Must be the one to check genetic equivalency. - * - * @param pollen IIndividual representing the pollen. - * @return true if mating is possible, false otherwise. - */ - boolean canMateWith(IIndividual pollen); - - boolean isPollinated(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.genetics.pollination; + +import forestry.api.genetics.IIndividual; +import java.util.EnumSet; +import net.minecraftforge.common.EnumPlantType; + +/** Just like IPollinatible but for checking only, it can't be mated */ +public interface ICheckPollinatable { + + /** + * @return plant types this pollinatable is classified as. (Can be used by bees to determine whether to interact or not. + */ + EnumSet getPlantType(); + + /** + * @return IIndividual containing the genetic information of this IPollinatable + */ + IIndividual getPollen(); + + /** + * Checks whether this can mate with the given pollen. + * + * Must be the one to check genetic equivalency. + * + * @param pollen IIndividual representing the pollen. + * @return true if mating is possible, false otherwise. + */ + boolean canMateWith(IIndividual pollen); + + boolean isPollinated(); +} diff --git a/src/main/java/forestry/arboriculture/gui/GuiTreealyzer.java b/src/main/java/forestry/arboriculture/gui/GuiTreealyzer.java index d537c95ea..87da50b03 100755 --- a/src/main/java/forestry/arboriculture/gui/GuiTreealyzer.java +++ b/src/main/java/forestry/arboriculture/gui/GuiTreealyzer.java @@ -10,17 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.gui; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumChatFormatting; - -import net.minecraftforge.common.EnumPlantType; - import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleFruit; @@ -40,269 +29,359 @@ import forestry.core.gui.ContainerAlyzer; import forestry.core.gui.GuiAlyzer; import forestry.core.utils.StringUtil; import forestry.plugins.PluginArboriculture; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; +import net.minecraftforge.common.EnumPlantType; public class GuiTreealyzer extends GuiAlyzer { - public GuiTreealyzer(EntityPlayer player, ItemInventoryTreealyzer inventory) { - super(TreeManager.treeRoot, player, new ContainerAlyzer(inventory, player), inventory, "gui.treealyzer"); + public GuiTreealyzer(EntityPlayer player, ItemInventoryTreealyzer inventory) { + super(TreeManager.treeRoot, player, new ContainerAlyzer(inventory, player), inventory, "gui.treealyzer"); - ArrayList treeList = new ArrayList<>(); - PluginArboriculture.items.sapling.addCreativeItems(treeList, false); - for (ItemStack treeStack : treeList) { - IAlleleTreeSpecies species = TreeGenome.getSpecies(treeStack); - if (species != null) { - iconStacks.put(species.getUID(), treeStack); - } - } - } + ArrayList treeList = new ArrayList<>(); + PluginArboriculture.items.sapling.addCreativeItems(treeList, false); + for (ItemStack treeStack : treeList) { + IAlleleTreeSpecies species = TreeGenome.getSpecies(treeStack); + if (species != null) { + iconStacks.put(species.getUID(), treeStack); + } + } + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - int page = 0; - ITree tree = null; - EnumGermlingType treeType = EnumGermlingType.SAPLING; - for (int k = 1; k < ItemInventoryTreealyzer.SLOT_ANALYZE_5 + 1; k++) { - if (k == ItemInventoryTreealyzer.SLOT_ENERGY) { - continue; - } + int page = 0; + ITree tree = null; + EnumGermlingType treeType = EnumGermlingType.SAPLING; + for (int k = 1; k < ItemInventoryTreealyzer.SLOT_ANALYZE_5 + 1; k++) { + if (k == ItemInventoryTreealyzer.SLOT_ENERGY) { + continue; + } - if (inventory.getStackInSlot(k) == null) { - continue; - } - tree = TreeManager.treeRoot.getMember(inventory.getStackInSlot(k)); - treeType = TreeManager.treeRoot.getType(inventory.getStackInSlot(k)); - if (tree == null || !tree.isAnalyzed()) { - continue; - } + if (inventory.getStackInSlot(k) == null) { + continue; + } + tree = TreeManager.treeRoot.getMember(inventory.getStackInSlot(k)); + treeType = TreeManager.treeRoot.getType(inventory.getStackInSlot(k)); + if (tree == null || !tree.isAnalyzed()) { + continue; + } - page = k; - break; - } + page = k; + break; + } - switch (page) { - case 1: - drawAnalyticsPage1(tree, treeType); - break; - case 2: - drawAnalyticsPage2(tree); - break; - case 3: - drawAnalyticsPage3(tree); - break; - case 4: - drawAnalyticsPageMutations(tree); - break; - case 6: - drawAnalyticsPageClassification(tree); - break; - default: - drawAnalyticsOverview(); - } + switch (page) { + case 1: + drawAnalyticsPage1(tree, treeType); + break; + case 2: + drawAnalyticsPage2(tree); + break; + case 3: + drawAnalyticsPage3(tree); + break; + case 4: + drawAnalyticsPageMutations(tree); + break; + case 6: + drawAnalyticsPageClassification(tree); + break; + default: + drawAnalyticsOverview(); + } + } - } + private void drawAnalyticsPage1(ITree tree, EnumGermlingType type) { - private void drawAnalyticsPage1(ITree tree, EnumGermlingType type) { + textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); - textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); + textLayout.drawLine(StringUtil.localize("gui.active"), COLUMN_1); + textLayout.drawLine(StringUtil.localize("gui.inactive"), COLUMN_2); - textLayout.drawLine(StringUtil.localize("gui.active"), COLUMN_1); - textLayout.drawLine(StringUtil.localize("gui.inactive"), COLUMN_2); + textLayout.newLine(); + textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); + { + String customPrimaryTreeKey = "trees.custom.treealyzer." + type.getName() + "." + + tree.getGenome().getPrimary().getUnlocalizedName().replace("trees.species.", ""); + String customSecondaryTreeKey = "trees.custom.treealyzer." + type.getName() + "." + + tree.getGenome().getSecondary().getUnlocalizedName().replace("trees.species.", ""); - { - String customPrimaryTreeKey = "trees.custom.treealyzer." + type.getName() + "." + tree.getGenome().getPrimary().getUnlocalizedName().replace("trees.species.", ""); - String customSecondaryTreeKey = "trees.custom.treealyzer." + type.getName() + "." + tree.getGenome().getSecondary().getUnlocalizedName().replace("trees.species.", ""); + drawSpeciesRow( + StringUtil.localize("gui.species"), + tree, + EnumTreeChromosome.SPECIES, + checkCustomName(customPrimaryTreeKey), + checkCustomName(customSecondaryTreeKey)); + textLayout.newLine(); + } - drawSpeciesRow(StringUtil.localize("gui.species"), tree, EnumTreeChromosome.SPECIES, checkCustomName(customPrimaryTreeKey), checkCustomName(customSecondaryTreeKey)); - textLayout.newLine(); - } + drawChromosomeRow(StringUtil.localize("gui.saplings"), tree, EnumTreeChromosome.FERTILITY); + textLayout.newLineCompressed(); + drawChromosomeRow(StringUtil.localize("gui.maturity"), tree, EnumTreeChromosome.MATURATION); + textLayout.newLineCompressed(); + drawChromosomeRow(StringUtil.localize("gui.height"), tree, EnumTreeChromosome.HEIGHT); + textLayout.newLineCompressed(); - drawChromosomeRow(StringUtil.localize("gui.saplings"), tree, EnumTreeChromosome.FERTILITY); - textLayout.newLineCompressed(); - drawChromosomeRow(StringUtil.localize("gui.maturity"), tree, EnumTreeChromosome.MATURATION); - textLayout.newLineCompressed(); - drawChromosomeRow(StringUtil.localize("gui.height"), tree, EnumTreeChromosome.HEIGHT); - textLayout.newLineCompressed(); + IAlleleInteger activeGirth = (IAlleleInteger) tree.getGenome().getActiveAllele(EnumTreeChromosome.GIRTH); + IAlleleInteger inactiveGirth = (IAlleleInteger) tree.getGenome().getInactiveAllele(EnumTreeChromosome.GIRTH); + textLayout.drawLine(StringUtil.localize("gui.girth"), COLUMN_0); + drawLine( + String.format("%sx%s", activeGirth.getValue(), activeGirth.getValue()), + COLUMN_1, + tree, + EnumTreeChromosome.GIRTH, + false); + drawLine( + String.format("%sx%s", inactiveGirth.getValue(), inactiveGirth.getValue()), + COLUMN_2, + tree, + EnumTreeChromosome.GIRTH, + true); - IAlleleInteger activeGirth = (IAlleleInteger) tree.getGenome().getActiveAllele(EnumTreeChromosome.GIRTH); - IAlleleInteger inactiveGirth = (IAlleleInteger) tree.getGenome().getInactiveAllele(EnumTreeChromosome.GIRTH); - textLayout.drawLine(StringUtil.localize("gui.girth"), COLUMN_0); - drawLine(String.format("%sx%s", activeGirth.getValue(), activeGirth.getValue()), COLUMN_1, tree, EnumTreeChromosome.GIRTH, false); - drawLine(String.format("%sx%s", inactiveGirth.getValue(), inactiveGirth.getValue()), COLUMN_2, tree, EnumTreeChromosome.GIRTH, true); + textLayout.newLineCompressed(); - textLayout.newLineCompressed(); + drawChromosomeRow(StringUtil.localize("gui.yield"), tree, EnumTreeChromosome.YIELD); + textLayout.newLineCompressed(); + drawChromosomeRow(StringUtil.localize("gui.sappiness"), tree, EnumTreeChromosome.SAPPINESS); + textLayout.newLineCompressed(); - drawChromosomeRow(StringUtil.localize("gui.yield"), tree, EnumTreeChromosome.YIELD); - textLayout.newLineCompressed(); - drawChromosomeRow(StringUtil.localize("gui.sappiness"), tree, EnumTreeChromosome.SAPPINESS); - textLayout.newLineCompressed(); + String yes = StringUtil.localize("yes"); + String no = StringUtil.localize("no"); - String yes = StringUtil.localize("yes"); - String no = StringUtil.localize("no"); + AlleleBoolean primaryFireproof = (AlleleBoolean) tree.getGenome().getActiveAllele(EnumTreeChromosome.FIREPROOF); + AlleleBoolean secondaryFireproof = + (AlleleBoolean) tree.getGenome().getInactiveAllele(EnumTreeChromosome.FIREPROOF); - AlleleBoolean primaryFireproof = (AlleleBoolean) tree.getGenome().getActiveAllele(EnumTreeChromosome.FIREPROOF); - AlleleBoolean secondaryFireproof = (AlleleBoolean) tree.getGenome().getInactiveAllele(EnumTreeChromosome.FIREPROOF); + textLayout.drawLine(StringUtil.localize("gui.fireproof"), COLUMN_0); + drawLine( + StringUtil.readableBoolean(primaryFireproof.getValue(), yes, no), + COLUMN_1, + tree, + EnumTreeChromosome.FIREPROOF, + false); + drawLine( + StringUtil.readableBoolean(secondaryFireproof.getValue(), yes, no), + COLUMN_2, + tree, + EnumTreeChromosome.FIREPROOF, + false); - textLayout.drawLine(StringUtil.localize("gui.fireproof"), COLUMN_0); - drawLine(StringUtil.readableBoolean(primaryFireproof.getValue(), yes, no), COLUMN_1, tree, EnumTreeChromosome.FIREPROOF, false); - drawLine(StringUtil.readableBoolean(secondaryFireproof.getValue(), yes, no), COLUMN_2, tree, EnumTreeChromosome.FIREPROOF, false); + textLayout.newLineCompressed(); - textLayout.newLineCompressed(); + drawChromosomeRow(StringUtil.localize("gui.effect"), tree, EnumTreeChromosome.EFFECT); - drawChromosomeRow(StringUtil.localize("gui.effect"), tree, EnumTreeChromosome.EFFECT); + textLayout.endPage(); + } - textLayout.endPage(); - } + private void drawAnalyticsPage2(ITree tree) { - private void drawAnalyticsPage2(ITree tree) { + textLayout.startPage(); - textLayout.startPage(); + int speciesDominance0 = getColorCoding(tree.getGenome().getPrimary().isDominant()); + int speciesDominance1 = getColorCoding(tree.getGenome().getSecondary().isDominant()); - int speciesDominance0 = getColorCoding(tree.getGenome().getPrimary().isDominant()); - int speciesDominance1 = getColorCoding(tree.getGenome().getSecondary().isDominant()); + textLayout.drawLine(StringUtil.localize("gui.active"), COLUMN_1); + textLayout.drawLine(StringUtil.localize("gui.inactive"), COLUMN_2); - textLayout.drawLine(StringUtil.localize("gui.active"), COLUMN_1); - textLayout.drawLine(StringUtil.localize("gui.inactive"), COLUMN_2); + textLayout.newLine(); + textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); + textLayout.drawLine(StringUtil.localize("gui.growth"), COLUMN_0); + drawLine( + tree.getGenome().getGrowthProvider().getDescription(), + COLUMN_1, + tree, + EnumTreeChromosome.GROWTH, + false); + drawLine( + ((IAlleleGrowth) tree.getGenome().getInactiveAllele(EnumTreeChromosome.GROWTH)) + .getProvider() + .getDescription(), + COLUMN_2, + tree, + EnumTreeChromosome.GROWTH, + true); - textLayout.drawLine(StringUtil.localize("gui.growth"), COLUMN_0); - drawLine(tree.getGenome().getGrowthProvider().getDescription(), COLUMN_1, tree, EnumTreeChromosome.GROWTH, false); - drawLine(((IAlleleGrowth) tree.getGenome().getInactiveAllele(EnumTreeChromosome.GROWTH)).getProvider().getDescription(), COLUMN_2, tree, - EnumTreeChromosome.GROWTH, true); + textLayout.newLine(); - textLayout.newLine(); + textLayout.drawLine(StringUtil.localize("gui.native"), COLUMN_0); + textLayout.drawLine( + StringUtil.localize("gui." + + tree.getGenome() + .getPrimary() + .getPlantType() + .toString() + .toLowerCase(Locale.ENGLISH)), + COLUMN_1, + speciesDominance0); + textLayout.drawLine( + StringUtil.localize("gui." + + tree.getGenome() + .getSecondary() + .getPlantType() + .toString() + .toLowerCase(Locale.ENGLISH)), + COLUMN_2, + speciesDominance1); - textLayout.drawLine(StringUtil.localize("gui.native"), COLUMN_0); - textLayout.drawLine(StringUtil.localize("gui." + tree.getGenome().getPrimary().getPlantType().toString().toLowerCase(Locale.ENGLISH)), COLUMN_1, - speciesDominance0); - textLayout.drawLine(StringUtil.localize("gui." + tree.getGenome().getSecondary().getPlantType().toString().toLowerCase(Locale.ENGLISH)), COLUMN_2, - speciesDominance1); + textLayout.newLine(); - textLayout.newLine(); + textLayout.drawLine(StringUtil.localize("gui.tolerated"), COLUMN_0); - textLayout.drawLine(StringUtil.localize("gui.tolerated"), COLUMN_0); + List activeTolerated = new ArrayList<>(tree.getGenome().getPlantTypes()); + List inactiveTolerated = Collections.emptyList(); - List activeTolerated = new ArrayList<>(tree.getGenome().getPlantTypes()); - List inactiveTolerated = Collections.emptyList(); + IAllele inactiveAllelePlant = tree.getGenome().getInactiveAllele(EnumTreeChromosome.PLANT); + if (inactiveAllelePlant instanceof AllelePlantType) { + inactiveTolerated = new ArrayList<>(((AllelePlantType) inactiveAllelePlant).getPlantTypes()); + } - IAllele inactiveAllelePlant = tree.getGenome().getInactiveAllele(EnumTreeChromosome.PLANT); - if (inactiveAllelePlant instanceof AllelePlantType) { - inactiveTolerated = new ArrayList<>(((AllelePlantType) inactiveAllelePlant).getPlantTypes()); - } + int max = Math.max(activeTolerated.size(), inactiveTolerated.size()); + for (int i = 0; i < max; i++) { + if (i > 0) { + textLayout.newLine(); + } + if (activeTolerated.size() > i) { + drawLine( + StringUtil.localize( + "gui." + activeTolerated.get(i).toString().toLowerCase(Locale.ENGLISH)), + COLUMN_1, + tree, + EnumTreeChromosome.PLANT, + false); + } + if (inactiveTolerated.size() > i) { + drawLine( + StringUtil.localize( + "gui." + inactiveTolerated.get(i).toString().toLowerCase(Locale.ENGLISH)), + COLUMN_2, + tree, + EnumTreeChromosome.PLANT, + true); + } + } + textLayout.newLine(); - int max = Math.max(activeTolerated.size(), inactiveTolerated.size()); - for (int i = 0; i < max; i++) { - if (i > 0) { - textLayout.newLine(); - } - if (activeTolerated.size() > i) { - drawLine(StringUtil.localize("gui." + activeTolerated.get(i).toString().toLowerCase(Locale.ENGLISH)), COLUMN_1, tree, EnumTreeChromosome.PLANT, false); - } - if (inactiveTolerated.size() > i) { - drawLine(StringUtil.localize("gui." + inactiveTolerated.get(i).toString().toLowerCase(Locale.ENGLISH)), COLUMN_2, tree, EnumTreeChromosome.PLANT, true); - } - } - textLayout.newLine(); + // FRUITS + textLayout.drawLine(StringUtil.localize("gui.supports"), COLUMN_0); + List families0 = + new ArrayList<>(tree.getGenome().getPrimary().getSuitableFruit()); + List families1 = + new ArrayList<>(tree.getGenome().getSecondary().getSuitableFruit()); - // FRUITS - textLayout.drawLine(StringUtil.localize("gui.supports"), COLUMN_0); - List families0 = new ArrayList<>(tree.getGenome().getPrimary().getSuitableFruit()); - List families1 = new ArrayList<>(tree.getGenome().getSecondary().getSuitableFruit()); + max = Math.max(families0.size(), families1.size()); + for (int i = 0; i < max; i++) { + if (i > 0) { + textLayout.newLine(); + } - max = Math.max(families0.size(), families1.size()); - for (int i = 0; i < max; i++) { - if (i > 0) { - textLayout.newLine(); - } + if (families0.size() > i) { + textLayout.drawLine(families0.get(i).getName(), COLUMN_1, speciesDominance0); + } + if (families1.size() > i) { + textLayout.drawLine(families1.get(i).getName(), COLUMN_2, speciesDominance1); + } + } - if (families0.size() > i) { - textLayout.drawLine(families0.get(i).getName(), COLUMN_1, speciesDominance0); - } - if (families1.size() > i) { - textLayout.drawLine(families1.get(i).getName(), COLUMN_2, speciesDominance1); - } + textLayout.newLine(); + textLayout.newLine(); - } + int fruitDominance0 = getColorCoding( + tree.getGenome().getActiveAllele(EnumTreeChromosome.FRUITS).isDominant()); + int fruitDominance1 = getColorCoding( + tree.getGenome().getInactiveAllele(EnumTreeChromosome.FRUITS).isDominant()); - textLayout.newLine(); - textLayout.newLine(); + textLayout.drawLine(StringUtil.localize("gui.fruits"), COLUMN_0); + String strike = ""; + IAllele fruit0 = tree.getGenome().getActiveAllele(EnumTreeChromosome.FRUITS); + if (!tree.canBearFruit() && fruit0 != AlleleFruit.fruitNone) { + strike = EnumChatFormatting.STRIKETHROUGH.toString(); + } + textLayout.drawLine( + strike + StringUtil.localize(tree.getGenome().getFruitProvider().getDescription()), + COLUMN_1, + fruitDominance0); - int fruitDominance0 = getColorCoding(tree.getGenome().getActiveAllele(EnumTreeChromosome.FRUITS).isDominant()); - int fruitDominance1 = getColorCoding(tree.getGenome().getInactiveAllele(EnumTreeChromosome.FRUITS).isDominant()); + strike = ""; + IAllele fruit1 = tree.getGenome().getInactiveAllele(EnumTreeChromosome.FRUITS); + if (!tree.getGenome() + .getSecondary() + .getSuitableFruit() + .contains(((IAlleleFruit) fruit1).getProvider().getFamily()) + && fruit1 != AlleleFruit.fruitNone) { + strike = EnumChatFormatting.STRIKETHROUGH.toString(); + } + textLayout.drawLine( + strike + + StringUtil.localize( + ((IAlleleFruit) fruit1).getProvider().getDescription()), + COLUMN_2, + fruitDominance1); - textLayout.drawLine(StringUtil.localize("gui.fruits"), COLUMN_0); - String strike = ""; - IAllele fruit0 = tree.getGenome().getActiveAllele(EnumTreeChromosome.FRUITS); - if (!tree.canBearFruit() && fruit0 != AlleleFruit.fruitNone) { - strike = EnumChatFormatting.STRIKETHROUGH.toString(); - } - textLayout.drawLine(strike + StringUtil.localize(tree.getGenome().getFruitProvider().getDescription()), COLUMN_1, fruitDominance0); + textLayout.newLine(); - strike = ""; - IAllele fruit1 = tree.getGenome().getInactiveAllele(EnumTreeChromosome.FRUITS); - if (!tree.getGenome().getSecondary().getSuitableFruit().contains(((IAlleleFruit) fruit1).getProvider().getFamily()) && fruit1 != AlleleFruit.fruitNone) { - strike = EnumChatFormatting.STRIKETHROUGH.toString(); - } - textLayout.drawLine(strike + StringUtil.localize(((IAlleleFruit) fruit1).getProvider().getDescription()), COLUMN_2, fruitDominance1); + textLayout.drawLine(StringUtil.localize("gui.family"), COLUMN_0); + IFruitFamily primary = tree.getGenome().getFruitProvider().getFamily(); + IFruitFamily secondary = ((IAlleleFruit) tree.getGenome().getInactiveAllele(EnumTreeChromosome.FRUITS)) + .getProvider() + .getFamily(); - textLayout.newLine(); + if (primary != null) { + textLayout.drawLine(primary.getName(), COLUMN_1, fruitDominance0); + } + if (secondary != null) { + textLayout.drawLine(secondary.getName(), COLUMN_2, fruitDominance1); + } - textLayout.drawLine(StringUtil.localize("gui.family"), COLUMN_0); - IFruitFamily primary = tree.getGenome().getFruitProvider().getFamily(); - IFruitFamily secondary = ((IAlleleFruit) tree.getGenome().getInactiveAllele(EnumTreeChromosome.FRUITS)).getProvider().getFamily(); + textLayout.endPage(); + } - if (primary != null) { - textLayout.drawLine(primary.getName(), COLUMN_1, fruitDominance0); - } - if (secondary != null) { - textLayout.drawLine(secondary.getName(), COLUMN_2, fruitDominance1); - } + private void drawAnalyticsPage3(ITree tree) { - textLayout.endPage(); - } + textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); - private void drawAnalyticsPage3(ITree tree) { + textLayout.drawLine(StringUtil.localize("gui.beealyzer.produce") + ":", COLUMN_0); + textLayout.newLine(); - textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); + int x = COLUMN_0; + for (ItemStack stack : tree.getProduceList()) { + itemRender.renderItemIntoGUI( + fontRendererObj, mc.renderEngine, stack, guiLeft + x, guiTop + textLayout.getLineY()); + x += 18; + if (x > 148) { + x = COLUMN_0; + textLayout.newLine(); + } + } - textLayout.drawLine(StringUtil.localize("gui.beealyzer.produce") + ":", COLUMN_0); - textLayout.newLine(); + textLayout.newLine(); + textLayout.newLine(); + textLayout.newLine(); + textLayout.newLine(); - int x = COLUMN_0; - for (ItemStack stack : tree.getProduceList()) { - itemRender.renderItemIntoGUI(fontRendererObj, mc.renderEngine, stack, guiLeft + x, guiTop + textLayout.getLineY()); - x += 18; - if (x > 148) { - x = COLUMN_0; - textLayout.newLine(); - } - } + textLayout.drawLine(StringUtil.localize("gui.beealyzer.specialty") + ":", COLUMN_0); + textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); - - textLayout.drawLine(StringUtil.localize("gui.beealyzer.specialty") + ":", COLUMN_0); - textLayout.newLine(); - - x = COLUMN_0; - for (ItemStack stack : tree.getSpecialtyList()) { - itemRender.renderItemIntoGUI(fontRendererObj, mc.renderEngine, stack, guiLeft + x, guiTop + textLayout.getLineY()); - x += 18; - if (x > 148) { - x = COLUMN_0; - textLayout.newLine(); - } - } - - textLayout.endPage(); - } + x = COLUMN_0; + for (ItemStack stack : tree.getSpecialtyList()) { + itemRender.renderItemIntoGUI( + fontRendererObj, mc.renderEngine, stack, guiLeft + x, guiTop + textLayout.getLineY()); + x += 18; + if (x > 148) { + x = COLUMN_0; + textLayout.newLine(); + } + } + textLayout.endPage(); + } } diff --git a/src/main/java/forestry/arboriculture/inventory/ItemInventoryTreealyzer.java b/src/main/java/forestry/arboriculture/inventory/ItemInventoryTreealyzer.java index f5aa6e9ef..b73127513 100644 --- a/src/main/java/forestry/arboriculture/inventory/ItemInventoryTreealyzer.java +++ b/src/main/java/forestry/arboriculture/inventory/ItemInventoryTreealyzer.java @@ -1,59 +1,57 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.inventory; - -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.api.arboriculture.TreeManager; -import forestry.core.config.Config; -import forestry.core.gui.IHintSource; -import forestry.core.inventory.ItemInventoryAlyzer; -import forestry.core.utils.GeneticsUtil; - -public class ItemInventoryTreealyzer extends ItemInventoryAlyzer implements IHintSource { - - public ItemInventoryTreealyzer(EntityPlayer player, ItemStack itemStack) { - super(TreeManager.treeRoot, player, itemStack); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (!TreeManager.treeRoot.isMember(itemStack)) { - ItemStack ersatz = GeneticsUtil.convertSaplingToGeneticEquivalent(itemStack); - if (ersatz != null) { - return super.canSlotAccept(slotIndex, ersatz); - } - } - return super.canSlotAccept(slotIndex, itemStack); - } - - @Override - public void onSlotClick(EntityPlayer player) { - ItemStack specimen = getStackInSlot(SLOT_SPECIMEN); - if (!TreeManager.treeRoot.isMember(specimen)) { - ItemStack ersatz = GeneticsUtil.convertSaplingToGeneticEquivalent(specimen); - if (ersatz != null) { - setInventorySlotContents(SLOT_SPECIMEN, ersatz); - } - } - - super.onSlotClick(player); - } - - /* IHintSource */ - @Override - public List getHints() { - return Config.hints.get("treealyzer"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.inventory; + +import forestry.api.arboriculture.TreeManager; +import forestry.core.config.Config; +import forestry.core.gui.IHintSource; +import forestry.core.inventory.ItemInventoryAlyzer; +import forestry.core.utils.GeneticsUtil; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class ItemInventoryTreealyzer extends ItemInventoryAlyzer implements IHintSource { + + public ItemInventoryTreealyzer(EntityPlayer player, ItemStack itemStack) { + super(TreeManager.treeRoot, player, itemStack); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (!TreeManager.treeRoot.isMember(itemStack)) { + ItemStack ersatz = GeneticsUtil.convertSaplingToGeneticEquivalent(itemStack); + if (ersatz != null) { + return super.canSlotAccept(slotIndex, ersatz); + } + } + return super.canSlotAccept(slotIndex, itemStack); + } + + @Override + public void onSlotClick(EntityPlayer player) { + ItemStack specimen = getStackInSlot(SLOT_SPECIMEN); + if (!TreeManager.treeRoot.isMember(specimen)) { + ItemStack ersatz = GeneticsUtil.convertSaplingToGeneticEquivalent(specimen); + if (ersatz != null) { + setInventorySlotContents(SLOT_SPECIMEN, ersatz); + } + } + + super.onSlotClick(player); + } + + /* IHintSource */ + @Override + public List getHints() { + return Config.hints.get("treealyzer"); + } +} diff --git a/src/main/java/forestry/arboriculture/items/ItemBlockLeaves.java b/src/main/java/forestry/arboriculture/items/ItemBlockLeaves.java index d2c715c66..515b60c6e 100644 --- a/src/main/java/forestry/arboriculture/items/ItemBlockLeaves.java +++ b/src/main/java/forestry/arboriculture/items/ItemBlockLeaves.java @@ -10,70 +10,79 @@ ******************************************************************************/ package forestry.arboriculture.items; +import forestry.arboriculture.tiles.TileLeaves; +import forestry.core.items.ItemBlockForestry; +import forestry.core.proxy.Proxies; +import forestry.core.utils.StringUtil; +import forestry.plugins.PluginArboriculture; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -import forestry.arboriculture.tiles.TileLeaves; -import forestry.core.items.ItemBlockForestry; -import forestry.core.proxy.Proxies; -import forestry.core.utils.StringUtil; -import forestry.plugins.PluginArboriculture; - public class ItemBlockLeaves extends ItemBlockForestry { - public ItemBlockLeaves(Block block) { - super(block); - } + public ItemBlockLeaves(Block block) { + super(block); + } - @Override - public String getItemStackDisplayName(ItemStack itemstack) { - String type = StringUtil.localize("trees.grammar.leaves.type"); - if (!itemstack.hasTagCompound()) { - return type; - } + @Override + public String getItemStackDisplayName(ItemStack itemstack) { + String type = StringUtil.localize("trees.grammar.leaves.type"); + if (!itemstack.hasTagCompound()) { + return type; + } - TileLeaves tileLeaves = new TileLeaves(); - tileLeaves.readFromNBT(itemstack.getTagCompound()); + TileLeaves tileLeaves = new TileLeaves(); + tileLeaves.readFromNBT(itemstack.getTagCompound()); - String unlocalizedName = tileLeaves.getUnlocalizedName(); + String unlocalizedName = tileLeaves.getUnlocalizedName(); - String customTreeKey = "trees.custom.leaves." + unlocalizedName.replace("trees.species.", ""); - if (StringUtil.canTranslate(customTreeKey)) { - return StringUtil.localize(customTreeKey); - } + String customTreeKey = "trees.custom.leaves." + unlocalizedName.replace("trees.species.", ""); + if (StringUtil.canTranslate(customTreeKey)) { + return StringUtil.localize(customTreeKey); + } - String grammar = StringUtil.localize("trees.grammar.leaves"); - String localizedName = StatCollector.translateToLocal(unlocalizedName); + String grammar = StringUtil.localize("trees.grammar.leaves"); + String localizedName = StatCollector.translateToLocal(unlocalizedName); - return grammar.replaceAll("%SPECIES", localizedName).replaceAll("%TYPE", type); - } + return grammar.replaceAll("%SPECIES", localizedName).replaceAll("%TYPE", type); + } - @Override - public int getColorFromItemStack(ItemStack itemStack, int renderPass) { - if (!itemStack.hasTagCompound()) { - return PluginArboriculture.proxy.getFoliageColorBasic(); - } + @Override + public int getColorFromItemStack(ItemStack itemStack, int renderPass) { + if (!itemStack.hasTagCompound()) { + return PluginArboriculture.proxy.getFoliageColorBasic(); + } - TileLeaves tileLeaves = new TileLeaves(); - tileLeaves.readFromNBT(itemStack.getTagCompound()); + TileLeaves tileLeaves = new TileLeaves(); + tileLeaves.readFromNBT(itemStack.getTagCompound()); - return tileLeaves.getFoliageColour(Proxies.common.getPlayer()); - } + return tileLeaves.getFoliageColour(Proxies.common.getPlayer()); + } - @Override - public boolean placeBlockAt(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metadata) { - if (!itemStack.hasTagCompound()) { - return false; - } + @Override + public boolean placeBlockAt( + ItemStack itemStack, + EntityPlayer player, + World world, + int x, + int y, + int z, + int side, + float hitX, + float hitY, + float hitZ, + int metadata) { + if (!itemStack.hasTagCompound()) { + return false; + } - TileLeaves tileLeaves = new TileLeaves(); - tileLeaves.readFromNBT(itemStack.getTagCompound()); - tileLeaves.getTree().setLeavesDecorative(world, player.getGameProfile(), x, y, z); - - return true; - } + TileLeaves tileLeaves = new TileLeaves(); + tileLeaves.readFromNBT(itemStack.getTagCompound()); + tileLeaves.getTree().setLeavesDecorative(world, player.getGameProfile(), x, y, z); + return true; + } } diff --git a/src/main/java/forestry/arboriculture/items/ItemBlockWood.java b/src/main/java/forestry/arboriculture/items/ItemBlockWood.java index 57ad32bd2..4d27f9388 100644 --- a/src/main/java/forestry/arboriculture/items/ItemBlockWood.java +++ b/src/main/java/forestry/arboriculture/items/ItemBlockWood.java @@ -10,8 +10,17 @@ ******************************************************************************/ package forestry.arboriculture.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.arboriculture.EnumWoodType; +import forestry.arboriculture.IWoodTyped; +import forestry.arboriculture.blocks.BlockLog; +import forestry.arboriculture.render.IconProviderWood; +import forestry.arboriculture.tiles.TileWood; +import forestry.core.config.Constants; +import forestry.core.items.ItemBlockForestry; +import forestry.core.utils.StringUtil; import javax.annotation.Nullable; - import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; @@ -21,170 +30,179 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.arboriculture.IWoodTyped; -import forestry.arboriculture.blocks.BlockLog; -import forestry.arboriculture.render.IconProviderWood; -import forestry.arboriculture.tiles.TileWood; -import forestry.core.config.Constants; -import forestry.core.items.ItemBlockForestry; -import forestry.core.utils.StringUtil; - public class ItemBlockWood extends ItemBlockForestry { - private static final String LEGACY_WOOD_TYPE_KEY = "WoodType"; + private static final String LEGACY_WOOD_TYPE_KEY = "WoodType"; - public ItemBlockWood(Block block) { - super(block); - } + public ItemBlockWood(Block block) { + super(block); + } - public static boolean placeWood(ItemStack stack, @Nullable EntityPlayer player, World world, int x, int y, int z, int metadata) { - EnumWoodType woodType = getWoodType(stack); - Block block = Block.getBlockFromItem(stack.getItem()); + public static boolean placeWood( + ItemStack stack, @Nullable EntityPlayer player, World world, int x, int y, int z, int metadata) { + EnumWoodType woodType = getWoodType(stack); + Block block = Block.getBlockFromItem(stack.getItem()); - return placeWood(stack, woodType, block, player, world, x, y, z, metadata); - } + return placeWood(stack, woodType, block, player, world, x, y, z, metadata); + } - public static boolean placeWood(ItemStack stack, EnumWoodType woodType, Block block, @Nullable EntityPlayer player, World world, int x, int y, int z, int metadata) { - boolean placed = world.setBlock(x, y, z, block, metadata, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); - if (!placed) { - return false; - } + public static boolean placeWood( + ItemStack stack, + EnumWoodType woodType, + Block block, + @Nullable EntityPlayer player, + World world, + int x, + int y, + int z, + int metadata) { + boolean placed = world.setBlock(x, y, z, block, metadata, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); + if (!placed) { + return false; + } - Block worldBlock = world.getBlock(x, y, z); - if (!Block.isEqualTo(block, worldBlock)) { - return false; - } + Block worldBlock = world.getBlock(x, y, z); + if (!Block.isEqualTo(block, worldBlock)) { + return false; + } - TileEntity tile = world.getTileEntity(x, y, z); - if (!(tile instanceof TileWood)) { - world.setBlockToAir(x, y, z); - return false; - } + TileEntity tile = world.getTileEntity(x, y, z); + if (!(tile instanceof TileWood)) { + world.setBlockToAir(x, y, z); + return false; + } - if (player != null) { - worldBlock.onBlockPlacedBy(world, x, y, z, player, stack); - worldBlock.onPostBlockPlaced(world, x, y, z, metadata); - } + if (player != null) { + worldBlock.onBlockPlacedBy(world, x, y, z, player, stack); + worldBlock.onPostBlockPlaced(world, x, y, z, metadata); + } - ((TileWood) tile).setWoodType(woodType); - return true; - } + ((TileWood) tile).setWoodType(woodType); + return true; + } - public static void saveToItemStack(EnumWoodType woodType, ItemStack itemStack) { - int ordinal = woodType.ordinal(); - itemStack.setItemDamage(ordinal); - } + public static void saveToItemStack(EnumWoodType woodType, ItemStack itemStack) { + int ordinal = woodType.ordinal(); + itemStack.setItemDamage(ordinal); + } - public static EnumWoodType getWoodType(ItemStack stack) { - EnumWoodType woodType = convertLegacyWood(stack); - if (woodType == null) { - int typeOrdinal = stack.getItemDamage(); - woodType = getFromOrdinal(typeOrdinal); - } + public static EnumWoodType getWoodType(ItemStack stack) { + EnumWoodType woodType = convertLegacyWood(stack); + if (woodType == null) { + int typeOrdinal = stack.getItemDamage(); + woodType = getFromOrdinal(typeOrdinal); + } - return woodType; - } + return woodType; + } - // legacy handling of wood that has wood type saved to NBT - private static EnumWoodType convertLegacyWood(ItemStack itemStack) { - if (!itemStack.hasTagCompound()) { - return null; - } + // legacy handling of wood that has wood type saved to NBT + private static EnumWoodType convertLegacyWood(ItemStack itemStack) { + if (!itemStack.hasTagCompound()) { + return null; + } - NBTTagCompound compound = itemStack.getTagCompound(); - if (!compound.hasKey(LEGACY_WOOD_TYPE_KEY)) { - return null; - } + NBTTagCompound compound = itemStack.getTagCompound(); + if (!compound.hasKey(LEGACY_WOOD_TYPE_KEY)) { + return null; + } - int typeOrdinal = compound.getInteger(LEGACY_WOOD_TYPE_KEY); - EnumWoodType woodType = getFromOrdinal(typeOrdinal); - if (woodType != null) { - compound.removeTag(LEGACY_WOOD_TYPE_KEY); - if (compound.hasNoTags()) { - itemStack.setTagCompound(null); - } - saveToItemStack(woodType, itemStack); - } - return woodType; - } + int typeOrdinal = compound.getInteger(LEGACY_WOOD_TYPE_KEY); + EnumWoodType woodType = getFromOrdinal(typeOrdinal); + if (woodType != null) { + compound.removeTag(LEGACY_WOOD_TYPE_KEY); + if (compound.hasNoTags()) { + itemStack.setTagCompound(null); + } + saveToItemStack(woodType, itemStack); + } + return woodType; + } - @Override - public void onUpdate(ItemStack stack, World world, Entity player, int p_77663_4_, boolean p_77663_5_) { - super.onUpdate(stack, world, player, p_77663_4_, p_77663_5_); - convertLegacyWood(stack); - } + @Override + public void onUpdate(ItemStack stack, World world, Entity player, int p_77663_4_, boolean p_77663_5_) { + super.onUpdate(stack, world, player, p_77663_4_, p_77663_5_); + convertLegacyWood(stack); + } - private static EnumWoodType getFromOrdinal(int ordinal) { - if (ordinal >= 0 && ordinal < EnumWoodType.VALUES.length) { - return EnumWoodType.VALUES[ordinal]; - } - return EnumWoodType.LARCH; - } + private static EnumWoodType getFromOrdinal(int ordinal) { + if (ordinal >= 0 && ordinal < EnumWoodType.VALUES.length) { + return EnumWoodType.VALUES[ordinal]; + } + return EnumWoodType.LARCH; + } - @Override - public int getMetadata(int i) { - return 0; - } + @Override + public int getMetadata(int i) { + return 0; + } - @Override - public boolean placeBlockAt(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metadata) { - return placeWood(stack, player, world, x, y, z, metadata); - } + @Override + public boolean placeBlockAt( + ItemStack stack, + EntityPlayer player, + World world, + int x, + int y, + int z, + int side, + float hitX, + float hitY, + float hitZ, + int metadata) { + return placeWood(stack, player, world, x, y, z, metadata); + } - @Override - public String getItemStackDisplayName(ItemStack itemstack) { - Block block = getBlock(); - if (!(block instanceof IWoodTyped)) { - return super.getItemStackDisplayName(itemstack); - } + @Override + public String getItemStackDisplayName(ItemStack itemstack) { + Block block = getBlock(); + if (!(block instanceof IWoodTyped)) { + return super.getItemStackDisplayName(itemstack); + } - EnumWoodType woodType = getWoodType(itemstack); - if (woodType == null) { - return super.getItemStackDisplayName(itemstack); - } + EnumWoodType woodType = getWoodType(itemstack); + if (woodType == null) { + return super.getItemStackDisplayName(itemstack); + } - IWoodTyped wood = (IWoodTyped) block; - String blockKind = wood.getBlockKind(); + IWoodTyped wood = (IWoodTyped) block; + String blockKind = wood.getBlockKind(); - String displayName; - String customUnlocalizedName = blockKind + "." + woodType.ordinal() + ".name"; - if (StringUtil.canTranslateTile(customUnlocalizedName)) { - displayName = StringUtil.localizeTile(customUnlocalizedName); - } else { - String woodGrammar = StringUtil.localize(blockKind + ".grammar"); - String woodTypeName = StringUtil.localize("trees.woodType." + woodType); + String displayName; + String customUnlocalizedName = blockKind + "." + woodType.ordinal() + ".name"; + if (StringUtil.canTranslateTile(customUnlocalizedName)) { + displayName = StringUtil.localizeTile(customUnlocalizedName); + } else { + String woodGrammar = StringUtil.localize(blockKind + ".grammar"); + String woodTypeName = StringUtil.localize("trees.woodType." + woodType); - displayName = woodGrammar.replaceAll("%TYPE", woodTypeName); - } + displayName = woodGrammar.replaceAll("%TYPE", woodTypeName); + } - if (wood.isFireproof()) { - displayName = StringUtil.localizeAndFormatRaw("tile.for.fireproof", displayName); - } + if (wood.isFireproof()) { + displayName = StringUtil.localizeAndFormatRaw("tile.for.fireproof", displayName); + } - return displayName; - } + return displayName; + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(ItemStack stack, int pass) { - EnumWoodType woodType = getWoodType(stack); - if (woodType == null) { - return super.getIcon(stack, pass); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(ItemStack stack, int pass) { + EnumWoodType woodType = getWoodType(stack); + if (woodType == null) { + return super.getIcon(stack, pass); + } - if (getBlock() instanceof BlockLog) { - return IconProviderWood.getBarkIcon(woodType); - } else { - return IconProviderWood.getPlankIcon(woodType); - } - } + if (getBlock() instanceof BlockLog) { + return IconProviderWood.getBarkIcon(woodType); + } else { + return IconProviderWood.getPlankIcon(woodType); + } + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIconIndex(ItemStack stack) { - return getIcon(stack, 0); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIconIndex(ItemStack stack) { + return getIcon(stack, 0); + } } diff --git a/src/main/java/forestry/arboriculture/items/ItemBlockWoodSlab.java b/src/main/java/forestry/arboriculture/items/ItemBlockWoodSlab.java index 4d28b3c7b..262297b28 100644 --- a/src/main/java/forestry/arboriculture/items/ItemBlockWoodSlab.java +++ b/src/main/java/forestry/arboriculture/items/ItemBlockWoodSlab.java @@ -1,173 +1,194 @@ -package forestry.arboriculture.items; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.arboriculture.blocks.BlockSlab; -import forestry.arboriculture.tiles.TileWood; -import forestry.core.tiles.TileUtil; - -public class ItemBlockWoodSlab extends ItemBlockWood { - private final BlockSlab slab; - private final BlockSlab doubleSlab; - private final boolean isDoubleSlab; - - public ItemBlockWoodSlab(Block block, BlockSlab doubleSlab, BlockSlab slab) { - super(block); - this.doubleSlab = doubleSlab; - this.slab = slab; - this.isDoubleSlab = (block == doubleSlab); - } - - @Override - public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { - if (isDoubleSlab) { - return super.onItemUse(itemStack, player, world, x, y, z, side, hitX, hitY, hitZ); - } else if (itemStack.stackSize == 0) { - return false; - } else if (!player.canPlayerEdit(x, y, z, side, itemStack)) { - return false; - } else { - Block block = world.getBlock(x, y, z); - int i1 = world.getBlockMetadata(x, y, z); - boolean flag = (i1 & 8) != 0; - - EnumWoodType blockWoodType = null; - EnumWoodType stackWoodType = getWoodType(itemStack); - TileWood tile = TileUtil.getTile(world, x, y, z, TileWood.class); - if (tile != null) { - blockWoodType = tile.getWoodType(); - } - - if ((side == 1 && !flag || side == 0 && flag) && block == this.slab && blockWoodType == stackWoodType) { - if (world.checkNoEntityCollision(this.doubleSlab.getCollisionBoundingBoxFromPool(world, x, y, z))) { - if (placeWood(itemStack, stackWoodType, doubleSlab, player, world, x, y, z, 0)) { - world.playSoundEffect((double) ((float) x + 0.5F), (double) ((float) y + 0.5F), (double) ((float) z + 0.5F), this.doubleSlab.stepSound.func_150496_b(), (this.doubleSlab.stepSound.getVolume() + 1.0F) / 2.0F, this.doubleSlab.stepSound.getPitch() * 0.8F); - --itemStack.stackSize; - } - } - - return true; - } else { - if (this.func_150946_a(itemStack, player, world, x, y, z, side)) { - return true; - } else { - return super.onItemUse(itemStack, player, world, x, y, z, side, hitX, hitY, hitZ); - } - } - } - } - - @Override - @SideOnly(Side.CLIENT) - public boolean func_150936_a(World world, int x, int y, int z, int side, EntityPlayer player, ItemStack itemStack) { - int i1 = x; - int j1 = y; - int k1 = z; - Block block = world.getBlock(x, y, z); - int l1 = world.getBlockMetadata(x, y, z); - boolean flag = (l1 & 8) != 0; - - EnumWoodType blockWoodType = null; - EnumWoodType stackWoodType = getWoodType(itemStack); - TileWood tile = TileUtil.getTile(world, x, y, z, TileWood.class); - if (tile != null) { - blockWoodType = tile.getWoodType(); - } - - if ((side == 1 && !flag || side == 0 && flag) && block == this.slab && stackWoodType == blockWoodType) { - return true; - } else { - if (side == 0) { - --y; - } - - if (side == 1) { - ++y; - } - - if (side == 2) { - --z; - } - - if (side == 3) { - ++z; - } - - if (side == 4) { - --x; - } - - if (side == 5) { - ++x; - } - - Block block1 = world.getBlock(x, y, z); - tile = TileUtil.getTile(world, x, y, z, TileWood.class); - if (tile == null) { - blockWoodType = null; - } else { - blockWoodType = tile.getWoodType(); - } - - if (block1 == this.slab && stackWoodType == blockWoodType) { - return true; - } else { - return super.func_150936_a(world, i1, j1, k1, side, player, itemStack); - } - } - } - - private boolean func_150946_a(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side) { - if (side == 0) { - --y; - } - - if (side == 1) { - ++y; - } - - if (side == 2) { - --z; - } - - if (side == 3) { - ++z; - } - - if (side == 4) { - --x; - } - - if (side == 5) { - ++x; - } - - Block block = world.getBlock(x, y, z); - EnumWoodType blockWoodType = null; - EnumWoodType stackWoodType = getWoodType(itemStack); - TileWood tile = TileUtil.getTile(world, x, y, z, TileWood.class); - if (tile != null) { - blockWoodType = tile.getWoodType(); - } - - if (block == this.slab && blockWoodType == stackWoodType) { - if (world.checkNoEntityCollision(this.doubleSlab.getCollisionBoundingBoxFromPool(world, x, y, z))) { - if (placeWood(itemStack, stackWoodType, doubleSlab, player, world, x, y, z, 0)) { - world.playSoundEffect((double) ((float) x + 0.5F), (double) ((float) y + 0.5F), (double) ((float) z + 0.5F), this.doubleSlab.stepSound.func_150496_b(), (this.doubleSlab.stepSound.getVolume() + 1.0F) / 2.0F, this.doubleSlab.stepSound.getPitch() * 0.8F); - --itemStack.stackSize; - } - } - - return true; - } else { - return false; - } - } -} +package forestry.arboriculture.items; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.arboriculture.EnumWoodType; +import forestry.arboriculture.blocks.BlockSlab; +import forestry.arboriculture.tiles.TileWood; +import forestry.core.tiles.TileUtil; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; + +public class ItemBlockWoodSlab extends ItemBlockWood { + private final BlockSlab slab; + private final BlockSlab doubleSlab; + private final boolean isDoubleSlab; + + public ItemBlockWoodSlab(Block block, BlockSlab doubleSlab, BlockSlab slab) { + super(block); + this.doubleSlab = doubleSlab; + this.slab = slab; + this.isDoubleSlab = (block == doubleSlab); + } + + @Override + public boolean onItemUse( + ItemStack itemStack, + EntityPlayer player, + World world, + int x, + int y, + int z, + int side, + float hitX, + float hitY, + float hitZ) { + if (isDoubleSlab) { + return super.onItemUse(itemStack, player, world, x, y, z, side, hitX, hitY, hitZ); + } else if (itemStack.stackSize == 0) { + return false; + } else if (!player.canPlayerEdit(x, y, z, side, itemStack)) { + return false; + } else { + Block block = world.getBlock(x, y, z); + int i1 = world.getBlockMetadata(x, y, z); + boolean flag = (i1 & 8) != 0; + + EnumWoodType blockWoodType = null; + EnumWoodType stackWoodType = getWoodType(itemStack); + TileWood tile = TileUtil.getTile(world, x, y, z, TileWood.class); + if (tile != null) { + blockWoodType = tile.getWoodType(); + } + + if ((side == 1 && !flag || side == 0 && flag) && block == this.slab && blockWoodType == stackWoodType) { + if (world.checkNoEntityCollision(this.doubleSlab.getCollisionBoundingBoxFromPool(world, x, y, z))) { + if (placeWood(itemStack, stackWoodType, doubleSlab, player, world, x, y, z, 0)) { + world.playSoundEffect( + (double) ((float) x + 0.5F), + (double) ((float) y + 0.5F), + (double) ((float) z + 0.5F), + this.doubleSlab.stepSound.func_150496_b(), + (this.doubleSlab.stepSound.getVolume() + 1.0F) / 2.0F, + this.doubleSlab.stepSound.getPitch() * 0.8F); + --itemStack.stackSize; + } + } + + return true; + } else { + if (this.func_150946_a(itemStack, player, world, x, y, z, side)) { + return true; + } else { + return super.onItemUse(itemStack, player, world, x, y, z, side, hitX, hitY, hitZ); + } + } + } + } + + @Override + @SideOnly(Side.CLIENT) + public boolean func_150936_a(World world, int x, int y, int z, int side, EntityPlayer player, ItemStack itemStack) { + int i1 = x; + int j1 = y; + int k1 = z; + Block block = world.getBlock(x, y, z); + int l1 = world.getBlockMetadata(x, y, z); + boolean flag = (l1 & 8) != 0; + + EnumWoodType blockWoodType = null; + EnumWoodType stackWoodType = getWoodType(itemStack); + TileWood tile = TileUtil.getTile(world, x, y, z, TileWood.class); + if (tile != null) { + blockWoodType = tile.getWoodType(); + } + + if ((side == 1 && !flag || side == 0 && flag) && block == this.slab && stackWoodType == blockWoodType) { + return true; + } else { + if (side == 0) { + --y; + } + + if (side == 1) { + ++y; + } + + if (side == 2) { + --z; + } + + if (side == 3) { + ++z; + } + + if (side == 4) { + --x; + } + + if (side == 5) { + ++x; + } + + Block block1 = world.getBlock(x, y, z); + tile = TileUtil.getTile(world, x, y, z, TileWood.class); + if (tile == null) { + blockWoodType = null; + } else { + blockWoodType = tile.getWoodType(); + } + + if (block1 == this.slab && stackWoodType == blockWoodType) { + return true; + } else { + return super.func_150936_a(world, i1, j1, k1, side, player, itemStack); + } + } + } + + private boolean func_150946_a( + ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side) { + if (side == 0) { + --y; + } + + if (side == 1) { + ++y; + } + + if (side == 2) { + --z; + } + + if (side == 3) { + ++z; + } + + if (side == 4) { + --x; + } + + if (side == 5) { + ++x; + } + + Block block = world.getBlock(x, y, z); + EnumWoodType blockWoodType = null; + EnumWoodType stackWoodType = getWoodType(itemStack); + TileWood tile = TileUtil.getTile(world, x, y, z, TileWood.class); + if (tile != null) { + blockWoodType = tile.getWoodType(); + } + + if (block == this.slab && blockWoodType == stackWoodType) { + if (world.checkNoEntityCollision(this.doubleSlab.getCollisionBoundingBoxFromPool(world, x, y, z))) { + if (placeWood(itemStack, stackWoodType, doubleSlab, player, world, x, y, z, 0)) { + world.playSoundEffect( + (double) ((float) x + 0.5F), + (double) ((float) y + 0.5F), + (double) ((float) z + 0.5F), + this.doubleSlab.stepSound.func_150496_b(), + (this.doubleSlab.stepSound.getVolume() + 1.0F) / 2.0F, + this.doubleSlab.stepSound.getPitch() * 0.8F); + --itemStack.stackSize; + } + } + + return true; + } else { + return false; + } + } +} diff --git a/src/main/java/forestry/arboriculture/items/ItemGermlingGE.java b/src/main/java/forestry/arboriculture/items/ItemGermlingGE.java index 74b97a2b1..08b8e73dc 100755 --- a/src/main/java/forestry/arboriculture/items/ItemGermlingGE.java +++ b/src/main/java/forestry/arboriculture/items/ItemGermlingGE.java @@ -10,18 +10,8 @@ ******************************************************************************/ package forestry.arboriculture.items; -import java.util.List; - -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.arboriculture.ITree; @@ -43,177 +33,204 @@ import forestry.core.render.SpriteSheet; import forestry.core.utils.BlockUtil; import forestry.core.utils.GeneticsUtil; import forestry.core.utils.StringUtil; +import java.util.List; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; public class ItemGermlingGE extends ItemGE implements IVariableFermentable { - private final EnumGermlingType type; + private final EnumGermlingType type; - public ItemGermlingGE(EnumGermlingType type) { - super(Tabs.tabArboriculture); - this.type = type; - } + public ItemGermlingGE(EnumGermlingType type) { + super(Tabs.tabArboriculture); + this.type = type; + } - @Override - public ITree getIndividual(ItemStack itemstack) { - return new Tree(itemstack.getTagCompound()); - } + @Override + public ITree getIndividual(ItemStack itemstack) { + return new Tree(itemstack.getTagCompound()); + } - @Override - protected IAlleleTreeSpecies getSpecies(ItemStack itemStack) { - return TreeGenome.getSpecies(itemStack); - } + @Override + protected IAlleleTreeSpecies getSpecies(ItemStack itemStack) { + return TreeGenome.getSpecies(itemStack); + } - private static IAlleleTreeSpecies getSpeciesOrDefault(ItemStack itemstack) { - IAlleleTreeSpecies treeSpecies = TreeGenome.getSpecies(itemstack); - if (treeSpecies == null) { - treeSpecies = TreeDefinition.Oak.getGenome().getPrimary(); - } + private static IAlleleTreeSpecies getSpeciesOrDefault(ItemStack itemstack) { + IAlleleTreeSpecies treeSpecies = TreeGenome.getSpecies(itemstack); + if (treeSpecies == null) { + treeSpecies = TreeDefinition.Oak.getGenome().getPrimary(); + } - return treeSpecies; - } + return treeSpecies; + } - @Override - protected int getDefaultPrimaryColour() { - return 0; - } + @Override + protected int getDefaultPrimaryColour() { + return 0; + } - @Override - protected int getDefaultSecondaryColour() { - return 0; - } + @Override + protected int getDefaultSecondaryColour() { + return 0; + } - @Override - public String getItemStackDisplayName(ItemStack itemstack) { - if (!itemstack.hasTagCompound()) { - return "Unknown"; - } - IAlleleSpecies species = getSpecies(itemstack); + @Override + public String getItemStackDisplayName(ItemStack itemstack) { + if (!itemstack.hasTagCompound()) { + return "Unknown"; + } + IAlleleSpecies species = getSpecies(itemstack); - String customTreeKey = "trees.custom." + type.getName() + "." + species.getUnlocalizedName().replace("trees.species.", ""); - if (StringUtil.canTranslate(customTreeKey)) { - return StringUtil.localize(customTreeKey); - } - return StringUtil.localize("trees.grammar." + type.getName()).replaceAll("%SPECIES", species.getName()).replaceAll("%TYPE", StringUtil.localize("trees.grammar." + type.getName() + ".type")); - } + String customTreeKey = "trees.custom." + type.getName() + "." + + species.getUnlocalizedName().replace("trees.species.", ""); + if (StringUtil.canTranslate(customTreeKey)) { + return StringUtil.localize(customTreeKey); + } + return StringUtil.localize("trees.grammar." + type.getName()) + .replaceAll("%SPECIES", species.getName()) + .replaceAll("%TYPE", StringUtil.localize("trees.grammar." + type.getName() + ".type")); + } - @SuppressWarnings("rawtypes") - @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - addCreativeItems(itemList, true); - } + @SuppressWarnings("rawtypes") + @Override + public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + addCreativeItems(itemList, true); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - public void addCreativeItems(List itemList, boolean hideSecrets) { - for (IIndividual individual : TreeManager.treeRoot.getIndividualTemplates()) { - // Don't show secrets unless ordered to. - if (hideSecrets && individual.isSecret() && !Config.isDebug) { - continue; - } + @SuppressWarnings({"rawtypes", "unchecked"}) + public void addCreativeItems(List itemList, boolean hideSecrets) { + for (IIndividual individual : TreeManager.treeRoot.getIndividualTemplates()) { + // Don't show secrets unless ordered to. + if (hideSecrets && individual.isSecret() && !Config.isDebug) { + continue; + } - itemList.add(TreeManager.treeRoot.getMemberStack(individual, type.ordinal())); - } - } + itemList.add(TreeManager.treeRoot.getMemberStack(individual, type.ordinal())); + } + } - @Override - public int getColorFromItemStack(ItemStack itemstack, int renderPass) { - return getSpeciesOrDefault(itemstack).getGermlingColour(type, renderPass); - } + @Override + public int getColorFromItemStack(ItemStack itemstack, int renderPass) { + return getSpeciesOrDefault(itemstack).getGermlingColour(type, renderPass); + } - /* ICONS */ - @Override - public boolean requiresMultipleRenderPasses() { - return true; - } + /* ICONS */ + @Override + public boolean requiresMultipleRenderPasses() { + return true; + } - @Override - public int getRenderPasses(int metadata) { - return 2; - } + @Override + public int getRenderPasses(int metadata) { + return 2; + } - @Override - public int getSpriteNumber() { - return SpriteSheet.BLOCKS.getSheetOrdinal(); - } + @Override + public int getSpriteNumber() { + return SpriteSheet.BLOCKS.getSheetOrdinal(); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(ItemStack itemstack, int renderPass) { - IAlleleTreeSpecies species = getSpeciesOrDefault(itemstack); - return species.getGermlingIcon(type, renderPass); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(ItemStack itemstack, int renderPass) { + IAlleleTreeSpecies species = getSpeciesOrDefault(itemstack); + return species.getGermlingIcon(type, renderPass); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIconIndex(ItemStack stack) { - return getIcon(stack, 0); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIconIndex(ItemStack stack) { + return getIcon(stack, 0); + } - @Override - public boolean onItemUse(ItemStack itemstack, EntityPlayer player, World world, int x, int y, int z, int par7, float facingX, float facingY, float facingZ) { - ITree tree = TreeManager.treeRoot.getMember(itemstack); - if (tree == null) { - return false; - } + @Override + public boolean onItemUse( + ItemStack itemstack, + EntityPlayer player, + World world, + int x, + int y, + int z, + int par7, + float facingX, + float facingY, + float facingZ) { + ITree tree = TreeManager.treeRoot.getMember(itemstack); + if (tree == null) { + return false; + } - if (type == EnumGermlingType.SAPLING) { - // x, y, z are the coordinates of the block "hit", can thus either be the soil or tall grass, etc. - int yShift; - if (!BlockUtil.isReplaceableBlock(world, x, y, z)) { - if (!world.isAirBlock(x, y + 1, z)) { - return false; - } - yShift = 1; - } else { - yShift = 0; - } + if (type == EnumGermlingType.SAPLING) { + // x, y, z are the coordinates of the block "hit", can thus either be the soil or tall grass, etc. + int yShift; + if (!BlockUtil.isReplaceableBlock(world, x, y, z)) { + if (!world.isAirBlock(x, y + 1, z)) { + return false; + } + yShift = 1; + } else { + yShift = 0; + } - if (!tree.canStay(world, x, y + yShift, z)) { - return false; - } + if (!tree.canStay(world, x, y + yShift, z)) { + return false; + } - if (TreeManager.treeRoot.plantSapling(world, tree, player.getGameProfile(), x, y + yShift, z)) { - Proxies.common.addBlockPlaceEffects(world, x, y, z, world.getBlock(x, y + yShift, z), 0); - if (!player.capabilities.isCreativeMode) { - itemstack.stackSize--; - } - return true; - } else { - return false; - } - } else if (type == EnumGermlingType.POLLEN) { + if (TreeManager.treeRoot.plantSapling(world, tree, player.getGameProfile(), x, y + yShift, z)) { + Proxies.common.addBlockPlaceEffects(world, x, y, z, world.getBlock(x, y + yShift, z), 0); + if (!player.capabilities.isCreativeMode) { + itemstack.stackSize--; + } + return true; + } else { + return false; + } + } else if (type == EnumGermlingType.POLLEN) { - ICheckPollinatable checkPollinatable = GeneticsUtil.getCheckPollinatable(world, x, y, z); + ICheckPollinatable checkPollinatable = GeneticsUtil.getCheckPollinatable(world, x, y, z); - if (checkPollinatable == null || !checkPollinatable.canMateWith(tree)) { - return false; - } + if (checkPollinatable == null || !checkPollinatable.canMateWith(tree)) { + return false; + } - IPollinatable pollinatable = GeneticsUtil.getOrCreatePollinatable(player.getGameProfile(), world, x, y, z); + IPollinatable pollinatable = GeneticsUtil.getOrCreatePollinatable(player.getGameProfile(), world, x, y, z); - if (pollinatable == null || !pollinatable.canMateWith(tree)) { - return false; - } + if (pollinatable == null || !pollinatable.canMateWith(tree)) { + return false; + } - pollinatable.mateWith(tree); - Proxies.common.sendFXSignal(PacketFXSignal.VisualFXType.BLOCK_DESTROY, PacketFXSignal.SoundFXType.LEAF, world, x, y, z, - world.getBlock(x, y, z), 0); - if (!player.capabilities.isCreativeMode) { - itemstack.stackSize--; - } - return true; + pollinatable.mateWith(tree); + Proxies.common.sendFXSignal( + PacketFXSignal.VisualFXType.BLOCK_DESTROY, + PacketFXSignal.SoundFXType.LEAF, + world, + x, + y, + z, + world.getBlock(x, y, z), + 0); + if (!player.capabilities.isCreativeMode) { + itemstack.stackSize--; + } + return true; - } else { - return false; - } - } + } else { + return false; + } + } - @Override - public float getFermentationModifier(ItemStack itemstack) { - ITree tree = TreeManager.treeRoot.getMember(itemstack); - if (tree == null) { - return 1.0f; - } + @Override + public float getFermentationModifier(ItemStack itemstack) { + ITree tree = TreeManager.treeRoot.getMember(itemstack); + if (tree == null) { + return 1.0f; + } - return tree.getGenome().getSappiness() * 10; - } + return tree.getGenome().getSappiness() * 10; + } } diff --git a/src/main/java/forestry/arboriculture/items/ItemGrafter.java b/src/main/java/forestry/arboriculture/items/ItemGrafter.java index da5113a10..001c1388f 100755 --- a/src/main/java/forestry/arboriculture/items/ItemGrafter.java +++ b/src/main/java/forestry/arboriculture/items/ItemGrafter.java @@ -10,6 +10,9 @@ ******************************************************************************/ package forestry.arboriculture.items; +import forestry.api.arboriculture.IToolGrafter; +import forestry.api.core.Tabs; +import forestry.core.items.ItemForestryTool; import net.minecraft.block.Block; import net.minecraft.block.BlockLeaves; import net.minecraft.block.material.Material; @@ -18,36 +21,33 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import forestry.api.arboriculture.IToolGrafter; -import forestry.api.core.Tabs; -import forestry.core.items.ItemForestryTool; - public class ItemGrafter extends ItemForestryTool implements IToolGrafter { - public ItemGrafter(int maxDamage) { - super(null); - setMaxDamage(maxDamage); - setMaxStackSize(1); - setCreativeTab(Tabs.tabArboriculture); - setHarvestLevel("grafter", 3); - setEfficiencyOnProperMaterial(4.0f); - } + public ItemGrafter(int maxDamage) { + super(null); + setMaxDamage(maxDamage); + setMaxStackSize(1); + setCreativeTab(Tabs.tabArboriculture); + setHarvestLevel("grafter", 3); + setEfficiencyOnProperMaterial(4.0f); + } - @Override - public boolean canHarvestBlock(Block block, ItemStack itemStack) { - if (block instanceof BlockLeaves || block.getMaterial() == Material.leaves) { - return true; - } - return super.canHarvestBlock(block, itemStack); - } + @Override + public boolean canHarvestBlock(Block block, ItemStack itemStack) { + if (block instanceof BlockLeaves || block.getMaterial() == Material.leaves) { + return true; + } + return super.canHarvestBlock(block, itemStack); + } - @Override - public boolean onBlockDestroyed(ItemStack itemstack, World world, Block block, int j, int k, int l, EntityLivingBase entityliving) { - // damage is done by the harvested leaves - return true; - } + @Override + public boolean onBlockDestroyed( + ItemStack itemstack, World world, Block block, int j, int k, int l, EntityLivingBase entityliving) { + // damage is done by the harvested leaves + return true; + } - @Override - public float getSaplingModifier(ItemStack stack, World world, EntityPlayer player, int x, int y, int z) { - return 100f; - } + @Override + public float getSaplingModifier(ItemStack stack, World world, EntityPlayer player, int x, int y, int z) { + return 100f; + } } diff --git a/src/main/java/forestry/arboriculture/items/ItemRegistryArboriculture.java b/src/main/java/forestry/arboriculture/items/ItemRegistryArboriculture.java index 227c0d44c..dfbb9c1bd 100644 --- a/src/main/java/forestry/arboriculture/items/ItemRegistryArboriculture.java +++ b/src/main/java/forestry/arboriculture/items/ItemRegistryArboriculture.java @@ -1,34 +1,33 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.items; - -import net.minecraftforge.oredict.OreDictionary; - -import forestry.api.arboriculture.EnumGermlingType; -import forestry.core.items.ItemRegistry; - -public class ItemRegistryArboriculture extends ItemRegistry { - public final ItemGermlingGE sapling; - public final ItemGermlingGE pollenFertile; - public final ItemTreealyzer treealyzer; - public final ItemGrafter grafter; - public final ItemGrafter grafterProven; - - public ItemRegistryArboriculture() { - sapling = registerItem(new ItemGermlingGE(EnumGermlingType.SAPLING), "sapling"); - OreDictionary.registerOre("treeSapling", sapling.getWildcard()); - - pollenFertile = registerItem(new ItemGermlingGE(EnumGermlingType.POLLEN), "pollenFertile"); - treealyzer = registerItem(new ItemTreealyzer(), "treealyzer"); - grafter = registerItem(new ItemGrafter(4), "grafter"); - grafterProven = registerItem(new ItemGrafter(149), "grafterProven"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.items; + +import forestry.api.arboriculture.EnumGermlingType; +import forestry.core.items.ItemRegistry; +import net.minecraftforge.oredict.OreDictionary; + +public class ItemRegistryArboriculture extends ItemRegistry { + public final ItemGermlingGE sapling; + public final ItemGermlingGE pollenFertile; + public final ItemTreealyzer treealyzer; + public final ItemGrafter grafter; + public final ItemGrafter grafterProven; + + public ItemRegistryArboriculture() { + sapling = registerItem(new ItemGermlingGE(EnumGermlingType.SAPLING), "sapling"); + OreDictionary.registerOre("treeSapling", sapling.getWildcard()); + + pollenFertile = registerItem(new ItemGermlingGE(EnumGermlingType.POLLEN), "pollenFertile"); + treealyzer = registerItem(new ItemTreealyzer(), "treealyzer"); + grafter = registerItem(new ItemGrafter(4), "grafter"); + grafterProven = registerItem(new ItemGrafter(149), "grafterProven"); + } +} diff --git a/src/main/java/forestry/arboriculture/items/ItemTreealyzer.java b/src/main/java/forestry/arboriculture/items/ItemTreealyzer.java index 19a56d175..39918aa55 100644 --- a/src/main/java/forestry/arboriculture/items/ItemTreealyzer.java +++ b/src/main/java/forestry/arboriculture/items/ItemTreealyzer.java @@ -1,36 +1,35 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.items; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.api.core.Tabs; -import forestry.arboriculture.gui.GuiTreealyzer; -import forestry.arboriculture.inventory.ItemInventoryTreealyzer; -import forestry.core.gui.ContainerAlyzer; -import forestry.core.items.ItemWithGui; - -public class ItemTreealyzer extends ItemWithGui { - public ItemTreealyzer() { - setCreativeTab(Tabs.tabArboriculture); - } - - @Override - public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { - return new GuiTreealyzer(player, new ItemInventoryTreealyzer(player, heldItem)); - } - - @Override - public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { - return new ContainerAlyzer(new ItemInventoryTreealyzer(player, heldItem), player); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.items; + +import forestry.api.core.Tabs; +import forestry.arboriculture.gui.GuiTreealyzer; +import forestry.arboriculture.inventory.ItemInventoryTreealyzer; +import forestry.core.gui.ContainerAlyzer; +import forestry.core.items.ItemWithGui; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class ItemTreealyzer extends ItemWithGui { + public ItemTreealyzer() { + setCreativeTab(Tabs.tabArboriculture); + } + + @Override + public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { + return new GuiTreealyzer(player, new ItemInventoryTreealyzer(player, heldItem)); + } + + @Override + public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { + return new ContainerAlyzer(new ItemInventoryTreealyzer(player, heldItem), player); + } +} diff --git a/src/main/java/forestry/arboriculture/network/IRipeningPacketReceiver.java b/src/main/java/forestry/arboriculture/network/IRipeningPacketReceiver.java index 6ec779e22..c6ffd1188 100644 --- a/src/main/java/forestry/arboriculture/network/IRipeningPacketReceiver.java +++ b/src/main/java/forestry/arboriculture/network/IRipeningPacketReceiver.java @@ -1,15 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.network; - -public interface IRipeningPacketReceiver { - void fromRipeningPacket(int ripeningValue); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.network; + +public interface IRipeningPacketReceiver { + void fromRipeningPacket(int ripeningValue); +} diff --git a/src/main/java/forestry/arboriculture/network/PacketRegistryArboriculture.java b/src/main/java/forestry/arboriculture/network/PacketRegistryArboriculture.java index a217bf55a..e64a3d3e9 100644 --- a/src/main/java/forestry/arboriculture/network/PacketRegistryArboriculture.java +++ b/src/main/java/forestry/arboriculture/network/PacketRegistryArboriculture.java @@ -1,21 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.network; - -import forestry.arboriculture.network.packets.PacketRipeningUpdate; -import forestry.core.network.PacketRegistry; - -public class PacketRegistryArboriculture extends PacketRegistry { - @Override - public void registerPackets() { - registerClientPacket(new PacketRipeningUpdate()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.network; + +import forestry.arboriculture.network.packets.PacketRipeningUpdate; +import forestry.core.network.PacketRegistry; + +public class PacketRegistryArboriculture extends PacketRegistry { + @Override + public void registerPackets() { + registerClientPacket(new PacketRipeningUpdate()); + } +} diff --git a/src/main/java/forestry/arboriculture/network/packets/PacketRipeningUpdate.java b/src/main/java/forestry/arboriculture/network/packets/PacketRipeningUpdate.java index 967ff814c..c91b3a583 100644 --- a/src/main/java/forestry/arboriculture/network/packets/PacketRipeningUpdate.java +++ b/src/main/java/forestry/arboriculture/network/packets/PacketRipeningUpdate.java @@ -1,69 +1,66 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.arboriculture.network.IRipeningPacketReceiver; -import forestry.arboriculture.tiles.TileFruitPod; -import forestry.arboriculture.tiles.TileLeaves; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.core.proxy.Proxies; - -public class PacketRipeningUpdate extends PacketCoordinates implements IForestryPacketClient { - - private int value; - - public PacketRipeningUpdate() { - } - - public PacketRipeningUpdate(TileFruitPod fruitPod) { - super(fruitPod); - value = fruitPod.getMaturity(); - } - - public PacketRipeningUpdate(TileLeaves leaves) { - super(leaves); - value = leaves.getFruitColour(); - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.RIPENING_UPDATE; - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeVarInt(value); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - value = data.readVarInt(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IRipeningPacketReceiver) { - ((IRipeningPacketReceiver) tile).fromRipeningPacket(value); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.network.packets; + +import forestry.arboriculture.network.IRipeningPacketReceiver; +import forestry.arboriculture.tiles.TileFruitPod; +import forestry.arboriculture.tiles.TileLeaves; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.network.packets.PacketCoordinates; +import forestry.core.proxy.Proxies; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; + +public class PacketRipeningUpdate extends PacketCoordinates implements IForestryPacketClient { + + private int value; + + public PacketRipeningUpdate() {} + + public PacketRipeningUpdate(TileFruitPod fruitPod) { + super(fruitPod); + value = fruitPod.getMaturity(); + } + + public PacketRipeningUpdate(TileLeaves leaves) { + super(leaves); + value = leaves.getFruitColour(); + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.RIPENING_UPDATE; + } + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeVarInt(value); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + value = data.readVarInt(); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof IRipeningPacketReceiver) { + ((IRipeningPacketReceiver) tile).fromRipeningPacket(value); + } + } +} diff --git a/src/main/java/forestry/arboriculture/proxy/ProxyArboriculture.java b/src/main/java/forestry/arboriculture/proxy/ProxyArboriculture.java index e6df896af..e2706691a 100755 --- a/src/main/java/forestry/arboriculture/proxy/ProxyArboriculture.java +++ b/src/main/java/forestry/arboriculture/proxy/ProxyArboriculture.java @@ -12,19 +12,17 @@ package forestry.arboriculture.proxy; public class ProxyArboriculture { - public void initializeRendering() { - } + public void initializeRendering() {} - public int getFoliageColorBasic() { - return 4764952; - } + public int getFoliageColorBasic() { + return 4764952; + } - public int getFoliageColorBirch() { - return 8431445; - } - - public int getFoliageColorPine() { - return 6396257; - } + public int getFoliageColorBirch() { + return 8431445; + } + public int getFoliageColorPine() { + return 6396257; + } } diff --git a/src/main/java/forestry/arboriculture/proxy/ProxyArboricultureClient.java b/src/main/java/forestry/arboriculture/proxy/ProxyArboricultureClient.java index 5f96ec7d1..184805dee 100644 --- a/src/main/java/forestry/arboriculture/proxy/ProxyArboricultureClient.java +++ b/src/main/java/forestry/arboriculture/proxy/ProxyArboricultureClient.java @@ -10,15 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.proxy; -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.world.ColorizerFoliage; - -import net.minecraftforge.client.IItemRenderer; -import net.minecraftforge.client.MinecraftForgeClient; - import cpw.mods.fml.client.registry.RenderingRegistry; - import forestry.arboriculture.render.RenderFenceItem; import forestry.arboriculture.render.RenderFruitPodBlock; import forestry.arboriculture.render.RenderLeavesBlock; @@ -29,53 +21,58 @@ import forestry.arboriculture.render.RenderSaplingBlock; import forestry.arboriculture.render.RenderSlabItem; import forestry.arboriculture.render.RenderStairItem; import forestry.plugins.PluginArboriculture; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.world.ColorizerFoliage; +import net.minecraftforge.client.IItemRenderer; +import net.minecraftforge.client.MinecraftForgeClient; public class ProxyArboricultureClient extends ProxyArboriculture { - @Override - public void initializeRendering() { - PluginArboriculture.modelIdSaplings = RenderingRegistry.getNextAvailableRenderId(); - PluginArboriculture.modelIdLeaves = RenderingRegistry.getNextAvailableRenderId(); - PluginArboriculture.modelIdPods = RenderingRegistry.getNextAvailableRenderId(); + @Override + public void initializeRendering() { + PluginArboriculture.modelIdSaplings = RenderingRegistry.getNextAvailableRenderId(); + PluginArboriculture.modelIdLeaves = RenderingRegistry.getNextAvailableRenderId(); + PluginArboriculture.modelIdPods = RenderingRegistry.getNextAvailableRenderId(); - RenderingRegistry.registerBlockHandler(new RenderSaplingBlock()); - RenderingRegistry.registerBlockHandler(new RenderLeavesBlock()); - RenderingRegistry.registerBlockHandler(new RenderFruitPodBlock()); + RenderingRegistry.registerBlockHandler(new RenderSaplingBlock()); + RenderingRegistry.registerBlockHandler(new RenderLeavesBlock()); + RenderingRegistry.registerBlockHandler(new RenderFruitPodBlock()); - registerItemRenderer(PluginArboriculture.blocks.logs, new RenderLogItem()); - registerItemRenderer(PluginArboriculture.blocks.logsFireproof, new RenderLogItem()); + registerItemRenderer(PluginArboriculture.blocks.logs, new RenderLogItem()); + registerItemRenderer(PluginArboriculture.blocks.logsFireproof, new RenderLogItem()); - registerItemRenderer(PluginArboriculture.blocks.stairs, new RenderStairItem()); - registerItemRenderer(PluginArboriculture.blocks.stairsFireproof, new RenderStairItem()); + registerItemRenderer(PluginArboriculture.blocks.stairs, new RenderStairItem()); + registerItemRenderer(PluginArboriculture.blocks.stairsFireproof, new RenderStairItem()); - registerItemRenderer(PluginArboriculture.blocks.planks, new RenderPlankItem()); - registerItemRenderer(PluginArboriculture.blocks.planksFireproof, new RenderPlankItem()); + registerItemRenderer(PluginArboriculture.blocks.planks, new RenderPlankItem()); + registerItemRenderer(PluginArboriculture.blocks.planksFireproof, new RenderPlankItem()); - registerItemRenderer(PluginArboriculture.blocks.slabs, new RenderSlabItem()); - registerItemRenderer(PluginArboriculture.blocks.slabsFireproof, new RenderSlabItem()); + registerItemRenderer(PluginArboriculture.blocks.slabs, new RenderSlabItem()); + registerItemRenderer(PluginArboriculture.blocks.slabsFireproof, new RenderSlabItem()); - registerItemRenderer(PluginArboriculture.blocks.fences, new RenderFenceItem()); - registerItemRenderer(PluginArboriculture.blocks.fencesFireproof, new RenderFenceItem()); + registerItemRenderer(PluginArboriculture.blocks.fences, new RenderFenceItem()); + registerItemRenderer(PluginArboriculture.blocks.fencesFireproof, new RenderFenceItem()); - registerItemRenderer(PluginArboriculture.blocks.leaves, new RenderLeavesItem()); - } + registerItemRenderer(PluginArboriculture.blocks.leaves, new RenderLeavesItem()); + } - private static void registerItemRenderer(Block block, IItemRenderer renderer) { - Item item = Item.getItemFromBlock(block); - MinecraftForgeClient.registerItemRenderer(item, renderer); - } + private static void registerItemRenderer(Block block, IItemRenderer renderer) { + Item item = Item.getItemFromBlock(block); + MinecraftForgeClient.registerItemRenderer(item, renderer); + } - @Override - public int getFoliageColorBasic() { - return ColorizerFoliage.getFoliageColorBasic(); - } + @Override + public int getFoliageColorBasic() { + return ColorizerFoliage.getFoliageColorBasic(); + } - @Override - public int getFoliageColorBirch() { - return ColorizerFoliage.getFoliageColorBirch(); - } + @Override + public int getFoliageColorBirch() { + return ColorizerFoliage.getFoliageColorBirch(); + } - @Override - public int getFoliageColorPine() { - return ColorizerFoliage.getFoliageColorPine(); - } + @Override + public int getFoliageColorPine() { + return ColorizerFoliage.getFoliageColorPine(); + } } diff --git a/src/main/java/forestry/arboriculture/render/IconProviderGermling.java b/src/main/java/forestry/arboriculture/render/IconProviderGermling.java index 0d3da9e1b..ac7d87c0f 100644 --- a/src/main/java/forestry/arboriculture/render/IconProviderGermling.java +++ b/src/main/java/forestry/arboriculture/render/IconProviderGermling.java @@ -1,47 +1,46 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.render; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.util.IIcon; - -import forestry.api.arboriculture.EnumGermlingType; -import forestry.api.arboriculture.IGermlingIconProvider; -import forestry.core.render.TextureManager; - -public class IconProviderGermling implements IGermlingIconProvider { - - private final String name; - - private IIcon icon; - private IIcon[] pollenIcons; - - public IconProviderGermling(String uid) { - this.name = uid.substring("forestry.".length()); - } - - @Override - public void registerIcons(IIconRegister register) { - icon = TextureManager.registerTex(register, "germlings/sapling." + name); - pollenIcons = new IIcon[2]; - pollenIcons[0] = TextureManager.registerTex(register, "germlings/pollen.0"); - pollenIcons[1] = TextureManager.registerTex(register, "germlings/pollen.1"); - } - - @Override - public IIcon getIcon(EnumGermlingType type, int renderPass) { - if (type == EnumGermlingType.POLLEN) { - return pollenIcons[renderPass]; - } - - return icon; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.render; + +import forestry.api.arboriculture.EnumGermlingType; +import forestry.api.arboriculture.IGermlingIconProvider; +import forestry.core.render.TextureManager; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.util.IIcon; + +public class IconProviderGermling implements IGermlingIconProvider { + + private final String name; + + private IIcon icon; + private IIcon[] pollenIcons; + + public IconProviderGermling(String uid) { + this.name = uid.substring("forestry.".length()); + } + + @Override + public void registerIcons(IIconRegister register) { + icon = TextureManager.registerTex(register, "germlings/sapling." + name); + pollenIcons = new IIcon[2]; + pollenIcons[0] = TextureManager.registerTex(register, "germlings/pollen.0"); + pollenIcons[1] = TextureManager.registerTex(register, "germlings/pollen.1"); + } + + @Override + public IIcon getIcon(EnumGermlingType type, int renderPass) { + if (type == EnumGermlingType.POLLEN) { + return pollenIcons[renderPass]; + } + + return icon; + } +} diff --git a/src/main/java/forestry/arboriculture/render/IconProviderGermlingVanilla.java b/src/main/java/forestry/arboriculture/render/IconProviderGermlingVanilla.java index 95440e410..9ee9f1e15 100644 --- a/src/main/java/forestry/arboriculture/render/IconProviderGermlingVanilla.java +++ b/src/main/java/forestry/arboriculture/render/IconProviderGermlingVanilla.java @@ -1,47 +1,46 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.render; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.init.Blocks; -import net.minecraft.util.IIcon; - -import forestry.api.arboriculture.EnumGermlingType; -import forestry.api.arboriculture.IGermlingIconProvider; -import forestry.core.render.TextureManager; - -public class IconProviderGermlingVanilla implements IGermlingIconProvider { - private final int vanillaMap; - - private IIcon icon; - private IIcon[] pollenIcons; - - public IconProviderGermlingVanilla(int vanillaMap) { - this.vanillaMap = vanillaMap; - } - - @Override - public void registerIcons(IIconRegister register) { - icon = Blocks.sapling.getIcon(0, vanillaMap); - pollenIcons = new IIcon[2]; - pollenIcons[0] = TextureManager.registerTex(register, "germlings/pollen.0"); - pollenIcons[1] = TextureManager.registerTex(register, "germlings/pollen.1"); - } - - @Override - public IIcon getIcon(EnumGermlingType type, int renderPass) { - if (type == EnumGermlingType.POLLEN) { - return pollenIcons[renderPass]; - } - - return icon; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.render; + +import forestry.api.arboriculture.EnumGermlingType; +import forestry.api.arboriculture.IGermlingIconProvider; +import forestry.core.render.TextureManager; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.init.Blocks; +import net.minecraft.util.IIcon; + +public class IconProviderGermlingVanilla implements IGermlingIconProvider { + private final int vanillaMap; + + private IIcon icon; + private IIcon[] pollenIcons; + + public IconProviderGermlingVanilla(int vanillaMap) { + this.vanillaMap = vanillaMap; + } + + @Override + public void registerIcons(IIconRegister register) { + icon = Blocks.sapling.getIcon(0, vanillaMap); + pollenIcons = new IIcon[2]; + pollenIcons[0] = TextureManager.registerTex(register, "germlings/pollen.0"); + pollenIcons[1] = TextureManager.registerTex(register, "germlings/pollen.1"); + } + + @Override + public IIcon getIcon(EnumGermlingType type, int renderPass) { + if (type == EnumGermlingType.POLLEN) { + return pollenIcons[renderPass]; + } + + return icon; + } +} diff --git a/src/main/java/forestry/arboriculture/render/IconProviderLeaves.java b/src/main/java/forestry/arboriculture/render/IconProviderLeaves.java index 9b0112777..41b0d949c 100644 --- a/src/main/java/forestry/arboriculture/render/IconProviderLeaves.java +++ b/src/main/java/forestry/arboriculture/render/IconProviderLeaves.java @@ -1,53 +1,49 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.render; - -import java.awt.Color; - -import net.minecraft.util.IIcon; - -import forestry.api.arboriculture.EnumLeafType; -import forestry.api.arboriculture.ILeafIconProvider; - -public class IconProviderLeaves implements ILeafIconProvider { - - private final TextureLeaves leafTexture; - private final int color; - private final int colorPollinated; - - public IconProviderLeaves(EnumLeafType leafType, Color color, Color colorPollinated) { - this.leafTexture = TextureLeaves.get(leafType); - this.color = color.getRGB(); - this.colorPollinated = colorPollinated.getRGB(); - } - - @Override - public int getColor(boolean pollinated) { - if (pollinated) { - return colorPollinated; - } else { - return color; - } - } - - @Override - public IIcon getIcon(boolean pollinated, boolean fancy) { - if (pollinated) { - return leafTexture.getPollinated(); - } else if (fancy) { - return leafTexture.getFancy(); - } else { - return leafTexture.getPlain(); - } - } - -} - +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.render; + +import forestry.api.arboriculture.EnumLeafType; +import forestry.api.arboriculture.ILeafIconProvider; +import java.awt.Color; +import net.minecraft.util.IIcon; + +public class IconProviderLeaves implements ILeafIconProvider { + + private final TextureLeaves leafTexture; + private final int color; + private final int colorPollinated; + + public IconProviderLeaves(EnumLeafType leafType, Color color, Color colorPollinated) { + this.leafTexture = TextureLeaves.get(leafType); + this.color = color.getRGB(); + this.colorPollinated = colorPollinated.getRGB(); + } + + @Override + public int getColor(boolean pollinated) { + if (pollinated) { + return colorPollinated; + } else { + return color; + } + } + + @Override + public IIcon getIcon(boolean pollinated, boolean fancy) { + if (pollinated) { + return leafTexture.getPollinated(); + } else if (fancy) { + return leafTexture.getFancy(); + } else { + return leafTexture.getPlain(); + } + } +} diff --git a/src/main/java/forestry/arboriculture/render/IconProviderWood.java b/src/main/java/forestry/arboriculture/render/IconProviderWood.java index fcbb91c4e..2429873bd 100644 --- a/src/main/java/forestry/arboriculture/render/IconProviderWood.java +++ b/src/main/java/forestry/arboriculture/render/IconProviderWood.java @@ -1,90 +1,87 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.render; - -import java.util.Locale; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.util.IIcon; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.core.render.TextureManager; - -public abstract class IconProviderWood { - @SideOnly(Side.CLIENT) - private static IIcon[][] icons; - - @SideOnly(Side.CLIENT) - public static void registerIcons(IIconRegister register) { - icons = new IIcon[3][EnumWoodType.VALUES.length]; - for (int i = 0; i < EnumWoodType.VALUES.length; i++) { - EnumWoodType woodType = EnumWoodType.VALUES[i]; - String woodName = woodType.toString().toLowerCase(Locale.ENGLISH); - - icons[0][i] = TextureManager.registerTex(register, "wood/planks." + woodName); - icons[1][i] = TextureManager.registerTex(register, "wood/bark." + woodName); - icons[2][i] = TextureManager.registerTex(register, "wood/heart." + woodName); - } - } - - @SideOnly(Side.CLIENT) - public static IIcon getPlankIcon(EnumWoodType woodType) { - if (woodType == null) { - woodType = EnumWoodType.LARCH; - } - return icons[0][woodType.ordinal()]; - } - - @SideOnly(Side.CLIENT) - public static IIcon getBarkIcon(EnumWoodType woodType) { - if (woodType == null) { - woodType = EnumWoodType.LARCH; - } - return icons[1][woodType.ordinal()]; - } - - @SideOnly(Side.CLIENT) - public static IIcon getHeartIcon(EnumWoodType woodType) { - if (woodType == null) { - woodType = EnumWoodType.LARCH; - } - return icons[2][woodType.ordinal()]; - } - - @SideOnly(Side.CLIENT) - public static IIcon getLogIcon(EnumWoodType woodType, int meta, int side) { - int oriented = meta & 12; - switch (oriented) { - case 4: - if (side > 3) { - return getHeartIcon(woodType); - } else { - return getBarkIcon(woodType); - } - case 8: - if (side == 2 || side == 3) { - return getHeartIcon(woodType); - } else { - return getBarkIcon(woodType); - } - case 0: - default: - if (side < 2) { - return getHeartIcon(woodType); - } else { - return getBarkIcon(woodType); - } - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.render; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.arboriculture.EnumWoodType; +import forestry.core.render.TextureManager; +import java.util.Locale; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.util.IIcon; + +public abstract class IconProviderWood { + @SideOnly(Side.CLIENT) + private static IIcon[][] icons; + + @SideOnly(Side.CLIENT) + public static void registerIcons(IIconRegister register) { + icons = new IIcon[3][EnumWoodType.VALUES.length]; + for (int i = 0; i < EnumWoodType.VALUES.length; i++) { + EnumWoodType woodType = EnumWoodType.VALUES[i]; + String woodName = woodType.toString().toLowerCase(Locale.ENGLISH); + + icons[0][i] = TextureManager.registerTex(register, "wood/planks." + woodName); + icons[1][i] = TextureManager.registerTex(register, "wood/bark." + woodName); + icons[2][i] = TextureManager.registerTex(register, "wood/heart." + woodName); + } + } + + @SideOnly(Side.CLIENT) + public static IIcon getPlankIcon(EnumWoodType woodType) { + if (woodType == null) { + woodType = EnumWoodType.LARCH; + } + return icons[0][woodType.ordinal()]; + } + + @SideOnly(Side.CLIENT) + public static IIcon getBarkIcon(EnumWoodType woodType) { + if (woodType == null) { + woodType = EnumWoodType.LARCH; + } + return icons[1][woodType.ordinal()]; + } + + @SideOnly(Side.CLIENT) + public static IIcon getHeartIcon(EnumWoodType woodType) { + if (woodType == null) { + woodType = EnumWoodType.LARCH; + } + return icons[2][woodType.ordinal()]; + } + + @SideOnly(Side.CLIENT) + public static IIcon getLogIcon(EnumWoodType woodType, int meta, int side) { + int oriented = meta & 12; + switch (oriented) { + case 4: + if (side > 3) { + return getHeartIcon(woodType); + } else { + return getBarkIcon(woodType); + } + case 8: + if (side == 2 || side == 3) { + return getHeartIcon(woodType); + } else { + return getBarkIcon(woodType); + } + case 0: + default: + if (side < 2) { + return getHeartIcon(woodType); + } else { + return getBarkIcon(woodType); + } + } + } +} diff --git a/src/main/java/forestry/arboriculture/render/RenderFenceItem.java b/src/main/java/forestry/arboriculture/render/RenderFenceItem.java index 4580ba399..39cb2fda4 100644 --- a/src/main/java/forestry/arboriculture/render/RenderFenceItem.java +++ b/src/main/java/forestry/arboriculture/render/RenderFenceItem.java @@ -1,130 +1,139 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.render; - -import net.minecraft.block.Block; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; - -import net.minecraftforge.client.IItemRenderer; - -import org.lwjgl.opengl.GL11; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.arboriculture.items.ItemBlockWood; - -public class RenderFenceItem implements IItemRenderer { - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - switch (type) { - case ENTITY: - case EQUIPPED_FIRST_PERSON: - case EQUIPPED: - case INVENTORY: - return true; - default: - return false; - } - } - - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { - return true; - } - - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { - switch (type) { - case ENTITY: - renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f); - break; - case EQUIPPED: - case EQUIPPED_FIRST_PERSON: - renderItem((RenderBlocks) data[0], item, 0.5f, 0.5f, 0.5f); - break; - case INVENTORY: - renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f); - break; - default: - } - } - - private static void renderItem(RenderBlocks renderer, ItemStack itemStack, float x, float y, float z) { - Tessellator tess = Tessellator.instance; - - EnumWoodType woodType = ItemBlockWood.getWoodType(itemStack); - IIcon plankIcon = IconProviderWood.getPlankIcon(woodType); - Block block = Block.getBlockFromItem(itemStack.getItem()); - - for (int i = 0; i < 4; ++i) { - - float thickness = 0.125F; - - if (i == 0) { - block.setBlockBounds(0.5F - thickness, 0.0F, 0.0F, 0.5F + thickness, 1.0F, thickness * 2.0F); - } - - if (i == 1) { - block.setBlockBounds(0.5F - thickness, 0.0F, 1.0F - thickness * 2.0F, 0.5F + thickness, 1.0F, 1.0F); - } - - thickness = 0.0625F; - - if (i == 2) { - block.setBlockBounds(0.5F - thickness, 1.0F - thickness * 3.0F, -thickness * 2.0F, 0.5F + thickness, 1.0F - thickness, 1.0F + thickness * 2.0F); - } - - if (i == 3) { - block.setBlockBounds(0.5F - thickness, 0.5F - thickness * 3.0F, -thickness * 2.0F, 0.5F + thickness, 0.5F - thickness, 1.0F + thickness * 2.0F); - } - - renderer.setRenderBoundsFromBlock(block); - - GL11.glTranslatef(-0.5F, -0.5F, -0.5F); - tess.startDrawingQuads(); - tess.setNormal(0.0F, -1.0F, 0.0F); - renderer.renderFaceYNeg(block, x, y, z, plankIcon); - tess.draw(); - - tess.startDrawingQuads(); - tess.setNormal(0.0F, 1.0F, 0.0F); - renderer.renderFaceYPos(block, x, y, z, plankIcon); - tess.draw(); - - tess.startDrawingQuads(); - tess.setNormal(0.0F, 0.0F, -1.0F); - renderer.renderFaceZNeg(block, x, y, z, plankIcon); - tess.draw(); - - tess.startDrawingQuads(); - tess.setNormal(0.0F, 0.0F, 1.0F); - renderer.renderFaceZPos(block, x, y, z, plankIcon); - tess.draw(); - - tess.startDrawingQuads(); - tess.setNormal(-1.0F, 0.0F, 0.0F); - renderer.renderFaceXNeg(block, x, y, z, plankIcon); - tess.draw(); - - tess.startDrawingQuads(); - tess.setNormal(1.0F, 0.0F, 0.0F); - renderer.renderFaceXPos(block, x, y, z, plankIcon); - tess.draw(); - - GL11.glTranslatef(0.5F, 0.5F, 0.5F); - } - - block.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - renderer.setRenderBoundsFromBlock(block); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.render; + +import forestry.api.arboriculture.EnumWoodType; +import forestry.arboriculture.items.ItemBlockWood; +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraftforge.client.IItemRenderer; +import org.lwjgl.opengl.GL11; + +public class RenderFenceItem implements IItemRenderer { + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + switch (type) { + case ENTITY: + case EQUIPPED_FIRST_PERSON: + case EQUIPPED: + case INVENTORY: + return true; + default: + return false; + } + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return true; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + switch (type) { + case ENTITY: + renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f); + break; + case EQUIPPED: + case EQUIPPED_FIRST_PERSON: + renderItem((RenderBlocks) data[0], item, 0.5f, 0.5f, 0.5f); + break; + case INVENTORY: + renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f); + break; + default: + } + } + + private static void renderItem(RenderBlocks renderer, ItemStack itemStack, float x, float y, float z) { + Tessellator tess = Tessellator.instance; + + EnumWoodType woodType = ItemBlockWood.getWoodType(itemStack); + IIcon plankIcon = IconProviderWood.getPlankIcon(woodType); + Block block = Block.getBlockFromItem(itemStack.getItem()); + + for (int i = 0; i < 4; ++i) { + + float thickness = 0.125F; + + if (i == 0) { + block.setBlockBounds(0.5F - thickness, 0.0F, 0.0F, 0.5F + thickness, 1.0F, thickness * 2.0F); + } + + if (i == 1) { + block.setBlockBounds(0.5F - thickness, 0.0F, 1.0F - thickness * 2.0F, 0.5F + thickness, 1.0F, 1.0F); + } + + thickness = 0.0625F; + + if (i == 2) { + block.setBlockBounds( + 0.5F - thickness, + 1.0F - thickness * 3.0F, + -thickness * 2.0F, + 0.5F + thickness, + 1.0F - thickness, + 1.0F + thickness * 2.0F); + } + + if (i == 3) { + block.setBlockBounds( + 0.5F - thickness, + 0.5F - thickness * 3.0F, + -thickness * 2.0F, + 0.5F + thickness, + 0.5F - thickness, + 1.0F + thickness * 2.0F); + } + + renderer.setRenderBoundsFromBlock(block); + + GL11.glTranslatef(-0.5F, -0.5F, -0.5F); + tess.startDrawingQuads(); + tess.setNormal(0.0F, -1.0F, 0.0F); + renderer.renderFaceYNeg(block, x, y, z, plankIcon); + tess.draw(); + + tess.startDrawingQuads(); + tess.setNormal(0.0F, 1.0F, 0.0F); + renderer.renderFaceYPos(block, x, y, z, plankIcon); + tess.draw(); + + tess.startDrawingQuads(); + tess.setNormal(0.0F, 0.0F, -1.0F); + renderer.renderFaceZNeg(block, x, y, z, plankIcon); + tess.draw(); + + tess.startDrawingQuads(); + tess.setNormal(0.0F, 0.0F, 1.0F); + renderer.renderFaceZPos(block, x, y, z, plankIcon); + tess.draw(); + + tess.startDrawingQuads(); + tess.setNormal(-1.0F, 0.0F, 0.0F); + renderer.renderFaceXNeg(block, x, y, z, plankIcon); + tess.draw(); + + tess.startDrawingQuads(); + tess.setNormal(1.0F, 0.0F, 0.0F); + renderer.renderFaceXPos(block, x, y, z, plankIcon); + tess.draw(); + + GL11.glTranslatef(0.5F, 0.5F, 0.5F); + } + + block.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + renderer.setRenderBoundsFromBlock(block); + } +} diff --git a/src/main/java/forestry/arboriculture/render/RenderFruitPodBlock.java b/src/main/java/forestry/arboriculture/render/RenderFruitPodBlock.java index 63cc27c39..eb20c23d4 100644 --- a/src/main/java/forestry/arboriculture/render/RenderFruitPodBlock.java +++ b/src/main/java/forestry/arboriculture/render/RenderFruitPodBlock.java @@ -10,6 +10,10 @@ ******************************************************************************/ package forestry.arboriculture.render; +import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; +import forestry.arboriculture.blocks.BlockFruitPod; +import forestry.arboriculture.tiles.TileFruitPod; +import forestry.plugins.PluginArboriculture; import net.minecraft.block.Block; import net.minecraft.block.BlockDirectional; import net.minecraft.client.renderer.RenderBlocks; @@ -17,180 +21,173 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; -import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; - -import forestry.arboriculture.blocks.BlockFruitPod; -import forestry.arboriculture.tiles.TileFruitPod; -import forestry.plugins.PluginArboriculture; - public class RenderFruitPodBlock implements ISimpleBlockRenderingHandler { - @Override - public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { - } + @Override + public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) {} - @Override - public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { + @Override + public boolean renderWorldBlock( + IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { - int maturity = 0; + int maturity = 0; - BlockFruitPod blockPod = (BlockFruitPod) block; - TileFruitPod pod = BlockFruitPod.getPodTile(world, x, y, z); - if (pod != null) { - maturity = pod.getMaturity(); - } + BlockFruitPod blockPod = (BlockFruitPod) block; + TileFruitPod pod = BlockFruitPod.getPodTile(world, x, y, z); + if (pod != null) { + maturity = pod.getMaturity(); + } - Tessellator tessellator = Tessellator.instance; - tessellator.setBrightness(blockPod.getMixedBrightnessForBlock(world, x, y, z)); - tessellator.setColorOpaque_F(1.0f, 1.0f, 1.0f); - int metadata = world.getBlockMetadata(x, y, z); - IIcon podIcon = blockPod.getIcon(world, x, y, z, metadata); - int notchDirection = BlockDirectional.getDirection(metadata); + Tessellator tessellator = Tessellator.instance; + tessellator.setBrightness(blockPod.getMixedBrightnessForBlock(world, x, y, z)); + tessellator.setColorOpaque_F(1.0f, 1.0f, 1.0f); + int metadata = world.getBlockMetadata(x, y, z); + IIcon podIcon = blockPod.getIcon(world, x, y, z, metadata); + int notchDirection = BlockDirectional.getDirection(metadata); - int k1 = 4 + maturity * 2; - int l1 = 5 + maturity * 2; - double d0 = 15.0D - k1; - double d1 = 15.0D; - double d2 = 4.0D; - double d3 = 4.0D + l1; - double d4 = (double) podIcon.getInterpolatedU(d0); - double d5 = (double) podIcon.getInterpolatedU(d1); - double d6 = (double) podIcon.getInterpolatedV(d2); - double d7 = (double) podIcon.getInterpolatedV(d3); - double d8 = 0.0D; - double d9 = 0.0D; + int k1 = 4 + maturity * 2; + int l1 = 5 + maturity * 2; + double d0 = 15.0D - k1; + double d1 = 15.0D; + double d2 = 4.0D; + double d3 = 4.0D + l1; + double d4 = (double) podIcon.getInterpolatedU(d0); + double d5 = (double) podIcon.getInterpolatedU(d1); + double d6 = (double) podIcon.getInterpolatedV(d2); + double d7 = (double) podIcon.getInterpolatedV(d3); + double d8 = 0.0D; + double d9 = 0.0D; - switch (notchDirection) { - case 0: - d8 = 8.0D - k1 / 2; - d9 = 15.0D - k1; - break; - case 1: - d8 = 1.0D; - d9 = 8.0D - k1 / 2; - break; - case 2: - d8 = 8.0D - k1 / 2; - d9 = 1.0D; - break; - case 3: - d8 = 15.0D - k1; - d9 = 8.0D - k1 / 2; - } + switch (notchDirection) { + case 0: + d8 = 8.0D - k1 / 2; + d9 = 15.0D - k1; + break; + case 1: + d8 = 1.0D; + d9 = 8.0D - k1 / 2; + break; + case 2: + d8 = 8.0D - k1 / 2; + d9 = 1.0D; + break; + case 3: + d8 = 15.0D - k1; + d9 = 8.0D - k1 / 2; + } - double d10 = x + d8 / 16.0D; - double d11 = x + (d8 + k1) / 16.0D; - double d12 = y + (12.0D - l1) / 16.0D; - double d13 = y + 0.75D; - double d14 = z + d9 / 16.0D; - double d15 = z + (d9 + k1) / 16.0D; - tessellator.addVertexWithUV(d10, d12, d14, d4, d7); - tessellator.addVertexWithUV(d10, d12, d15, d5, d7); - tessellator.addVertexWithUV(d10, d13, d15, d5, d6); - tessellator.addVertexWithUV(d10, d13, d14, d4, d6); - tessellator.addVertexWithUV(d11, d12, d15, d4, d7); - tessellator.addVertexWithUV(d11, d12, d14, d5, d7); - tessellator.addVertexWithUV(d11, d13, d14, d5, d6); - tessellator.addVertexWithUV(d11, d13, d15, d4, d6); - tessellator.addVertexWithUV(d11, d12, d14, d4, d7); - tessellator.addVertexWithUV(d10, d12, d14, d5, d7); - tessellator.addVertexWithUV(d10, d13, d14, d5, d6); - tessellator.addVertexWithUV(d11, d13, d14, d4, d6); - tessellator.addVertexWithUV(d10, d12, d15, d4, d7); - tessellator.addVertexWithUV(d11, d12, d15, d5, d7); - tessellator.addVertexWithUV(d11, d13, d15, d5, d6); - tessellator.addVertexWithUV(d10, d13, d15, d4, d6); - int i2 = k1; + double d10 = x + d8 / 16.0D; + double d11 = x + (d8 + k1) / 16.0D; + double d12 = y + (12.0D - l1) / 16.0D; + double d13 = y + 0.75D; + double d14 = z + d9 / 16.0D; + double d15 = z + (d9 + k1) / 16.0D; + tessellator.addVertexWithUV(d10, d12, d14, d4, d7); + tessellator.addVertexWithUV(d10, d12, d15, d5, d7); + tessellator.addVertexWithUV(d10, d13, d15, d5, d6); + tessellator.addVertexWithUV(d10, d13, d14, d4, d6); + tessellator.addVertexWithUV(d11, d12, d15, d4, d7); + tessellator.addVertexWithUV(d11, d12, d14, d5, d7); + tessellator.addVertexWithUV(d11, d13, d14, d5, d6); + tessellator.addVertexWithUV(d11, d13, d15, d4, d6); + tessellator.addVertexWithUV(d11, d12, d14, d4, d7); + tessellator.addVertexWithUV(d10, d12, d14, d5, d7); + tessellator.addVertexWithUV(d10, d13, d14, d5, d6); + tessellator.addVertexWithUV(d11, d13, d14, d4, d6); + tessellator.addVertexWithUV(d10, d12, d15, d4, d7); + tessellator.addVertexWithUV(d11, d12, d15, d5, d7); + tessellator.addVertexWithUV(d11, d13, d15, d5, d6); + tessellator.addVertexWithUV(d10, d13, d15, d4, d6); + int i2 = k1; - if (maturity >= 2) { - i2 = k1 - 1; - } + if (maturity >= 2) { + i2 = k1 - 1; + } - d4 = (double) podIcon.getMinU(); - d5 = (double) podIcon.getInterpolatedU((double) i2); - d6 = (double) podIcon.getMinV(); - d7 = (double) podIcon.getInterpolatedV((double) i2); + d4 = (double) podIcon.getMinU(); + d5 = (double) podIcon.getInterpolatedU((double) i2); + d6 = (double) podIcon.getMinV(); + d7 = (double) podIcon.getInterpolatedV((double) i2); - tessellator.addVertexWithUV(d10, d13, d15, d4, d7); - tessellator.addVertexWithUV(d11, d13, d15, d5, d7); - tessellator.addVertexWithUV(d11, d13, d14, d5, d6); - tessellator.addVertexWithUV(d10, d13, d14, d4, d6); - tessellator.addVertexWithUV(d10, d12, d14, d4, d6); - tessellator.addVertexWithUV(d11, d12, d14, d5, d6); - tessellator.addVertexWithUV(d11, d12, d15, d5, d7); - tessellator.addVertexWithUV(d10, d12, d15, d4, d7); - d4 = (double) podIcon.getInterpolatedU(12.0D); - d5 = (double) podIcon.getMaxU(); - d6 = (double) podIcon.getMinV(); - d7 = (double) podIcon.getInterpolatedV(4.0D); - d8 = 8.0D; - d9 = 0.0D; - double d16; + tessellator.addVertexWithUV(d10, d13, d15, d4, d7); + tessellator.addVertexWithUV(d11, d13, d15, d5, d7); + tessellator.addVertexWithUV(d11, d13, d14, d5, d6); + tessellator.addVertexWithUV(d10, d13, d14, d4, d6); + tessellator.addVertexWithUV(d10, d12, d14, d4, d6); + tessellator.addVertexWithUV(d11, d12, d14, d5, d6); + tessellator.addVertexWithUV(d11, d12, d15, d5, d7); + tessellator.addVertexWithUV(d10, d12, d15, d4, d7); + d4 = (double) podIcon.getInterpolatedU(12.0D); + d5 = (double) podIcon.getMaxU(); + d6 = (double) podIcon.getMinV(); + d7 = (double) podIcon.getInterpolatedV(4.0D); + d8 = 8.0D; + d9 = 0.0D; + double d16; - switch (notchDirection) { - case 0: - d8 = 8.0D; - d9 = 12.0D; - d16 = d4; - d4 = d5; - d5 = d16; - break; - case 1: - d8 = 0.0D; - d9 = 8.0D; - break; - case 2: - d8 = 8.0D; - d9 = 0.0D; - break; - case 3: - d8 = 12.0D; - d9 = 8.0D; - d16 = d4; - d4 = d5; - d5 = d16; - } + switch (notchDirection) { + case 0: + d8 = 8.0D; + d9 = 12.0D; + d16 = d4; + d4 = d5; + d5 = d16; + break; + case 1: + d8 = 0.0D; + d9 = 8.0D; + break; + case 2: + d8 = 8.0D; + d9 = 0.0D; + break; + case 3: + d8 = 12.0D; + d9 = 8.0D; + d16 = d4; + d4 = d5; + d5 = d16; + } - d10 = x + d8 / 16.0D; - d11 = x + (d8 + 4.0D) / 16.0D; - d12 = y + 0.75D; - d13 = y + 1.0D; - d14 = z + d9 / 16.0D; - d15 = z + (d9 + 4.0D) / 16.0D; + d10 = x + d8 / 16.0D; + d11 = x + (d8 + 4.0D) / 16.0D; + d12 = y + 0.75D; + d13 = y + 1.0D; + d14 = z + d9 / 16.0D; + d15 = z + (d9 + 4.0D) / 16.0D; - if (notchDirection != 2 && notchDirection != 0) { - if (notchDirection == 1 || notchDirection == 3) { - tessellator.addVertexWithUV(d11, d12, d14, d4, d7); - tessellator.addVertexWithUV(d10, d12, d14, d5, d7); - tessellator.addVertexWithUV(d10, d13, d14, d5, d6); - tessellator.addVertexWithUV(d11, d13, d14, d4, d6); - tessellator.addVertexWithUV(d10, d12, d14, d5, d7); - tessellator.addVertexWithUV(d11, d12, d14, d4, d7); - tessellator.addVertexWithUV(d11, d13, d14, d4, d6); - tessellator.addVertexWithUV(d10, d13, d14, d5, d6); - } - } else { - tessellator.addVertexWithUV(d10, d12, d14, d5, d7); - tessellator.addVertexWithUV(d10, d12, d15, d4, d7); - tessellator.addVertexWithUV(d10, d13, d15, d4, d6); - tessellator.addVertexWithUV(d10, d13, d14, d5, d6); - tessellator.addVertexWithUV(d10, d12, d15, d4, d7); - tessellator.addVertexWithUV(d10, d12, d14, d5, d7); - tessellator.addVertexWithUV(d10, d13, d14, d5, d6); - tessellator.addVertexWithUV(d10, d13, d15, d4, d6); - } + if (notchDirection != 2 && notchDirection != 0) { + if (notchDirection == 1 || notchDirection == 3) { + tessellator.addVertexWithUV(d11, d12, d14, d4, d7); + tessellator.addVertexWithUV(d10, d12, d14, d5, d7); + tessellator.addVertexWithUV(d10, d13, d14, d5, d6); + tessellator.addVertexWithUV(d11, d13, d14, d4, d6); + tessellator.addVertexWithUV(d10, d12, d14, d5, d7); + tessellator.addVertexWithUV(d11, d12, d14, d4, d7); + tessellator.addVertexWithUV(d11, d13, d14, d4, d6); + tessellator.addVertexWithUV(d10, d13, d14, d5, d6); + } + } else { + tessellator.addVertexWithUV(d10, d12, d14, d5, d7); + tessellator.addVertexWithUV(d10, d12, d15, d4, d7); + tessellator.addVertexWithUV(d10, d13, d15, d4, d6); + tessellator.addVertexWithUV(d10, d13, d14, d5, d6); + tessellator.addVertexWithUV(d10, d12, d15, d4, d7); + tessellator.addVertexWithUV(d10, d12, d14, d5, d7); + tessellator.addVertexWithUV(d10, d13, d14, d5, d6); + tessellator.addVertexWithUV(d10, d13, d15, d4, d6); + } - return true; - } + return true; + } - @Override - public boolean shouldRender3DInInventory(int modelId) { - return false; - } - - @Override - public int getRenderId() { - return PluginArboriculture.modelIdPods; - } + @Override + public boolean shouldRender3DInInventory(int modelId) { + return false; + } + @Override + public int getRenderId() { + return PluginArboriculture.modelIdPods; + } } diff --git a/src/main/java/forestry/arboriculture/render/RenderLeavesBlock.java b/src/main/java/forestry/arboriculture/render/RenderLeavesBlock.java index 77d94e2c8..469010615 100644 --- a/src/main/java/forestry/arboriculture/render/RenderLeavesBlock.java +++ b/src/main/java/forestry/arboriculture/render/RenderLeavesBlock.java @@ -10,91 +10,108 @@ ******************************************************************************/ package forestry.arboriculture.render; +import forestry.arboriculture.blocks.BlockForestryLeaves; +import forestry.arboriculture.tiles.TileLeaves; +import forestry.core.render.RenderOverlayBlock; +import forestry.plugins.PluginArboriculture; import net.minecraft.block.Block; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; -import forestry.arboriculture.blocks.BlockForestryLeaves; -import forestry.arboriculture.tiles.TileLeaves; -import forestry.core.render.RenderOverlayBlock; -import forestry.plugins.PluginArboriculture; - /** * Ugly but serviceable renderer for leaves, taking fruits into account. */ public class RenderLeavesBlock extends RenderOverlayBlock { - @Override - public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { - // uses IItemRenderer - } + @Override + public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { + // uses IItemRenderer + } - @Override - public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { + @Override + public boolean renderWorldBlock( + IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { - TileLeaves tile = BlockForestryLeaves.getLeafTile(world, x, y, z); - if (tile == null) { - return false; - } + TileLeaves tile = BlockForestryLeaves.getLeafTile(world, x, y, z); + if (tile == null) { + return false; + } - // Render the plain leaf block. - renderer.renderStandardBlock(block, x, y, z); + // Render the plain leaf block. + renderer.renderStandardBlock(block, x, y, z); - // Render overlay for fruit leaves. - IIcon fruitIcon = tile.getFruitTexture(); + // Render overlay for fruit leaves. + IIcon fruitIcon = tile.getFruitTexture(); - if (fruitIcon != null) { - int fruitColor = tile.getFruitColour(); - renderFruitOverlay(world, block, x, y, z, renderer, fruitIcon, fruitColor); - } + if (fruitIcon != null) { + int fruitColor = tile.getFruitColour(); + renderFruitOverlay(world, block, x, y, z, renderer, fruitIcon, fruitColor); + } - return true; - } + return true; + } - @Override - public boolean shouldRender3DInInventory(int modelId) { - return true; - } + @Override + public boolean shouldRender3DInInventory(int modelId) { + return true; + } - @Override - public int getRenderId() { - return PluginArboriculture.modelIdLeaves; - } + @Override + public int getRenderId() { + return PluginArboriculture.modelIdLeaves; + } - private static boolean renderFruitOverlay(IBlockAccess world, Block block, int x, int y, int z, RenderBlocks renderer, IIcon texture, int multiplier) { + private static boolean renderFruitOverlay( + IBlockAccess world, + Block block, + int x, + int y, + int z, + RenderBlocks renderer, + IIcon texture, + int multiplier) { - float mR = (multiplier >> 16 & 255) / 255.0F; - float mG = (multiplier >> 8 & 255) / 255.0F; - float mB = (multiplier & 255) / 255.0F; + float mR = (multiplier >> 16 & 255) / 255.0F; + float mG = (multiplier >> 8 & 255) / 255.0F; + float mB = (multiplier & 255) / 255.0F; - if (EntityRenderer.anaglyphEnable) { - mR = (mR * 30.0F + mG * 59.0F + mB * 11.0F) / 100.0F; - mG = (mR * 30.0F + mG * 70.0F) / 100.0F; - mB = (mR * 30.0F + mB * 70.0F) / 100.0F; - } + if (EntityRenderer.anaglyphEnable) { + mR = (mR * 30.0F + mG * 59.0F + mB * 11.0F) / 100.0F; + mG = (mR * 30.0F + mG * 70.0F) / 100.0F; + mB = (mR * 30.0F + mB * 70.0F) / 100.0F; + } - return renderFruitOverlayWithColorMultiplier(world, block, x, y, z, mR, mG, mB, renderer, texture); - } + return renderFruitOverlayWithColorMultiplier(world, block, x, y, z, mR, mG, mB, renderer, texture); + } - private static boolean renderFruitOverlayWithColorMultiplier(IBlockAccess world, Block block, int x, int y, int z, float r, float g, float b, - RenderBlocks renderer, IIcon texture) { + private static boolean renderFruitOverlayWithColorMultiplier( + IBlockAccess world, + Block block, + int x, + int y, + int z, + float r, + float g, + float b, + RenderBlocks renderer, + IIcon texture) { - int mixedBrightness = block.getMixedBrightnessForBlock(world, x, y, z); + int mixedBrightness = block.getMixedBrightnessForBlock(world, x, y, z); - float adjR = 0.5f * r; - float adjG = 0.5f * g; - float adjB = 0.5f * b; + float adjR = 0.5f * r; + float adjG = 0.5f * g; + float adjB = 0.5f * b; - // Bottom - renderBottomFace(world, block, x, y, z, renderer, texture, mixedBrightness, adjR, adjG, adjB); - renderTopFace(world, block, x, y, z, renderer, texture, mixedBrightness, adjR, adjG, adjB); - renderEastFace(world, block, x, y, z, renderer, texture, mixedBrightness, adjR, adjG, adjB); - renderWestFace(world, block, x, y, z, renderer, texture, mixedBrightness, adjR, adjG, adjB); - renderNorthFace(world, block, x, y, z, renderer, texture, mixedBrightness, adjR, adjG, adjB); - renderSouthFace(world, block, x, y, z, renderer, texture, mixedBrightness, adjR, adjG, adjB); + // Bottom + renderBottomFace(world, block, x, y, z, renderer, texture, mixedBrightness, adjR, adjG, adjB); + renderTopFace(world, block, x, y, z, renderer, texture, mixedBrightness, adjR, adjG, adjB); + renderEastFace(world, block, x, y, z, renderer, texture, mixedBrightness, adjR, adjG, adjB); + renderWestFace(world, block, x, y, z, renderer, texture, mixedBrightness, adjR, adjG, adjB); + renderNorthFace(world, block, x, y, z, renderer, texture, mixedBrightness, adjR, adjG, adjB); + renderSouthFace(world, block, x, y, z, renderer, texture, mixedBrightness, adjR, adjG, adjB); - return true; - } + return true; + } } diff --git a/src/main/java/forestry/arboriculture/render/RenderLeavesItem.java b/src/main/java/forestry/arboriculture/render/RenderLeavesItem.java index 2138bcbb0..25ca3804d 100644 --- a/src/main/java/forestry/arboriculture/render/RenderLeavesItem.java +++ b/src/main/java/forestry/arboriculture/render/RenderLeavesItem.java @@ -1,181 +1,178 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.render; - -import net.minecraft.block.Block; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; - -import net.minecraftforge.client.IItemRenderer; - -import org.lwjgl.opengl.GL11; - -import forestry.arboriculture.genetics.TreeHelper; -import forestry.arboriculture.items.ItemBlockLeaves; -import forestry.arboriculture.tiles.TileLeaves; -import forestry.core.proxy.Proxies; -import forestry.core.utils.ItemStackUtil; - -public class RenderLeavesItem implements IItemRenderer { - protected static final double OVERLAY_SHIFT = 0.001; - - @Override - public boolean handleRenderType(ItemStack item, IItemRenderer.ItemRenderType type) { - switch (type) { - case ENTITY: - case EQUIPPED_FIRST_PERSON: - case EQUIPPED: - case INVENTORY: - return true; - default: - return false; - } - } - - @Override - public boolean shouldUseRenderHelper(IItemRenderer.ItemRenderType type, ItemStack item, IItemRenderer.ItemRendererHelper helper) { - return true; - } - - @Override - public void renderItem(IItemRenderer.ItemRenderType type, ItemStack item, Object... data) { - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - - switch (type) { - case ENTITY: - renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f); - break; - case EQUIPPED: - case EQUIPPED_FIRST_PERSON: - renderItem((RenderBlocks) data[0], item, 0.5f, 0.5f, 0.5f); - break; - case INVENTORY: - renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f); - break; - default: - } - - GL11.glPopAttrib(); - } - - private static void renderItem(RenderBlocks renderer, ItemStack itemStack, float x, float y, float z) { - Tessellator tessellator = Tessellator.instance; - Block block = ItemStackUtil.getBlock(itemStack); - - if (!(itemStack.getItem() instanceof ItemBlockLeaves) || block == null) { - return; - } - - TileLeaves leaves = new TileLeaves(); - if (itemStack.hasTagCompound()) { - leaves.readFromNBT(itemStack.getTagCompound()); - } else { - leaves.setTree(TreeHelper.treeTemplates.get(0)); - } - - IIcon leavesIcon = leaves.getIcon(Proxies.render.fancyGraphicsEnabled()); - if (leavesIcon == null) { - return; - } - int color = leaves.getFoliageColour(Proxies.common.getPlayer()); - - float r1 = (float) (color >> 16 & 255) / 255.0F; - float g1 = (float) (color >> 8 & 255) / 255.0F; - float b1 = (float) (color & 255) / 255.0F; - GL11.glColor4f(r1, g1, b1, 1.0F); - - GL11.glTranslatef(x, y, z); - - block.setBlockBoundsForItemRender(); - renderer.setRenderBoundsFromBlock(block); - - GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); - GL11.glTranslatef(-0.5F, -0.5F, -0.5F); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, -1.0F, 0.0F); - renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, leavesIcon); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 1.0F, 0.0F); - renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, leavesIcon); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, -1.0F); - renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, leavesIcon); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, 1.0F); - renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, leavesIcon); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(-1.0F, 0.0F, 0.0F); - renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, leavesIcon); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(1.0F, 0.0F, 0.0F); - renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, leavesIcon); - tessellator.draw(); - GL11.glTranslatef(0.5F, 0.5F, 0.5F); - - - // add fruit - if (!leaves.hasFruit()) { - return; - } - - IIcon fruitTexture = leaves.getFruitTexture(); - if (fruitTexture == null) { - return; - } - int fruitColor = leaves.getFruitColour(); - - float r2 = (float) (fruitColor >> 16 & 255) / 255.0F; - float g2 = (float) (fruitColor >> 8 & 255) / 255.0F; - float b2 = (float) (fruitColor & 255) / 255.0F; - GL11.glColor4f(r2, g2, b2, 1.0F); - - block.setBlockBoundsForItemRender(); - renderer.setRenderBoundsFromBlock(block); - - GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); - GL11.glTranslatef(-0.5F, -0.5F, -0.5F); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, -1.0F, 0.0F); - renderer.renderFaceYNeg(block, 0.0D, 0.0D - OVERLAY_SHIFT, 0.0D, fruitTexture); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 1.0F, 0.0F); - renderer.renderFaceYPos(block, 0.0D, 0.0D + OVERLAY_SHIFT, 0.0D, fruitTexture); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, -1.0F); - renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D - OVERLAY_SHIFT, fruitTexture); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, 1.0F); - renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D + OVERLAY_SHIFT, fruitTexture); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(-1.0F, 0.0F, 0.0F); - renderer.renderFaceXNeg(block, 0.0D - OVERLAY_SHIFT, 0.0D, 0.0D, fruitTexture); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(1.0F, 0.0F, 0.0F); - renderer.renderFaceXPos(block, 0.0D + OVERLAY_SHIFT, 0.0D, 0.0D, fruitTexture); - tessellator.draw(); - GL11.glTranslatef(0.5F, 0.5F, 0.5F); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.render; + +import forestry.arboriculture.genetics.TreeHelper; +import forestry.arboriculture.items.ItemBlockLeaves; +import forestry.arboriculture.tiles.TileLeaves; +import forestry.core.proxy.Proxies; +import forestry.core.utils.ItemStackUtil; +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraftforge.client.IItemRenderer; +import org.lwjgl.opengl.GL11; + +public class RenderLeavesItem implements IItemRenderer { + protected static final double OVERLAY_SHIFT = 0.001; + + @Override + public boolean handleRenderType(ItemStack item, IItemRenderer.ItemRenderType type) { + switch (type) { + case ENTITY: + case EQUIPPED_FIRST_PERSON: + case EQUIPPED: + case INVENTORY: + return true; + default: + return false; + } + } + + @Override + public boolean shouldUseRenderHelper( + IItemRenderer.ItemRenderType type, ItemStack item, IItemRenderer.ItemRendererHelper helper) { + return true; + } + + @Override + public void renderItem(IItemRenderer.ItemRenderType type, ItemStack item, Object... data) { + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + switch (type) { + case ENTITY: + renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f); + break; + case EQUIPPED: + case EQUIPPED_FIRST_PERSON: + renderItem((RenderBlocks) data[0], item, 0.5f, 0.5f, 0.5f); + break; + case INVENTORY: + renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f); + break; + default: + } + + GL11.glPopAttrib(); + } + + private static void renderItem(RenderBlocks renderer, ItemStack itemStack, float x, float y, float z) { + Tessellator tessellator = Tessellator.instance; + Block block = ItemStackUtil.getBlock(itemStack); + + if (!(itemStack.getItem() instanceof ItemBlockLeaves) || block == null) { + return; + } + + TileLeaves leaves = new TileLeaves(); + if (itemStack.hasTagCompound()) { + leaves.readFromNBT(itemStack.getTagCompound()); + } else { + leaves.setTree(TreeHelper.treeTemplates.get(0)); + } + + IIcon leavesIcon = leaves.getIcon(Proxies.render.fancyGraphicsEnabled()); + if (leavesIcon == null) { + return; + } + int color = leaves.getFoliageColour(Proxies.common.getPlayer()); + + float r1 = (float) (color >> 16 & 255) / 255.0F; + float g1 = (float) (color >> 8 & 255) / 255.0F; + float b1 = (float) (color & 255) / 255.0F; + GL11.glColor4f(r1, g1, b1, 1.0F); + + GL11.glTranslatef(x, y, z); + + block.setBlockBoundsForItemRender(); + renderer.setRenderBoundsFromBlock(block); + + GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); + GL11.glTranslatef(-0.5F, -0.5F, -0.5F); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, -1.0F, 0.0F); + renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, leavesIcon); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, leavesIcon); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, -1.0F); + renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, leavesIcon); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, 1.0F); + renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, leavesIcon); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(-1.0F, 0.0F, 0.0F); + renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, leavesIcon); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(1.0F, 0.0F, 0.0F); + renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, leavesIcon); + tessellator.draw(); + GL11.glTranslatef(0.5F, 0.5F, 0.5F); + + // add fruit + if (!leaves.hasFruit()) { + return; + } + + IIcon fruitTexture = leaves.getFruitTexture(); + if (fruitTexture == null) { + return; + } + int fruitColor = leaves.getFruitColour(); + + float r2 = (float) (fruitColor >> 16 & 255) / 255.0F; + float g2 = (float) (fruitColor >> 8 & 255) / 255.0F; + float b2 = (float) (fruitColor & 255) / 255.0F; + GL11.glColor4f(r2, g2, b2, 1.0F); + + block.setBlockBoundsForItemRender(); + renderer.setRenderBoundsFromBlock(block); + + GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); + GL11.glTranslatef(-0.5F, -0.5F, -0.5F); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, -1.0F, 0.0F); + renderer.renderFaceYNeg(block, 0.0D, 0.0D - OVERLAY_SHIFT, 0.0D, fruitTexture); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + renderer.renderFaceYPos(block, 0.0D, 0.0D + OVERLAY_SHIFT, 0.0D, fruitTexture); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, -1.0F); + renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D - OVERLAY_SHIFT, fruitTexture); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, 1.0F); + renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D + OVERLAY_SHIFT, fruitTexture); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(-1.0F, 0.0F, 0.0F); + renderer.renderFaceXNeg(block, 0.0D - OVERLAY_SHIFT, 0.0D, 0.0D, fruitTexture); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(1.0F, 0.0F, 0.0F); + renderer.renderFaceXPos(block, 0.0D + OVERLAY_SHIFT, 0.0D, 0.0D, fruitTexture); + tessellator.draw(); + GL11.glTranslatef(0.5F, 0.5F, 0.5F); + } +} diff --git a/src/main/java/forestry/arboriculture/render/RenderLogItem.java b/src/main/java/forestry/arboriculture/render/RenderLogItem.java index fce837ab3..5bf8b769a 100644 --- a/src/main/java/forestry/arboriculture/render/RenderLogItem.java +++ b/src/main/java/forestry/arboriculture/render/RenderLogItem.java @@ -1,127 +1,125 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.render; - -import net.minecraft.block.Block; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; - -import net.minecraftforge.client.IItemRenderer; - -import org.lwjgl.opengl.GL11; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.arboriculture.items.ItemBlockWood; -import forestry.core.utils.ItemStackUtil; - -public class RenderLogItem implements IItemRenderer { - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - switch (type) { - case ENTITY: - case EQUIPPED_FIRST_PERSON: - case EQUIPPED: - case INVENTORY: - return true; - default: - return false; - } - } - - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { - return true; - } - - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { - switch (type) { - case ENTITY: - renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f, true); - break; - case EQUIPPED: - case EQUIPPED_FIRST_PERSON: - renderItem((RenderBlocks) data[0], item, 0.5f, 0.5f, 0.5f, true); - break; - case INVENTORY: - renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f, false); - break; - default: - } - } - - private static void renderItem(RenderBlocks renderer, ItemStack itemStack, float x, float y, float z, boolean fullBlock) { - Tessellator tessellator = Tessellator.instance; - Block block = ItemStackUtil.getBlock(itemStack); - - if (!(itemStack.getItem() instanceof ItemBlockWood) || block == null) { - return; - } - - EnumWoodType woodType = ItemBlockWood.getWoodType(itemStack); - - IIcon barkIcon = IconProviderWood.getBarkIcon(woodType); - IIcon heartIcon = IconProviderWood.getHeartIcon(woodType); - if (barkIcon == null || heartIcon == null) { - return; - } - - GL11.glTranslatef(x, y, z); - - block.setBlockBoundsForItemRender(); - renderer.setRenderBoundsFromBlock(block); - - GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); - GL11.glTranslatef(-0.5F, -0.5F, -0.5F); - - // top - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 1.0F, 0.0F); - renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, heartIcon); - tessellator.draw(); - - // front right - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, 1.0F); - renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, barkIcon); - tessellator.draw(); - - // front left - tessellator.startDrawingQuads(); - tessellator.setNormal(-1.0F, 0.0F, 0.0F); - renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, barkIcon); - tessellator.draw(); - - if (fullBlock) { - // bottom - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, -1.0F, 0.0F); - renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, heartIcon); - tessellator.draw(); - - // back right - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, -1.0F); - renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, barkIcon); - tessellator.draw(); - - // back left - tessellator.startDrawingQuads(); - tessellator.setNormal(1.0F, 0.0F, 0.0F); - renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, barkIcon); - tessellator.draw(); - } - - GL11.glTranslatef(0.5F, 0.5F, 0.5F); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.render; + +import forestry.api.arboriculture.EnumWoodType; +import forestry.arboriculture.items.ItemBlockWood; +import forestry.core.utils.ItemStackUtil; +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraftforge.client.IItemRenderer; +import org.lwjgl.opengl.GL11; + +public class RenderLogItem implements IItemRenderer { + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + switch (type) { + case ENTITY: + case EQUIPPED_FIRST_PERSON: + case EQUIPPED: + case INVENTORY: + return true; + default: + return false; + } + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return true; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + switch (type) { + case ENTITY: + renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f, true); + break; + case EQUIPPED: + case EQUIPPED_FIRST_PERSON: + renderItem((RenderBlocks) data[0], item, 0.5f, 0.5f, 0.5f, true); + break; + case INVENTORY: + renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f, false); + break; + default: + } + } + + private static void renderItem( + RenderBlocks renderer, ItemStack itemStack, float x, float y, float z, boolean fullBlock) { + Tessellator tessellator = Tessellator.instance; + Block block = ItemStackUtil.getBlock(itemStack); + + if (!(itemStack.getItem() instanceof ItemBlockWood) || block == null) { + return; + } + + EnumWoodType woodType = ItemBlockWood.getWoodType(itemStack); + + IIcon barkIcon = IconProviderWood.getBarkIcon(woodType); + IIcon heartIcon = IconProviderWood.getHeartIcon(woodType); + if (barkIcon == null || heartIcon == null) { + return; + } + + GL11.glTranslatef(x, y, z); + + block.setBlockBoundsForItemRender(); + renderer.setRenderBoundsFromBlock(block); + + GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); + GL11.glTranslatef(-0.5F, -0.5F, -0.5F); + + // top + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, heartIcon); + tessellator.draw(); + + // front right + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, 1.0F); + renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, barkIcon); + tessellator.draw(); + + // front left + tessellator.startDrawingQuads(); + tessellator.setNormal(-1.0F, 0.0F, 0.0F); + renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, barkIcon); + tessellator.draw(); + + if (fullBlock) { + // bottom + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, -1.0F, 0.0F); + renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, heartIcon); + tessellator.draw(); + + // back right + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, -1.0F); + renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, barkIcon); + tessellator.draw(); + + // back left + tessellator.startDrawingQuads(); + tessellator.setNormal(1.0F, 0.0F, 0.0F); + renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, barkIcon); + tessellator.draw(); + } + + GL11.glTranslatef(0.5F, 0.5F, 0.5F); + } +} diff --git a/src/main/java/forestry/arboriculture/render/RenderPlankItem.java b/src/main/java/forestry/arboriculture/render/RenderPlankItem.java index bd54dfaf2..73206e46c 100644 --- a/src/main/java/forestry/arboriculture/render/RenderPlankItem.java +++ b/src/main/java/forestry/arboriculture/render/RenderPlankItem.java @@ -1,126 +1,124 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.render; - -import net.minecraft.block.Block; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; - -import net.minecraftforge.client.IItemRenderer; - -import org.lwjgl.opengl.GL11; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.arboriculture.items.ItemBlockWood; -import forestry.core.utils.ItemStackUtil; - -public class RenderPlankItem implements IItemRenderer { - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - switch (type) { - case ENTITY: - case EQUIPPED_FIRST_PERSON: - case EQUIPPED: - case INVENTORY: - return true; - default: - return false; - } - } - - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { - return true; - } - - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { - switch (type) { - case ENTITY: - renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f, true); - break; - case EQUIPPED: - case EQUIPPED_FIRST_PERSON: - renderItem((RenderBlocks) data[0], item, 0.5f, 0.5f, 0.5f, true); - break; - case INVENTORY: - renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f, false); - break; - default: - } - } - - private static void renderItem(RenderBlocks renderer, ItemStack itemStack, float x, float y, float z, boolean fullBlock) { - Tessellator tessellator = Tessellator.instance; - Block block = ItemStackUtil.getBlock(itemStack); - - if (!(itemStack.getItem() instanceof ItemBlockWood) || block == null) { - return; - } - - EnumWoodType woodType = ItemBlockWood.getWoodType(itemStack); - - IIcon plankIcon = IconProviderWood.getPlankIcon(woodType); - if (plankIcon == null) { - return; - } - - GL11.glTranslatef(x, y, z); - - block.setBlockBoundsForItemRender(); - renderer.setRenderBoundsFromBlock(block); - - GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); - GL11.glTranslatef(-0.5F, -0.5F, -0.5F); - - // top - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 1.0F, 0.0F); - renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, plankIcon); - tessellator.draw(); - - // front right - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, 1.0F); - renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, plankIcon); - tessellator.draw(); - - // front left - tessellator.startDrawingQuads(); - tessellator.setNormal(-1.0F, 0.0F, 0.0F); - renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, plankIcon); - tessellator.draw(); - - if (fullBlock) { - // bottom - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, -1.0F, 0.0F); - renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, plankIcon); - tessellator.draw(); - - // back right - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, -1.0F); - renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, plankIcon); - tessellator.draw(); - - // back left - tessellator.startDrawingQuads(); - tessellator.setNormal(1.0F, 0.0F, 0.0F); - renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, plankIcon); - tessellator.draw(); - } - - GL11.glTranslatef(0.5F, 0.5F, 0.5F); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.render; + +import forestry.api.arboriculture.EnumWoodType; +import forestry.arboriculture.items.ItemBlockWood; +import forestry.core.utils.ItemStackUtil; +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraftforge.client.IItemRenderer; +import org.lwjgl.opengl.GL11; + +public class RenderPlankItem implements IItemRenderer { + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + switch (type) { + case ENTITY: + case EQUIPPED_FIRST_PERSON: + case EQUIPPED: + case INVENTORY: + return true; + default: + return false; + } + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return true; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + switch (type) { + case ENTITY: + renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f, true); + break; + case EQUIPPED: + case EQUIPPED_FIRST_PERSON: + renderItem((RenderBlocks) data[0], item, 0.5f, 0.5f, 0.5f, true); + break; + case INVENTORY: + renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f, false); + break; + default: + } + } + + private static void renderItem( + RenderBlocks renderer, ItemStack itemStack, float x, float y, float z, boolean fullBlock) { + Tessellator tessellator = Tessellator.instance; + Block block = ItemStackUtil.getBlock(itemStack); + + if (!(itemStack.getItem() instanceof ItemBlockWood) || block == null) { + return; + } + + EnumWoodType woodType = ItemBlockWood.getWoodType(itemStack); + + IIcon plankIcon = IconProviderWood.getPlankIcon(woodType); + if (plankIcon == null) { + return; + } + + GL11.glTranslatef(x, y, z); + + block.setBlockBoundsForItemRender(); + renderer.setRenderBoundsFromBlock(block); + + GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); + GL11.glTranslatef(-0.5F, -0.5F, -0.5F); + + // top + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, plankIcon); + tessellator.draw(); + + // front right + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, 1.0F); + renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, plankIcon); + tessellator.draw(); + + // front left + tessellator.startDrawingQuads(); + tessellator.setNormal(-1.0F, 0.0F, 0.0F); + renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, plankIcon); + tessellator.draw(); + + if (fullBlock) { + // bottom + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, -1.0F, 0.0F); + renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, plankIcon); + tessellator.draw(); + + // back right + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, -1.0F); + renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, plankIcon); + tessellator.draw(); + + // back left + tessellator.startDrawingQuads(); + tessellator.setNormal(1.0F, 0.0F, 0.0F); + renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, plankIcon); + tessellator.draw(); + } + + GL11.glTranslatef(0.5F, 0.5F, 0.5F); + } +} diff --git a/src/main/java/forestry/arboriculture/render/RenderSaplingBlock.java b/src/main/java/forestry/arboriculture/render/RenderSaplingBlock.java index 433fc19b0..026d72a0c 100644 --- a/src/main/java/forestry/arboriculture/render/RenderSaplingBlock.java +++ b/src/main/java/forestry/arboriculture/render/RenderSaplingBlock.java @@ -10,6 +10,12 @@ ******************************************************************************/ package forestry.arboriculture.render; +import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; +import forestry.api.arboriculture.EnumGermlingType; +import forestry.api.arboriculture.IAlleleTreeSpecies; +import forestry.arboriculture.blocks.BlockSapling; +import forestry.arboriculture.tiles.TileSapling; +import forestry.plugins.PluginArboriculture; import net.minecraft.block.Block; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.RenderBlocks; @@ -17,106 +23,99 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; -import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; - -import forestry.api.arboriculture.EnumGermlingType; -import forestry.api.arboriculture.IAlleleTreeSpecies; -import forestry.arboriculture.blocks.BlockSapling; -import forestry.arboriculture.tiles.TileSapling; -import forestry.plugins.PluginArboriculture; - public class RenderSaplingBlock implements ISimpleBlockRenderingHandler { - private static int renderLayer = 0; - - @Override - public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { - } + private static int renderLayer = 0; - @Override - public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { + @Override + public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) {} - if (modelId != this.getRenderId()) { - return false; - } + @Override + public boolean renderWorldBlock( + IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { - TileSapling tile = BlockSapling.getSaplingTile(world, x, y, z); + if (modelId != this.getRenderId()) { + return false; + } - if (tile == null || tile.getTree() == null) { - return true; - } + TileSapling tile = BlockSapling.getSaplingTile(world, x, y, z); - IAlleleTreeSpecies species = tile.getTree().getGenome().getPrimary(); + if (tile == null || tile.getTree() == null) { + return true; + } - renderCrossedSquares(species, world, block, x, y, z); - renderLayer = 1; - renderCrossedSquares(species, world, block, x, y, z); - renderLayer = 0; - return true; - } + IAlleleTreeSpecies species = tile.getTree().getGenome().getPrimary(); - @Override - public boolean shouldRender3DInInventory(int modelId) { - return false; - } + renderCrossedSquares(species, world, block, x, y, z); + renderLayer = 1; + renderCrossedSquares(species, world, block, x, y, z); + renderLayer = 0; + return true; + } - @Override - public int getRenderId() { - return PluginArboriculture.modelIdSaplings; - } + @Override + public boolean shouldRender3DInInventory(int modelId) { + return false; + } - private static boolean renderCrossedSquares(IAlleleTreeSpecies species, IBlockAccess world, Block block, int x, int y, int z) { + @Override + public int getRenderId() { + return PluginArboriculture.modelIdSaplings; + } - Tessellator tess = Tessellator.instance; - - tess.setBrightness(block.getMixedBrightnessForBlock(world, x, y, z)); - int colourMultiplier = species.getGermlingColour(EnumGermlingType.SAPLING, renderLayer); - float r = (colourMultiplier >> 16 & 255) / 255.0F; - float g = (colourMultiplier >> 8 & 255) / 255.0F; - float b = (colourMultiplier & 255) / 255.0F; + private static boolean renderCrossedSquares( + IAlleleTreeSpecies species, IBlockAccess world, Block block, int x, int y, int z) { - if (EntityRenderer.anaglyphEnable) { + Tessellator tess = Tessellator.instance; - r = (r * 30.0F + g * 59.0F + b * 11.0F) / 100.0F; - g = (r * 30.0F + g * 70.0F) / 100.0F; - b = (r * 30.0F + b * 70.0F) / 100.0F; - } + tess.setBrightness(block.getMixedBrightnessForBlock(world, x, y, z)); + int colourMultiplier = species.getGermlingColour(EnumGermlingType.SAPLING, renderLayer); + float r = (colourMultiplier >> 16 & 255) / 255.0F; + float g = (colourMultiplier >> 8 & 255) / 255.0F; + float b = (colourMultiplier & 255) / 255.0F; - tess.setColorOpaque_F(r, g, b); - drawCrossedSquares(species, x, y, z, 1.0f); - return true; - } + if (EntityRenderer.anaglyphEnable) { - private static void drawCrossedSquares(IAlleleTreeSpecies species, double par3, double par5, double par7, float mod) { + r = (r * 30.0F + g * 59.0F + b * 11.0F) / 100.0F; + g = (r * 30.0F + g * 70.0F) / 100.0F; + b = (r * 30.0F + b * 70.0F) / 100.0F; + } - Tessellator tess = Tessellator.instance; - IIcon icon = species.getGermlingIcon(EnumGermlingType.SAPLING, renderLayer); + tess.setColorOpaque_F(r, g, b); + drawCrossedSquares(species, x, y, z, 1.0f); + return true; + } - double d3 = (double) icon.getMinU(); - double d4 = (double) icon.getMinV(); - double d5 = (double) icon.getMaxU(); - double d6 = (double) icon.getMaxV(); - double d7 = 0.45D * mod; - double d8 = par3 + 0.5D - d7; - double d9 = par3 + 0.5D + d7; - double d10 = par7 + 0.5D - d7; - double d11 = par7 + 0.5D + d7; - tess.addVertexWithUV(d8, par5 + mod, d10, d3, d4); - tess.addVertexWithUV(d8, par5 + 0.0D, d10, d3, d6); - tess.addVertexWithUV(d9, par5 + 0.0D, d11, d5, d6); - tess.addVertexWithUV(d9, par5 + mod, d11, d5, d4); - tess.addVertexWithUV(d9, par5 + mod, d11, d3, d4); - tess.addVertexWithUV(d9, par5 + 0.0D, d11, d3, d6); - tess.addVertexWithUV(d8, par5 + 0.0D, d10, d5, d6); - tess.addVertexWithUV(d8, par5 + mod, d10, d5, d4); - tess.addVertexWithUV(d8, par5 + mod, d11, d3, d4); - tess.addVertexWithUV(d8, par5 + 0.0D, d11, d3, d6); - tess.addVertexWithUV(d9, par5 + 0.0D, d10, d5, d6); - tess.addVertexWithUV(d9, par5 + mod, d10, d5, d4); - tess.addVertexWithUV(d9, par5 + mod, d10, d3, d4); - tess.addVertexWithUV(d9, par5 + 0.0D, d10, d3, d6); - tess.addVertexWithUV(d8, par5 + 0.0D, d11, d5, d6); - tess.addVertexWithUV(d8, par5 + mod, d11, d5, d4); - } + private static void drawCrossedSquares( + IAlleleTreeSpecies species, double par3, double par5, double par7, float mod) { + Tessellator tess = Tessellator.instance; + IIcon icon = species.getGermlingIcon(EnumGermlingType.SAPLING, renderLayer); + + double d3 = (double) icon.getMinU(); + double d4 = (double) icon.getMinV(); + double d5 = (double) icon.getMaxU(); + double d6 = (double) icon.getMaxV(); + double d7 = 0.45D * mod; + double d8 = par3 + 0.5D - d7; + double d9 = par3 + 0.5D + d7; + double d10 = par7 + 0.5D - d7; + double d11 = par7 + 0.5D + d7; + tess.addVertexWithUV(d8, par5 + mod, d10, d3, d4); + tess.addVertexWithUV(d8, par5 + 0.0D, d10, d3, d6); + tess.addVertexWithUV(d9, par5 + 0.0D, d11, d5, d6); + tess.addVertexWithUV(d9, par5 + mod, d11, d5, d4); + tess.addVertexWithUV(d9, par5 + mod, d11, d3, d4); + tess.addVertexWithUV(d9, par5 + 0.0D, d11, d3, d6); + tess.addVertexWithUV(d8, par5 + 0.0D, d10, d5, d6); + tess.addVertexWithUV(d8, par5 + mod, d10, d5, d4); + tess.addVertexWithUV(d8, par5 + mod, d11, d3, d4); + tess.addVertexWithUV(d8, par5 + 0.0D, d11, d3, d6); + tess.addVertexWithUV(d9, par5 + 0.0D, d10, d5, d6); + tess.addVertexWithUV(d9, par5 + mod, d10, d5, d4); + tess.addVertexWithUV(d9, par5 + mod, d10, d3, d4); + tess.addVertexWithUV(d9, par5 + 0.0D, d10, d3, d6); + tess.addVertexWithUV(d8, par5 + 0.0D, d11, d5, d6); + tess.addVertexWithUV(d8, par5 + mod, d11, d5, d4); + } } diff --git a/src/main/java/forestry/arboriculture/render/RenderSlabItem.java b/src/main/java/forestry/arboriculture/render/RenderSlabItem.java index 083604f59..d6883d42a 100644 --- a/src/main/java/forestry/arboriculture/render/RenderSlabItem.java +++ b/src/main/java/forestry/arboriculture/render/RenderSlabItem.java @@ -1,116 +1,114 @@ -package forestry.arboriculture.render; - -import net.minecraft.block.Block; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; - -import net.minecraftforge.client.IItemRenderer; - -import org.lwjgl.opengl.GL11; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.arboriculture.items.ItemBlockWood; -import forestry.core.utils.ItemStackUtil; - -public class RenderSlabItem implements IItemRenderer { - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - switch (type) { - case ENTITY: - case EQUIPPED_FIRST_PERSON: - case EQUIPPED: - case INVENTORY: - return true; - default: - return false; - } - } - - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { - return true; - } - - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { - switch (type) { - case ENTITY: - renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f, true); - break; - case EQUIPPED: - case EQUIPPED_FIRST_PERSON: - renderItem((RenderBlocks) data[0], item, 0.5f, 0.5f, 0.5f, true); - break; - case INVENTORY: - renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f, false); - break; - default: - } - } - - private static void renderItem(RenderBlocks renderer, ItemStack itemStack, float x, float y, float z, boolean fullBlock) { - Tessellator tessellator = Tessellator.instance; - Block block = ItemStackUtil.getBlock(itemStack); - - if (!(itemStack.getItem() instanceof ItemBlockWood) || block == null) { - return; - } - - EnumWoodType woodType = ItemBlockWood.getWoodType(itemStack); - - IIcon plankIcon = IconProviderWood.getPlankIcon(woodType); - if (plankIcon == null) { - return; - } - - GL11.glTranslatef(x, y, z); - - block.setBlockBoundsForItemRender(); - renderer.setRenderBoundsFromBlock(block); - - GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); - GL11.glTranslatef(-0.5F, -0.5F, -0.5F); - - // top - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 1.0F, 0.0F); - renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, plankIcon); - tessellator.draw(); - - // front right - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, 1.0F); - renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, plankIcon); - tessellator.draw(); - - // front left - tessellator.startDrawingQuads(); - tessellator.setNormal(-1.0F, 0.0F, 0.0F); - renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, plankIcon); - tessellator.draw(); - - if (fullBlock) { - // bottom - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, -1.0F, 0.0F); - renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, plankIcon); - tessellator.draw(); - - // back right - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, -1.0F); - renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, plankIcon); - tessellator.draw(); - - // back left - tessellator.startDrawingQuads(); - tessellator.setNormal(1.0F, 0.0F, 0.0F); - renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, plankIcon); - tessellator.draw(); - } - - GL11.glTranslatef(0.5F, 0.5F, 0.5F); - } -} +package forestry.arboriculture.render; + +import forestry.api.arboriculture.EnumWoodType; +import forestry.arboriculture.items.ItemBlockWood; +import forestry.core.utils.ItemStackUtil; +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraftforge.client.IItemRenderer; +import org.lwjgl.opengl.GL11; + +public class RenderSlabItem implements IItemRenderer { + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + switch (type) { + case ENTITY: + case EQUIPPED_FIRST_PERSON: + case EQUIPPED: + case INVENTORY: + return true; + default: + return false; + } + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return true; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + switch (type) { + case ENTITY: + renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f, true); + break; + case EQUIPPED: + case EQUIPPED_FIRST_PERSON: + renderItem((RenderBlocks) data[0], item, 0.5f, 0.5f, 0.5f, true); + break; + case INVENTORY: + renderItem((RenderBlocks) data[0], item, 0f, 0f, 0f, false); + break; + default: + } + } + + private static void renderItem( + RenderBlocks renderer, ItemStack itemStack, float x, float y, float z, boolean fullBlock) { + Tessellator tessellator = Tessellator.instance; + Block block = ItemStackUtil.getBlock(itemStack); + + if (!(itemStack.getItem() instanceof ItemBlockWood) || block == null) { + return; + } + + EnumWoodType woodType = ItemBlockWood.getWoodType(itemStack); + + IIcon plankIcon = IconProviderWood.getPlankIcon(woodType); + if (plankIcon == null) { + return; + } + + GL11.glTranslatef(x, y, z); + + block.setBlockBoundsForItemRender(); + renderer.setRenderBoundsFromBlock(block); + + GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F); + GL11.glTranslatef(-0.5F, -0.5F, -0.5F); + + // top + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, plankIcon); + tessellator.draw(); + + // front right + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, 1.0F); + renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, plankIcon); + tessellator.draw(); + + // front left + tessellator.startDrawingQuads(); + tessellator.setNormal(-1.0F, 0.0F, 0.0F); + renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, plankIcon); + tessellator.draw(); + + if (fullBlock) { + // bottom + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, -1.0F, 0.0F); + renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, plankIcon); + tessellator.draw(); + + // back right + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, -1.0F); + renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, plankIcon); + tessellator.draw(); + + // back left + tessellator.startDrawingQuads(); + tessellator.setNormal(1.0F, 0.0F, 0.0F); + renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, plankIcon); + tessellator.draw(); + } + + GL11.glTranslatef(0.5F, 0.5F, 0.5F); + } +} diff --git a/src/main/java/forestry/arboriculture/render/RenderStairItem.java b/src/main/java/forestry/arboriculture/render/RenderStairItem.java index fc79cd737..eb44cacae 100644 --- a/src/main/java/forestry/arboriculture/render/RenderStairItem.java +++ b/src/main/java/forestry/arboriculture/render/RenderStairItem.java @@ -10,105 +10,101 @@ ******************************************************************************/ package forestry.arboriculture.render; +import forestry.api.arboriculture.EnumWoodType; +import forestry.arboriculture.items.ItemBlockWood; +import forestry.core.utils.ItemStackUtil; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; - import net.minecraftforge.client.IItemRenderer; - import org.lwjgl.opengl.GL11; -import forestry.api.arboriculture.EnumWoodType; -import forestry.arboriculture.items.ItemBlockWood; -import forestry.core.utils.ItemStackUtil; - public class RenderStairItem implements IItemRenderer { - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - switch (type) { - case ENTITY: - case EQUIPPED_FIRST_PERSON: - case EQUIPPED: - case INVENTORY: - return true; - default: - return false; - } - } + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + switch (type) { + case ENTITY: + case EQUIPPED_FIRST_PERSON: + case EQUIPPED: + case INVENTORY: + return true; + default: + return false; + } + } - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { - return true; - } + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return true; + } - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { - switch (type) { - case ENTITY: - renderStairBlock((RenderBlocks) data[0], item, 0f, 0f, 0f); - break; - case EQUIPPED: - case EQUIPPED_FIRST_PERSON: - renderStairBlock((RenderBlocks) data[0], item, 0.5f, 0.5f, 0.5f); - break; - case INVENTORY: - renderStairBlock((RenderBlocks) data[0], item, 0f, 0f, 0f); - break; - default: - } - } + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + switch (type) { + case ENTITY: + renderStairBlock((RenderBlocks) data[0], item, 0f, 0f, 0f); + break; + case EQUIPPED: + case EQUIPPED_FIRST_PERSON: + renderStairBlock((RenderBlocks) data[0], item, 0.5f, 0.5f, 0.5f); + break; + case INVENTORY: + renderStairBlock((RenderBlocks) data[0], item, 0f, 0f, 0f); + break; + default: + } + } - private static void renderStairBlock(RenderBlocks renderBlocks, ItemStack itemStack, float x, float y, float z) { + private static void renderStairBlock(RenderBlocks renderBlocks, ItemStack itemStack, float x, float y, float z) { - Tessellator tessellator = Tessellator.instance; - Block block = ItemStackUtil.getBlock(itemStack); + Tessellator tessellator = Tessellator.instance; + Block block = ItemStackUtil.getBlock(itemStack); - if (!(itemStack.getItem() instanceof ItemBlockWood) || block == null) { - return; - } + if (!(itemStack.getItem() instanceof ItemBlockWood) || block == null) { + return; + } - EnumWoodType woodType = ItemBlockWood.getWoodType(itemStack); - IIcon texture = IconProviderWood.getPlankIcon(woodType); + EnumWoodType woodType = ItemBlockWood.getWoodType(itemStack); + IIcon texture = IconProviderWood.getPlankIcon(woodType); - for (int i = 0; i < 2; ++i) { - if (i == 0) { - renderBlocks.setRenderBounds(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 0.5D); - } + for (int i = 0; i < 2; ++i) { + if (i == 0) { + renderBlocks.setRenderBounds(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 0.5D); + } - if (i == 1) { - renderBlocks.setRenderBounds(0.0D, 0.0D, 0.5D, 1.0D, 0.5D, 1.0D); - } - - GL11.glTranslatef(-0.5F, -0.5F, -0.5F); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, -1.0F, 0.0F); - renderBlocks.renderFaceYNeg(block, x, y, z, texture); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 1.0F, 0.0F); - renderBlocks.renderFaceYPos(block, x, y, z, texture); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, -1.0F); - renderBlocks.renderFaceZNeg(block, x, y, z, texture); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, 1.0F); - renderBlocks.renderFaceZPos(block, x, y, z, texture); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(-1.0F, 0.0F, 0.0F); - renderBlocks.renderFaceXNeg(block, x, y, z, texture); - tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(1.0F, 0.0F, 0.0F); - renderBlocks.renderFaceXPos(block, x, y, z, texture); - tessellator.draw(); - GL11.glTranslatef(0.5F, 0.5F, 0.5F); - } - } + if (i == 1) { + renderBlocks.setRenderBounds(0.0D, 0.0D, 0.5D, 1.0D, 0.5D, 1.0D); + } + GL11.glTranslatef(-0.5F, -0.5F, -0.5F); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, -1.0F, 0.0F); + renderBlocks.renderFaceYNeg(block, x, y, z, texture); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + renderBlocks.renderFaceYPos(block, x, y, z, texture); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, -1.0F); + renderBlocks.renderFaceZNeg(block, x, y, z, texture); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, 1.0F); + renderBlocks.renderFaceZPos(block, x, y, z, texture); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(-1.0F, 0.0F, 0.0F); + renderBlocks.renderFaceXNeg(block, x, y, z, texture); + tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(1.0F, 0.0F, 0.0F); + renderBlocks.renderFaceXPos(block, x, y, z, texture); + tessellator.draw(); + GL11.glTranslatef(0.5F, 0.5F, 0.5F); + } + } } diff --git a/src/main/java/forestry/arboriculture/render/TextureLeaves.java b/src/main/java/forestry/arboriculture/render/TextureLeaves.java index fc8e518f4..11b230210 100644 --- a/src/main/java/forestry/arboriculture/render/TextureLeaves.java +++ b/src/main/java/forestry/arboriculture/render/TextureLeaves.java @@ -1,71 +1,69 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.render; - -import java.util.EnumMap; -import java.util.Locale; -import java.util.Map; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.util.IIcon; - -import forestry.api.arboriculture.EnumLeafType; -import forestry.core.render.TextureManager; - -public class TextureLeaves { - private static final Map leafTextures = new EnumMap<>(EnumLeafType.class); - - static { - for (EnumLeafType leafType : EnumLeafType.values()) { - leafTextures.put(leafType, new TextureLeaves(leafType)); - } - } - - public static TextureLeaves get(EnumLeafType leafType) { - return leafTextures.get(leafType); - } - - public static void registerAllIcons(IIconRegister register) { - for (TextureLeaves leafTexture : leafTextures.values()) { - leafTexture.registerIcons(register); - } - } - - private final EnumLeafType leafType; - - private IIcon plain; - private IIcon pollinated; - private IIcon fancy; - - private TextureLeaves(EnumLeafType enumLeafType) { - this.leafType = enumLeafType; - } - - private void registerIcons(IIconRegister register) { - String ident = leafType.toString().toLowerCase(Locale.ENGLISH); - - plain = TextureManager.registerTex(register, "leaves/" + ident + ".plain"); - pollinated = TextureManager.registerTex(register, "leaves/" + ident + ".changed"); - fancy = TextureManager.registerTex(register, "leaves/" + ident + ".fancy"); - } - - public IIcon getPlain() { - return plain; - } - - public IIcon getPollinated() { - return pollinated; - } - - public IIcon getFancy() { - return fancy; - } -} \ No newline at end of file +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.render; + +import forestry.api.arboriculture.EnumLeafType; +import forestry.core.render.TextureManager; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.util.IIcon; + +public class TextureLeaves { + private static final Map leafTextures = new EnumMap<>(EnumLeafType.class); + + static { + for (EnumLeafType leafType : EnumLeafType.values()) { + leafTextures.put(leafType, new TextureLeaves(leafType)); + } + } + + public static TextureLeaves get(EnumLeafType leafType) { + return leafTextures.get(leafType); + } + + public static void registerAllIcons(IIconRegister register) { + for (TextureLeaves leafTexture : leafTextures.values()) { + leafTexture.registerIcons(register); + } + } + + private final EnumLeafType leafType; + + private IIcon plain; + private IIcon pollinated; + private IIcon fancy; + + private TextureLeaves(EnumLeafType enumLeafType) { + this.leafType = enumLeafType; + } + + private void registerIcons(IIconRegister register) { + String ident = leafType.toString().toLowerCase(Locale.ENGLISH); + + plain = TextureManager.registerTex(register, "leaves/" + ident + ".plain"); + pollinated = TextureManager.registerTex(register, "leaves/" + ident + ".changed"); + fancy = TextureManager.registerTex(register, "leaves/" + ident + ".fancy"); + } + + public IIcon getPlain() { + return plain; + } + + public IIcon getPollinated() { + return pollinated; + } + + public IIcon getFancy() { + return fancy; + } +} diff --git a/src/main/java/forestry/arboriculture/tiles/TileArboristChest.java b/src/main/java/forestry/arboriculture/tiles/TileArboristChest.java index cf40c67da..372edea85 100644 --- a/src/main/java/forestry/arboriculture/tiles/TileArboristChest.java +++ b/src/main/java/forestry/arboriculture/tiles/TileArboristChest.java @@ -14,7 +14,7 @@ import forestry.api.arboriculture.TreeManager; import forestry.core.tiles.TileNaturalistChest; public class TileArboristChest extends TileNaturalistChest { - public TileArboristChest() { - super(TreeManager.treeRoot); - } + public TileArboristChest() { + super(TreeManager.treeRoot); + } } diff --git a/src/main/java/forestry/arboriculture/tiles/TileFruitPod.java b/src/main/java/forestry/arboriculture/tiles/TileFruitPod.java index 6f6a221e8..f67a1452b 100644 --- a/src/main/java/forestry/arboriculture/tiles/TileFruitPod.java +++ b/src/main/java/forestry/arboriculture/tiles/TileFruitPod.java @@ -10,20 +10,8 @@ ******************************************************************************/ package forestry.arboriculture.tiles; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.Packet; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.IIcon; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.arboriculture.IAlleleFruit; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; @@ -37,172 +25,181 @@ import forestry.core.network.IStreamable; import forestry.core.network.packets.PacketTileStream; import forestry.core.proxy.Proxies; import forestry.core.render.TextureManager; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.Packet; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; public class TileFruitPod extends TileEntity implements IFruitBearer, IStreamable, IRipeningPacketReceiver { - private static final short MAX_MATURITY = 2; + private static final short MAX_MATURITY = 2; - private IAlleleFruit allele; + private IAlleleFruit allele; - private short maturity; - private int[] indices = new int[0]; - private float sappiness; + private short maturity; + private int[] indices = new int[0]; + private float sappiness; - public void setFruit(IAlleleFruit allele, float sappiness, short[] indices) { - this.allele = allele; - this.sappiness = sappiness; - this.indices = new int[indices.length]; - for (int i = 0; i < indices.length; i++) { - this.indices[i] = indices[i]; - } - } + public void setFruit(IAlleleFruit allele, float sappiness, short[] indices) { + this.allele = allele; + this.sappiness = sappiness; + this.indices = new int[indices.length]; + for (int i = 0; i < indices.length; i++) { + this.indices[i] = indices[i]; + } + } - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); - IAllele stored = AlleleManager.alleleRegistry.getAllele(nbttagcompound.getString("UID")); - if (stored != null && stored instanceof IAlleleFruit) { - allele = (IAlleleFruit) stored; - } else { - allele = (IAlleleFruit) AlleleManager.alleleRegistry.getAllele("fruitCocoa"); - } + IAllele stored = AlleleManager.alleleRegistry.getAllele(nbttagcompound.getString("UID")); + if (stored != null && stored instanceof IAlleleFruit) { + allele = (IAlleleFruit) stored; + } else { + allele = (IAlleleFruit) AlleleManager.alleleRegistry.getAllele("fruitCocoa"); + } - maturity = nbttagcompound.getShort("MT"); - sappiness = nbttagcompound.getFloat("SP"); - indices = nbttagcompound.getIntArray("IN"); - } + maturity = nbttagcompound.getShort("MT"); + sappiness = nbttagcompound.getFloat("SP"); + indices = nbttagcompound.getIntArray("IN"); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - if (allele != null) { - nbttagcompound.setString("UID", allele.getUID()); - } + if (allele != null) { + nbttagcompound.setString("UID", allele.getUID()); + } - nbttagcompound.setShort("MT", maturity); - nbttagcompound.setFloat("SP", sappiness); - nbttagcompound.setIntArray("IN", indices); - } + nbttagcompound.setShort("MT", maturity); + nbttagcompound.setFloat("SP", sappiness); + nbttagcompound.setIntArray("IN", indices); + } - /* UPDATING */ + /* UPDATING */ - /** - * This doesn't use normal TE updates - */ - @Override - public boolean canUpdate() { - return false; - } + /** + * This doesn't use normal TE updates + */ + @Override + public boolean canUpdate() { + return false; + } - public void onBlockTick() { - if (canMature() && worldObj.rand.nextFloat() <= sappiness) { - mature(); - } - } + public void onBlockTick() { + if (canMature() && worldObj.rand.nextFloat() <= sappiness) { + mature(); + } + } - public void mature() { - maturity++; - sendNetworkUpdateRipening(); - } + public void mature() { + maturity++; + sendNetworkUpdateRipening(); + } - public boolean canMature() { - return maturity < MAX_MATURITY; - } + public boolean canMature() { + return maturity < MAX_MATURITY; + } - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - if (maturity < indices.length) { - return TextureManager.getInstance().getIcon((short) indices[maturity]); - } else { - return null; - } - } + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + if (maturity < indices.length) { + return TextureManager.getInstance().getIcon((short) indices[maturity]); + } else { + return null; + } + } - public short getMaturity() { - return maturity; - } + public short getMaturity() { + return maturity; + } - public ItemStack[] getDrop() { - return allele.getProvider().getFruits(null, worldObj, xCoord, yCoord, zCoord, maturity); - } + public ItemStack[] getDrop() { + return allele.getProvider().getFruits(null, worldObj, xCoord, yCoord, zCoord, maturity); + } - /* NETWORK */ - @Override - public Packet getDescriptionPacket() { - return new PacketTileStream(this).getPacket(); - } + /* NETWORK */ + @Override + public Packet getDescriptionPacket() { + return new PacketTileStream(this).getPacket(); + } - private void sendNetworkUpdateRipening() { - Proxies.net.sendNetworkPacket(new PacketRipeningUpdate(this), worldObj); - } + private void sendNetworkUpdateRipening() { + Proxies.net.sendNetworkPacket(new PacketRipeningUpdate(this), worldObj); + } - @Override - public void fromRipeningPacket(int newMaturity) { - if (newMaturity == maturity) { - return; - } - maturity = (short) newMaturity; - worldObj.func_147479_m(xCoord, yCoord, zCoord); - } + @Override + public void fromRipeningPacket(int newMaturity) { + if (newMaturity == maturity) { + return; + } + maturity = (short) newMaturity; + worldObj.func_147479_m(xCoord, yCoord, zCoord); + } - /* IFRUITBEARER */ - @Override - public boolean hasFruit() { - return true; - } + /* IFRUITBEARER */ + @Override + public boolean hasFruit() { + return true; + } - @Override - public IFruitFamily getFruitFamily() { - if (allele == null) { - return null; - } - return allele.getProvider().getFamily(); - } + @Override + public IFruitFamily getFruitFamily() { + if (allele == null) { + return null; + } + return allele.getProvider().getFamily(); + } - @Override - public Collection pickFruit(ItemStack tool) { - if (allele == null) { - return new ArrayList<>(); - } + @Override + public Collection pickFruit(ItemStack tool) { + if (allele == null) { + return new ArrayList<>(); + } - Collection fruits = Arrays.asList(getDrop()); - maturity = 0; - sendNetworkUpdateRipening(); - return fruits; - } + Collection fruits = Arrays.asList(getDrop()); + maturity = 0; + sendNetworkUpdateRipening(); + return fruits; + } - @Override - public float getRipeness() { - return (float) maturity / MAX_MATURITY; - } + @Override + public float getRipeness() { + return (float) maturity / MAX_MATURITY; + } - @Override - public void addRipeness(float add) { - maturity += MAX_MATURITY * add; - sendNetworkUpdateRipening(); - } + @Override + public void addRipeness(float add) { + maturity += MAX_MATURITY * add; + sendNetworkUpdateRipening(); + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeShort(maturity); - data.writeShort(indices.length); - for (int i : indices) { - data.writeInt(i); - } - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeShort(maturity); + data.writeShort(indices.length); + for (int i : indices) { + data.writeInt(i); + } + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - maturity = data.readShort(); - int indicesLength = data.readShort(); - indices = new int[indicesLength]; - for (int i = 0; i < indicesLength; i++) { - indices[i] = data.readInt(); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + maturity = data.readShort(); + int indicesLength = data.readShort(); + indices = new int[indicesLength]; + for (int i = 0; i < indicesLength; i++) { + indices[i] = data.readInt(); + } - worldObj.func_147479_m(xCoord, yCoord, zCoord); - } + worldObj.func_147479_m(xCoord, yCoord, zCoord); + } } diff --git a/src/main/java/forestry/arboriculture/tiles/TileLeaves.java b/src/main/java/forestry/arboriculture/tiles/TileLeaves.java index 8934a0665..1e62d67f4 100644 --- a/src/main/java/forestry/arboriculture/tiles/TileLeaves.java +++ b/src/main/java/forestry/arboriculture/tiles/TileLeaves.java @@ -10,28 +10,9 @@ ******************************************************************************/ package forestry.arboriculture.tiles; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTUtil; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.EnumPlantType; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.arboriculture.IFruitProvider; @@ -67,532 +48,553 @@ import forestry.core.render.TextureManager; import forestry.core.utils.ColourUtil; import forestry.core.utils.GeneticsUtil; import forestry.core.utils.Log; - -public class TileLeaves extends TileTreeContainer implements IPollinatable, IFruitBearer, IButterflyNursery, IRipeningPacketReceiver { - - private int colourLeaves; - private int colourLeavesPollinated; - private int colourFruits; - - private short textureIndexFruits = -1; - private IAlleleTreeSpecies species; - - private boolean isFruitLeaf; - private boolean isPollinatedState; - private int ripeningTime; - private short ripeningPeriod = Short.MAX_VALUE - 1; - - // set true when placed by a player - private boolean isDecorative = false; - - private int maturationTime; - private int damage; - - private IEffectData effectData[] = new IEffectData[2]; - - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - // trees from itemStacks will have no coordinates - if (nbttagcompound.hasKey("x")) { - this.xCoord = nbttagcompound.getInteger("x"); - this.yCoord = nbttagcompound.getInteger("y"); - this.zCoord = nbttagcompound.getInteger("z"); - } - - if (nbttagcompound.hasKey("species")) { - isDecorative = true; - - String speciesUID = nbttagcompound.getString("species"); - IAllele[] treeTemplate = TreeManager.treeRoot.getTemplate(speciesUID); - ITree containedTree = TreeManager.treeRoot.templateAsIndividual(treeTemplate); - setTree(containedTree); - } else { - if (nbttagcompound.hasKey("owner")) { - setOwner(NBTUtil.func_152459_a(nbttagcompound.getCompoundTag("owner"))); - } - - ripeningTime = nbttagcompound.getShort("RT"); - damage = nbttagcompound.getInteger("ENC"); - - if (nbttagcompound.hasKey("CATER")) { - maturationTime = nbttagcompound.getInteger("CATMAT"); - caterpillar = ButterflyManager.butterflyRoot.getMember(nbttagcompound.getCompoundTag("CATER")); - } - - if (nbttagcompound.hasKey("Decorative")) { //legacy - isDecorative = nbttagcompound.getBoolean("Decorative"); - } else { //legacy - isDecorative = nbttagcompound.getBoolean("DEC"); - } - - if (nbttagcompound.hasKey("ContainedTree")) { - setTree(new Tree(nbttagcompound.getCompoundTag("ContainedTree"))); - } - } - } - - public void writeToNBTDecorative(NBTTagCompound nbtTagCompound) { - String speciesUID = getSpeciesUID(); - if (speciesUID != null) { - nbtTagCompound.setString("species", speciesUID); - } - } - - @Override - public void writeToNBT(NBTTagCompound nbtTagCompound) { - nbtTagCompound.setString("id", "forestry.Leaves"); - nbtTagCompound.setInteger("x", this.xCoord); - nbtTagCompound.setInteger("y", this.yCoord); - nbtTagCompound.setInteger("z", this.zCoord); - - if (isDecorative) { - writeToNBTDecorative(nbtTagCompound); - } else { - ITree tree = getTree(); - if (tree != null) { - NBTTagCompound subcompound = new NBTTagCompound(); - tree.writeToNBT(subcompound); - nbtTagCompound.setTag("ContainedTree", subcompound); - } - - GameProfile owner = getOwner(); - if (owner != null) { - NBTTagCompound nbt = new NBTTagCompound(); - NBTUtil.func_152460_a(nbt, owner); - nbtTagCompound.setTag("owner", nbt); - } - - nbtTagCompound.setInteger("RT", getRipeningTime()); - nbtTagCompound.setInteger("ENC", damage); - - if (caterpillar != null) { - nbtTagCompound.setInteger("CATMAT", maturationTime); - - NBTTagCompound subcompound = new NBTTagCompound(); - caterpillar.writeToNBT(subcompound); - nbtTagCompound.setTag("CATER", subcompound); - } - } - } - - @Override - public void onBlockTick() { - ITree tree = getTree(); - if (isDecorative || tree == null) { - return; - } - - ITreeGenome genome = tree.getGenome(); - - boolean isDestroyed = isDestroyed(tree, damage); - for (ILeafTickHandler tickHandler : genome.getPrimary().getRoot().getLeafTickHandlers()) { - if (tickHandler.onRandomLeafTick(tree, worldObj, xCoord, yCoord, zCoord, isDestroyed)) { - return; - } - } - - if (isDestroyed) { - return; - } - - if (damage > 0) { - damage--; - } - - if (hasFruit() && getRipeningTime() < ripeningPeriod) { - ITreekeepingMode treekeepingMode = TreeManager.treeRoot.getTreekeepingMode(worldObj); - float sappinessModifier = treekeepingMode.getSappinessModifier(genome, 1f); - float sappiness = genome.getSappiness() * sappinessModifier; - - if (worldObj.rand.nextFloat() < sappiness) { - ripeningTime++; - sendNetworkUpdateRipening(); - } - } - - if (caterpillar != null) { - matureCaterpillar(); - } - - effectData = tree.doEffect(effectData, worldObj, xCoord, yCoord, zCoord); - } - - @Override - public void setTree(ITree tree) { - super.setTree(tree); - - ITreeGenome genome = tree.getGenome(); - species = genome.getPrimary(); - - if (tree.canBearFruit()) { - IFruitProvider fruitProvider = genome.getFruitProvider(); - - isFruitLeaf = fruitProvider.markAsFruitLeaf(genome, worldObj, xCoord, yCoord, zCoord); - if (isFruitLeaf) { - // Hardcoded because vanilla oak trees don't show fruits. - if ((species == TreeDefinition.Oak.getGenome().getPrimary()) && (fruitProvider == AlleleFruit.fruitApple.getProvider())) { - textureIndexFruits = -1; - } else { - textureIndexFruits = fruitProvider.getIconIndex(genome, worldObj, xCoord, yCoord, zCoord, getRipeningTime(), true); - } - - ripeningPeriod = (short) tree.getGenome().getFruitProvider().getRipeningPeriod(); - } - } else { - isFruitLeaf = false; - textureIndexFruits = -1; - } - - colourLeaves = species.getLeafColour(false); - colourLeavesPollinated = species.getLeafColour(true); - if (isDestroyed(tree, damage)) { - colourLeaves = ColourUtil.addRGBComponents(colourLeaves, 92, 61, 0); - } else if (caterpillar != null) { - colourLeaves = ColourUtil.multiplyRGBComponents(colourLeaves, 1.5f); - } - markDirty(); - } - - /* INFORMATION */ - private static boolean isDestroyed(ITree tree, int damage) { - if (tree == null) { - return false; - } - return damage > tree.getResilience(); - } - - @Override - public boolean isPollinated() { - ITree tree = getTree(); - return tree != null && !isDestroyed(tree, damage) && tree.getMate() != null; - } - - public int getFoliageColour(EntityPlayer player) { - if (isPollinatedState && GeneticsUtil.hasNaturalistEye(player)) { - return colourLeavesPollinated; - } else { - return colourLeaves; - } - } - - public int getFruitColour() { - if (colourFruits == 0 && hasFruit()) { - colourFruits = determineFruitColour(); - } - return colourFruits; - } - - private int determineFruitColour() { - ITree tree = getTree(); - ITreeGenome genome = tree.getGenome(); - IFruitProvider fruit = genome.getFruitProvider(); - return fruit.getColour(genome, worldObj, xCoord, yCoord, zCoord, getRipeningTime()); - } - - @SideOnly(Side.CLIENT) - public IIcon getIcon(boolean fancy) { - if (species == null) { - return TreeDefinition.Oak.getIndividual().getGenome().getPrimary().getLeafIcon(false, fancy); - } - return species.getLeafIcon(isPollinatedState, fancy); - } - - @SideOnly(Side.CLIENT) - public IIcon getFruitTexture() { - if (textureIndexFruits >= 0) { - return TextureManager.getInstance().getIcon(textureIndexFruits); - } else { - return null; - } - } - - public int getRipeningTime() { - return isDecorative ? ripeningPeriod : ripeningTime; - } - - public void setDecorative() { - isDecorative = true; - } - - public boolean isDecorative() { - return isDecorative; - } - - /* IPOLLINATABLE */ - @Override - public EnumSet getPlantType() { - if (getTree() == null) { - return EnumSet.noneOf(EnumPlantType.class); - } - - return getTree().getPlantTypes(); - } - - @Override - public boolean canMateWith(IIndividual individual) { - if (getTree() == null || isDecorative) { - return false; - } - if (getTree().getMate() != null) { - return false; - } - if (!(individual instanceof ITree)) { - return false; - } - - return !getTree().isGeneticEqual(individual); - } - - @Override - public void mateWith(IIndividual individual) { - if (getTree() == null || isDecorative) { - return; - } - - getTree().mate((ITree) individual); - worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); - } - - @Override - public IIndividual getPollen() { - if (isDecorative) { - return null; - } - return getTree(); - } - - public String getUnlocalizedName() { - ITree tree = getTree(); - if (tree == null) { - return "for.leaves.corrupted"; - } - return tree.getGenome().getPrimary().getUnlocalizedName(); - } - - /* NETWORK */ - private void sendNetworkUpdate() { - Proxies.net.sendNetworkPacket(new PacketTileStream(this), worldObj); - } - - private void sendNetworkUpdateRipening() { - int newColourFruits = determineFruitColour(); - if (newColourFruits == colourFruits) { - return; - } - colourFruits = newColourFruits; - - PacketRipeningUpdate ripeningUpdate = new PacketRipeningUpdate(this); - Proxies.net.sendNetworkPacket(ripeningUpdate, worldObj); - } - - private static final short hasFruitFlag = 1; - private static final short isPollinatedFlag = 1 << 1; - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - - byte leafState = 0; - boolean hasFruit = hasFruit(); - - if (isPollinated()) { - leafState |= isPollinatedFlag; - } - - if (hasFruit) { - leafState |= hasFruitFlag; - } - - data.writeByte(leafState); - - if (hasFruit) { - String fruitAlleleUID = getTree().getGenome().getActiveAllele(EnumTreeChromosome.FRUITS).getUID(); - int colourFruits = getFruitColour(); - - data.writeUTF(fruitAlleleUID); - data.writeInt(colourFruits); - } - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - - String speciesUID = data.readUTF(); // this is called instead of super.readData, be careful! - - byte leafState = data.readByte(); - isFruitLeaf = (leafState & hasFruitFlag) > 0; - isPollinatedState = (leafState & isPollinatedFlag) > 0; - String fruitAlleleUID = null; - - if (isFruitLeaf) { - fruitAlleleUID = data.readUTF(); - colourFruits = data.readInt(); - } - - IAllele[] treeTemplate = TreeManager.treeRoot.getTemplate(speciesUID); - - if (fruitAlleleUID != null) { - IAllele fruitAllele = AlleleManager.alleleRegistry.getAllele(fruitAlleleUID); - if (fruitAllele != null) { - treeTemplate[EnumTreeChromosome.FRUITS.ordinal()] = fruitAllele; - } - } - - if (treeTemplate != null) { - ITree tree = TreeManager.treeRoot.templateAsIndividual(treeTemplate); - if (isPollinatedState) { - tree.mate(tree); - } - - setTree(tree); - - worldObj.func_147479_m(xCoord, yCoord, zCoord); - } - } - - @Override - public void fromRipeningPacket(int newColourFruits) { - if (newColourFruits == colourFruits) { - return; - } - colourFruits = newColourFruits; - worldObj.func_147479_m(xCoord, yCoord, zCoord); - } - - /* IFRUITBEARER */ - @Override - public Collection pickFruit(ItemStack tool) { - ITree tree = getTree(); - if (tree == null || !hasFruit() || isDecorative) { - return Collections.emptyList(); - } - - ItemStack[] produceStacks = tree.produceStacks(worldObj, xCoord, yCoord, zCoord, getRipeningTime()); - ripeningTime = 0; - sendNetworkUpdateRipening(); - return Arrays.asList(produceStacks); - } - - @Override - public IFruitFamily getFruitFamily() { - ITree tree = getTree(); - if (tree == null) { - return null; - } - return tree.getGenome().getFruitProvider().getFamily(); - } - - @Override - public float getRipeness() { - if (ripeningPeriod == 0) { - return 1.0f; - } - if (getTree() == null) { - return 0f; - } - return (float) getRipeningTime() / ripeningPeriod; - } - - @Override - public boolean hasFruit() { - return isFruitLeaf && !isDestroyed(getTree(), damage); - } - - @Override - public void addRipeness(float add) { - if (getTree() == null || !isFruitLeaf || getRipeningTime() >= ripeningPeriod || isDecorative) { - return; - } - ripeningTime += ripeningPeriod * add; - sendNetworkUpdateRipening(); - } - - public String getSpeciesUID() { - if (species == null) { - return null; - } - return species.getUID(); - } - - /* IBUTTERFLYNURSERY */ - private IButterfly caterpillar; - - private void matureCaterpillar() { - maturationTime++; - - ITree tree = getTree(); - boolean wasDestroyed = isDestroyed(tree, damage); - damage += caterpillar.getGenome().getMetabolism(); - - IButterflyGenome caterpillarGenome = caterpillar.getGenome(); - int caterpillarMatureTime = Math.round((float) caterpillarGenome.getLifespan() / (caterpillarGenome.getFertility() * 2)); - - if (maturationTime >= caterpillarMatureTime && caterpillar.canTakeFlight(worldObj, xCoord, yCoord, zCoord)) { - if (worldObj.isAirBlock(xCoord - 1, yCoord, zCoord)) { - attemptButterflySpawn(worldObj, caterpillar, xCoord - 1, yCoord, zCoord); - } else if (worldObj.isAirBlock(xCoord + 1, yCoord, zCoord)) { - attemptButterflySpawn(worldObj, caterpillar, xCoord + 1, yCoord, zCoord); - } else if (worldObj.isAirBlock(xCoord, yCoord, zCoord - 1)) { - attemptButterflySpawn(worldObj, caterpillar, xCoord, yCoord, zCoord - 1); - } else if (worldObj.isAirBlock(xCoord, yCoord, zCoord + 1)) { - attemptButterflySpawn(worldObj, caterpillar, xCoord, yCoord, zCoord + 1); - } - setCaterpillar(null); - } else if (!wasDestroyed && isDestroyed(tree, damage)) { - sendNetworkUpdate(); - } - } - - private static void attemptButterflySpawn(World world, IButterfly butterfly, double x, double y, double z) { - if (ButterflyManager.butterflyRoot.spawnButterflyInWorld(world, butterfly.copy(), x, y + 0.1f, z) != null) { - Log.finest("A caterpillar '%s' hatched at %s/%s/%s.", butterfly.getDisplayName(), x, y, z); - } - } - - @Override - public ChunkCoordinates getCoordinates() { - return new ChunkCoordinates(xCoord, yCoord, zCoord); - } - - @Override - public IButterfly getCaterpillar() { - return caterpillar; - } - - @Override - public IIndividual getNanny() { - return getTree(); - } - - @Override - public void setCaterpillar(IButterfly butterfly) { - if (isDecorative) { - return; - } - maturationTime = 0; - caterpillar = butterfly; - sendNetworkUpdate(); - } - - @Override - public boolean canNurse(IButterfly butterfly) { - ITree tree = getTree(); - return !isDecorative && !isDestroyed(tree, damage) && caterpillar == null; - } - - @Override - public BiomeGenBase getBiome() { - return worldObj.getBiomeGenForCoords(xCoord, zCoord); - } - - @Override - public EnumTemperature getTemperature() { - return EnumTemperature.getFromBiome(getBiome(), xCoord, yCoord, zCoord); - } - - @Override - public EnumHumidity getHumidity() { - return EnumHumidity.getFromValue(ForestryAPI.climateManager.getHumidity(worldObj, xCoord, yCoord, zCoord)); - } +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTUtil; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; +import net.minecraftforge.common.EnumPlantType; + +public class TileLeaves extends TileTreeContainer + implements IPollinatable, IFruitBearer, IButterflyNursery, IRipeningPacketReceiver { + + private int colourLeaves; + private int colourLeavesPollinated; + private int colourFruits; + + private short textureIndexFruits = -1; + private IAlleleTreeSpecies species; + + private boolean isFruitLeaf; + private boolean isPollinatedState; + private int ripeningTime; + private short ripeningPeriod = Short.MAX_VALUE - 1; + + // set true when placed by a player + private boolean isDecorative = false; + + private int maturationTime; + private int damage; + + private IEffectData effectData[] = new IEffectData[2]; + + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + // trees from itemStacks will have no coordinates + if (nbttagcompound.hasKey("x")) { + this.xCoord = nbttagcompound.getInteger("x"); + this.yCoord = nbttagcompound.getInteger("y"); + this.zCoord = nbttagcompound.getInteger("z"); + } + + if (nbttagcompound.hasKey("species")) { + isDecorative = true; + + String speciesUID = nbttagcompound.getString("species"); + IAllele[] treeTemplate = TreeManager.treeRoot.getTemplate(speciesUID); + ITree containedTree = TreeManager.treeRoot.templateAsIndividual(treeTemplate); + setTree(containedTree); + } else { + if (nbttagcompound.hasKey("owner")) { + setOwner(NBTUtil.func_152459_a(nbttagcompound.getCompoundTag("owner"))); + } + + ripeningTime = nbttagcompound.getShort("RT"); + damage = nbttagcompound.getInteger("ENC"); + + if (nbttagcompound.hasKey("CATER")) { + maturationTime = nbttagcompound.getInteger("CATMAT"); + caterpillar = ButterflyManager.butterflyRoot.getMember(nbttagcompound.getCompoundTag("CATER")); + } + + if (nbttagcompound.hasKey("Decorative")) { // legacy + isDecorative = nbttagcompound.getBoolean("Decorative"); + } else { // legacy + isDecorative = nbttagcompound.getBoolean("DEC"); + } + + if (nbttagcompound.hasKey("ContainedTree")) { + setTree(new Tree(nbttagcompound.getCompoundTag("ContainedTree"))); + } + } + } + + public void writeToNBTDecorative(NBTTagCompound nbtTagCompound) { + String speciesUID = getSpeciesUID(); + if (speciesUID != null) { + nbtTagCompound.setString("species", speciesUID); + } + } + + @Override + public void writeToNBT(NBTTagCompound nbtTagCompound) { + nbtTagCompound.setString("id", "forestry.Leaves"); + nbtTagCompound.setInteger("x", this.xCoord); + nbtTagCompound.setInteger("y", this.yCoord); + nbtTagCompound.setInteger("z", this.zCoord); + + if (isDecorative) { + writeToNBTDecorative(nbtTagCompound); + } else { + ITree tree = getTree(); + if (tree != null) { + NBTTagCompound subcompound = new NBTTagCompound(); + tree.writeToNBT(subcompound); + nbtTagCompound.setTag("ContainedTree", subcompound); + } + + GameProfile owner = getOwner(); + if (owner != null) { + NBTTagCompound nbt = new NBTTagCompound(); + NBTUtil.func_152460_a(nbt, owner); + nbtTagCompound.setTag("owner", nbt); + } + + nbtTagCompound.setInteger("RT", getRipeningTime()); + nbtTagCompound.setInteger("ENC", damage); + + if (caterpillar != null) { + nbtTagCompound.setInteger("CATMAT", maturationTime); + + NBTTagCompound subcompound = new NBTTagCompound(); + caterpillar.writeToNBT(subcompound); + nbtTagCompound.setTag("CATER", subcompound); + } + } + } + + @Override + public void onBlockTick() { + ITree tree = getTree(); + if (isDecorative || tree == null) { + return; + } + + ITreeGenome genome = tree.getGenome(); + + boolean isDestroyed = isDestroyed(tree, damage); + for (ILeafTickHandler tickHandler : genome.getPrimary().getRoot().getLeafTickHandlers()) { + if (tickHandler.onRandomLeafTick(tree, worldObj, xCoord, yCoord, zCoord, isDestroyed)) { + return; + } + } + + if (isDestroyed) { + return; + } + + if (damage > 0) { + damage--; + } + + if (hasFruit() && getRipeningTime() < ripeningPeriod) { + ITreekeepingMode treekeepingMode = TreeManager.treeRoot.getTreekeepingMode(worldObj); + float sappinessModifier = treekeepingMode.getSappinessModifier(genome, 1f); + float sappiness = genome.getSappiness() * sappinessModifier; + + if (worldObj.rand.nextFloat() < sappiness) { + ripeningTime++; + sendNetworkUpdateRipening(); + } + } + + if (caterpillar != null) { + matureCaterpillar(); + } + + effectData = tree.doEffect(effectData, worldObj, xCoord, yCoord, zCoord); + } + + @Override + public void setTree(ITree tree) { + super.setTree(tree); + + ITreeGenome genome = tree.getGenome(); + species = genome.getPrimary(); + + if (tree.canBearFruit()) { + IFruitProvider fruitProvider = genome.getFruitProvider(); + + isFruitLeaf = fruitProvider.markAsFruitLeaf(genome, worldObj, xCoord, yCoord, zCoord); + if (isFruitLeaf) { + // Hardcoded because vanilla oak trees don't show fruits. + if ((species == TreeDefinition.Oak.getGenome().getPrimary()) + && (fruitProvider == AlleleFruit.fruitApple.getProvider())) { + textureIndexFruits = -1; + } else { + textureIndexFruits = fruitProvider.getIconIndex( + genome, worldObj, xCoord, yCoord, zCoord, getRipeningTime(), true); + } + + ripeningPeriod = (short) tree.getGenome().getFruitProvider().getRipeningPeriod(); + } + } else { + isFruitLeaf = false; + textureIndexFruits = -1; + } + + colourLeaves = species.getLeafColour(false); + colourLeavesPollinated = species.getLeafColour(true); + if (isDestroyed(tree, damage)) { + colourLeaves = ColourUtil.addRGBComponents(colourLeaves, 92, 61, 0); + } else if (caterpillar != null) { + colourLeaves = ColourUtil.multiplyRGBComponents(colourLeaves, 1.5f); + } + markDirty(); + } + + /* INFORMATION */ + private static boolean isDestroyed(ITree tree, int damage) { + if (tree == null) { + return false; + } + return damage > tree.getResilience(); + } + + @Override + public boolean isPollinated() { + ITree tree = getTree(); + return tree != null && !isDestroyed(tree, damage) && tree.getMate() != null; + } + + public int getFoliageColour(EntityPlayer player) { + if (isPollinatedState && GeneticsUtil.hasNaturalistEye(player)) { + return colourLeavesPollinated; + } else { + return colourLeaves; + } + } + + public int getFruitColour() { + if (colourFruits == 0 && hasFruit()) { + colourFruits = determineFruitColour(); + } + return colourFruits; + } + + private int determineFruitColour() { + ITree tree = getTree(); + ITreeGenome genome = tree.getGenome(); + IFruitProvider fruit = genome.getFruitProvider(); + return fruit.getColour(genome, worldObj, xCoord, yCoord, zCoord, getRipeningTime()); + } + + @SideOnly(Side.CLIENT) + public IIcon getIcon(boolean fancy) { + if (species == null) { + return TreeDefinition.Oak.getIndividual().getGenome().getPrimary().getLeafIcon(false, fancy); + } + return species.getLeafIcon(isPollinatedState, fancy); + } + + @SideOnly(Side.CLIENT) + public IIcon getFruitTexture() { + if (textureIndexFruits >= 0) { + return TextureManager.getInstance().getIcon(textureIndexFruits); + } else { + return null; + } + } + + public int getRipeningTime() { + return isDecorative ? ripeningPeriod : ripeningTime; + } + + public void setDecorative() { + isDecorative = true; + } + + public boolean isDecorative() { + return isDecorative; + } + + /* IPOLLINATABLE */ + @Override + public EnumSet getPlantType() { + if (getTree() == null) { + return EnumSet.noneOf(EnumPlantType.class); + } + + return getTree().getPlantTypes(); + } + + @Override + public boolean canMateWith(IIndividual individual) { + if (getTree() == null || isDecorative) { + return false; + } + if (getTree().getMate() != null) { + return false; + } + if (!(individual instanceof ITree)) { + return false; + } + + return !getTree().isGeneticEqual(individual); + } + + @Override + public void mateWith(IIndividual individual) { + if (getTree() == null || isDecorative) { + return; + } + + getTree().mate((ITree) individual); + worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); + } + + @Override + public IIndividual getPollen() { + if (isDecorative) { + return null; + } + return getTree(); + } + + public String getUnlocalizedName() { + ITree tree = getTree(); + if (tree == null) { + return "for.leaves.corrupted"; + } + return tree.getGenome().getPrimary().getUnlocalizedName(); + } + + /* NETWORK */ + private void sendNetworkUpdate() { + Proxies.net.sendNetworkPacket(new PacketTileStream(this), worldObj); + } + + private void sendNetworkUpdateRipening() { + int newColourFruits = determineFruitColour(); + if (newColourFruits == colourFruits) { + return; + } + colourFruits = newColourFruits; + + PacketRipeningUpdate ripeningUpdate = new PacketRipeningUpdate(this); + Proxies.net.sendNetworkPacket(ripeningUpdate, worldObj); + } + + private static final short hasFruitFlag = 1; + private static final short isPollinatedFlag = 1 << 1; + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + + byte leafState = 0; + boolean hasFruit = hasFruit(); + + if (isPollinated()) { + leafState |= isPollinatedFlag; + } + + if (hasFruit) { + leafState |= hasFruitFlag; + } + + data.writeByte(leafState); + + if (hasFruit) { + String fruitAlleleUID = getTree() + .getGenome() + .getActiveAllele(EnumTreeChromosome.FRUITS) + .getUID(); + int colourFruits = getFruitColour(); + + data.writeUTF(fruitAlleleUID); + data.writeInt(colourFruits); + } + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + + String speciesUID = data.readUTF(); // this is called instead of super.readData, be careful! + + byte leafState = data.readByte(); + isFruitLeaf = (leafState & hasFruitFlag) > 0; + isPollinatedState = (leafState & isPollinatedFlag) > 0; + String fruitAlleleUID = null; + + if (isFruitLeaf) { + fruitAlleleUID = data.readUTF(); + colourFruits = data.readInt(); + } + + IAllele[] treeTemplate = TreeManager.treeRoot.getTemplate(speciesUID); + + if (fruitAlleleUID != null) { + IAllele fruitAllele = AlleleManager.alleleRegistry.getAllele(fruitAlleleUID); + if (fruitAllele != null) { + treeTemplate[EnumTreeChromosome.FRUITS.ordinal()] = fruitAllele; + } + } + + if (treeTemplate != null) { + ITree tree = TreeManager.treeRoot.templateAsIndividual(treeTemplate); + if (isPollinatedState) { + tree.mate(tree); + } + + setTree(tree); + + worldObj.func_147479_m(xCoord, yCoord, zCoord); + } + } + + @Override + public void fromRipeningPacket(int newColourFruits) { + if (newColourFruits == colourFruits) { + return; + } + colourFruits = newColourFruits; + worldObj.func_147479_m(xCoord, yCoord, zCoord); + } + + /* IFRUITBEARER */ + @Override + public Collection pickFruit(ItemStack tool) { + ITree tree = getTree(); + if (tree == null || !hasFruit() || isDecorative) { + return Collections.emptyList(); + } + + ItemStack[] produceStacks = tree.produceStacks(worldObj, xCoord, yCoord, zCoord, getRipeningTime()); + ripeningTime = 0; + sendNetworkUpdateRipening(); + return Arrays.asList(produceStacks); + } + + @Override + public IFruitFamily getFruitFamily() { + ITree tree = getTree(); + if (tree == null) { + return null; + } + return tree.getGenome().getFruitProvider().getFamily(); + } + + @Override + public float getRipeness() { + if (ripeningPeriod == 0) { + return 1.0f; + } + if (getTree() == null) { + return 0f; + } + return (float) getRipeningTime() / ripeningPeriod; + } + + @Override + public boolean hasFruit() { + return isFruitLeaf && !isDestroyed(getTree(), damage); + } + + @Override + public void addRipeness(float add) { + if (getTree() == null || !isFruitLeaf || getRipeningTime() >= ripeningPeriod || isDecorative) { + return; + } + ripeningTime += ripeningPeriod * add; + sendNetworkUpdateRipening(); + } + + public String getSpeciesUID() { + if (species == null) { + return null; + } + return species.getUID(); + } + + /* IBUTTERFLYNURSERY */ + private IButterfly caterpillar; + + private void matureCaterpillar() { + maturationTime++; + + ITree tree = getTree(); + boolean wasDestroyed = isDestroyed(tree, damage); + damage += caterpillar.getGenome().getMetabolism(); + + IButterflyGenome caterpillarGenome = caterpillar.getGenome(); + int caterpillarMatureTime = + Math.round((float) caterpillarGenome.getLifespan() / (caterpillarGenome.getFertility() * 2)); + + if (maturationTime >= caterpillarMatureTime && caterpillar.canTakeFlight(worldObj, xCoord, yCoord, zCoord)) { + if (worldObj.isAirBlock(xCoord - 1, yCoord, zCoord)) { + attemptButterflySpawn(worldObj, caterpillar, xCoord - 1, yCoord, zCoord); + } else if (worldObj.isAirBlock(xCoord + 1, yCoord, zCoord)) { + attemptButterflySpawn(worldObj, caterpillar, xCoord + 1, yCoord, zCoord); + } else if (worldObj.isAirBlock(xCoord, yCoord, zCoord - 1)) { + attemptButterflySpawn(worldObj, caterpillar, xCoord, yCoord, zCoord - 1); + } else if (worldObj.isAirBlock(xCoord, yCoord, zCoord + 1)) { + attemptButterflySpawn(worldObj, caterpillar, xCoord, yCoord, zCoord + 1); + } + setCaterpillar(null); + } else if (!wasDestroyed && isDestroyed(tree, damage)) { + sendNetworkUpdate(); + } + } + + private static void attemptButterflySpawn(World world, IButterfly butterfly, double x, double y, double z) { + if (ButterflyManager.butterflyRoot.spawnButterflyInWorld(world, butterfly.copy(), x, y + 0.1f, z) != null) { + Log.finest("A caterpillar '%s' hatched at %s/%s/%s.", butterfly.getDisplayName(), x, y, z); + } + } + + @Override + public ChunkCoordinates getCoordinates() { + return new ChunkCoordinates(xCoord, yCoord, zCoord); + } + + @Override + public IButterfly getCaterpillar() { + return caterpillar; + } + + @Override + public IIndividual getNanny() { + return getTree(); + } + + @Override + public void setCaterpillar(IButterfly butterfly) { + if (isDecorative) { + return; + } + maturationTime = 0; + caterpillar = butterfly; + sendNetworkUpdate(); + } + + @Override + public boolean canNurse(IButterfly butterfly) { + ITree tree = getTree(); + return !isDecorative && !isDestroyed(tree, damage) && caterpillar == null; + } + + @Override + public BiomeGenBase getBiome() { + return worldObj.getBiomeGenForCoords(xCoord, zCoord); + } + + @Override + public EnumTemperature getTemperature() { + return EnumTemperature.getFromBiome(getBiome(), xCoord, yCoord, zCoord); + } + + @Override + public EnumHumidity getHumidity() { + return EnumHumidity.getFromValue(ForestryAPI.climateManager.getHumidity(worldObj, xCoord, yCoord, zCoord)); + } } diff --git a/src/main/java/forestry/arboriculture/tiles/TileSapling.java b/src/main/java/forestry/arboriculture/tiles/TileSapling.java index d32d8836c..010f71c4e 100644 --- a/src/main/java/forestry/arboriculture/tiles/TileSapling.java +++ b/src/main/java/forestry/arboriculture/tiles/TileSapling.java @@ -10,99 +10,97 @@ ******************************************************************************/ package forestry.arboriculture.tiles; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; -import net.minecraft.world.gen.feature.WorldGenerator; - import forestry.api.arboriculture.ITree; import forestry.api.arboriculture.ITreekeepingMode; import forestry.api.arboriculture.TreeManager; import forestry.api.genetics.IBreedingTracker; import forestry.arboriculture.worldgen.WorldGenArboriculture; import forestry.core.worldgen.WorldGenBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import net.minecraft.world.gen.feature.WorldGenerator; public class TileSapling extends TileTreeContainer { - private int timesTicked = 0; + private int timesTicked = 0; - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); - timesTicked = nbttagcompound.getInteger("TT"); - } + timesTicked = nbttagcompound.getInteger("TT"); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - nbttagcompound.setInteger("TT", timesTicked); - } + nbttagcompound.setInteger("TT", timesTicked); + } - @Override - public void onBlockTick() { + @Override + public void onBlockTick() { - timesTicked++; - tryGrow(false); - } + timesTicked++; + tryGrow(false); + } - private static int getRequiredMaturity(World world, ITree tree) { - ITreekeepingMode treekeepingMode = TreeManager.treeRoot.getTreekeepingMode(world); - float maturationModifier = treekeepingMode.getMaturationModifier(tree.getGenome(), 1f); - return Math.round(tree.getRequiredMaturity() * maturationModifier); - } + private static int getRequiredMaturity(World world, ITree tree) { + ITreekeepingMode treekeepingMode = TreeManager.treeRoot.getTreekeepingMode(world); + float maturationModifier = treekeepingMode.getMaturationModifier(tree.getGenome(), 1f); + return Math.round(tree.getRequiredMaturity() * maturationModifier); + } - public boolean canAcceptBoneMeal() { - ITree tree = getTree(); + public boolean canAcceptBoneMeal() { + ITree tree = getTree(); - if (tree == null) { - return false; - } + if (tree == null) { + return false; + } - int maturity = getRequiredMaturity(worldObj, tree); - if (timesTicked < maturity) { - return true; - } + int maturity = getRequiredMaturity(worldObj, tree); + if (timesTicked < maturity) { + return true; + } - WorldGenerator generator = tree.getTreeGenerator(worldObj, xCoord, yCoord, zCoord, true); - if (generator instanceof WorldGenArboriculture) { - WorldGenArboriculture arboricultureGenerator = (WorldGenArboriculture) generator; - arboricultureGenerator.preGenerate(worldObj, xCoord, yCoord, zCoord); - return arboricultureGenerator.canGrow(worldObj, xCoord, yCoord, zCoord); - } else { - return true; - } - } + WorldGenerator generator = tree.getTreeGenerator(worldObj, xCoord, yCoord, zCoord, true); + if (generator instanceof WorldGenArboriculture) { + WorldGenArboriculture arboricultureGenerator = (WorldGenArboriculture) generator; + arboricultureGenerator.preGenerate(worldObj, xCoord, yCoord, zCoord); + return arboricultureGenerator.canGrow(worldObj, xCoord, yCoord, zCoord); + } else { + return true; + } + } - public void tryGrow(boolean bonemealed) { + public void tryGrow(boolean bonemealed) { - ITree tree = getTree(); + ITree tree = getTree(); - if (tree == null) { - return; - } + if (tree == null) { + return; + } - int maturity = getRequiredMaturity(worldObj, tree); - if (timesTicked < maturity) { - if (bonemealed) { - timesTicked = maturity; - } - return; - } + int maturity = getRequiredMaturity(worldObj, tree); + if (timesTicked < maturity) { + if (bonemealed) { + timesTicked = maturity; + } + return; + } - WorldGenerator generator = tree.getTreeGenerator(worldObj, xCoord, yCoord, zCoord, bonemealed); - final boolean generated; - if (generator instanceof WorldGenBase) { - generated = ((WorldGenBase) generator).generate(worldObj, xCoord, yCoord, zCoord, bonemealed); - } else { - generated = generator.generate(worldObj, worldObj.rand, xCoord, yCoord, zCoord); - } - - if (generated) { - IBreedingTracker breedingTracker = TreeManager.treeRoot.getBreedingTracker(worldObj, getOwner()); - breedingTracker.registerBirth(tree); - } - } + WorldGenerator generator = tree.getTreeGenerator(worldObj, xCoord, yCoord, zCoord, bonemealed); + final boolean generated; + if (generator instanceof WorldGenBase) { + generated = ((WorldGenBase) generator).generate(worldObj, xCoord, yCoord, zCoord, bonemealed); + } else { + generated = generator.generate(worldObj, worldObj.rand, xCoord, yCoord, zCoord); + } + if (generated) { + IBreedingTracker breedingTracker = TreeManager.treeRoot.getBreedingTracker(worldObj, getOwner()); + breedingTracker.registerBirth(tree); + } + } } diff --git a/src/main/java/forestry/arboriculture/tiles/TileTreeContainer.java b/src/main/java/forestry/arboriculture/tiles/TileTreeContainer.java index 89290b647..d552fc1bf 100644 --- a/src/main/java/forestry/arboriculture/tiles/TileTreeContainer.java +++ b/src/main/java/forestry/arboriculture/tiles/TileTreeContainer.java @@ -10,18 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.tiles; -import java.io.IOException; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTUtil; -import net.minecraft.network.Packet; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import forestry.api.arboriculture.ITree; import forestry.api.arboriculture.TreeManager; import forestry.api.genetics.IAllele; @@ -32,6 +21,14 @@ import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; import forestry.core.network.packets.PacketTileStream; import forestry.core.utils.PlayerUtil; +import java.io.IOException; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTUtil; +import net.minecraft.network.Packet; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; /** * This is the base TE class for any block that needs to contain tree genome information. @@ -40,126 +37,126 @@ import forestry.core.utils.PlayerUtil; */ public abstract class TileTreeContainer extends TileEntity implements IStreamable, IOwnable { - private ITree containedTree; - private GameProfile owner; + private ITree containedTree; + private GameProfile owner; - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); - if (nbttagcompound.hasKey("ContainedTree")) { - containedTree = new Tree(nbttagcompound.getCompoundTag("ContainedTree")); - } - if (nbttagcompound.hasKey("owner")) { - owner = NBTUtil.func_152459_a(nbttagcompound.getCompoundTag("owner")); - } - } + if (nbttagcompound.hasKey("ContainedTree")) { + containedTree = new Tree(nbttagcompound.getCompoundTag("ContainedTree")); + } + if (nbttagcompound.hasKey("owner")) { + owner = NBTUtil.func_152459_a(nbttagcompound.getCompoundTag("owner")); + } + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - if (containedTree != null) { - NBTTagCompound subcompound = new NBTTagCompound(); - containedTree.writeToNBT(subcompound); - nbttagcompound.setTag("ContainedTree", subcompound); - } - if (this.owner != null) { - NBTTagCompound nbt = new NBTTagCompound(); - NBTUtil.func_152460_a(nbt, owner); - nbttagcompound.setTag("owner", nbt); - } - } + if (containedTree != null) { + NBTTagCompound subcompound = new NBTTagCompound(); + containedTree.writeToNBT(subcompound); + nbttagcompound.setTag("ContainedTree", subcompound); + } + if (this.owner != null) { + NBTTagCompound nbt = new NBTTagCompound(); + NBTUtil.func_152460_a(nbt, owner); + nbttagcompound.setTag("owner", nbt); + } + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - String speciesUID = ""; - ITree tree = getTree(); - if (tree != null) { - speciesUID = tree.getIdent(); - } - data.writeUTF(speciesUID); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + String speciesUID = ""; + ITree tree = getTree(); + if (tree != null) { + speciesUID = tree.getIdent(); + } + data.writeUTF(speciesUID); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - String speciesUID = data.readUTF(); - ITree tree = getTree(speciesUID); - setTree(tree); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + String speciesUID = data.readUTF(); + ITree tree = getTree(speciesUID); + setTree(tree); + } - private static ITree getTree(String speciesUID) { - IAllele[] treeTemplate = TreeManager.treeRoot.getTemplate(speciesUID); - if (treeTemplate == null) { - return null; - } - return TreeManager.treeRoot.templateAsIndividual(treeTemplate); - } + private static ITree getTree(String speciesUID) { + IAllele[] treeTemplate = TreeManager.treeRoot.getTemplate(speciesUID); + if (treeTemplate == null) { + return null; + } + return TreeManager.treeRoot.templateAsIndividual(treeTemplate); + } - /* CLIENT INFORMATION */ + /* CLIENT INFORMATION */ - /* CONTAINED TREE */ - public void setTree(ITree tree) { - this.containedTree = tree; - if (worldObj != null && worldObj.isRemote) { - worldObj.func_147479_m(xCoord, yCoord, zCoord); - } - } + /* CONTAINED TREE */ + public void setTree(ITree tree) { + this.containedTree = tree; + if (worldObj != null && worldObj.isRemote) { + worldObj.func_147479_m(xCoord, yCoord, zCoord); + } + } - public ITree getTree() { - return this.containedTree; - } + public ITree getTree() { + return this.containedTree; + } - /* IOwnable */ - @Override - public GameProfile getOwner() { - return owner; - } + /* IOwnable */ + @Override + public GameProfile getOwner() { + return owner; + } - @Override - public void setOwner(GameProfile owner) { - this.owner = owner; - } + @Override + public void setOwner(GameProfile owner) { + this.owner = owner; + } - @Override - public boolean isOwned() { - return owner != null; - } + @Override + public boolean isOwned() { + return owner != null; + } - @Override - public boolean isOwner(EntityPlayer player) { - return player != null && PlayerUtil.isSameGameProfile(player.getGameProfile(), owner); - } + @Override + public boolean isOwner(EntityPlayer player) { + return player != null && PlayerUtil.isSameGameProfile(player.getGameProfile(), owner); + } - /* UPDATING */ + /* UPDATING */ - /** - * This doesn't use normal TE updates - */ - @Override - public boolean canUpdate() { - return false; - } + /** + * This doesn't use normal TE updates + */ + @Override + public boolean canUpdate() { + return false; + } - /** - * Leaves and saplings will implement their logic here. - */ - public abstract void onBlockTick(); + /** + * Leaves and saplings will implement their logic here. + */ + public abstract void onBlockTick(); - /** - * Called from Chunk.setBlockIDWithMetadata, determines if this tile entity should be re-created when the ID, or Metadata changes. - * Use with caution as this will leave straggler TileEntities, or create conflicts with other TileEntities if not used properly. - */ - @Override - public boolean shouldRefresh(Block oldBlock, Block newBlock, int oldMeta, int newMeta, World world, int x, int y, int z) { - return !Block.isEqualTo(oldBlock, newBlock); - } - - /* INETWORKEDENTITY */ - @Override - public Packet getDescriptionPacket() { - return new PacketTileStream(this).getPacket(); - } + /** + * Called from Chunk.setBlockIDWithMetadata, determines if this tile entity should be re-created when the ID, or Metadata changes. + * Use with caution as this will leave straggler TileEntities, or create conflicts with other TileEntities if not used properly. + */ + @Override + public boolean shouldRefresh( + Block oldBlock, Block newBlock, int oldMeta, int newMeta, World world, int x, int y, int z) { + return !Block.isEqualTo(oldBlock, newBlock); + } + /* INETWORKEDENTITY */ + @Override + public Packet getDescriptionPacket() { + return new PacketTileStream(this).getPacket(); + } } diff --git a/src/main/java/forestry/arboriculture/tiles/TileWood.java b/src/main/java/forestry/arboriculture/tiles/TileWood.java index d6aacc894..f23dbfaeb 100644 --- a/src/main/java/forestry/arboriculture/tiles/TileWood.java +++ b/src/main/java/forestry/arboriculture/tiles/TileWood.java @@ -1,126 +1,125 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.tiles; - -import java.io.IOException; -import java.util.ArrayList; - -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.Packet; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - -import forestry.api.arboriculture.EnumWoodType; -import forestry.arboriculture.IWoodTyped; -import forestry.arboriculture.blocks.BlockSlab; -import forestry.arboriculture.items.ItemBlockWood; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamable; -import forestry.core.network.packets.PacketTileStream; -import forestry.core.tiles.TileUtil; -import forestry.plugins.PluginArboriculture; - -public class TileWood extends TileEntity implements IStreamable { - private EnumWoodType woodType; - - public TileWood() { - this.woodType = EnumWoodType.LARCH; - } - - public void setWoodType(EnumWoodType woodType) { - this.woodType = woodType; - markDirty(); - } - - public EnumWoodType getWoodType() { - return woodType; - } - - @Override - public boolean canUpdate() { - return false; - } - - /* NETWORK */ - @Override - public Packet getDescriptionPacket() { - return new PacketTileStream(this).getPacket(); - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeVarInt(woodType.ordinal()); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - int ordinal = data.readVarInt(); - woodType = EnumWoodType.VALUES[ordinal]; - worldObj.func_147479_m(xCoord, yCoord, zCoord); - } - - @Override - public void writeToNBT(NBTTagCompound nbt) { - super.writeToNBT(nbt); - if (woodType != null) { - nbt.setInteger("WT", woodType.ordinal()); - } - } - - @Override - public void readFromNBT(NBTTagCompound nbt) { - super.readFromNBT(nbt); - if (nbt.hasKey("WT")) { - int ordinal = nbt.getInteger("WT"); - woodType = EnumWoodType.VALUES[ordinal]; - } - } - - public static ItemStack getPickBlock(Block block, IBlockAccess world, int x, int y, int z) { - TileWood wood = getWoodTile(world, x, y, z); - if (wood == null) { - return null; - } - EnumWoodType woodType = wood.getWoodType(); - - int amount = 1; - if (block instanceof BlockSlab) { - BlockSlab blockSlab = (BlockSlab) block; - if (blockSlab.isDoubleSlab()) { - amount = 2; - block = PluginArboriculture.blocks.slabs; - } - } - - ItemStack itemStack = new ItemStack(block, amount); - ItemBlockWood.saveToItemStack(woodType, itemStack); - return itemStack; - } - - public static TileWood getWoodTile(IBlockAccess world, int x, int y, int z) { - return TileUtil.getTile(world, x, y, z, TileWood.class); - } - - public static ArrayList getDrops(T block, World world, int x, int y, int z) { - ArrayList drops = new ArrayList<>(); - - ItemStack stack = getPickBlock(block, world, x, y, z); - if (stack != null) { - drops.add(stack); - } - - return drops; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.tiles; + +import forestry.api.arboriculture.EnumWoodType; +import forestry.arboriculture.IWoodTyped; +import forestry.arboriculture.blocks.BlockSlab; +import forestry.arboriculture.items.ItemBlockWood; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; +import forestry.core.network.packets.PacketTileStream; +import forestry.core.tiles.TileUtil; +import forestry.plugins.PluginArboriculture; +import java.io.IOException; +import java.util.ArrayList; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.Packet; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; + +public class TileWood extends TileEntity implements IStreamable { + private EnumWoodType woodType; + + public TileWood() { + this.woodType = EnumWoodType.LARCH; + } + + public void setWoodType(EnumWoodType woodType) { + this.woodType = woodType; + markDirty(); + } + + public EnumWoodType getWoodType() { + return woodType; + } + + @Override + public boolean canUpdate() { + return false; + } + + /* NETWORK */ + @Override + public Packet getDescriptionPacket() { + return new PacketTileStream(this).getPacket(); + } + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeVarInt(woodType.ordinal()); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + int ordinal = data.readVarInt(); + woodType = EnumWoodType.VALUES[ordinal]; + worldObj.func_147479_m(xCoord, yCoord, zCoord); + } + + @Override + public void writeToNBT(NBTTagCompound nbt) { + super.writeToNBT(nbt); + if (woodType != null) { + nbt.setInteger("WT", woodType.ordinal()); + } + } + + @Override + public void readFromNBT(NBTTagCompound nbt) { + super.readFromNBT(nbt); + if (nbt.hasKey("WT")) { + int ordinal = nbt.getInteger("WT"); + woodType = EnumWoodType.VALUES[ordinal]; + } + } + + public static ItemStack getPickBlock(Block block, IBlockAccess world, int x, int y, int z) { + TileWood wood = getWoodTile(world, x, y, z); + if (wood == null) { + return null; + } + EnumWoodType woodType = wood.getWoodType(); + + int amount = 1; + if (block instanceof BlockSlab) { + BlockSlab blockSlab = (BlockSlab) block; + if (blockSlab.isDoubleSlab()) { + amount = 2; + block = PluginArboriculture.blocks.slabs; + } + } + + ItemStack itemStack = new ItemStack(block, amount); + ItemBlockWood.saveToItemStack(woodType, itemStack); + return itemStack; + } + + public static TileWood getWoodTile(IBlockAccess world, int x, int y, int z) { + return TileUtil.getTile(world, x, y, z, TileWood.class); + } + + public static ArrayList getDrops( + T block, World world, int x, int y, int z) { + ArrayList drops = new ArrayList<>(); + + ItemStack stack = getPickBlock(block, world, x, y, z); + if (stack != null) { + drops.add(stack); + } + + return drops; + } +} diff --git a/src/main/java/forestry/arboriculture/worldgen/BlockTypeLog.java b/src/main/java/forestry/arboriculture/worldgen/BlockTypeLog.java index 172512529..3c08b1a91 100644 --- a/src/main/java/forestry/arboriculture/worldgen/BlockTypeLog.java +++ b/src/main/java/forestry/arboriculture/worldgen/BlockTypeLog.java @@ -1,32 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.worldgen; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.common.util.ForgeDirection; - -public class BlockTypeLog extends BlockTypeWood { - public BlockTypeLog(ItemStack itemStack) { - super(itemStack); - } - - @Override - public void setDirection(ForgeDirection facing) { - if (facing.offsetX != 0) { - blockMeta = 4; - } else if (facing.offsetZ != 0) { - blockMeta = 8; - } else { - blockMeta = 0; - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.worldgen; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.util.ForgeDirection; + +public class BlockTypeLog extends BlockTypeWood { + public BlockTypeLog(ItemStack itemStack) { + super(itemStack); + } + + @Override + public void setDirection(ForgeDirection facing) { + if (facing.offsetX != 0) { + blockMeta = 4; + } else if (facing.offsetZ != 0) { + blockMeta = 8; + } else { + blockMeta = 0; + } + } +} diff --git a/src/main/java/forestry/arboriculture/worldgen/BlockTypeVanillaStairs.java b/src/main/java/forestry/arboriculture/worldgen/BlockTypeVanillaStairs.java index f7b49613e..7c26f278e 100644 --- a/src/main/java/forestry/arboriculture/worldgen/BlockTypeVanillaStairs.java +++ b/src/main/java/forestry/arboriculture/worldgen/BlockTypeVanillaStairs.java @@ -1,41 +1,39 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.worldgen; - -import net.minecraft.init.Blocks; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.core.worldgen.BlockType; - -public class BlockTypeVanillaStairs extends BlockType { - public BlockTypeVanillaStairs(int meta) { - super(Blocks.oak_stairs, meta); - } - - @Override - public void setDirection(ForgeDirection facing) { - switch (facing) { - case NORTH: - meta = 3; - break; - case SOUTH: - meta = 2; - break; - case WEST: - meta = 1; - break; - default: - meta = 0; - break; - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.worldgen; + +import forestry.core.worldgen.BlockType; +import net.minecraft.init.Blocks; +import net.minecraftforge.common.util.ForgeDirection; + +public class BlockTypeVanillaStairs extends BlockType { + public BlockTypeVanillaStairs(int meta) { + super(Blocks.oak_stairs, meta); + } + + @Override + public void setDirection(ForgeDirection facing) { + switch (facing) { + case NORTH: + meta = 3; + break; + case SOUTH: + meta = 2; + break; + case WEST: + meta = 1; + break; + default: + meta = 0; + break; + } + } +} diff --git a/src/main/java/forestry/arboriculture/worldgen/BlockTypeWood.java b/src/main/java/forestry/arboriculture/worldgen/BlockTypeWood.java index e3a06dca1..9a8c13932 100644 --- a/src/main/java/forestry/arboriculture/worldgen/BlockTypeWood.java +++ b/src/main/java/forestry/arboriculture/worldgen/BlockTypeWood.java @@ -1,45 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.worldgen; - -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.api.world.ITreeGenData; -import forestry.arboriculture.items.ItemBlockWood; -import forestry.core.worldgen.IBlockType; - -public class BlockTypeWood implements IBlockType, ITreeBlockType { - - protected final ItemStack itemStack; - protected int blockMeta; - - public BlockTypeWood(ItemStack itemStack) { - this.itemStack = itemStack; - } - - @Override - public void setBlock(World world, ITreeGenData tree, int x, int y, int z) { - setBlock(world, x, y, z); - } - - @Override - public void setBlock(World world, int x, int y, int z) { - ItemBlockWood.placeWood(itemStack, null, world, x, y, z, blockMeta); - } - - @Override - public void setDirection(ForgeDirection facing) { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.worldgen; + +import forestry.api.world.ITreeGenData; +import forestry.arboriculture.items.ItemBlockWood; +import forestry.core.worldgen.IBlockType; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +public class BlockTypeWood implements IBlockType, ITreeBlockType { + + protected final ItemStack itemStack; + protected int blockMeta; + + public BlockTypeWood(ItemStack itemStack) { + this.itemStack = itemStack; + } + + @Override + public void setBlock(World world, ITreeGenData tree, int x, int y, int z) { + setBlock(world, x, y, z); + } + + @Override + public void setBlock(World world, int x, int y, int z) { + ItemBlockWood.placeWood(itemStack, null, world, x, y, z, blockMeta); + } + + @Override + public void setDirection(ForgeDirection facing) {} +} diff --git a/src/main/java/forestry/arboriculture/worldgen/BlockTypeWoodStairs.java b/src/main/java/forestry/arboriculture/worldgen/BlockTypeWoodStairs.java index 75881fee4..25f3d468f 100644 --- a/src/main/java/forestry/arboriculture/worldgen/BlockTypeWoodStairs.java +++ b/src/main/java/forestry/arboriculture/worldgen/BlockTypeWoodStairs.java @@ -1,39 +1,38 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.worldgen; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.common.util.ForgeDirection; - -public class BlockTypeWoodStairs extends BlockTypeWood { - public BlockTypeWoodStairs(ItemStack itemStack) { - super(itemStack); - } - - @Override - public void setDirection(ForgeDirection facing) { - switch (facing) { - case NORTH: - blockMeta = 3; - break; - case SOUTH: - blockMeta = 2; - break; - case WEST: - blockMeta = 1; - break; - default: - blockMeta = 0; - break; - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.worldgen; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.util.ForgeDirection; + +public class BlockTypeWoodStairs extends BlockTypeWood { + public BlockTypeWoodStairs(ItemStack itemStack) { + super(itemStack); + } + + @Override + public void setDirection(ForgeDirection facing) { + switch (facing) { + case NORTH: + blockMeta = 3; + break; + case SOUTH: + blockMeta = 2; + break; + case WEST: + blockMeta = 1; + break; + default: + blockMeta = 0; + break; + } + } +} diff --git a/src/main/java/forestry/arboriculture/worldgen/ITreeBlockType.java b/src/main/java/forestry/arboriculture/worldgen/ITreeBlockType.java index 94f1cb836..f02c6d749 100644 --- a/src/main/java/forestry/arboriculture/worldgen/ITreeBlockType.java +++ b/src/main/java/forestry/arboriculture/worldgen/ITreeBlockType.java @@ -1,23 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.worldgen; - -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.api.world.ITreeGenData; - -public interface ITreeBlockType { - void setDirection(ForgeDirection facing); - - void setBlock(World world, ITreeGenData tree, int x, int y, int z); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.worldgen; + +import forestry.api.world.ITreeGenData; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +public interface ITreeBlockType { + void setDirection(ForgeDirection facing); + + void setBlock(World world, ITreeGenData tree, int x, int y, int z); +} diff --git a/src/main/java/forestry/arboriculture/worldgen/TreeBlockType.java b/src/main/java/forestry/arboriculture/worldgen/TreeBlockType.java index 1fa6c032e..7968d6464 100644 --- a/src/main/java/forestry/arboriculture/worldgen/TreeBlockType.java +++ b/src/main/java/forestry/arboriculture/worldgen/TreeBlockType.java @@ -1,48 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.worldgen; - -import net.minecraft.block.Block; -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.api.world.ITreeGenData; -import forestry.core.config.Constants; - -public class TreeBlockType implements ITreeBlockType { - - private final Block block; - private final int meta; - - public TreeBlockType(Block block, int meta) { - this.block = block; - this.meta = meta; - } - - @Override - public void setDirection(ForgeDirection facing) { - - } - - @Override - public void setBlock(World world, ITreeGenData tree, int x, int y, int z) { - world.setBlock(x, y, z, block, meta, Constants.FLAG_BLOCK_SYNCH); - } - - public int getMeta() { - return this.meta; - } - - public Block getBlock() { - return this.block; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.worldgen; + +import forestry.api.world.ITreeGenData; +import forestry.core.config.Constants; +import net.minecraft.block.Block; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +public class TreeBlockType implements ITreeBlockType { + + private final Block block; + private final int meta; + + public TreeBlockType(Block block, int meta) { + this.block = block; + this.meta = meta; + } + + @Override + public void setDirection(ForgeDirection facing) {} + + @Override + public void setBlock(World world, ITreeGenData tree, int x, int y, int z) { + world.setBlock(x, y, z, block, meta, Constants.FLAG_BLOCK_SYNCH); + } + + public int getMeta() { + return this.meta; + } + + public Block getBlock() { + return this.block; + } +} diff --git a/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLeaf.java b/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLeaf.java index c101a02a2..852f37b8b 100644 --- a/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLeaf.java +++ b/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLeaf.java @@ -1,38 +1,33 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.worldgen; - -import net.minecraft.world.World; - -import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.api.world.ITreeGenData; - -public class TreeBlockTypeLeaf implements ITreeBlockType { - - private final GameProfile owner; - - public TreeBlockTypeLeaf(GameProfile owner) { - this.owner = owner; - } - - @Override - public void setDirection(ForgeDirection facing) { - - } - - @Override - public void setBlock(World world, ITreeGenData tree, int x, int y, int z) { - tree.setLeaves(world, owner, x, y, z); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.worldgen; + +import com.mojang.authlib.GameProfile; +import forestry.api.world.ITreeGenData; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +public class TreeBlockTypeLeaf implements ITreeBlockType { + + private final GameProfile owner; + + public TreeBlockTypeLeaf(GameProfile owner) { + this.owner = owner; + } + + @Override + public void setDirection(ForgeDirection facing) {} + + @Override + public void setBlock(World world, ITreeGenData tree, int x, int y, int z) { + tree.setLeaves(world, owner, x, y, z); + } +} diff --git a/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLog.java b/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLog.java index 0dd097979..7223c6c83 100644 --- a/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLog.java +++ b/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLog.java @@ -1,35 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.worldgen; - -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.api.world.ITreeGenData; - -public class TreeBlockTypeLog implements ITreeBlockType { - private ForgeDirection facing = ForgeDirection.UP; - - public TreeBlockTypeLog() { - - } - - @Override - public void setDirection(ForgeDirection facing) { - this.facing = facing; - } - - @Override - public void setBlock(World world, ITreeGenData tree, int x, int y, int z) { - tree.setLogBlock(world, x, y, z, facing); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.worldgen; + +import forestry.api.world.ITreeGenData; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +public class TreeBlockTypeLog implements ITreeBlockType { + private ForgeDirection facing = ForgeDirection.UP; + + public TreeBlockTypeLog() {} + + @Override + public void setDirection(ForgeDirection facing) { + this.facing = facing; + } + + @Override + public void setBlock(World world, ITreeGenData tree, int x, int y, int z) { + tree.setLogBlock(world, x, y, z, facing); + } +} diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenAcacia.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenAcacia.java index 33807e323..a4b95f0ff 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenAcacia.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenAcacia.java @@ -10,55 +10,71 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.ArrayList; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenAcacia extends WorldGenTree { - public WorldGenAcacia(ITreeGenData tree) { - super(tree, 5, 2); - } + public WorldGenAcacia(ITreeGenData tree) { + super(tree, 5, 2); + } - @Override - public void generate(World world) { - Direction leanDirection = Direction.getRandom(world.rand); - float leanAmount = height / 4.0f; + @Override + public void generate(World world) { + Direction leanDirection = Direction.getRandom(world.rand); + float leanAmount = height / 4.0f; - List treeTops = generateTreeTrunk(world, height, girth, 0, leanDirection.forgeDirection, leanAmount); - if (height > 5 && world.rand.nextBoolean()) { - Direction branchDirection = Direction.getRandomOther(world.rand, leanDirection); - List treeTops2 = generateTreeTrunk(world, Math.round(height * 0.66f), girth, 0, branchDirection.forgeDirection, leanAmount); - treeTops.addAll(treeTops2); - } + List treeTops = + generateTreeTrunk(world, height, girth, 0, leanDirection.forgeDirection, leanAmount); + if (height > 5 && world.rand.nextBoolean()) { + Direction branchDirection = Direction.getRandomOther(world.rand, leanDirection); + List treeTops2 = generateTreeTrunk( + world, Math.round(height * 0.66f), girth, 0, branchDirection.forgeDirection, leanAmount); + treeTops.addAll(treeTops2); + } - List branchLocations = new ArrayList<>(); + List branchLocations = new ArrayList<>(); - for (ChunkCoordinates treeTop : treeTops) { - int xOffset = treeTop.posX; - int yOffset = treeTop.posY + 1; - int zOffset = treeTop.posZ; - float canopyMultiplier = (1.5f * height - yOffset + 2) / 4.0f; - int canopyThickness = Math.max(1, Math.round(yOffset / 10.0f)); + for (ChunkCoordinates treeTop : treeTops) { + int xOffset = treeTop.posX; + int yOffset = treeTop.posY + 1; + int zOffset = treeTop.posZ; + float canopyMultiplier = (1.5f * height - yOffset + 2) / 4.0f; + int canopyThickness = Math.max(1, Math.round(yOffset / 10.0f)); - generateAdjustedCylinder(world, yOffset--, xOffset, zOffset, canopyMultiplier, 1, leaf, EnumReplaceMode.NONE); + generateAdjustedCylinder( + world, yOffset--, xOffset, zOffset, canopyMultiplier, 1, leaf, EnumReplaceMode.NONE); - float canopyWidth = world.rand.nextBoolean() ? 3.0f : 2.5f; - List branches = generateBranches(world, yOffset - canopyThickness, xOffset, zOffset, 0.0f, 0.1f, Math.round(canopyMultiplier * canopyWidth - 4), 2); - branchLocations.addAll(branches); - } - - for (ChunkCoordinates branchLocation : branchLocations) { - int leafSpawn = branchLocation.posY; - int canopyThickness = Math.max(1, Math.round(leafSpawn / 10.0f)); - float canopyMultiplier = (1.5f * height - leafSpawn + 2) / 4.0f; - float canopyWidth = world.rand.nextBoolean() ? 1.0f : 1.5f; - generateAdjustedCylinder(world, leafSpawn - canopyThickness + 1, branchLocation.posX, branchLocation.posZ, canopyMultiplier * canopyWidth, canopyThickness, leaf, EnumReplaceMode.NONE); - } - } + float canopyWidth = world.rand.nextBoolean() ? 3.0f : 2.5f; + List branches = generateBranches( + world, + yOffset - canopyThickness, + xOffset, + zOffset, + 0.0f, + 0.1f, + Math.round(canopyMultiplier * canopyWidth - 4), + 2); + branchLocations.addAll(branches); + } + for (ChunkCoordinates branchLocation : branchLocations) { + int leafSpawn = branchLocation.posY; + int canopyThickness = Math.max(1, Math.round(leafSpawn / 10.0f)); + float canopyMultiplier = (1.5f * height - leafSpawn + 2) / 4.0f; + float canopyWidth = world.rand.nextBoolean() ? 1.0f : 1.5f; + generateAdjustedCylinder( + world, + leafSpawn - canopyThickness + 1, + branchLocation.posX, + branchLocation.posZ, + canopyMultiplier * canopyWidth, + canopyThickness, + leaf, + EnumReplaceMode.NONE); + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenAcaciaVanilla.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenAcaciaVanilla.java index eb4b15846..e78729ab0 100644 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenAcaciaVanilla.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenAcaciaVanilla.java @@ -14,8 +14,7 @@ import forestry.api.world.ITreeGenData; public class WorldGenAcaciaVanilla extends WorldGenTreeVanilla { - public WorldGenAcaciaVanilla(ITreeGenData tree) { - super(tree); - } - + public WorldGenAcaciaVanilla(ITreeGenData tree) { + super(tree); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java index cfc2c624c..39e4643a8 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java @@ -10,19 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; - -import net.minecraft.init.Blocks; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.util.ForgeDirection; - import forestry.api.world.ITreeGenData; import forestry.arboriculture.tiles.TileTreeContainer; import forestry.core.tiles.TileUtil; @@ -30,317 +18,350 @@ import forestry.core.utils.BlockUtil; import forestry.core.worldgen.BlockType; import forestry.core.worldgen.BlockTypeVoid; import forestry.core.worldgen.WorldGenBase; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; +import net.minecraft.init.Blocks; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; public abstract class WorldGenArboriculture extends WorldGenBase { - enum Direction { - NORTH(ForgeDirection.NORTH), - SOUTH(ForgeDirection.SOUTH), - WEST(ForgeDirection.WEST), - EAST(ForgeDirection.EAST); + enum Direction { + NORTH(ForgeDirection.NORTH), + SOUTH(ForgeDirection.SOUTH), + WEST(ForgeDirection.WEST), + EAST(ForgeDirection.EAST); - public final ForgeDirection forgeDirection; + public final ForgeDirection forgeDirection; - Direction(ForgeDirection forgeDirection) { - this.forgeDirection = forgeDirection; - } + Direction(ForgeDirection forgeDirection) { + this.forgeDirection = forgeDirection; + } - public static Direction getRandom(Random random) { - return values()[random.nextInt(values().length)]; - } + public static Direction getRandom(Random random) { + return values()[random.nextInt(values().length)]; + } - public static Direction getRandomOther(Random random, Direction direction) { - EnumSet directions = EnumSet.allOf(Direction.class); - directions.remove(direction); - int size = directions.size(); - return directions.toArray(new Direction[size])[random.nextInt(size)]; - } - } + public static Direction getRandomOther(Random random, Direction direction) { + EnumSet directions = EnumSet.allOf(Direction.class); + directions.remove(direction); + int size = directions.size(); + return directions.toArray(new Direction[size])[random.nextInt(size)]; + } + } - private static final ITreeBlockType vineNorth = new TreeBlockType(Blocks.vine, 1); - private static final ITreeBlockType vineSouth = new TreeBlockType(Blocks.vine, 4); - private static final ITreeBlockType vineWest = new TreeBlockType(Blocks.vine, 8); - private static final ITreeBlockType vineEast = new TreeBlockType(Blocks.vine, 2); - private static final int minPodHeight = 3; + private static final ITreeBlockType vineNorth = new TreeBlockType(Blocks.vine, 1); + private static final ITreeBlockType vineSouth = new TreeBlockType(Blocks.vine, 4); + private static final ITreeBlockType vineWest = new TreeBlockType(Blocks.vine, 8); + private static final ITreeBlockType vineEast = new TreeBlockType(Blocks.vine, 2); + private static final int minPodHeight = 3; - private static final BlockType air = new BlockTypeVoid(); + private static final BlockType air = new BlockTypeVoid(); - protected final ITreeGenData tree; - private int startX; - private int startY; - private int startZ; + protected final ITreeGenData tree; + private int startX; + private int startY; + private int startZ; - protected TreeBlockTypeLeaf leaf; - protected ITreeBlockType wood; + protected TreeBlockTypeLeaf leaf; + protected ITreeBlockType wood; - private boolean spawnPods = false; + private boolean spawnPods = false; - protected WorldGenArboriculture(ITreeGenData tree) { - this.tree = tree; - } + protected WorldGenArboriculture(ITreeGenData tree) { + this.tree = tree; + } - @Override - public boolean generate(World world, int x, int y, int z, boolean forced) { - this.spawnPods = tree.allowsFruitBlocks(); - this.leaf = getLeaf(getOwner(world, x, y, z)); - this.wood = getWood(); + @Override + public boolean generate(World world, int x, int y, int z, boolean forced) { + this.spawnPods = tree.allowsFruitBlocks(); + this.leaf = getLeaf(getOwner(world, x, y, z)); + this.wood = getWood(); - preGenerate(world, x, y, z); - if (forced || canGrow(world, x, y, z)) { - generate(world); - return true; - } + preGenerate(world, x, y, z); + if (forced || canGrow(world, x, y, z)) { + generate(world); + return true; + } - return false; - } + return false; + } - private static GameProfile getOwner(World world, int x, int y, int z) { - TileTreeContainer tile = TileUtil.getTile(world, x, y, z, TileTreeContainer.class); - if (tile == null) { - return null; - } - return tile.getOwner(); - } + private static GameProfile getOwner(World world, int x, int y, int z) { + TileTreeContainer tile = TileUtil.getTile(world, x, y, z, TileTreeContainer.class); + if (tile == null) { + return null; + } + return tile.getOwner(); + } - public void preGenerate(World world, int startX, int startY, int startZ) { - this.startX = startX; - this.startY = startY; - this.startZ = startZ; - } + public void preGenerate(World world, int startX, int startY, int startZ) { + this.startX = startX; + this.startY = startY; + this.startZ = startZ; + } - protected abstract void generate(World world); + protected abstract void generate(World world); - public abstract boolean canGrow(World world, int x, int y, int z); + public abstract boolean canGrow(World world, int x, int y, int z); - protected abstract TreeBlockTypeLeaf getLeaf(GameProfile owner); + protected abstract TreeBlockTypeLeaf getLeaf(GameProfile owner); - protected abstract ITreeBlockType getWood(); + protected abstract ITreeBlockType getWood(); - protected List generateTreeTrunk(World world, int height, int girth) { - return generateTreeTrunk(world, height, girth, 0); - } + protected List generateTreeTrunk(World world, int height, int girth) { + return generateTreeTrunk(world, height, girth, 0); + } - protected List generateTreeTrunk(World world, int height, int girth, float vinesChance) { - return generateTreeTrunk(world, height, girth, vinesChance, ForgeDirection.UNKNOWN, 0); - } + protected List generateTreeTrunk(World world, int height, int girth, float vinesChance) { + return generateTreeTrunk(world, height, girth, vinesChance, ForgeDirection.UNKNOWN, 0); + } - protected List generateTreeTrunk(World world, int height, int girth, float vinesChance, ForgeDirection leanDirection, float leanAmount) { - return generateTreeTrunk(world, height, girth, 0, vinesChance, leanDirection, leanAmount); - } + protected List generateTreeTrunk( + World world, int height, int girth, float vinesChance, ForgeDirection leanDirection, float leanAmount) { + return generateTreeTrunk(world, height, girth, 0, vinesChance, leanDirection, leanAmount); + } - /** Returns a list of trunk top coordinates */ - protected List generateTreeTrunk(World world, int height, int girth, int yStart, float vinesChance, ForgeDirection leanDirection, float leanAmount) { - List treeTops = new ArrayList<>(); + /** Returns a list of trunk top coordinates */ + protected List generateTreeTrunk( + World world, + int height, + int girth, + int yStart, + float vinesChance, + ForgeDirection leanDirection, + float leanAmount) { + List treeTops = new ArrayList<>(); - final int leanStartY = (int) Math.floor(height * 0.33f); - int prevXOffset = 0; - int prevZOffset = 0; + final int leanStartY = (int) Math.floor(height * 0.33f); + int prevXOffset = 0; + int prevZOffset = 0; - int offset = (girth - 1) / 2; - for (int x = 0; x < girth; x++) { - for (int z = 0; z < girth; z++) { - for (int y = yStart; y < height; y++) { - float lean; - if (y < leanStartY) { - lean = 0; - } else { - lean = leanAmount * (y - leanStartY) / (height - leanStartY); - } - int xOffset = (int) Math.floor(leanDirection.offsetX * lean - offset); - int zOffset = (int) Math.floor(leanDirection.offsetZ * lean - offset); + int offset = (girth - 1) / 2; + for (int x = 0; x < girth; x++) { + for (int z = 0; z < girth; z++) { + for (int y = yStart; y < height; y++) { + float lean; + if (y < leanStartY) { + lean = 0; + } else { + lean = leanAmount * (y - leanStartY) / (height - leanStartY); + } + int xOffset = (int) Math.floor(leanDirection.offsetX * lean - offset); + int zOffset = (int) Math.floor(leanDirection.offsetZ * lean - offset); - if (xOffset != prevXOffset || zOffset != prevZOffset) { - prevXOffset = xOffset; - prevZOffset = zOffset; - if (y > 0) { - wood.setDirection(leanDirection); - addWood(world, x + xOffset, y - 1, z + zOffset, EnumReplaceMode.ALL); - wood.setDirection(ForgeDirection.UP); - } - } + if (xOffset != prevXOffset || zOffset != prevZOffset) { + prevXOffset = xOffset; + prevZOffset = zOffset; + if (y > 0) { + wood.setDirection(leanDirection); + addWood(world, x + xOffset, y - 1, z + zOffset, EnumReplaceMode.ALL); + wood.setDirection(ForgeDirection.UP); + } + } - addWood(world, x + xOffset, y, z + zOffset, EnumReplaceMode.ALL); - addVines(world, x + xOffset, y, z + zOffset, vinesChance); + addWood(world, x + xOffset, y, z + zOffset, EnumReplaceMode.ALL); + addVines(world, x + xOffset, y, z + zOffset, vinesChance); - if (y + 1 == height) { - treeTops.add(new ChunkCoordinates(x + xOffset, y, z + zOffset)); - } - } - } - } + if (y + 1 == height) { + treeTops.add(new ChunkCoordinates(x + xOffset, y, z + zOffset)); + } + } + } + } - if (spawnPods) { - generatePods(world, height, girth); - } + if (spawnPods) { + generatePods(world, height, girth); + } - return treeTops; - } + return treeTops; + } - protected void generatePods(World world, int height, int girth) { - for (int y = minPodHeight; y < height; y++) { - for (int x = 0; x < girth; x++) { - for (int z = 0; z < girth; z++) { + protected void generatePods(World world, int height, int girth) { + for (int y = minPodHeight; y < height; y++) { + for (int x = 0; x < girth; x++) { + for (int z = 0; z < girth; z++) { - if ((x > 0 && x < girth) && (z > 0 && z < girth)) { - continue; - } + if ((x > 0 && x < girth) && (z > 0 && z < girth)) { + continue; + } - trySpawnFruitBlock(world, x + 1, y, z); - trySpawnFruitBlock(world, x - 1, y, z); - trySpawnFruitBlock(world, x, y, z + 1); - trySpawnFruitBlock(world, x, y, z - 1); - } - } - } - } + trySpawnFruitBlock(world, x + 1, y, z); + trySpawnFruitBlock(world, x - 1, y, z); + trySpawnFruitBlock(world, x, y, z + 1); + trySpawnFruitBlock(world, x, y, z - 1); + } + } + } + } - private void trySpawnFruitBlock(World world, int x, int y, int z) { - x += startX; - y += startY; - z += startZ; - if (BlockUtil.isReplaceableBlock(world, x, y, z) || world.isAirBlock(x, y, z)) { - tree.trySpawnFruitBlock(world, x, y, z); - } - } + private void trySpawnFruitBlock(World world, int x, int y, int z) { + x += startX; + y += startY; + z += startZ; + if (BlockUtil.isReplaceableBlock(world, x, y, z) || world.isAirBlock(x, y, z)) { + tree.trySpawnFruitBlock(world, x, y, z); + } + } - protected void generateSupportStems(World world, int height, int girth, float chance, float maxHeight) { + protected void generateSupportStems(World world, int height, int girth, float chance, float maxHeight) { - int offset = (int) Math.ceil(girth / 2.0f); - int max = (int) Math.floor(girth / 2.0f) + offset; - if (girth % 2 == 0) { - max++; - } + int offset = (int) Math.ceil(girth / 2.0f); + int max = (int) Math.floor(girth / 2.0f) + offset; + if (girth % 2 == 0) { + max++; + } - for (int x = -offset; x < max; x++) { - for (int z = -offset; z < max; z++) { + for (int x = -offset; x < max; x++) { + for (int z = -offset; z < max; z++) { - if (x == -offset && z == -offset) { - continue; - } - if (x == max && z == max) { - continue; - } - if (x == -offset && z == max) { - continue; - } - if (x == max && z == -offset) { - continue; - } + if (x == -offset && z == -offset) { + continue; + } + if (x == max && z == max) { + continue; + } + if (x == -offset && z == max) { + continue; + } + if (x == max && z == -offset) { + continue; + } - int stemHeight = world.rand.nextInt(Math.round(height * maxHeight)); - if (world.rand.nextFloat() < chance) { - for (int i = 0; i < stemHeight; i++) { - addWood(world, x, i, z, EnumReplaceMode.SOFT); - } - } - } - } - } + int stemHeight = world.rand.nextInt(Math.round(height * maxHeight)); + if (world.rand.nextFloat() < chance) { + for (int i = 0; i < stemHeight; i++) { + addWood(world, x, i, z, EnumReplaceMode.SOFT); + } + } + } + } + } - protected List generateBranches(World world, final int startY, int xOffset, int zOffset, float spreadY, float spreadXZ, int radius, int count) { - return generateBranches(world, startY, xOffset, zOffset, spreadY, spreadXZ, radius, count, 1.0f); - } + protected List generateBranches( + World world, + final int startY, + int xOffset, + int zOffset, + float spreadY, + float spreadXZ, + int radius, + int count) { + return generateBranches(world, startY, xOffset, zOffset, spreadY, spreadXZ, radius, count, 1.0f); + } - protected List generateBranches(World world, final int startY, final int xOffset, final int zOffset, final float spreadY, final float spreadXZ, int radius, final int count, final float chance) { - List branchEnds = new ArrayList<>(); - if (radius < 1) { - radius = 1; - } + protected List generateBranches( + World world, + final int startY, + final int xOffset, + final int zOffset, + final float spreadY, + final float spreadXZ, + int radius, + final int count, + final float chance) { + List branchEnds = new ArrayList<>(); + if (radius < 1) { + radius = 1; + } - for (Direction cardinalDirection : Direction.values()) { - ForgeDirection branchDirection = cardinalDirection.forgeDirection; - wood.setDirection(branchDirection); - for (int i = 0; i < count; i++) { - if (world.rand.nextFloat() > chance) { - continue; - } - int y = startY; - int x = xOffset; - int z = zOffset; + for (Direction cardinalDirection : Direction.values()) { + ForgeDirection branchDirection = cardinalDirection.forgeDirection; + wood.setDirection(branchDirection); + for (int i = 0; i < count; i++) { + if (world.rand.nextFloat() > chance) { + continue; + } + int y = startY; + int x = xOffset; + int z = zOffset; - for (int r = 0; r < radius; r++) { - if (world.rand.nextFloat() < spreadY) { - // make branches only spread up, not down - y++; - } else { - if (world.rand.nextFloat() < spreadXZ) { - if (branchDirection.offsetX == 0) { - if (world.rand.nextBoolean()) { - x++; - } else { - x--; - } - wood.setDirection(ForgeDirection.EAST); - } else if (branchDirection.offsetZ == 0) { - if (world.rand.nextBoolean()) { - z++; - } else { - z--; - } - wood.setDirection(ForgeDirection.SOUTH); - } - } else { - x += branchDirection.offsetX; - z += branchDirection.offsetZ; - wood.setDirection(branchDirection); - } - } - if (addWood(world, x, y, z, EnumReplaceMode.SOFT)) { - branchEnds.add(new ChunkCoordinates(x, y, z)); - } else { - break; - } - } - } - } + for (int r = 0; r < radius; r++) { + if (world.rand.nextFloat() < spreadY) { + // make branches only spread up, not down + y++; + } else { + if (world.rand.nextFloat() < spreadXZ) { + if (branchDirection.offsetX == 0) { + if (world.rand.nextBoolean()) { + x++; + } else { + x--; + } + wood.setDirection(ForgeDirection.EAST); + } else if (branchDirection.offsetZ == 0) { + if (world.rand.nextBoolean()) { + z++; + } else { + z--; + } + wood.setDirection(ForgeDirection.SOUTH); + } + } else { + x += branchDirection.offsetX; + z += branchDirection.offsetZ; + wood.setDirection(branchDirection); + } + } + if (addWood(world, x, y, z, EnumReplaceMode.SOFT)) { + branchEnds.add(new ChunkCoordinates(x, y, z)); + } else { + break; + } + } + } + } - return branchEnds; - } + return branchEnds; + } - @Override - protected boolean addBlock(World world, int x, int y, int z, ITreeBlockType type, EnumReplaceMode replace) { - if (replace == EnumReplaceMode.ALL - || (replace == EnumReplaceMode.SOFT && BlockUtil.isReplaceableBlock(world, startX + x, startY + y, startZ + z)) - || world.isAirBlock(startX + x, startY + y, startZ + z)) { - type.setBlock(world, tree, startX + x, startY + y, startZ + z); - return true; - } - return false; - } + @Override + protected boolean addBlock(World world, int x, int y, int z, ITreeBlockType type, EnumReplaceMode replace) { + if (replace == EnumReplaceMode.ALL + || (replace == EnumReplaceMode.SOFT + && BlockUtil.isReplaceableBlock(world, startX + x, startY + y, startZ + z)) + || world.isAirBlock(startX + x, startY + y, startZ + z)) { + type.setBlock(world, tree, startX + x, startY + y, startZ + z); + return true; + } + return false; + } - protected final void clearBlock(World world, int x, int y, int z) { - air.setBlock(world, startX + x, startY + y, startZ + z); - } + protected final void clearBlock(World world, int x, int y, int z) { + air.setBlock(world, startX + x, startY + y, startZ + z); + } - protected final boolean addWood(World world, int x, int y, int z, EnumReplaceMode replace) { - return addBlock(world, x, y, z, wood, replace); - } - - protected final boolean addLeaf(World world, int x, int y, int z, EnumReplaceMode replace) { - return addBlock(world, x, y, z, leaf, replace); - } + protected final boolean addWood(World world, int x, int y, int z, EnumReplaceMode replace) { + return addBlock(world, x, y, z, wood, replace); + } - protected final boolean addVine(World world, int x, int y, int z, ITreeBlockType vine) { - return addBlock(world, x, y, z, vine, EnumReplaceMode.NONE); - } + protected final boolean addLeaf(World world, int x, int y, int z, EnumReplaceMode replace) { + return addBlock(world, x, y, z, leaf, replace); + } - protected final void addVines(World world, int x, int y, int z, float chance) { - if (chance <= 0) { - return; - } + protected final boolean addVine(World world, int x, int y, int z, ITreeBlockType vine) { + return addBlock(world, x, y, z, vine, EnumReplaceMode.NONE); + } - if (world.rand.nextFloat() < chance) { - addVine(world, x - 1, y, z, vineWest); - } - if (world.rand.nextFloat() < chance) { - addVine(world, x + 1, y, z, vineEast); - } - if (world.rand.nextFloat() < chance) { - addVine(world, x, y, z - 1, vineNorth); - } - if (world.rand.nextFloat() < chance) { - addVine(world, x, y, z + 1, vineSouth); - } - } + protected final void addVines(World world, int x, int y, int z, float chance) { + if (chance <= 0) { + return; + } + if (world.rand.nextFloat() < chance) { + addVine(world, x - 1, y, z, vineWest); + } + if (world.rand.nextFloat() < chance) { + addVine(world, x + 1, y, z, vineEast); + } + if (world.rand.nextFloat() < chance) { + addVine(world, x, y, z - 1, vineNorth); + } + if (world.rand.nextFloat() < chance) { + addVine(world, x, y, z + 1, vineSouth); + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenBalsa.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenBalsa.java index e3ab7398b..24a6a09ae 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenBalsa.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenBalsa.java @@ -10,37 +10,34 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; +import net.minecraft.world.World; public class WorldGenBalsa extends WorldGenTree { - public WorldGenBalsa(ITreeGenData tree) { - super(tree, 6, 6); - } + public WorldGenBalsa(ITreeGenData tree) { + super(tree, 6, 6); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - int leafSpawn = height; - float leafRadius = (girth - 1.0f) / 2.0f; + int leafSpawn = height; + float leafRadius = (girth - 1.0f) / 2.0f; - addLeaf(world, 0, leafSpawn--, 0, EnumReplaceMode.NONE); - generateAdjustedCylinder(world, leafSpawn--, leafRadius, 1, leaf); + addLeaf(world, 0, leafSpawn--, 0, EnumReplaceMode.NONE); + generateAdjustedCylinder(world, leafSpawn--, leafRadius, 1, leaf); - if (height > 10) { - generateAdjustedCylinder(world, leafSpawn--, leafRadius, 1, leaf); - } + if (height > 10) { + generateAdjustedCylinder(world, leafSpawn--, leafRadius, 1, leaf); + } - leafSpawn--; - - while (leafSpawn > 6) { - generateAdjustedCylinder(world, leafSpawn, leafRadius, 1, leaf); - leafSpawn--; - } - - } + leafSpawn--; + while (leafSpawn > 6) { + generateAdjustedCylinder(world, leafSpawn, leafRadius, 1, leaf); + leafSpawn--; + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenBaobab.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenBaobab.java index 142e9ef87..c2b4d2aff 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenBaobab.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenBaobab.java @@ -10,73 +10,70 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenBaobab extends WorldGenTree { - public WorldGenBaobab(ITreeGenData tree) { - super(tree, 6, 6); - } + public WorldGenBaobab(ITreeGenData tree) { + super(tree, 6, 6); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height - 1, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height - 1, girth); - List branchCoords = generateBranches(world, height, 0, 0, 0, 0.5f, 4, 6); - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCylinder(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 0.0f, 2, leaf, EnumReplaceMode.NONE); - } + List branchCoords = generateBranches(world, height, 0, 0, 0, 0.5f, 4, 6); + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCylinder( + world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 0.0f, 2, leaf, EnumReplaceMode.NONE); + } - if (world.rand.nextFloat() < 0.3f) { - generateCylinder(world, new Vector(0, height - 1, 0), girth, 1, wood, EnumReplaceMode.SOFT); - } else if (world.rand.nextBoolean()) { - generateCylinder(world, new Vector(0, height - 1, 0), girth - 1, 1, wood, EnumReplaceMode.SOFT); - } + if (world.rand.nextFloat() < 0.3f) { + generateCylinder(world, new Vector(0, height - 1, 0), girth, 1, wood, EnumReplaceMode.SOFT); + } else if (world.rand.nextBoolean()) { + generateCylinder(world, new Vector(0, height - 1, 0), girth - 1, 1, wood, EnumReplaceMode.SOFT); + } - int leafSpawn = height + 1; + int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1f, 1, leaf); - // Add tree top - for (int times = 0; times < height / 2; times++) { - int h = height - 1 + world.rand.nextInt(4); - if (world.rand.nextBoolean() && h < height / 2) { - h = height / 2 + world.rand.nextInt(height / 2); - } + // Add tree top + for (int times = 0; times < height / 2; times++) { + int h = height - 1 + world.rand.nextInt(4); + if (world.rand.nextBoolean() && h < height / 2) { + h = height / 2 + world.rand.nextInt(height / 2); + } - int x_off = -girth + world.rand.nextInt(2 * girth); - int y_off = -girth + world.rand.nextInt(2 * girth); + int x_off = -girth + world.rand.nextInt(2 * girth); + int y_off = -girth + world.rand.nextInt(2 * girth); - Vector center = new Vector(x_off, h, y_off); - int radius = 1; - if (girth > 1) { - radius += world.rand.nextInt(girth - 1); - } - generateSphere(world, center, radius, leaf, EnumReplaceMode.NONE); - } + Vector center = new Vector(x_off, h, y_off); + int radius = 1; + if (girth > 1) { + radius += world.rand.nextInt(girth - 1); + } + generateSphere(world, center, radius, leaf, EnumReplaceMode.NONE); + } - // Add some smaller twigs below for flavour - for (int times = 0; times < height / 4; times++) { - int delim = modifyByHeight(world, 6, 0, height); - int h = delim + (delim < height ? world.rand.nextInt(height - delim) : 0); - if (world.rand.nextBoolean() && h < height / 2) { - h = height / 2 + world.rand.nextInt(height / 2); - } - int x_off = -1 + world.rand.nextInt(3); - int y_off = -1 + world.rand.nextInt(3); - - Vector center = new Vector(x_off, h, y_off); - int radius = 1 + world.rand.nextInt(2); - generateSphere(world, center, radius, leaf, EnumReplaceMode.NONE); - } - - } + // Add some smaller twigs below for flavour + for (int times = 0; times < height / 4; times++) { + int delim = modifyByHeight(world, 6, 0, height); + int h = delim + (delim < height ? world.rand.nextInt(height - delim) : 0); + if (world.rand.nextBoolean() && h < height / 2) { + h = height / 2 + world.rand.nextInt(height / 2); + } + int x_off = -1 + world.rand.nextInt(3); + int y_off = -1 + world.rand.nextInt(3); + Vector center = new Vector(x_off, h, y_off); + int radius = 1 + world.rand.nextInt(2); + generateSphere(world, center, radius, leaf, EnumReplaceMode.NONE); + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenBirch.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenBirch.java index 582a22ece..2f2b9c7ae 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenBirch.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenBirch.java @@ -14,8 +14,7 @@ import forestry.api.world.ITreeGenData; public class WorldGenBirch extends WorldGenTreeVanilla { - public WorldGenBirch(ITreeGenData tree) { - super(tree); - } - + public WorldGenBirch(ITreeGenData tree) { + super(tree); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenCherry.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenCherry.java index c6a37e3dd..f7b07e8cd 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenCherry.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenCherry.java @@ -10,38 +10,44 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenCherry extends WorldGenTree { - public WorldGenCherry(ITreeGenData tree) { - super(tree, 4, 4); - } + public WorldGenCherry(ITreeGenData tree) { + super(tree, 4, 4); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); - - int branchWidth = height / 2; - while (leafSpawn > 2) { - int leafRadius = Math.min(4, branchWidth); - List branchCoords = generateBranches(world, leafSpawn, 0, 0, 0.2f, 0.5f, branchWidth, 1); - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCircle(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, leafRadius, 3, 2, leaf, 1.0f, EnumReplaceMode.NONE); - } - leafSpawn -= 2; - branchWidth++; - } - - } + int leafSpawn = height + 1; + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); + int branchWidth = height / 2; + while (leafSpawn > 2) { + int leafRadius = Math.min(4, branchWidth); + List branchCoords = generateBranches(world, leafSpawn, 0, 0, 0.2f, 0.5f, branchWidth, 1); + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCircle( + world, + branchEnd.posY, + branchEnd.posX, + branchEnd.posZ, + leafRadius, + 3, + 2, + leaf, + 1.0f, + EnumReplaceMode.NONE); + } + leafSpawn -= 2; + branchWidth++; + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenChestnut.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenChestnut.java index 30be01810..be020b4d6 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenChestnut.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenChestnut.java @@ -10,44 +10,41 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenChestnut extends WorldGenTree { - public WorldGenChestnut(ITreeGenData tree) { - super(tree, 7, 3); - } + public WorldGenChestnut(ITreeGenData tree) { + super(tree, 7, 3); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - int leafSpawn = height + 1; + int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); - while (leafSpawn > 4) { - generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); - } - if (world.rand.nextBoolean()) { - generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); - } + while (leafSpawn > 4) { + generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); + } + if (world.rand.nextBoolean()) { + generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); + } - int branchRadius = height / 2; + int branchRadius = height / 2; - List branchCoords = generateBranches(world, leafSpawn, 0, 0, 0.5f, 0.5f, branchRadius, 2); - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCylinder(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 1.0f, 2, leaf, EnumReplaceMode.NONE); - } - - generateAdjustedCylinder(world, leafSpawn, 1.5f, 1, leaf); - - } + List branchCoords = generateBranches(world, leafSpawn, 0, 0, 0.5f, 0.5f, branchRadius, 2); + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCylinder( + world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 1.0f, 2, leaf, EnumReplaceMode.NONE); + } + generateAdjustedCylinder(world, leafSpawn, 1.5f, 1, leaf); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenCocobolo.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenCocobolo.java index 4665f3c54..93c99dce8 100644 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenCocobolo.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenCocobolo.java @@ -10,54 +10,50 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenCocobolo extends WorldGenTree { - public WorldGenCocobolo(ITreeGenData tree) { - super(tree, 8, 8); - } - - @Override - public void generate(World world) { - List treeTops = generateTreeTrunk(world, height, girth); + public WorldGenCocobolo(ITreeGenData tree) { + super(tree, 8, 8); + } - int leafSpawn = height; + @Override + public void generate(World world) { + List treeTops = generateTreeTrunk(world, height, girth); - for (ChunkCoordinates treeTop : treeTops) { - addLeaf(world, treeTop.posX, treeTop.posY + 1, treeTop.posZ, EnumReplaceMode.NONE); - } - leafSpawn--; - generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); + int leafSpawn = height; - if (height > 10) { - generateAdjustedCylinder(world, leafSpawn--, 2, 1, leaf); - } - generateAdjustedCylinder(world, leafSpawn, 0, 1, leaf); - - leafSpawn--; - - while (leafSpawn > 4) { - int offset = 1; - if (leafSpawn % 2 == 0) { - if (world.rand.nextBoolean()) { - offset = -1; - } - generateAdjustedCylinder(world, leafSpawn, offset, offset, 2, 1, leaf, EnumReplaceMode.NONE); - } else { - if (world.rand.nextBoolean()) { - offset = -1; - } - generateAdjustedCylinder(world, leafSpawn, offset, offset, 0, 1, leaf, EnumReplaceMode.NONE); - } - leafSpawn--; - } + for (ChunkCoordinates treeTop : treeTops) { + addLeaf(world, treeTop.posX, treeTop.posY + 1, treeTop.posZ, EnumReplaceMode.NONE); + } + leafSpawn--; + generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); - } + if (height > 10) { + generateAdjustedCylinder(world, leafSpawn--, 2, 1, leaf); + } + generateAdjustedCylinder(world, leafSpawn, 0, 1, leaf); + leafSpawn--; + + while (leafSpawn > 4) { + int offset = 1; + if (leafSpawn % 2 == 0) { + if (world.rand.nextBoolean()) { + offset = -1; + } + generateAdjustedCylinder(world, leafSpawn, offset, offset, 2, 1, leaf, EnumReplaceMode.NONE); + } else { + if (world.rand.nextBoolean()) { + offset = -1; + } + generateAdjustedCylinder(world, leafSpawn, offset, offset, 0, 1, leaf, EnumReplaceMode.NONE); + } + leafSpawn--; + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenDarkOak.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenDarkOak.java index e0db60335..473270e53 100644 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenDarkOak.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenDarkOak.java @@ -14,8 +14,7 @@ import forestry.api.world.ITreeGenData; public class WorldGenDarkOak extends WorldGenTreeVanilla { - public WorldGenDarkOak(ITreeGenData tree) { - super(tree); - } - + public WorldGenDarkOak(ITreeGenData tree) { + super(tree); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenDate.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenDate.java index a9f9eec9f..895196991 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenDate.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenDate.java @@ -10,28 +10,25 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; +import net.minecraft.world.World; public class WorldGenDate extends WorldGenTree { - public WorldGenDate(ITreeGenData tree) { - super(tree, 6, 2); - } + public WorldGenDate(ITreeGenData tree) { + super(tree, 6, 2); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - int leafSpawn = height + 1; + int leafSpawn = height + 1; - float radiusMultiplier = height / 6f; - - generateAdjustedCylinder(world, leafSpawn--, radiusMultiplier * 2f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, radiusMultiplier * 0.5f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn, 0, 1, leaf); - - } + float radiusMultiplier = height / 6f; + generateAdjustedCylinder(world, leafSpawn--, radiusMultiplier * 2f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, radiusMultiplier * 0.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn, 0, 1, leaf); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenEbony.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenEbony.java index 700a80f28..fbac4dd25 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenEbony.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenEbony.java @@ -10,60 +10,57 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; +import net.minecraft.world.World; public class WorldGenEbony extends WorldGenTree { - public WorldGenEbony(ITreeGenData tree) { - super(tree, 10, 4); - } + public WorldGenEbony(ITreeGenData tree) { + super(tree, 10, 4); + } - @Override - public void generate(World world) { + @Override + public void generate(World world) { - int offset = (girth - 1) / 2; - int trunksgenerated = 0; + int offset = (girth - 1) / 2; + int trunksgenerated = 0; - for (int x = -offset; x < -offset + girth; x++) { - for (int z = -offset; z < -offset + girth; z++) { - if (world.rand.nextFloat() < 0.6f) { - for (int i = 0; i < height; i++) { - addWood(world, x, i, z, EnumReplaceMode.ALL); - if (i > height / 2 && world.rand.nextFloat() < 0.1f * (10 / height)) { - break; - } - } - trunksgenerated++; - } else { - for (int i = 0; i < 1; i++) { - clearBlock(world, x, i, z); - } - } - } - } + for (int x = -offset; x < -offset + girth; x++) { + for (int z = -offset; z < -offset + girth; z++) { + if (world.rand.nextFloat() < 0.6f) { + for (int i = 0; i < height; i++) { + addWood(world, x, i, z, EnumReplaceMode.ALL); + if (i > height / 2 && world.rand.nextFloat() < 0.1f * (10 / height)) { + break; + } + } + trunksgenerated++; + } else { + for (int i = 0; i < 1; i++) { + clearBlock(world, x, i, z); + } + } + } + } - // Generate backup trunk, if we failed to generate any. - if (trunksgenerated <= 0) { - generateTreeTrunk(world, height, 1, 0.6f); - } + // Generate backup trunk, if we failed to generate any. + if (trunksgenerated <= 0) { + generateTreeTrunk(world, height, 1, 0.6f); + } - // Add tree top - for (int times = 0; times < 2 * height; times++) { - int h = 2 * girth + world.rand.nextInt(height - girth); - if (world.rand.nextBoolean() && h < height / 2) { - h = height / 2 + world.rand.nextInt(height / 2); - } + // Add tree top + for (int times = 0; times < 2 * height; times++) { + int h = 2 * girth + world.rand.nextInt(height - girth); + if (world.rand.nextBoolean() && h < height / 2) { + h = height / 2 + world.rand.nextInt(height / 2); + } - int x_off = -(girth) + world.rand.nextInt(2 * girth); - int y_off = -(girth) + world.rand.nextInt(2 * girth); - - Vector center = new Vector(x_off, h, y_off); - int radius = 1 + world.rand.nextInt(girth); - generateSphere(world, center, radius, leaf, EnumReplaceMode.NONE); - } - - } + int x_off = -(girth) + world.rand.nextInt(2 * girth); + int y_off = -(girth) + world.rand.nextInt(2 * girth); + Vector center = new Vector(x_off, h, y_off); + int radius = 1 + world.rand.nextInt(girth); + generateSphere(world, center, radius, leaf, EnumReplaceMode.NONE); + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenGiganteum.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenGiganteum.java index 66481aea1..23f7e40ae 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenGiganteum.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenGiganteum.java @@ -14,8 +14,7 @@ import forestry.api.world.ITreeGenData; public class WorldGenGiganteum extends WorldGenSequoia { - public WorldGenGiganteum(ITreeGenData tree) { - super(tree, 35, 15); - } - + public WorldGenGiganteum(ITreeGenData tree) { + super(tree, 35, 15); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenGreenheart.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenGreenheart.java index 395e8eebb..492308bdd 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenGreenheart.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenGreenheart.java @@ -10,46 +10,43 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; +import net.minecraft.world.World; public class WorldGenGreenheart extends WorldGenTree { - public WorldGenGreenheart(ITreeGenData tree) { - super(tree, 10, 8); - } + public WorldGenGreenheart(ITreeGenData tree) { + super(tree, 10, 8); + } - @Override - public void generate(World world) { + @Override + public void generate(World world) { - generateTreeTrunk(world, height, girth, 0.4f); - generateSupportStems(world, height, girth, 0.5f, 0.2f); + generateTreeTrunk(world, height, girth, 0.4f); + generateSupportStems(world, height, girth, 0.5f, 0.2f); - int leafSpawn = height + 1; + int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); - while (leafSpawn > height - 4) { - generateAdjustedCylinder(world, leafSpawn--, 1.9f, 1, leaf); - } - generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); - - // Add some smaller twigs below for flavour - for (int times = 0; times < height / 4; times++) { - int h = 10 + world.rand.nextInt(height - 10); - if (world.rand.nextBoolean() && h < height / 2) { - h = height / 2 + world.rand.nextInt(height / 2); - } - int x_off = -1 + world.rand.nextInt(3); - int y_off = -1 + world.rand.nextInt(3); - generateSphere(world, new Vector(x_off, h, y_off), 1 + world.rand.nextInt(1), leaf, EnumReplaceMode.NONE); - } - - } + while (leafSpawn > height - 4) { + generateAdjustedCylinder(world, leafSpawn--, 1.9f, 1, leaf); + } + generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); + // Add some smaller twigs below for flavour + for (int times = 0; times < height / 4; times++) { + int h = 10 + world.rand.nextInt(height - 10); + if (world.rand.nextBoolean() && h < height / 2) { + h = height / 2 + world.rand.nextInt(height / 2); + } + int x_off = -1 + world.rand.nextInt(3); + int y_off = -1 + world.rand.nextInt(3); + generateSphere(world, new Vector(x_off, h, y_off), 1 + world.rand.nextInt(1), leaf, EnumReplaceMode.NONE); + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenIpe.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenIpe.java index 07154b319..11787861f 100644 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenIpe.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenIpe.java @@ -10,41 +10,39 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.ArrayList; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenIpe extends WorldGenTree { - public WorldGenIpe(ITreeGenData tree) { - super(tree, 6, 4); - } + public WorldGenIpe(ITreeGenData tree) { + super(tree, 6, 4); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - int leafSpawn = height + 1; - float adjustedGirth = girth * .65f; + int leafSpawn = height + 1; + float adjustedGirth = girth * .65f; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 0.2f * adjustedGirth, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 0.2f * adjustedGirth, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0.2f * adjustedGirth, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0.2f * adjustedGirth, 1, leaf); - List branchCoords = new ArrayList<>(); - while (leafSpawn > 2) { - int radius = Math.round(adjustedGirth * (height - leafSpawn) / 1.5f); - branchCoords.addAll(generateBranches(world, leafSpawn, 0, 0, 0.25f, 0.25f, radius, 2)); - leafSpawn -= 2; - } - - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCylinder(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 2.0f, 2, leaf, EnumReplaceMode.NONE); - } - } + List branchCoords = new ArrayList<>(); + while (leafSpawn > 2) { + int radius = Math.round(adjustedGirth * (height - leafSpawn) / 1.5f); + branchCoords.addAll(generateBranches(world, leafSpawn, 0, 0, 0.25f, 0.25f, radius, 2)); + leafSpawn -= 2; + } + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCylinder( + world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 2.0f, 2, leaf, EnumReplaceMode.NONE); + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenJungle.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenJungle.java index e1339bcd8..3ebed700a 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenJungle.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenJungle.java @@ -10,55 +10,52 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.ArrayList; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - /** * This is a dummy and needs to be replaced with something proper. */ public class WorldGenJungle extends WorldGenTreeVanilla { - public WorldGenJungle(ITreeGenData tree) { - super(tree); - } + public WorldGenJungle(ITreeGenData tree) { + super(tree); + } - @Override - public void generate(World world) { - float vinesChance = 0.0f; - if (girth >= 2) { - height *= 1.5f; - vinesChance = 0.8f; - } + @Override + public void generate(World world) { + float vinesChance = 0.0f; + if (girth >= 2) { + height *= 1.5f; + vinesChance = 0.8f; + } - generateTreeTrunk(world, height, girth, vinesChance); + generateTreeTrunk(world, height, girth, vinesChance); - if (height > 10) { - List branchCoords = new ArrayList<>(); - int branchSpawn = 6; - while (branchSpawn < height - 2) { - branchCoords.addAll(generateBranches(world, branchSpawn, 0, 0, 0.5f, 0f, 2, 1, 0.25f)); - branchSpawn += world.rand.nextInt(4); - } + if (height > 10) { + List branchCoords = new ArrayList<>(); + int branchSpawn = 6; + while (branchSpawn < height - 2) { + branchCoords.addAll(generateBranches(world, branchSpawn, 0, 0, 0.5f, 0f, 2, 1, 0.25f)); + branchSpawn += world.rand.nextInt(4); + } - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCylinder(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 0f, 1, leaf, EnumReplaceMode.NONE); - } - } + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCylinder( + world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 0f, 1, leaf, EnumReplaceMode.NONE); + } + } - int leafSpawn = height + 1; - float canopyRadiusMultiplier = height / 7.0f; + int leafSpawn = height + 1; + float canopyRadiusMultiplier = height / 7.0f; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 0.5f * canopyRadiusMultiplier, 1, leaf); - - generateAdjustedCylinder(world, leafSpawn--, 1.9f * canopyRadiusMultiplier, 1, leaf); - generateAdjustedCylinder(world, leafSpawn, 1.9f * canopyRadiusMultiplier, 1, leaf); - - } + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0.5f * canopyRadiusMultiplier, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1.9f * canopyRadiusMultiplier, 1, leaf); + generateAdjustedCylinder(world, leafSpawn, 1.9f * canopyRadiusMultiplier, 1, leaf); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenKapok.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenKapok.java index 4955939c8..0d920f302 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenKapok.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenKapok.java @@ -10,54 +10,52 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.ArrayList; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenKapok extends WorldGenTree { - public WorldGenKapok(ITreeGenData tree) { - super(tree, 10, 8); - } + public WorldGenKapok(ITreeGenData tree) { + super(tree, 10, 8); + } - @Override - public void generate(World world) { + @Override + public void generate(World world) { - generateTreeTrunk(world, height, girth, 0.6f); - generateSupportStems(world, height, girth, 0.8f, 0.4f); + generateTreeTrunk(world, height, girth, 0.6f); + generateSupportStems(world, height, girth, 0.8f, 0.4f); - int leafSpawn = height + 1; + int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1.9f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1.9f, 1, leaf); - List branchCoords = new ArrayList<>(); - while (leafSpawn > height - 4) { - int radius = Math.round(girth * (height - leafSpawn) / 1.5f) + 6; - branchCoords.addAll(generateBranches(world, leafSpawn, 0, 0, 0.3f, 0.25f, radius, 6)); - leafSpawn -= 2; - } + List branchCoords = new ArrayList<>(); + while (leafSpawn > height - 4) { + int radius = Math.round(girth * (height - leafSpawn) / 1.5f) + 6; + branchCoords.addAll(generateBranches(world, leafSpawn, 0, 0, 0.3f, 0.25f, radius, 6)); + leafSpawn -= 2; + } - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCylinder(world, branchEnd.posY + 1, branchEnd.posX, branchEnd.posZ, 2.0f, 2, leaf, EnumReplaceMode.NONE); - } - - // Add some smaller twigs below for flavour - for (int times = 0; times < height / 4; times++) { - int h = 10 + world.rand.nextInt(Math.max(1, height - 10)); - if (world.rand.nextBoolean() && h < height / 2) { - h = height / 2 + world.rand.nextInt(height / 2); - } - int x_off = -1 + world.rand.nextInt(3); - int y_off = -1 + world.rand.nextInt(3); - generateSphere(world, new Vector(x_off, h, y_off), 1 + world.rand.nextInt(1), leaf, EnumReplaceMode.NONE); - } - } + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCylinder( + world, branchEnd.posY + 1, branchEnd.posX, branchEnd.posZ, 2.0f, 2, leaf, EnumReplaceMode.NONE); + } + // Add some smaller twigs below for flavour + for (int times = 0; times < height / 4; times++) { + int h = 10 + world.rand.nextInt(Math.max(1, height - 10)); + if (world.rand.nextBoolean() && h < height / 2) { + h = height / 2 + world.rand.nextInt(height / 2); + } + int x_off = -1 + world.rand.nextInt(3); + int y_off = -1 + world.rand.nextInt(3); + generateSphere(world, new Vector(x_off, h, y_off), 1 + world.rand.nextInt(1), leaf, EnumReplaceMode.NONE); + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenLarch.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenLarch.java index f43597d17..6b6e974ae 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenLarch.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenLarch.java @@ -10,32 +10,29 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; +import net.minecraft.world.World; public class WorldGenLarch extends WorldGenTree { - public WorldGenLarch(ITreeGenData tree) { - super(tree, 6, 5); - } + public WorldGenLarch(ITreeGenData tree) { + super(tree, 6, 5); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - int leafSpawn = height + 1; + int leafSpawn = height + 1; - float sizeMultiplier = Math.max(height / 8, 1.0f); + float sizeMultiplier = Math.max(height / 8, 1.0f); - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, sizeMultiplier, 1, leaf); - - while (leafSpawn > 2) { - generateAdjustedCylinder(world, leafSpawn--, 2 * sizeMultiplier, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, sizeMultiplier, 1, leaf); - } - - } + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, sizeMultiplier, 1, leaf); + while (leafSpawn > 2) { + generateAdjustedCylinder(world, leafSpawn--, 2 * sizeMultiplier, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, sizeMultiplier, 1, leaf); + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenLemon.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenLemon.java index a06945d7f..a8b947c8f 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenLemon.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenLemon.java @@ -10,27 +10,25 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; +import net.minecraft.world.World; public class WorldGenLemon extends WorldGenTree { - public WorldGenLemon(ITreeGenData tree) { - super(tree, 6, 3); - } + public WorldGenLemon(ITreeGenData tree) { + super(tree, 6, 3); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); - - int yCenter = height - girth; - yCenter = yCenter > 2 ? yCenter : 3; - int radius = Math.round((2 + world.rand.nextInt(girth)) * (height / 4.0f)); - if (radius > 4) { - radius = 4; - } - generateSphere(world, getCenteredAt(yCenter, 0, 0), radius, leaf, EnumReplaceMode.NONE); - } + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); + int yCenter = height - girth; + yCenter = yCenter > 2 ? yCenter : 3; + int radius = Math.round((2 + world.rand.nextInt(girth)) * (height / 4.0f)); + if (radius > 4) { + radius = 4; + } + generateSphere(world, getCenteredAt(yCenter, 0, 0), radius, leaf, EnumReplaceMode.NONE); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenMahoe.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenMahoe.java index 4c63b5848..4f5a7b878 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenMahoe.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenMahoe.java @@ -10,36 +10,34 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.ArrayList; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenMahoe extends WorldGenTree { - public WorldGenMahoe(ITreeGenData tree) { - super(tree, 6, 3); - } + public WorldGenMahoe(ITreeGenData tree) { + super(tree, 6, 3); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - List branchCoords = new ArrayList<>(); - for (int yBranch = 2; yBranch < height - 1; yBranch++) { - branchCoords.addAll(generateBranches(world, yBranch, 0, 0, 0.15f, 0.25f, Math.round((height - yBranch) * 0.75f), 1, 0.25f)); - } - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCylinder(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 2, 2, leaf, EnumReplaceMode.NONE); - } - - int yCenter = height - girth; - yCenter = yCenter > 3 ? yCenter : 4; - generateSphere(world, getCenteredAt(yCenter, 0, 0), 3 + world.rand.nextInt(girth), leaf, EnumReplaceMode.NONE); - - } + List branchCoords = new ArrayList<>(); + for (int yBranch = 2; yBranch < height - 1; yBranch++) { + branchCoords.addAll(generateBranches( + world, yBranch, 0, 0, 0.15f, 0.25f, Math.round((height - yBranch) * 0.75f), 1, 0.25f)); + } + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCylinder( + world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 2, 2, leaf, EnumReplaceMode.NONE); + } + int yCenter = height - girth; + yCenter = yCenter > 3 ? yCenter : 4; + generateSphere(world, getCenteredAt(yCenter, 0, 0), 3 + world.rand.nextInt(girth), leaf, EnumReplaceMode.NONE); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenMahogany.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenMahogany.java index 1290be99b..f5f838dd1 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenMahogany.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenMahogany.java @@ -10,44 +10,42 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.ArrayList; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenMahogany extends WorldGenTree { - public WorldGenMahogany(ITreeGenData tree) { - super(tree, 12, 6); - } + public WorldGenMahogany(ITreeGenData tree) { + super(tree, 12, 6); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth, 0.6f); - generateSupportStems(world, height, girth, 0.4f, 0.4f); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth, 0.6f); + generateSupportStems(world, height, girth, 0.4f, 0.4f); - List branchCoords = new ArrayList<>(); - for (int yBranch = height - 4; yBranch < height - 2; yBranch++) { - branchCoords.addAll(generateBranches(world, yBranch, 0, 0, 0.15f, 0.25f, Math.round((height - yBranch) * 0.5f), 1, 0.25f)); - } - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCylinder(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 2, 2, leaf, EnumReplaceMode.NONE); - } + List branchCoords = new ArrayList<>(); + for (int yBranch = height - 4; yBranch < height - 2; yBranch++) { + branchCoords.addAll(generateBranches( + world, yBranch, 0, 0, 0.15f, 0.25f, Math.round((height - yBranch) * 0.5f), 1, 0.25f)); + } + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCylinder( + world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 2, 2, leaf, EnumReplaceMode.NONE); + } - int leafSpawn = height + 1; + int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); - - generateAdjustedCylinder(world, leafSpawn--, 3f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 3f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); - - } + generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 3f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 3f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenMaple.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenMaple.java index 696678250..f0860b17b 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenMaple.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenMaple.java @@ -10,45 +10,43 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.ArrayList; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenMaple extends WorldGenTree { - public WorldGenMaple(ITreeGenData tree) { - super(tree, 7, 5); - } + public WorldGenMaple(ITreeGenData tree) { + super(tree, 7, 5); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - List branchCoords = new ArrayList<>(); - for (int yBranch = 2; yBranch < height - 2; yBranch++) { - branchCoords.addAll(generateBranches(world, yBranch, 0, 0, 0.15f, 0.25f, Math.round((height - yBranch) * 0.25f), 1, 0.25f)); - } - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCylinder(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 2, 2, leaf, EnumReplaceMode.NONE); - } + List branchCoords = new ArrayList<>(); + for (int yBranch = 2; yBranch < height - 2; yBranch++) { + branchCoords.addAll(generateBranches( + world, yBranch, 0, 0, 0.15f, 0.25f, Math.round((height - yBranch) * 0.25f), 1, 0.25f)); + } + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCylinder( + world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 2, 2, leaf, EnumReplaceMode.NONE); + } - int leafSpawn = height + 1; - float diameterchange = (float) 1 / height; - int leafSpawned = 2; + int leafSpawn = height + 1; + float diameterchange = (float) 1 / height; + int leafSpawned = 2; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); - - while (leafSpawn > 1) { - generateAdjustedCylinder(world, leafSpawn--, 3 * diameterchange * leafSpawned, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 2 * diameterchange * leafSpawned, 1, leaf); - leafSpawned += 2; - } - - } + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); + while (leafSpawn > 1) { + generateAdjustedCylinder(world, leafSpawn--, 3 * diameterchange * leafSpawned, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 2 * diameterchange * leafSpawned, 1, leaf); + leafSpawned += 2; + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenOak.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenOak.java index d495115ee..89f5c9c41 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenOak.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenOak.java @@ -14,8 +14,7 @@ import forestry.api.world.ITreeGenData; public class WorldGenOak extends WorldGenTreeVanilla { - public WorldGenOak(ITreeGenData tree) { - super(tree); - } - + public WorldGenOak(ITreeGenData tree) { + super(tree); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenPadauk.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenPadauk.java index 70032e1d2..7faf56b5f 100644 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenPadauk.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenPadauk.java @@ -10,65 +10,63 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import java.util.Random; - -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - import forestry.api.world.ITreeGenData; +import java.util.Random; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; public class WorldGenPadauk extends WorldGenTree { - public WorldGenPadauk(ITreeGenData tree) { - super(tree, 6, 6); - } + public WorldGenPadauk(ITreeGenData tree) { + super(tree, 6, 6); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - int leafSpawn = height + 1; + int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 3f, 1, leaf); - - int count = 0; - int max = 3; - int min = 1; - int canopyHeight = world.rand.nextInt(max - min + 1) + min; - - while (leafSpawn > 3 && count < canopyHeight) { - generateAdjustedCylinder(world, leafSpawn--, 4.5f, 1, leaf); - count++; - //Random Trunk Branches - for (int i = 0; i < girth * 4; i++) { - if (world.rand.nextBoolean()) { - - int[] offset = {-1, 1}; - int offsetValue = (offset[new Random().nextInt(offset.length)]); - int maxBranchLength = 3; - int branchLength = new Random().nextInt(maxBranchLength + 1); - ForgeDirection[] direction = {ForgeDirection.NORTH, ForgeDirection.EAST}; - ForgeDirection directionValue = (direction[new Random().nextInt(direction.length)]); - int branchSpawn = leafSpawn; + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 3f, 1, leaf); - for (int j = 1; j < branchLength + 1; j++) { - if (j == branchLength && world.rand.nextBoolean()) { //Just adding a bit of variation to the ends for character - branchSpawn += 1; - } + int count = 0; + int max = 3; + int min = 1; + int canopyHeight = world.rand.nextInt(max - min + 1) + min; - wood.setDirection(directionValue); - if (directionValue == ForgeDirection.NORTH) { - addWood(world, 0, branchSpawn, j * offsetValue, EnumReplaceMode.ALL); - } else if (directionValue == ForgeDirection.EAST) { - addWood(world, j * offsetValue, branchSpawn, 0, EnumReplaceMode.ALL); - } - } - } - } - } - } + while (leafSpawn > 3 && count < canopyHeight) { + generateAdjustedCylinder(world, leafSpawn--, 4.5f, 1, leaf); + count++; + // Random Trunk Branches + for (int i = 0; i < girth * 4; i++) { + if (world.rand.nextBoolean()) { + int[] offset = {-1, 1}; + int offsetValue = (offset[new Random().nextInt(offset.length)]); + int maxBranchLength = 3; + int branchLength = new Random().nextInt(maxBranchLength + 1); + ForgeDirection[] direction = {ForgeDirection.NORTH, ForgeDirection.EAST}; + ForgeDirection directionValue = (direction[new Random().nextInt(direction.length)]); + int branchSpawn = leafSpawn; + + for (int j = 1; j < branchLength + 1; j++) { + if (j == branchLength + && world.rand + .nextBoolean()) { // Just adding a bit of variation to the ends for character + branchSpawn += 1; + } + + wood.setDirection(directionValue); + if (directionValue == ForgeDirection.NORTH) { + addWood(world, 0, branchSpawn, j * offsetValue, EnumReplaceMode.ALL); + } else if (directionValue == ForgeDirection.EAST) { + addWood(world, j * offsetValue, branchSpawn, 0, EnumReplaceMode.ALL); + } + } + } + } + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenPapaya.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenPapaya.java index e6e6e2158..0fc949ceb 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenPapaya.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenPapaya.java @@ -10,31 +10,34 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenPapaya extends WorldGenTree { - public WorldGenPapaya(ITreeGenData tree) { - super(tree, 7, 2); - } + public WorldGenPapaya(ITreeGenData tree) { + super(tree, 7, 2); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - List branchCoords = generateBranches(world, height, 0, 0, 0.15f, 0.25f, height / 4, 1, 0.25f); - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCylinder(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 1, 1, leaf, EnumReplaceMode.NONE); - } - - int yCenter = height - girth; - yCenter = yCenter > 3 ? yCenter : 4; - generateSphere(world, getCenteredAt(yCenter, 0, 0), Math.round((2 + world.rand.nextInt(girth)) * (height / 8.0f)), leaf, EnumReplaceMode.NONE); - } + List branchCoords = generateBranches(world, height, 0, 0, 0.15f, 0.25f, height / 4, 1, 0.25f); + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCylinder( + world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 1, 1, leaf, EnumReplaceMode.NONE); + } + int yCenter = height - girth; + yCenter = yCenter > 3 ? yCenter : 4; + generateSphere( + world, + getCenteredAt(yCenter, 0, 0), + Math.round((2 + world.rand.nextInt(girth)) * (height / 8.0f)), + leaf, + EnumReplaceMode.NONE); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenPine.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenPine.java index e6bd7608b..3676e5bc7 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenPine.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenPine.java @@ -10,45 +10,43 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.ArrayList; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenPine extends WorldGenTree { - public WorldGenPine(ITreeGenData tree) { - super(tree, 6, 4); - } + public WorldGenPine(ITreeGenData tree) { + super(tree, 6, 4); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - List branchCoords = new ArrayList<>(); - for (int yBranch = 2; yBranch < height - 2; yBranch++) { - branchCoords.addAll(generateBranches(world, yBranch, 0, 0, 0.05f, 0.1f, Math.round((height - yBranch) * 0.25f), 1, 0.25f)); - } - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCylinder(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 2, 1, leaf, EnumReplaceMode.NONE); - } + List branchCoords = new ArrayList<>(); + for (int yBranch = 2; yBranch < height - 2; yBranch++) { + branchCoords.addAll(generateBranches( + world, yBranch, 0, 0, 0.05f, 0.1f, Math.round((height - yBranch) * 0.25f), 1, 0.25f)); + } + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCylinder( + world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 2, 1, leaf, EnumReplaceMode.NONE); + } - int leafSpawn = height + 1; - float diameterchange = 1.25f / height; - int leafSpawned = 2; + int leafSpawn = height + 1; + float diameterchange = 1.25f / height; + int leafSpawned = 2; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); - - while (leafSpawn > 1) { - generateAdjustedCylinder(world, leafSpawn--, 3 * diameterchange * leafSpawned, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 2 * diameterchange * leafSpawned, 1, leaf); - leafSpawned += 2; - } - - } + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); + while (leafSpawn > 1) { + generateAdjustedCylinder(world, leafSpawn--, 3 * diameterchange * leafSpawned, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 2 * diameterchange * leafSpawned, 1, leaf); + leafSpawned += 2; + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenPlum.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenPlum.java index f67669e10..b69bc8404 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenPlum.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenPlum.java @@ -10,29 +10,27 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; +import net.minecraft.world.World; public class WorldGenPlum extends WorldGenTree { - public WorldGenPlum(ITreeGenData tree) { - super(tree, 6, 3); - } + public WorldGenPlum(ITreeGenData tree) { + super(tree, 6, 3); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - int yCenter = height - girth; - yCenter = yCenter > 2 ? yCenter : 3; - - Vector center = getCenteredAt(yCenter, 0, 0); - int radius = Math.round((2 + world.rand.nextInt(girth)) * (height / 4.0f)); - if (radius > 4) { - radius = 4; - } - generateSphere(world, center, radius, leaf, EnumReplaceMode.NONE); - } + int yCenter = height - girth; + yCenter = yCenter > 2 ? yCenter : 3; + Vector center = getCenteredAt(yCenter, 0, 0); + int radius = Math.round((2 + world.rand.nextInt(girth)) * (height / 4.0f)); + if (radius > 4) { + radius = 4; + } + generateSphere(world, center, radius, leaf, EnumReplaceMode.NONE); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenPoplar.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenPoplar.java index 3b12a9b6b..8d3aa68e6 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenPoplar.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenPoplar.java @@ -10,27 +10,24 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; +import net.minecraft.world.World; public class WorldGenPoplar extends WorldGenTree { - public WorldGenPoplar(ITreeGenData tree) { - super(tree, 8, 3); - } + public WorldGenPoplar(ITreeGenData tree) { + super(tree, 8, 3); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - int leafSpawn = height + 1; - float leafRadius = (girth - 1.0f) / 2.0f; - - while (leafSpawn > girth - 1) { - generateAdjustedCylinder(world, leafSpawn--, leafRadius, 1, leaf); - } - - } + int leafSpawn = height + 1; + float leafRadius = (girth - 1.0f) / 2.0f; + while (leafSpawn > girth - 1) { + generateAdjustedCylinder(world, leafSpawn--, leafRadius, 1, leaf); + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenSequoia.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenSequoia.java index d4137f9e3..a03dfb913 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenSequoia.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenSequoia.java @@ -10,54 +10,52 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.ArrayList; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenSequoia extends WorldGenTree { - public WorldGenSequoia(ITreeGenData tree) { - this(tree, 20, 5); - } + public WorldGenSequoia(ITreeGenData tree) { + this(tree, 20, 5); + } - protected WorldGenSequoia(ITreeGenData tree, int baseHeight, int heightVariation) { - super(tree, baseHeight, heightVariation); - } + protected WorldGenSequoia(ITreeGenData tree, int baseHeight, int heightVariation) { + super(tree, baseHeight, heightVariation); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); - generateSupportStems(world, height, girth, 0.4f, 0.4f); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); + generateSupportStems(world, height, girth, 0.4f, 0.4f); - int topHeight = (height / 3) + world.rand.nextInt(height / 6); + int topHeight = (height / 3) + world.rand.nextInt(height / 6); - List branchCoords = new ArrayList<>(); - for (int yBranch = topHeight; yBranch < height; yBranch++) { - int branchLength = Math.round(height - yBranch) / 2; - if (branchLength > 4) { - branchLength = 4; - } - branchCoords.addAll(generateBranches(world, yBranch, 0, 0, 0.05f, 0.25f, branchLength, 1, 0.5f)); - } - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCylinder(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 1.0f, 1, leaf, EnumReplaceMode.NONE); - } + List branchCoords = new ArrayList<>(); + for (int yBranch = topHeight; yBranch < height; yBranch++) { + int branchLength = Math.round(height - yBranch) / 2; + if (branchLength > 4) { + branchLength = 4; + } + branchCoords.addAll(generateBranches(world, yBranch, 0, 0, 0.05f, 0.25f, branchLength, 1, 0.5f)); + } + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCylinder( + world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 1.0f, 1, leaf, EnumReplaceMode.NONE); + } - int leafSpawn = height + 2; + int leafSpawn = height + 2; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); - while (leafSpawn > topHeight) { - generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); - } - - generateAdjustedCylinder(world, leafSpawn, 0, 1, leaf); - } + while (leafSpawn > topHeight) { + generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); + } + generateAdjustedCylinder(world, leafSpawn, 0, 1, leaf); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenSilverLime.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenSilverLime.java index ed4a65d20..20fdcbec3 100644 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenSilverLime.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenSilverLime.java @@ -10,35 +10,34 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenSilverLime extends WorldGenTree { - public WorldGenSilverLime(ITreeGenData tree) { - super(tree, 6, 4); - } + public WorldGenSilverLime(ITreeGenData tree) { + super(tree, 6, 4); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); - List branchCoords = generateBranches(world, 3 + world.rand.nextInt(1), 0, 0, 0.25f, 0.10f, Math.round(height * 0.25f), 2, 0.5f); - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCylinder(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 0, 1, leaf, EnumReplaceMode.NONE); - } + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); + List branchCoords = generateBranches( + world, 3 + world.rand.nextInt(1), 0, 0, 0.25f, 0.10f, Math.round(height * 0.25f), 2, 0.5f); + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCylinder( + world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 0, 1, leaf, EnumReplaceMode.NONE); + } - int leafSpawn = height + 1; - - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - float radius = 1; - while (leafSpawn > 1) { - generateAdjustedCylinder(world, leafSpawn--, radius, 1, leaf); - radius += 0.25; - } - } + int leafSpawn = height + 1; + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + float radius = 1; + while (leafSpawn > 1) { + generateAdjustedCylinder(world, leafSpawn--, radius, 1, leaf); + radius += 0.25; + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenSpruce.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenSpruce.java index d3177e48f..ba7a555e1 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenSpruce.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenSpruce.java @@ -10,39 +10,46 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenSpruce extends WorldGenTree { - public WorldGenSpruce(ITreeGenData tree) { - super(tree, 5, 3); - } + public WorldGenSpruce(ITreeGenData tree) { + super(tree, 5, 3); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - int leafSpawn = height + 1; + int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); - - int branchWidth = height / 4; - while (leafSpawn > 2) { - int leafRadius = Math.min(4, branchWidth); - List branchCoords = generateBranches(world, leafSpawn, 0, 0, 0.2f, 0.5f, branchWidth, 1); - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCircle(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, leafRadius, 3, 2, leaf, 1.0f, EnumReplaceMode.SOFT); - } - generateAdjustedCylinder(world, leafSpawn--, 2, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); - branchWidth++; - } - } + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); + int branchWidth = height / 4; + while (leafSpawn > 2) { + int leafRadius = Math.min(4, branchWidth); + List branchCoords = generateBranches(world, leafSpawn, 0, 0, 0.2f, 0.5f, branchWidth, 1); + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCircle( + world, + branchEnd.posY, + branchEnd.posX, + branchEnd.posZ, + leafRadius, + 3, + 2, + leaf, + 1.0f, + EnumReplaceMode.SOFT); + } + generateAdjustedCylinder(world, leafSpawn--, 2, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1, 1, leaf); + branchWidth++; + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenTeak.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenTeak.java index 1798c952e..535fe40ee 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenTeak.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenTeak.java @@ -10,46 +10,52 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenTeak extends WorldGenTree { - public WorldGenTeak(ITreeGenData tree) { - super(tree, 6, 3); - } + public WorldGenTeak(ITreeGenData tree) { + super(tree, 6, 3); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - float leafMultiplier = (height / 6.0f); - if (leafMultiplier > 2) { - leafMultiplier = 2; - } - int branchWidth = height / 3; - List branchCoords = generateBranches(world, height - 3, 0, 0, 0.2f, 0.5f, branchWidth, 1); - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCircle(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 2, Math.round(3 * leafMultiplier), 2, leaf, 1.0f, EnumReplaceMode.NONE); - } + float leafMultiplier = (height / 6.0f); + if (leafMultiplier > 2) { + leafMultiplier = 2; + } + int branchWidth = height / 3; + List branchCoords = generateBranches(world, height - 3, 0, 0, 0.2f, 0.5f, branchWidth, 1); + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCircle( + world, + branchEnd.posY, + branchEnd.posX, + branchEnd.posZ, + 2, + Math.round(3 * leafMultiplier), + 2, + leaf, + 1.0f, + EnumReplaceMode.NONE); + } - int leafSpawn = height + 1; + int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 0.5f * leafMultiplier, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0.5f * leafMultiplier, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1.9f * leafMultiplier, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1.9f * leafMultiplier, 1, leaf); - if (world.rand.nextBoolean()) { - generateAdjustedCylinder(world, leafSpawn--, 1.9f * leafMultiplier, 1, leaf); - } - - generateAdjustedCylinder(world, leafSpawn, 0.5f * leafMultiplier, 1, leaf); - - } + generateAdjustedCylinder(world, leafSpawn--, 1.9f * leafMultiplier, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1.9f * leafMultiplier, 1, leaf); + if (world.rand.nextBoolean()) { + generateAdjustedCylinder(world, leafSpawn--, 1.9f * leafMultiplier, 1, leaf); + } + generateAdjustedCylinder(world, leafSpawn, 0.5f * leafMultiplier, 1, leaf); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenTree.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenTree.java index b1b670218..542fb8f7d 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenTree.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenTree.java @@ -10,99 +10,117 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import forestry.api.arboriculture.ITreeModifier; import forestry.api.arboriculture.TreeManager; import forestry.api.world.ITreeGenData; +import net.minecraft.world.World; public abstract class WorldGenTree extends WorldGenArboriculture { - private static final int minHeight = 4; - private static final int maxHeight = 80; + private static final int minHeight = 4; + private static final int maxHeight = 80; - private final int baseHeight; - private final int heightVariation; + private final int baseHeight; + private final int heightVariation; - protected int girth; - protected int height; + protected int girth; + protected int height; - protected WorldGenTree(ITreeGenData tree, int baseHeight, int heightVariation) { - super(tree); - this.baseHeight = baseHeight; - this.heightVariation = heightVariation; - } + protected WorldGenTree(ITreeGenData tree, int baseHeight, int heightVariation) { + super(tree); + this.baseHeight = baseHeight; + this.heightVariation = heightVariation; + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - int leafSpawn = height + 1; + int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf, EnumReplaceMode.NONE); - generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf, EnumReplaceMode.NONE); + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf, EnumReplaceMode.NONE); + generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf, EnumReplaceMode.NONE); - generateAdjustedCylinder(world, leafSpawn--, 1.9f, 1, leaf, EnumReplaceMode.NONE); - generateAdjustedCylinder(world, leafSpawn--, 1.9f, 1, leaf, EnumReplaceMode.NONE); - } + generateAdjustedCylinder(world, leafSpawn--, 1.9f, 1, leaf, EnumReplaceMode.NONE); + generateAdjustedCylinder(world, leafSpawn--, 1.9f, 1, leaf, EnumReplaceMode.NONE); + } - protected Vector getCenteredAt(int yCenter, int xOffset, int zOffset) { - float cent = girth % 2 == 0 ? 0.5f : 0f; - return new Vector(cent + xOffset, yCenter, cent + zOffset); - } + protected Vector getCenteredAt(int yCenter, int xOffset, int zOffset) { + float cent = girth % 2 == 0 ? 0.5f : 0f; + return new Vector(cent + xOffset, yCenter, cent + zOffset); + } - protected void generateAdjustedCylinder(World world, int yCenter, float radius, int height, ITreeBlockType block) { - generateAdjustedCylinder(world, yCenter, 0, 0, radius, height, block, EnumReplaceMode.SOFT); - } + protected void generateAdjustedCylinder(World world, int yCenter, float radius, int height, ITreeBlockType block) { + generateAdjustedCylinder(world, yCenter, 0, 0, radius, height, block, EnumReplaceMode.SOFT); + } - protected void generateAdjustedCylinder(World world, int yCenter, float radius, int height, ITreeBlockType block, EnumReplaceMode replace) { - generateAdjustedCylinder(world, yCenter, 0, 0, radius, height, block, replace); - } + protected void generateAdjustedCylinder( + World world, int yCenter, float radius, int height, ITreeBlockType block, EnumReplaceMode replace) { + generateAdjustedCylinder(world, yCenter, 0, 0, radius, height, block, replace); + } - protected void generateAdjustedCylinder(World world, int yCenter, int xOffset, int zOffset, float radius, int height, ITreeBlockType block, EnumReplaceMode replace) { - Vector center = getCenteredAt(yCenter, xOffset, zOffset); - generateCylinder(world, center, radius + girth, height, block, replace); - } + protected void generateAdjustedCylinder( + World world, + int yCenter, + int xOffset, + int zOffset, + float radius, + int height, + ITreeBlockType block, + EnumReplaceMode replace) { + Vector center = getCenteredAt(yCenter, xOffset, zOffset); + generateCylinder(world, center, radius + girth, height, block, replace); + } - protected void generateAdjustedCircle(World world, int yCenter, int xOffset, int zOffset, float radius, int width, int height, ITreeBlockType block, float chance, EnumReplaceMode replace) { - Vector center = getCenteredAt(yCenter, xOffset, zOffset); - generateCircle(world, center, radius, width, height, block, chance, replace); - } + protected void generateAdjustedCircle( + World world, + int yCenter, + int xOffset, + int zOffset, + float radius, + int width, + int height, + ITreeBlockType block, + float chance, + EnumReplaceMode replace) { + Vector center = getCenteredAt(yCenter, xOffset, zOffset); + generateCircle(world, center, radius, width, height, block, chance, replace); + } - @Override - public boolean canGrow(World world, int x, int y, int z) { - return tree.canGrow(world, x, y, z, girth, height); - } + @Override + public boolean canGrow(World world, int x, int y, int z) { + return tree.canGrow(world, x, y, z, girth, height); + } - @Override - public final void preGenerate(World world, int startX, int startY, int startZ) { - super.preGenerate(world, startX, startY, startZ); - height = determineHeight(world, baseHeight, heightVariation); - girth = tree.getGirth(world, startX, startY, startZ); - } + @Override + public final void preGenerate(World world, int startX, int startY, int startZ) { + super.preGenerate(world, startX, startY, startZ); + height = determineHeight(world, baseHeight, heightVariation); + girth = tree.getGirth(world, startX, startY, startZ); + } - protected int modifyByHeight(World world, int val, int min, int max) { - ITreeModifier treeModifier = TreeManager.treeRoot.getTreekeepingMode(world); - int determined = Math.round(val * tree.getHeightModifier() * treeModifier.getHeightModifier(tree.getGenome(), 1f)); - return determined < min ? min : determined > max ? max : determined; - } + protected int modifyByHeight(World world, int val, int min, int max) { + ITreeModifier treeModifier = TreeManager.treeRoot.getTreekeepingMode(world); + int determined = + Math.round(val * tree.getHeightModifier() * treeModifier.getHeightModifier(tree.getGenome(), 1f)); + return determined < min ? min : determined > max ? max : determined; + } - private int determineHeight(World world, int required, int variation) { - ITreeModifier treeModifier = TreeManager.treeRoot.getTreekeepingMode(world); - int baseHeight = required + world.rand.nextInt(variation); - int height = Math.round(baseHeight * tree.getHeightModifier() * treeModifier.getHeightModifier(tree.getGenome(), 1f)); - return height < minHeight ? minHeight : height > maxHeight ? maxHeight : height; - } + private int determineHeight(World world, int required, int variation) { + ITreeModifier treeModifier = TreeManager.treeRoot.getTreekeepingMode(world); + int baseHeight = required + world.rand.nextInt(variation); + int height = Math.round( + baseHeight * tree.getHeightModifier() * treeModifier.getHeightModifier(tree.getGenome(), 1f)); + return height < minHeight ? minHeight : height > maxHeight ? maxHeight : height; + } - @Override - public TreeBlockTypeLeaf getLeaf(GameProfile owner) { - return new TreeBlockTypeLeaf(owner); - } - - @Override - public ITreeBlockType getWood() { - return new TreeBlockTypeLog(); - } + @Override + public TreeBlockTypeLeaf getLeaf(GameProfile owner) { + return new TreeBlockTypeLeaf(owner); + } + @Override + public ITreeBlockType getWood() { + return new TreeBlockTypeLog(); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenTreeVanilla.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenTreeVanilla.java index f2ce98548..05e0f9328 100644 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenTreeVanilla.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenTreeVanilla.java @@ -1,19 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.worldgen; - -import forestry.api.world.ITreeGenData; - -public abstract class WorldGenTreeVanilla extends WorldGenTree { - protected WorldGenTreeVanilla(ITreeGenData tree) { - super(tree, 5, 2); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.worldgen; + +import forestry.api.world.ITreeGenData; + +public abstract class WorldGenTreeVanilla extends WorldGenTree { + protected WorldGenTreeVanilla(ITreeGenData tree) { + super(tree, 5, 2); + } +} diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenWalnut.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenWalnut.java index aada614ab..00f036fa4 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenWalnut.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenWalnut.java @@ -10,41 +10,49 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenWalnut extends WorldGenTree { - public WorldGenWalnut(ITreeGenData tree) { - super(tree, 7, 3); - } + public WorldGenWalnut(ITreeGenData tree) { + super(tree, 7, 3); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - int leafSpawn = height + 1; + int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); - - float branchSize = 2; - while (leafSpawn >= 3) { - int leafRadius = Math.min(4, (int) branchSize); - List branchCoords = generateBranches(world, leafSpawn, 0, 0, 0.2f, 0.2f, (int) branchSize, 1, 0.5f); - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCircle(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, leafRadius, 2, 2, leaf, 1.0f, EnumReplaceMode.SOFT); - } - leafSpawn--; - branchSize += 0.25f; - } - } + generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); + float branchSize = 2; + while (leafSpawn >= 3) { + int leafRadius = Math.min(4, (int) branchSize); + List branchCoords = + generateBranches(world, leafSpawn, 0, 0, 0.2f, 0.2f, (int) branchSize, 1, 0.5f); + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCircle( + world, + branchEnd.posY, + branchEnd.posX, + branchEnd.posZ, + leafRadius, + 2, + 2, + leaf, + 1.0f, + EnumReplaceMode.SOFT); + } + leafSpawn--; + branchSize += 0.25f; + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenWenge.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenWenge.java index 1a1714c0d..a280076fe 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenWenge.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenWenge.java @@ -10,42 +10,50 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenWenge extends WorldGenTree { - public WorldGenWenge(ITreeGenData tree) { - super(tree, 6, 2); - } + public WorldGenWenge(ITreeGenData tree) { + super(tree, 6, 2); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth); - int leafSpawn = height + 1; + int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 2f, 1, leaf); - float branchSize = 3; - while (leafSpawn > 1) { - generateAdjustedCylinder(world, leafSpawn--, 3f, 1, leaf); - - List branchCoords = generateBranches(world, leafSpawn, 0, 0, 0.2f, 0.2f, (int) branchSize, 2, 0.75f); - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCircle(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 3, 3, 2, leaf, 1.0f, EnumReplaceMode.SOFT); - } - leafSpawn--; - branchSize += 0.5f; - } - } + float branchSize = 3; + while (leafSpawn > 1) { + generateAdjustedCylinder(world, leafSpawn--, 3f, 1, leaf); + List branchCoords = + generateBranches(world, leafSpawn, 0, 0, 0.2f, 0.2f, (int) branchSize, 2, 0.75f); + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCircle( + world, + branchEnd.posY, + branchEnd.posX, + branchEnd.posZ, + 3, + 3, + 2, + leaf, + 1.0f, + EnumReplaceMode.SOFT); + } + leafSpawn--; + branchSize += 0.5f; + } + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenWillow.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenWillow.java index 9e9caf93b..7231644cd 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenWillow.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenWillow.java @@ -10,40 +10,37 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; +import net.minecraft.world.World; public class WorldGenWillow extends WorldGenTree { - public WorldGenWillow(ITreeGenData tree) { - super(tree, 5, 2); - } + public WorldGenWillow(ITreeGenData tree) { + super(tree, 5, 2); + } - @Override - public void generate(World world) { - generateTreeTrunk(world, height, girth, 0.8f); - generateSupportStems(world, height, girth, 0.2f, 0.2f); + @Override + public void generate(World world) { + generateTreeTrunk(world, height, girth, 0.8f); + generateSupportStems(world, height, girth, 0.2f, 0.2f); - int leafSpawn = height + 1; + int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); - - generateAdjustedCylinder(world, leafSpawn--, 2.5f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 3f, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 3f, 1, leaf); - while (leafSpawn > 2) { - // support branches for tall willows, keeps the leaves from decaying immediately - if ((leafSpawn - 3) % 6 == 0) { - generateBranches(world, leafSpawn, 0, 0, 0, 0, 2, 1); - } - generateCircle(world, new Vector(0f, leafSpawn--, 0f), 4f, 2, 1, leaf, EnumReplaceMode.NONE); - } - generateCircle(world, new Vector(0f, leafSpawn--, 0f), 4f, 1, 1, leaf, EnumReplaceMode.NONE); - generateCircle(world, new Vector(0f, leafSpawn--, 0f), 4f, 1, 1, leaf, EnumReplaceMode.NONE); - generateCircle(world, new Vector(0f, leafSpawn, 0f), 4f, 1, 1, leaf, 0.4f, EnumReplaceMode.NONE); - - } + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 2.5f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 3f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 3f, 1, leaf); + while (leafSpawn > 2) { + // support branches for tall willows, keeps the leaves from decaying immediately + if ((leafSpawn - 3) % 6 == 0) { + generateBranches(world, leafSpawn, 0, 0, 0, 0, 2, 1); + } + generateCircle(world, new Vector(0f, leafSpawn--, 0f), 4f, 2, 1, leaf, EnumReplaceMode.NONE); + } + generateCircle(world, new Vector(0f, leafSpawn--, 0f), 4f, 1, 1, leaf, EnumReplaceMode.NONE); + generateCircle(world, new Vector(0f, leafSpawn--, 0f), 4f, 1, 1, leaf, EnumReplaceMode.NONE); + generateCircle(world, new Vector(0f, leafSpawn, 0f), 4f, 1, 1, leaf, 0.4f, EnumReplaceMode.NONE); + } } diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenZebrawood.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenZebrawood.java index 5e23e6439..218f82e60 100644 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenZebrawood.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenZebrawood.java @@ -10,53 +10,50 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; +import forestry.api.world.ITreeGenData; import java.util.List; - import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; - public class WorldGenZebrawood extends WorldGenTree { - public WorldGenZebrawood(ITreeGenData tree) { - super(tree, 8, 8); - } - - @Override - public void generate(World world) { + public WorldGenZebrawood(ITreeGenData tree) { + super(tree, 8, 8); + } - generateTreeTrunk(world, height, girth); - generateSupportStems(world, height, girth, 0.8f, 0.3f); + @Override + public void generate(World world) { - List branchCoords = generateBranches(world, height - 4, 0, 0, 0, 0.25f, 3, 2, 0.75f); - for (ChunkCoordinates branchEnd : branchCoords) { - generateAdjustedCylinder(world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 1.0f, 2, leaf, EnumReplaceMode.NONE); - } + generateTreeTrunk(world, height, girth); + generateSupportStems(world, height, girth, 0.8f, 0.3f); - int leafSpawn = height + 1; + List branchCoords = generateBranches(world, height - 4, 0, 0, 0, 0.25f, 3, 2, 0.75f); + for (ChunkCoordinates branchEnd : branchCoords) { + generateAdjustedCylinder( + world, branchEnd.posY, branchEnd.posX, branchEnd.posZ, 1.0f, 2, leaf, EnumReplaceMode.NONE); + } - generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); - generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); + int leafSpawn = height + 1; - generateAdjustedCylinder(world, leafSpawn--, 1.9f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 0.5f, 1, leaf); - while (leafSpawn > height - 4) { - generateAdjustedCylinder(world, leafSpawn--, 2.5f, 1, leaf); - } - generateAdjustedCylinder(world, leafSpawn, 1.9f, 1, leaf); + generateAdjustedCylinder(world, leafSpawn--, 1.9f, 1, leaf); - // Add some smaller twigs below for flavour - for (int times = 0; times < height / 4; times++) { - int h = 10 + world.rand.nextInt(Math.max(1, height - 10)); - if (world.rand.nextBoolean() && h < height / 2) { - h = height / 2 + world.rand.nextInt(height / 2); - } - int x_off = -1 + world.rand.nextInt(3); - int y_off = -1 + world.rand.nextInt(3); - generateSphere(world, new Vector(x_off, h, y_off), 1 + world.rand.nextInt(1), leaf, EnumReplaceMode.NONE); - } - - } + while (leafSpawn > height - 4) { + generateAdjustedCylinder(world, leafSpawn--, 2.5f, 1, leaf); + } + generateAdjustedCylinder(world, leafSpawn, 1.9f, 1, leaf); + // Add some smaller twigs below for flavour + for (int times = 0; times < height / 4; times++) { + int h = 10 + world.rand.nextInt(Math.max(1, height - 10)); + if (world.rand.nextBoolean() && h < height / 2) { + h = height / 2 + world.rand.nextInt(height / 2); + } + int x_off = -1 + world.rand.nextInt(3); + int y_off = -1 + world.rand.nextInt(3); + generateSphere(world, new Vector(x_off, h, y_off), 1 + world.rand.nextInt(1), leaf, EnumReplaceMode.NONE); + } + } } diff --git a/src/main/java/forestry/core/ClimateManager.java b/src/main/java/forestry/core/ClimateManager.java index 7350cea32..cb823f8da 100644 --- a/src/main/java/forestry/core/ClimateManager.java +++ b/src/main/java/forestry/core/ClimateManager.java @@ -10,11 +10,10 @@ ******************************************************************************/ package forestry.core; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - import forestry.api.core.IClimateManager; import forestry.api.core.IClimateProvider; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; public class ClimateManager implements IClimateManager { diff --git a/src/main/java/forestry/core/CreativeTabForestry.java b/src/main/java/forestry/core/CreativeTabForestry.java index 4612e780a..6759b7033 100755 --- a/src/main/java/forestry/core/CreativeTabForestry.java +++ b/src/main/java/forestry/core/CreativeTabForestry.java @@ -10,66 +10,64 @@ ******************************************************************************/ package forestry.core; +import cpw.mods.fml.common.registry.GameRegistry; +import forestry.api.core.Tabs; +import forestry.plugins.PluginCore; +import forestry.plugins.PluginManager; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import cpw.mods.fml.common.registry.GameRegistry; - -import forestry.api.core.Tabs; -import forestry.plugins.PluginCore; -import forestry.plugins.PluginManager; - public class CreativeTabForestry extends CreativeTabs { - static { - if (PluginManager.Module.APICULTURE.isEnabled()) { - Tabs.tabApiculture = new CreativeTabForestry(1, "apiculture"); - } + static { + if (PluginManager.Module.APICULTURE.isEnabled()) { + Tabs.tabApiculture = new CreativeTabForestry(1, "apiculture"); + } - if (PluginManager.Module.ARBORICULTURE.isEnabled()) { - Tabs.tabArboriculture = new CreativeTabForestry(2, "arboriculture"); - } + if (PluginManager.Module.ARBORICULTURE.isEnabled()) { + Tabs.tabArboriculture = new CreativeTabForestry(2, "arboriculture"); + } - if (PluginManager.Module.LEPIDOPTEROLOGY.isEnabled()) { - Tabs.tabLepidopterology = new CreativeTabForestry(3, "lepidopterology"); - } - } + if (PluginManager.Module.LEPIDOPTEROLOGY.isEnabled()) { + Tabs.tabLepidopterology = new CreativeTabForestry(3, "lepidopterology"); + } + } - public static final CreativeTabs tabForestry = new CreativeTabForestry(0, "forestry"); + public static final CreativeTabs tabForestry = new CreativeTabForestry(0, "forestry"); - private final int icon; + private final int icon; - private CreativeTabForestry(int icon, String label) { - super(label); - this.icon = icon; - } + private CreativeTabForestry(int icon, String label) { + super(label); + this.icon = icon; + } - @Override - public ItemStack getIconItemStack() { - Item iconItem; - switch (icon) { - case 1: - iconItem = GameRegistry.findItem("Forestry", "beeDroneGE"); - break; - case 2: - iconItem = GameRegistry.findItem("Forestry", "sapling"); - break; - case 3: - iconItem = GameRegistry.findItem("Forestry", "butterflyGE"); - break; - default: - iconItem = GameRegistry.findItem("Forestry", "fertilizerCompound"); - break; - } - if (iconItem == null) { - iconItem = PluginCore.items.wrench; - } - return new ItemStack(iconItem); - } + @Override + public ItemStack getIconItemStack() { + Item iconItem; + switch (icon) { + case 1: + iconItem = GameRegistry.findItem("Forestry", "beeDroneGE"); + break; + case 2: + iconItem = GameRegistry.findItem("Forestry", "sapling"); + break; + case 3: + iconItem = GameRegistry.findItem("Forestry", "butterflyGE"); + break; + default: + iconItem = GameRegistry.findItem("Forestry", "fertilizerCompound"); + break; + } + if (iconItem == null) { + iconItem = PluginCore.items.wrench; + } + return new ItemStack(iconItem); + } - @Override - public Item getTabIconItem() { - return null; // not used due to overridden getIconItemStack - } + @Override + public Item getTabIconItem() { + return null; // not used due to overridden getIconItemStack + } } diff --git a/src/main/java/forestry/core/DefaultClimateProvider.java b/src/main/java/forestry/core/DefaultClimateProvider.java index e0a96f706..3df98d65f 100644 --- a/src/main/java/forestry/core/DefaultClimateProvider.java +++ b/src/main/java/forestry/core/DefaultClimateProvider.java @@ -4,7 +4,6 @@ import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; import forestry.api.core.ForestryAPI; import forestry.api.core.IClimateProvider; - import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; diff --git a/src/main/java/forestry/core/EventHandlerCore.java b/src/main/java/forestry/core/EventHandlerCore.java index 84b89603e..f1d50f027 100755 --- a/src/main/java/forestry/core/EventHandlerCore.java +++ b/src/main/java/forestry/core/EventHandlerCore.java @@ -10,87 +10,83 @@ ******************************************************************************/ package forestry.core; -import java.util.Collection; - -import net.minecraft.entity.player.EntityPlayer; - -import net.minecraftforge.client.event.TextureStitchEvent; -import net.minecraftforge.event.entity.player.EntityItemPickupEvent; -import net.minecraftforge.event.world.WorldEvent; - import cpw.mods.fml.common.eventhandler.Event.Result; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.ISpeciesRoot; import forestry.core.errors.ErrorStateRegistry; import forestry.core.render.TextureManager; import forestry.plugins.PluginManager; +import java.util.Collection; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraftforge.client.event.TextureStitchEvent; +import net.minecraftforge.event.entity.player.EntityItemPickupEvent; +import net.minecraftforge.event.world.WorldEvent; public class EventHandlerCore { - public EventHandlerCore() { - } + public EventHandlerCore() {} - @SubscribeEvent - public void handleItemPickup(EntityItemPickupEvent event) { + @SubscribeEvent + public void handleItemPickup(EntityItemPickupEvent event) { - if (event.isCanceled()) { - return; - } + if (event.isCanceled()) { + return; + } - for (IPickupHandler handler : PluginManager.pickupHandlers) { - if (handler.onItemPickup(event.entityPlayer, event.item)) { - event.setResult(Result.ALLOW); - return; - } - } - } + for (IPickupHandler handler : PluginManager.pickupHandlers) { + if (handler.onItemPickup(event.entityPlayer, event.item)) { + event.setResult(Result.ALLOW); + return; + } + } + } - @SubscribeEvent - public void handlePlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { - EntityPlayer player = event.player; - if (player != null) { - Collection speciesRoots = AlleleManager.alleleRegistry.getSpeciesRoot().values(); - for (ISpeciesRoot speciesRoot : speciesRoots) { - IBreedingTracker breedingTracker = speciesRoot.getBreedingTracker(player.getEntityWorld(), player.getGameProfile()); - breedingTracker.synchToPlayer(player); - } - } - } + @SubscribeEvent + public void handlePlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { + EntityPlayer player = event.player; + if (player != null) { + Collection speciesRoots = + AlleleManager.alleleRegistry.getSpeciesRoot().values(); + for (ISpeciesRoot speciesRoot : speciesRoots) { + IBreedingTracker breedingTracker = + speciesRoot.getBreedingTracker(player.getEntityWorld(), player.getGameProfile()); + breedingTracker.synchToPlayer(player); + } + } + } - @SubscribeEvent - public void handleWorldLoad(WorldEvent.Load event) { - for (ISaveEventHandler handler : PluginManager.saveEventHandlers) { - handler.onWorldLoad(event.world); - } - } + @SubscribeEvent + public void handleWorldLoad(WorldEvent.Load event) { + for (ISaveEventHandler handler : PluginManager.saveEventHandlers) { + handler.onWorldLoad(event.world); + } + } - @SubscribeEvent - public void handleWorldSave(WorldEvent.Save event) { - for (ISaveEventHandler handler : PluginManager.saveEventHandlers) { - handler.onWorldSave(event.world); - } - } + @SubscribeEvent + public void handleWorldSave(WorldEvent.Save event) { + for (ISaveEventHandler handler : PluginManager.saveEventHandlers) { + handler.onWorldSave(event.world); + } + } - @SubscribeEvent - public void handleWorldUnload(WorldEvent.Unload event) { - for (ISaveEventHandler handler : PluginManager.saveEventHandlers) { - handler.onWorldUnload(event.world); - } - } - - @SubscribeEvent - @SideOnly(Side.CLIENT) - public void handleTextureRemap(TextureStitchEvent.Pre event) { - if (event.map.getTextureType() == 1) { - ErrorStateRegistry.initIcons(event.map); - TextureManager.initDefaultIcons(event.map); - } - } + @SubscribeEvent + public void handleWorldUnload(WorldEvent.Unload event) { + for (ISaveEventHandler handler : PluginManager.saveEventHandlers) { + handler.onWorldUnload(event.world); + } + } + @SubscribeEvent + @SideOnly(Side.CLIENT) + public void handleTextureRemap(TextureStitchEvent.Pre event) { + if (event.map.getTextureType() == 1) { + ErrorStateRegistry.initIcons(event.map); + TextureManager.initDefaultIcons(event.map); + } + } } diff --git a/src/main/java/forestry/core/IPickupHandler.java b/src/main/java/forestry/core/IPickupHandler.java index b45d90c50..ad1ed57d7 100644 --- a/src/main/java/forestry/core/IPickupHandler.java +++ b/src/main/java/forestry/core/IPickupHandler.java @@ -15,7 +15,6 @@ import net.minecraft.entity.player.EntityPlayer; public interface IPickupHandler { - /** Returns true if the item was picked up completely */ - boolean onItemPickup(EntityPlayer entityPlayer, EntityItem item); - + /** Returns true if the item was picked up completely */ + boolean onItemPickup(EntityPlayer entityPlayer, EntityItem item); } diff --git a/src/main/java/forestry/core/IResupplyHandler.java b/src/main/java/forestry/core/IResupplyHandler.java index 5d4beacfd..595fd191e 100644 --- a/src/main/java/forestry/core/IResupplyHandler.java +++ b/src/main/java/forestry/core/IResupplyHandler.java @@ -14,6 +14,5 @@ import net.minecraft.entity.player.EntityPlayer; public interface IResupplyHandler { - void resupply(EntityPlayer player); - + void resupply(EntityPlayer player); } diff --git a/src/main/java/forestry/core/ISaveEventHandler.java b/src/main/java/forestry/core/ISaveEventHandler.java index dd73140ef..a41c064b0 100644 --- a/src/main/java/forestry/core/ISaveEventHandler.java +++ b/src/main/java/forestry/core/ISaveEventHandler.java @@ -14,10 +14,9 @@ import net.minecraft.world.World; public interface ISaveEventHandler { - void onWorldLoad(World world); + void onWorldLoad(World world); - void onWorldUnload(World world); - - void onWorldSave(World world); + void onWorldUnload(World world); + void onWorldSave(World world); } diff --git a/src/main/java/forestry/core/PickupHandlerCore.java b/src/main/java/forestry/core/PickupHandlerCore.java index 53374a6de..9ee7b4397 100755 --- a/src/main/java/forestry/core/PickupHandlerCore.java +++ b/src/main/java/forestry/core/PickupHandlerCore.java @@ -10,34 +10,32 @@ ******************************************************************************/ package forestry.core; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.IIndividual; import forestry.api.genetics.ISpeciesRoot; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; public class PickupHandlerCore implements IPickupHandler { - @Override - public boolean onItemPickup(EntityPlayer entityPlayer, EntityItem entityitem) { - ItemStack itemstack = entityitem.getEntityItem(); - if (itemstack == null || itemstack.stackSize <= 0) { - return false; - } + @Override + public boolean onItemPickup(EntityPlayer entityPlayer, EntityItem entityitem) { + ItemStack itemstack = entityitem.getEntityItem(); + if (itemstack == null || itemstack.stackSize <= 0) { + return false; + } - ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(itemstack); - if (root != null) { - IIndividual individual = root.getMember(itemstack); - if (individual != null) { - IBreedingTracker tracker = root.getBreedingTracker(entityitem.worldObj, entityPlayer.getGameProfile()); - tracker.registerPickup(individual); - } - } - - return false; - } + ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(itemstack); + if (root != null) { + IIndividual individual = root.getMember(itemstack); + if (individual != null) { + IBreedingTracker tracker = root.getBreedingTracker(entityitem.worldObj, entityPlayer.getGameProfile()); + tracker.registerPickup(individual); + } + } + return false; + } } diff --git a/src/main/java/forestry/core/SaveEventHandlerCore.java b/src/main/java/forestry/core/SaveEventHandlerCore.java index 1f4bb0e1b..5d1d445af 100755 --- a/src/main/java/forestry/core/SaveEventHandlerCore.java +++ b/src/main/java/forestry/core/SaveEventHandlerCore.java @@ -14,16 +14,12 @@ import net.minecraft.world.World; public class SaveEventHandlerCore implements ISaveEventHandler { - @Override - public void onWorldLoad(World world) { - } + @Override + public void onWorldLoad(World world) {} - @Override - public void onWorldSave(World world) { - } - - @Override - public void onWorldUnload(World world) { - } + @Override + public void onWorldSave(World world) {} + @Override + public void onWorldUnload(World world) {} } diff --git a/src/main/java/forestry/core/TickHandlerCoreClient.java b/src/main/java/forestry/core/TickHandlerCoreClient.java index 7646361b8..9dfbbbb3b 100755 --- a/src/main/java/forestry/core/TickHandlerCoreClient.java +++ b/src/main/java/forestry/core/TickHandlerCoreClient.java @@ -10,45 +10,47 @@ ******************************************************************************/ package forestry.core; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.TickEvent; +import cpw.mods.fml.common.gameevent.TickEvent.Phase; +import forestry.core.utils.GeneticsUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.entity.player.EntityPlayer; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.TickEvent; -import cpw.mods.fml.common.gameevent.TickEvent.Phase; - -import forestry.core.utils.GeneticsUtil; - public class TickHandlerCoreClient { - private boolean hasNaturalistEye; + private boolean hasNaturalistEye; - @SubscribeEvent - public void onClientTick(TickEvent.ClientTickEvent event) { - if (event.phase != Phase.END) { - return; - } + @SubscribeEvent + public void onClientTick(TickEvent.ClientTickEvent event) { + if (event.phase != Phase.END) { + return; + } - Minecraft minecraft = Minecraft.getMinecraft(); - if (minecraft == null) { - return; - } + Minecraft minecraft = Minecraft.getMinecraft(); + if (minecraft == null) { + return; + } - EntityPlayer player = minecraft.thePlayer; - if (player == null) { - return; - } + EntityPlayer player = minecraft.thePlayer; + if (player == null) { + return; + } - boolean hasNaturalistEye = GeneticsUtil.hasNaturalistEye(player); - if (this.hasNaturalistEye != hasNaturalistEye) { - this.hasNaturalistEye = hasNaturalistEye; - RenderGlobal renderGlobal = minecraft.renderGlobal; - if (renderGlobal != null) { - renderGlobal.markBlockRangeForRenderUpdate( - (int) player.posX - 32, (int) player.posY - 32, (int) player.posZ - 32, - (int) player.posX + 32, (int) player.posY + 32, (int) player.posZ + 32); - } - } - } + boolean hasNaturalistEye = GeneticsUtil.hasNaturalistEye(player); + if (this.hasNaturalistEye != hasNaturalistEye) { + this.hasNaturalistEye = hasNaturalistEye; + RenderGlobal renderGlobal = minecraft.renderGlobal; + if (renderGlobal != null) { + renderGlobal.markBlockRangeForRenderUpdate( + (int) player.posX - 32, + (int) player.posY - 32, + (int) player.posZ - 32, + (int) player.posX + 32, + (int) player.posY + 32, + (int) player.posZ + 32); + } + } + } } diff --git a/src/main/java/forestry/core/TickHandlerCoreServer.java b/src/main/java/forestry/core/TickHandlerCoreServer.java index 036e46ab4..708dd0028 100755 --- a/src/main/java/forestry/core/TickHandlerCoreServer.java +++ b/src/main/java/forestry/core/TickHandlerCoreServer.java @@ -11,102 +11,96 @@ package forestry.core; import com.google.common.collect.LinkedListMultimap; - -import java.util.List; -import java.util.Random; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; -import net.minecraft.world.chunk.Chunk; - -import net.minecraftforge.event.world.ChunkDataEvent; - import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; import cpw.mods.fml.common.gameevent.TickEvent.WorldTickEvent; - import forestry.core.config.Config; import forestry.core.config.Constants; import forestry.core.worldgen.WorldGenerator; import forestry.plugins.PluginManager; +import java.util.List; +import java.util.Random; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.event.world.ChunkDataEvent; public class TickHandlerCoreServer { - private final WorldGenerator worldGenerator; - private final LinkedListMultimap chunkRegenList = LinkedListMultimap.create(); + private final WorldGenerator worldGenerator; + private final LinkedListMultimap chunkRegenList = LinkedListMultimap.create(); - public TickHandlerCoreServer(WorldGenerator worldGenerator) { - this.worldGenerator = worldGenerator; - } + public TickHandlerCoreServer(WorldGenerator worldGenerator) { + this.worldGenerator = worldGenerator; + } - @SubscribeEvent - public void onWorldTick(WorldTickEvent event) { - if (event.phase != Phase.END) { - return; - } + @SubscribeEvent + public void onWorldTick(WorldTickEvent event) { + if (event.phase != Phase.END) { + return; + } - if (Config.enableBackpackResupply) { - for (Object obj : event.world.playerEntities) { - EntityPlayer player = (EntityPlayer) obj; - for (IResupplyHandler handler : PluginManager.resupplyHandlers) { - handler.resupply(player); - } - } - } + if (Config.enableBackpackResupply) { + for (Object obj : event.world.playerEntities) { + EntityPlayer player = (EntityPlayer) obj; + for (IResupplyHandler handler : PluginManager.resupplyHandlers) { + handler.resupply(player); + } + } + } - if (Config.doRetrogen) { - World world = event.world; - int dimensionID = world.provider.dimensionId; - List chunkList = chunkRegenList.get(dimensionID); + if (Config.doRetrogen) { + World world = event.world; + int dimensionID = world.provider.dimensionId; + List chunkList = chunkRegenList.get(dimensionID); - if (chunkList.size() > 0) { - ChunkCoords coords = chunkList.get(0); - chunkList.remove(0); + if (chunkList.size() > 0) { + ChunkCoords coords = chunkList.get(0); + chunkList.remove(0); - // This bit is from FML's GameRegistry.generateWorld where the seed is constructed. - long worldSeed = world.getSeed(); - Random random = new Random(worldSeed); - long xSeed = random.nextLong() >> 2 + 1L; - long zSeed = random.nextLong() >> 2 + 1L; - random.setSeed((xSeed * coords.xCoord + zSeed * coords.zCoord) ^ worldSeed); + // This bit is from FML's GameRegistry.generateWorld where the seed is constructed. + long worldSeed = world.getSeed(); + Random random = new Random(worldSeed); + long xSeed = random.nextLong() >> 2 + 1L; + long zSeed = random.nextLong() >> 2 + 1L; + random.setSeed((xSeed * coords.xCoord + zSeed * coords.zCoord) ^ worldSeed); - worldGenerator.retroGen(random, coords.xCoord, coords.zCoord, world); - } - } - } + worldGenerator.retroGen(random, coords.xCoord, coords.zCoord, world); + } + } + } - @SubscribeEvent - public void chunkSaveEventHandler(ChunkDataEvent.Save event) { - NBTTagCompound tag = new NBTTagCompound(); - if (Config.doRetrogen) { - tag.setBoolean("retrogen", true); - } + @SubscribeEvent + public void chunkSaveEventHandler(ChunkDataEvent.Save event) { + NBTTagCompound tag = new NBTTagCompound(); + if (Config.doRetrogen) { + tag.setBoolean("retrogen", true); + } - event.getData().setTag(Constants.MOD, tag); - } + event.getData().setTag(Constants.MOD, tag); + } - @SubscribeEvent - public void chunkLoadEventHandler(ChunkDataEvent.Load event) { - if (Config.doRetrogen) { - NBTTagCompound tag = (NBTTagCompound) event.getData().getTag(Constants.MOD); - if (tag == null || !tag.hasKey("retrogen") || Config.forceRetrogen) { - ChunkCoords coords = new ChunkCoords(event.getChunk()); - chunkRegenList.put(coords.dimension, coords); - } - } - } + @SubscribeEvent + public void chunkLoadEventHandler(ChunkDataEvent.Load event) { + if (Config.doRetrogen) { + NBTTagCompound tag = (NBTTagCompound) event.getData().getTag(Constants.MOD); + if (tag == null || !tag.hasKey("retrogen") || Config.forceRetrogen) { + ChunkCoords coords = new ChunkCoords(event.getChunk()); + chunkRegenList.put(coords.dimension, coords); + } + } + } - private static class ChunkCoords { - public final int dimension; - public final int xCoord; - public final int zCoord; - - public ChunkCoords(Chunk chunk) { - this.dimension = chunk.worldObj.provider.dimensionId; - this.xCoord = chunk.xPosition; - this.zCoord = chunk.zPosition; - } - } + private static class ChunkCoords { + public final int dimension; + public final int xCoord; + public final int zCoord; + public ChunkCoords(Chunk chunk) { + this.dimension = chunk.worldObj.provider.dimensionId; + this.xCoord = chunk.xPosition; + this.zCoord = chunk.zPosition; + } + } } diff --git a/src/main/java/forestry/core/access/AccessHandler.java b/src/main/java/forestry/core/access/AccessHandler.java index 3a4dc5adf..8fd9e9e30 100644 --- a/src/main/java/forestry/core/access/AccessHandler.java +++ b/src/main/java/forestry/core/access/AccessHandler.java @@ -1,183 +1,184 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.access; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTUtil; -import net.minecraft.world.World; - -import com.mojang.authlib.GameProfile; - -import forestry.core.config.Config; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.packets.PacketAccessSwitch; -import forestry.core.network.packets.PacketAccessSwitchEntity; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.ILocatable; -import forestry.core.utils.PlayerUtil; - -public final class AccessHandler implements IAccessHandler { - private final IRestrictedAccess accessListener; - private final List accessOwnerListeners = new ArrayList<>(); - private final Object target; - - private GameProfile owner = null; - private EnumAccess access = EnumAccess.SHARED; - - public AccessHandler(T tile) { - this.accessListener = tile; - this.target = tile; - } - - public AccessHandler(T entity) { - this.accessListener = entity; - this.target = entity; - } - - public void addOwnerListener(IAccessOwnerListener accessListener) { - accessOwnerListeners.add(accessListener); - } - - public void removeOwnerListener(IAccessOwnerListener accessListener) { - accessOwnerListeners.remove(accessListener); - } - - @Override - public final boolean allowsRemoval(EntityPlayer player) { - return !Config.enablePermissions || getAccess() == EnumAccess.SHARED || !isOwned() || isOwner(player) || Proxies.common.isOp(player); - } - - @Override - public final boolean allowsAlteration(EntityPlayer player) { - return allowsRemoval(player); - } - - @Override - public final boolean allowsViewing(EntityPlayer player) { - return allowsAlteration(player) || getAccess() == EnumAccess.VIEWABLE; - } - - @Override - public final boolean allowsPipeConnections() { - return access == EnumAccess.SHARED; - } - - @Override - public EnumAccess getAccess() { - return access; - } - - @Override - public boolean isOwned() { - return owner != null; - } - - @Override - public GameProfile getOwner() { - return owner; - } - - @Override - public void setOwner(GameProfile owner) { - this.owner = owner; - for (IAccessOwnerListener listener : accessOwnerListeners) { - listener.onOwnerSet(owner); - } - } - - @Override - public boolean isOwner(EntityPlayer player) { - return PlayerUtil.isSameGameProfile(owner, player.getGameProfile()); - } - - @Override - public boolean switchAccess(EntityPlayer player) { - if (!isOwner(player)) { - return false; - } - - int ordinal = (access.ordinal() + 1) % EnumAccess.values().length; - EnumAccess newAccess = EnumAccess.values()[ordinal]; - setAccess(player.worldObj, newAccess); - - return true; - } - - private void setAccess(World world, EnumAccess access) { - EnumAccess oldAccess = this.access; - if (oldAccess == access) { - return; - } - - this.access = access; - - if (world.isRemote) { - if (target instanceof ILocatable) { - Proxies.net.sendToServer(new PacketAccessSwitch((ILocatable) target)); - } else if (target instanceof Entity) { - Proxies.net.sendToServer(new PacketAccessSwitchEntity((Entity) target)); - } - } else { - accessListener.onSwitchAccess(oldAccess, access); - } - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - if (owner == null) { - data.writeByte(-1); - } else { - data.writeByte(access.ordinal()); - data.writeLong(owner.getId().getMostSignificantBits()); - data.writeLong(owner.getId().getLeastSignificantBits()); - data.writeUTF(owner.getName()); - } - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - byte accessOrdinal = data.readByte(); - if (accessOrdinal >= 0) { - access = EnumAccess.values()[accessOrdinal]; - GameProfile owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); - setOwner(owner); - } - } - - @Override - public void readFromNBT(NBTTagCompound data) { - access = EnumAccess.values()[data.getInteger("Access")]; - - if (data.hasKey("owner")) { - owner = NBTUtil.func_152459_a(data.getCompoundTag("owner")); - } - } - - @Override - public void writeToNBT(NBTTagCompound data) { - data.setInteger("Access", access.ordinal()); - - if (this.owner != null) { - NBTTagCompound nbt = new NBTTagCompound(); - NBTUtil.func_152460_a(nbt, owner); - nbt.removeTag("Properties"); - data.setTag("owner", nbt); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.access; + +import com.mojang.authlib.GameProfile; +import forestry.core.config.Config; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.packets.PacketAccessSwitch; +import forestry.core.network.packets.PacketAccessSwitchEntity; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.ILocatable; +import forestry.core.utils.PlayerUtil; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTUtil; +import net.minecraft.world.World; + +public final class AccessHandler implements IAccessHandler { + private final IRestrictedAccess accessListener; + private final List accessOwnerListeners = new ArrayList<>(); + private final Object target; + + private GameProfile owner = null; + private EnumAccess access = EnumAccess.SHARED; + + public AccessHandler(T tile) { + this.accessListener = tile; + this.target = tile; + } + + public AccessHandler(T entity) { + this.accessListener = entity; + this.target = entity; + } + + public void addOwnerListener(IAccessOwnerListener accessListener) { + accessOwnerListeners.add(accessListener); + } + + public void removeOwnerListener(IAccessOwnerListener accessListener) { + accessOwnerListeners.remove(accessListener); + } + + @Override + public final boolean allowsRemoval(EntityPlayer player) { + return !Config.enablePermissions + || getAccess() == EnumAccess.SHARED + || !isOwned() + || isOwner(player) + || Proxies.common.isOp(player); + } + + @Override + public final boolean allowsAlteration(EntityPlayer player) { + return allowsRemoval(player); + } + + @Override + public final boolean allowsViewing(EntityPlayer player) { + return allowsAlteration(player) || getAccess() == EnumAccess.VIEWABLE; + } + + @Override + public final boolean allowsPipeConnections() { + return access == EnumAccess.SHARED; + } + + @Override + public EnumAccess getAccess() { + return access; + } + + @Override + public boolean isOwned() { + return owner != null; + } + + @Override + public GameProfile getOwner() { + return owner; + } + + @Override + public void setOwner(GameProfile owner) { + this.owner = owner; + for (IAccessOwnerListener listener : accessOwnerListeners) { + listener.onOwnerSet(owner); + } + } + + @Override + public boolean isOwner(EntityPlayer player) { + return PlayerUtil.isSameGameProfile(owner, player.getGameProfile()); + } + + @Override + public boolean switchAccess(EntityPlayer player) { + if (!isOwner(player)) { + return false; + } + + int ordinal = (access.ordinal() + 1) % EnumAccess.values().length; + EnumAccess newAccess = EnumAccess.values()[ordinal]; + setAccess(player.worldObj, newAccess); + + return true; + } + + private void setAccess(World world, EnumAccess access) { + EnumAccess oldAccess = this.access; + if (oldAccess == access) { + return; + } + + this.access = access; + + if (world.isRemote) { + if (target instanceof ILocatable) { + Proxies.net.sendToServer(new PacketAccessSwitch((ILocatable) target)); + } else if (target instanceof Entity) { + Proxies.net.sendToServer(new PacketAccessSwitchEntity((Entity) target)); + } + } else { + accessListener.onSwitchAccess(oldAccess, access); + } + } + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + if (owner == null) { + data.writeByte(-1); + } else { + data.writeByte(access.ordinal()); + data.writeLong(owner.getId().getMostSignificantBits()); + data.writeLong(owner.getId().getLeastSignificantBits()); + data.writeUTF(owner.getName()); + } + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + byte accessOrdinal = data.readByte(); + if (accessOrdinal >= 0) { + access = EnumAccess.values()[accessOrdinal]; + GameProfile owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); + setOwner(owner); + } + } + + @Override + public void readFromNBT(NBTTagCompound data) { + access = EnumAccess.values()[data.getInteger("Access")]; + + if (data.hasKey("owner")) { + owner = NBTUtil.func_152459_a(data.getCompoundTag("owner")); + } + } + + @Override + public void writeToNBT(NBTTagCompound data) { + data.setInteger("Access", access.ordinal()); + + if (this.owner != null) { + NBTTagCompound nbt = new NBTTagCompound(); + NBTUtil.func_152460_a(nbt, owner); + nbt.removeTag("Properties"); + data.setTag("owner", nbt); + } + } +} diff --git a/src/main/java/forestry/core/access/EnumAccess.java b/src/main/java/forestry/core/access/EnumAccess.java index 5f13d8894..cb4943738 100644 --- a/src/main/java/forestry/core/access/EnumAccess.java +++ b/src/main/java/forestry/core/access/EnumAccess.java @@ -10,25 +10,25 @@ ******************************************************************************/ package forestry.core.access; -import net.minecraft.util.IIcon; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.util.IIcon; public enum EnumAccess { - SHARED("gui.rule.shared"), VIEWABLE("gui.rule.restricted"), PRIVATE("gui.rule.private"); + SHARED("gui.rule.shared"), + VIEWABLE("gui.rule.restricted"), + PRIVATE("gui.rule.private"); - private final String name; + private final String name; - @SideOnly(Side.CLIENT) - private IIcon icon; + @SideOnly(Side.CLIENT) + private IIcon icon; - EnumAccess(String name) { - this.name = name; - } - - public String getName() { - return this.name; - } + EnumAccess(String name) { + this.name = name; + } + public String getName() { + return this.name; + } } diff --git a/src/main/java/forestry/core/access/FakeAccessHandler.java b/src/main/java/forestry/core/access/FakeAccessHandler.java index 511cf3c0f..9be2d4608 100644 --- a/src/main/java/forestry/core/access/FakeAccessHandler.java +++ b/src/main/java/forestry/core/access/FakeAccessHandler.java @@ -1,116 +1,97 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.access; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; - -import com.mojang.authlib.GameProfile; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; - -public class FakeAccessHandler implements IAccessHandler { - private static FakeAccessHandler instance; - - public static FakeAccessHandler getInstance() { - if (instance == null) { - instance = new FakeAccessHandler(); - } - return instance; - } - - private FakeAccessHandler() { - - } - - @Override - public boolean switchAccess(EntityPlayer player) { - return false; - } - - @Override - public EnumAccess getAccess() { - return EnumAccess.SHARED; - } - - @Override - public boolean allowsRemoval(EntityPlayer player) { - return true; - } - - @Override - public boolean allowsAlteration(EntityPlayer player) { - return true; - } - - @Override - public boolean allowsViewing(EntityPlayer player) { - return true; - } - - @Override - public boolean allowsPipeConnections() { - return true; - } - - @Override - public void addOwnerListener(IAccessOwnerListener accessListener) { - - } - - @Override - public void removeOwnerListener(IAccessOwnerListener accessListener) { - - } - - @Override - public boolean isOwned() { - return false; - } - - @Override - public GameProfile getOwner() { - return null; - } - - @Override - public void setOwner(GameProfile owner) { - - } - - @Override - public boolean isOwner(EntityPlayer player) { - return true; - } - - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.access; + +import com.mojang.authlib.GameProfile; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; + +public class FakeAccessHandler implements IAccessHandler { + private static FakeAccessHandler instance; + + public static FakeAccessHandler getInstance() { + if (instance == null) { + instance = new FakeAccessHandler(); + } + return instance; + } + + private FakeAccessHandler() {} + + @Override + public boolean switchAccess(EntityPlayer player) { + return false; + } + + @Override + public EnumAccess getAccess() { + return EnumAccess.SHARED; + } + + @Override + public boolean allowsRemoval(EntityPlayer player) { + return true; + } + + @Override + public boolean allowsAlteration(EntityPlayer player) { + return true; + } + + @Override + public boolean allowsViewing(EntityPlayer player) { + return true; + } + + @Override + public boolean allowsPipeConnections() { + return true; + } + + @Override + public void addOwnerListener(IAccessOwnerListener accessListener) {} + + @Override + public void removeOwnerListener(IAccessOwnerListener accessListener) {} + + @Override + public boolean isOwned() { + return false; + } + + @Override + public GameProfile getOwner() { + return null; + } + + @Override + public void setOwner(GameProfile owner) {} + + @Override + public boolean isOwner(EntityPlayer player) { + return true; + } + + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) {} + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) {} + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException {} + + @Override + public void readData(DataInputStreamForestry data) throws IOException {} +} diff --git a/src/main/java/forestry/core/access/IAccessHandler.java b/src/main/java/forestry/core/access/IAccessHandler.java index 4b0195f0d..1e8e594a7 100644 --- a/src/main/java/forestry/core/access/IAccessHandler.java +++ b/src/main/java/forestry/core/access/IAccessHandler.java @@ -1,36 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.access; - -import net.minecraft.entity.player.EntityPlayer; - -import forestry.api.core.INBTTagable; -import forestry.core.network.IStreamable; - -public interface IAccessHandler extends IOwnable, IStreamable, INBTTagable { - - boolean switchAccess(EntityPlayer player); - - EnumAccess getAccess(); - - boolean allowsRemoval(EntityPlayer player); - - boolean allowsAlteration(EntityPlayer player); - - boolean allowsViewing(EntityPlayer player); - - boolean allowsPipeConnections(); - - void addOwnerListener(IAccessOwnerListener accessListener); - - void removeOwnerListener(IAccessOwnerListener accessListener); - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.access; + +import forestry.api.core.INBTTagable; +import forestry.core.network.IStreamable; +import net.minecraft.entity.player.EntityPlayer; + +public interface IAccessHandler extends IOwnable, IStreamable, INBTTagable { + + boolean switchAccess(EntityPlayer player); + + EnumAccess getAccess(); + + boolean allowsRemoval(EntityPlayer player); + + boolean allowsAlteration(EntityPlayer player); + + boolean allowsViewing(EntityPlayer player); + + boolean allowsPipeConnections(); + + void addOwnerListener(IAccessOwnerListener accessListener); + + void removeOwnerListener(IAccessOwnerListener accessListener); +} diff --git a/src/main/java/forestry/core/access/IAccessOwnerListener.java b/src/main/java/forestry/core/access/IAccessOwnerListener.java index cdd0ec89d..8023ef84b 100644 --- a/src/main/java/forestry/core/access/IAccessOwnerListener.java +++ b/src/main/java/forestry/core/access/IAccessOwnerListener.java @@ -1,17 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.access; - -import com.mojang.authlib.GameProfile; - -public interface IAccessOwnerListener { - void onOwnerSet(GameProfile gameProfile); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.access; + +import com.mojang.authlib.GameProfile; + +public interface IAccessOwnerListener { + void onOwnerSet(GameProfile gameProfile); +} diff --git a/src/main/java/forestry/core/access/IOwnable.java b/src/main/java/forestry/core/access/IOwnable.java index f801b60c4..a7877e213 100644 --- a/src/main/java/forestry/core/access/IOwnable.java +++ b/src/main/java/forestry/core/access/IOwnable.java @@ -10,18 +10,16 @@ ******************************************************************************/ package forestry.core.access; -import net.minecraft.entity.player.EntityPlayer; - import com.mojang.authlib.GameProfile; +import net.minecraft.entity.player.EntityPlayer; public interface IOwnable { - boolean isOwned(); + boolean isOwned(); - GameProfile getOwner(); + GameProfile getOwner(); - void setOwner(GameProfile owner); - - boolean isOwner(EntityPlayer player); + void setOwner(GameProfile owner); + boolean isOwner(EntityPlayer player); } diff --git a/src/main/java/forestry/core/access/IRestrictedAccess.java b/src/main/java/forestry/core/access/IRestrictedAccess.java index c30fca22d..944d69e09 100644 --- a/src/main/java/forestry/core/access/IRestrictedAccess.java +++ b/src/main/java/forestry/core/access/IRestrictedAccess.java @@ -1,17 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.access; - -public interface IRestrictedAccess { - IAccessHandler getAccessHandler(); - - void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.access; + +public interface IRestrictedAccess { + IAccessHandler getAccessHandler(); + + void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess); +} diff --git a/src/main/java/forestry/core/blocks/BlockBase.java b/src/main/java/forestry/core/blocks/BlockBase.java index 6b22eb049..94b4d54c3 100644 --- a/src/main/java/forestry/core/blocks/BlockBase.java +++ b/src/main/java/forestry/core/blocks/BlockBase.java @@ -10,9 +10,20 @@ ******************************************************************************/ package forestry.core.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.access.IAccessHandler; +import forestry.core.circuits.ISocketable; +import forestry.core.fluids.FluidHelper; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.MachineDefinition; +import forestry.core.tiles.TileBase; +import forestry.core.tiles.TileForestry; +import forestry.core.tiles.TileUtil; +import forestry.core.utils.InventoryUtil; +import forestry.core.utils.PlayerUtil; import java.util.ArrayList; import java.util.List; - import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -30,267 +41,263 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.IFluidHandler; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.access.IAccessHandler; -import forestry.core.circuits.ISocketable; -import forestry.core.fluids.FluidHelper; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.MachineDefinition; -import forestry.core.tiles.TileBase; -import forestry.core.tiles.TileForestry; -import forestry.core.tiles.TileUtil; -import forestry.core.utils.InventoryUtil; -import forestry.core.utils.PlayerUtil; - public class BlockBase extends BlockForestry { - private final List definitions = new ArrayList<>(); - private final boolean hasTESR; + private final List definitions = new ArrayList<>(); + private final boolean hasTESR; - public BlockBase() { - this(false); - } + public BlockBase() { + this(false); + } - public BlockBase(boolean hasTESR) { - super(Material.iron); + public BlockBase(boolean hasTESR) { + super(Material.iron); - this.hasTESR = hasTESR; - this.opaque = this.isOpaqueCube(); - this.lightOpacity = this.isOpaqueCube() ? 255 : 0; - } + this.hasTESR = hasTESR; + this.opaque = this.isOpaqueCube(); + this.lightOpacity = this.isOpaqueCube() ? 255 : 0; + } - public void addDefinitions(MachineDefinition... definitions) { - for (MachineDefinition definition : definitions) { - addDefinition(definition); - } - } + public void addDefinitions(MachineDefinition... definitions) { + for (MachineDefinition definition : definitions) { + addDefinition(definition); + } + } - public void addDefinition(MachineDefinition definition) { - definition.setBlock(this); + public void addDefinition(MachineDefinition definition) { + definition.setBlock(this); - while (definitions.size() <= definition.getMeta()) { - definitions.add(null); - } + while (definitions.size() <= definition.getMeta()) { + definitions.add(null); + } - definitions.set(definition.getMeta(), definition); - } + definitions.set(definition.getMeta(), definition); + } - @Override - public boolean isOpaqueCube() { - return !hasTESR; - } + @Override + public boolean isOpaqueCube() { + return !hasTESR; + } - @Override - public boolean renderAsNormalBlock() { - return !hasTESR; - } + @Override + public boolean renderAsNormalBlock() { + return !hasTESR; + } - @Override - public int getRenderType() { - if (hasTESR) { - return Proxies.render.getByBlockModelRenderId(); - } else { - return 0; - } - } + @Override + public int getRenderType() { + if (hasTESR) { + return Proxies.render.getByBlockModelRenderId(); + } else { + return 0; + } + } - private MachineDefinition getDefinition(IBlockAccess world, int x, int y, int z) { - if (!(world.getBlock(x, y, z) instanceof BlockBase)) { - return null; - } - int meta = world.getBlockMetadata(x, y, z); - return getDefinition(meta); - } + private MachineDefinition getDefinition(IBlockAccess world, int x, int y, int z) { + if (!(world.getBlock(x, y, z) instanceof BlockBase)) { + return null; + } + int meta = world.getBlockMetadata(x, y, z); + return getDefinition(meta); + } - private MachineDefinition getDefinition(int metadata) { - if (metadata < 0 || metadata >= definitions.size()) { - return null; - } + private MachineDefinition getDefinition(int metadata) { + if (metadata < 0 || metadata >= definitions.size()) { + return null; + } - return definitions.get(metadata); - } + return definitions.get(metadata); + } - @Override - public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z) { - MachineDefinition definition = getDefinition(world, x, y, z); - if (definition == null) { - return super.getCollisionBoundingBoxFromPool(world, x, y, z); - } - return definition.getBoundingBox(x, y, z); - } + @Override + public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z) { + MachineDefinition definition = getDefinition(world, x, y, z); + if (definition == null) { + return super.getCollisionBoundingBoxFromPool(world, x, y, z); + } + return definition.getBoundingBox(x, y, z); + } - @Override - @SideOnly(Side.CLIENT) - public AxisAlignedBB getSelectedBoundingBoxFromPool(World world, int x, int y, int z) { - MachineDefinition definition = getDefinition(world, x, y, z); - if (definition == null) { - return super.getCollisionBoundingBoxFromPool(world, x, y, z); - } - return definition.getBoundingBox(x, y, z); - } + @Override + @SideOnly(Side.CLIENT) + public AxisAlignedBB getSelectedBoundingBoxFromPool(World world, int x, int y, int z) { + MachineDefinition definition = getDefinition(world, x, y, z); + if (definition == null) { + return super.getCollisionBoundingBoxFromPool(world, x, y, z); + } + return definition.getBoundingBox(x, y, z); + } - @Override - public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 startVec, Vec3 endVec) { - MachineDefinition definition = getDefinition(world, x, y, z); - if (definition == null) { - return super.collisionRayTrace(world, x, y, z, startVec, endVec); - } else { - return definition.collisionRayTrace(world, x, y, z, startVec, endVec); - } - } + @Override + public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 startVec, Vec3 endVec) { + MachineDefinition definition = getDefinition(world, x, y, z); + if (definition == null) { + return super.collisionRayTrace(world, x, y, z, startVec, endVec); + } else { + return definition.collisionRayTrace(world, x, y, z, startVec, endVec); + } + } - /* CREATIVE INVENTORY */ - @SuppressWarnings("rawtypes") - @SideOnly(Side.CLIENT) - @Override - public void getSubBlocks(Item item, CreativeTabs tab, List list) { - for (MachineDefinition definition : definitions) { - if (definition == null) { - continue; - } - definition.getSubBlocks(item, tab, list); - } - } + /* CREATIVE INVENTORY */ + @SuppressWarnings("rawtypes") + @SideOnly(Side.CLIENT) + @Override + public void getSubBlocks(Item item, CreativeTabs tab, List list) { + for (MachineDefinition definition : definitions) { + if (definition == null) { + continue; + } + definition.getSubBlocks(item, tab, list); + } + } - /* TILE ENTITY CREATION */ - @Override - public TileEntity createTileEntity(World world, int metadata) { - MachineDefinition definition = getDefinition(metadata); - if (definition == null) { - return null; - } - return definition.createMachine(); - } + /* TILE ENTITY CREATION */ + @Override + public TileEntity createTileEntity(World world, int metadata) { + MachineDefinition definition = getDefinition(metadata); + if (definition == null) { + return null; + } + return definition.createMachine(); + } - @Override - public TileEntity createNewTileEntity(World world, int meta) { - return createTileEntity(world, meta); // TODO: refactor to just use Block, not BlockContainer - } + @Override + public TileEntity createNewTileEntity(World world, int meta) { + return createTileEntity(world, meta); // TODO: refactor to just use Block, not BlockContainer + } - /* INTERACTION */ - @Override - public boolean isSideSolid(IBlockAccess world, int x, int y, int z, ForgeDirection side) { - MachineDefinition definition = getDefinition(world, x, y, z); - return definition != null && definition.isSolidOnSide(world, x, y, z, side.ordinal()); - } + /* INTERACTION */ + @Override + public boolean isSideSolid(IBlockAccess world, int x, int y, int z, ForgeDirection side) { + MachineDefinition definition = getDefinition(world, x, y, z); + return definition != null && definition.isSolidOnSide(world, x, y, z, side.ordinal()); + } - @Override - public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float par7, float par8, float par9) { - if (player.isSneaking()) { - return false; - } + @Override + public boolean onBlockActivated( + World world, int x, int y, int z, EntityPlayer player, int side, float par7, float par8, float par9) { + if (player.isSneaking()) { + return false; + } - TileBase tile = (TileBase) world.getTileEntity(x, y, z); - if (!TileUtil.isUsableByPlayer(player, tile)) { - return false; - } + TileBase tile = (TileBase) world.getTileEntity(x, y, z); + if (!TileUtil.isUsableByPlayer(player, tile)) { + return false; + } - IAccessHandler access = tile.getAccessHandler(); + IAccessHandler access = tile.getAccessHandler(); - ItemStack current = player.getCurrentEquippedItem(); - if (current != null && current.getItem() != Items.bucket && tile instanceof IFluidHandler && access.allowsAlteration(player)) { - if (FluidHelper.handleRightClick((IFluidHandler) tile, ForgeDirection.getOrientation(side), player, true, tile.canDrainWithBucket())) { - return true; - } - } + ItemStack current = player.getCurrentEquippedItem(); + if (current != null + && current.getItem() != Items.bucket + && tile instanceof IFluidHandler + && access.allowsAlteration(player)) { + if (FluidHelper.handleRightClick( + (IFluidHandler) tile, + ForgeDirection.getOrientation(side), + player, + true, + tile.canDrainWithBucket())) { + return true; + } + } - if (world.isRemote) { - return true; - } + if (world.isRemote) { + return true; + } - if (access.allowsViewing(player)) { - tile.openGui(player); - } else { - player.addChatMessage(new ChatComponentTranslation("for.chat.accesslocked", PlayerUtil.getOwnerName(access))); - } - return true; - } + if (access.allowsViewing(player)) { + tile.openGui(player); + } else { + player.addChatMessage( + new ChatComponentTranslation("for.chat.accesslocked", PlayerUtil.getOwnerName(access))); + } + return true; + } - @Override - public boolean rotateBlock(World world, int x, int y, int z, ForgeDirection axis) { - MachineDefinition definition = getDefinition(world, x, y, z); - if (definition == null) { - return super.rotateBlock(world, x, y, z, axis); - } - return definition.rotateBlock(world, x, y, z, axis); - } + @Override + public boolean rotateBlock(World world, int x, int y, int z, ForgeDirection axis) { + MachineDefinition definition = getDefinition(world, x, y, z); + if (definition == null) { + return super.rotateBlock(world, x, y, z, axis); + } + return definition.rotateBlock(world, x, y, z, axis); + } - @Override - public void breakBlock(World world, int x, int y, int z, Block block, int meta) { + @Override + public void breakBlock(World world, int x, int y, int z, Block block, int meta) { - if (world.isRemote) { - return; - } + if (world.isRemote) { + return; + } - TileEntity tile = world.getTileEntity(x, y, z); - if (tile instanceof IInventory) { - IInventory inventory = (IInventory) tile; - InventoryUtil.dropInventory(inventory, world, x, y, z); - if (tile instanceof TileForestry) { - ((TileForestry) tile).onRemoval(); - } - if (tile instanceof ISocketable) { - InventoryUtil.dropSockets((ISocketable) tile, tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord); - } - } - super.breakBlock(world, x, y, z, block, meta); - } + TileEntity tile = world.getTileEntity(x, y, z); + if (tile instanceof IInventory) { + IInventory inventory = (IInventory) tile; + InventoryUtil.dropInventory(inventory, world, x, y, z); + if (tile instanceof TileForestry) { + ((TileForestry) tile).onRemoval(); + } + if (tile instanceof ISocketable) { + InventoryUtil.dropSockets( + (ISocketable) tile, tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord); + } + } + super.breakBlock(world, x, y, z, block, meta); + } - @Override - public int damageDropped(int metadata) { - return metadata; - } + @Override + public int damageDropped(int metadata) { + return metadata; + } - public void init() { - for (MachineDefinition def : definitions) { - if (def != null) { - def.register(); - } - } - } + public void init() { + for (MachineDefinition def : definitions) { + if (def != null) { + def.register(); + } + } + } - /* TEXTURES */ - @SideOnly(Side.CLIENT) - @Override - public void registerBlockIcons(IIconRegister register) { - for (MachineDefinition def : definitions) { - if (def == null) { - continue; - } - def.registerIcons(register); - } - } + /* TEXTURES */ + @SideOnly(Side.CLIENT) + @Override + public void registerBlockIcons(IIconRegister register) { + for (MachineDefinition def : definitions) { + if (def == null) { + continue; + } + def.registerIcons(register); + } + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(int side, int metadata) { - if (metadata >= definitions.size() || definitions.get(metadata) == null) { - return null; - } - return definitions.get(metadata).getBlockTextureForSide(side); - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(int side, int metadata) { + if (metadata >= definitions.size() || definitions.get(metadata) == null) { + return null; + } + return definitions.get(metadata).getBlockTextureForSide(side); + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { - int metadata = world.getBlockMetadata(x, y, z); - if (metadata >= definitions.size() || definitions.get(metadata) == null) { - metadata = 0; - } - return definitions.get(metadata).getIcon(world, x, y, z, side); - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { + int metadata = world.getBlockMetadata(x, y, z); + if (metadata >= definitions.size() || definitions.get(metadata) == null) { + metadata = 0; + } + return definitions.get(metadata).getIcon(world, x, y, z, side); + } - @Override - public boolean getUseNeighborBrightness() { - return hasTESR; - } + @Override + public boolean getUseNeighborBrightness() { + return hasTESR; + } - public final ItemStack get(T type) { - return new ItemStack(this, 1, type.getMeta()); - } + public final ItemStack get(T type) { + return new ItemStack(this, 1, type.getMeta()); + } } diff --git a/src/main/java/forestry/core/blocks/BlockCore.java b/src/main/java/forestry/core/blocks/BlockCore.java index 61d4b23fa..3a3eec5a1 100644 --- a/src/main/java/forestry/core/blocks/BlockCore.java +++ b/src/main/java/forestry/core/blocks/BlockCore.java @@ -1,17 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.blocks; - -public class BlockCore extends BlockBase { - public BlockCore() { - super(true); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.blocks; + +public class BlockCore extends BlockBase { + public BlockCore() { + super(true); + } +} diff --git a/src/main/java/forestry/core/blocks/BlockCoreType.java b/src/main/java/forestry/core/blocks/BlockCoreType.java index 0aaff8751..2e1e60bb9 100644 --- a/src/main/java/forestry/core/blocks/BlockCoreType.java +++ b/src/main/java/forestry/core/blocks/BlockCoreType.java @@ -1,63 +1,62 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.blocks; - -import javax.annotation.Nullable; - -import forestry.core.config.Constants; -import forestry.core.proxy.Proxies; -import forestry.core.render.IBlockRenderer; -import forestry.core.tiles.TileAnalyzer; -import forestry.core.tiles.TileEscritoire; -import forestry.core.tiles.TileForestry; -import forestry.plugins.PluginApiculture; - -public enum BlockCoreType implements IMachinePropertiesTESR { - ANALYZER(TileAnalyzer.class, "Analyzer") { - @Nullable - @Override - public IBlockRenderer getRenderer() { - return PluginApiculture.proxy.getRendererAnalyzer(Constants.TEXTURE_PATH_BLOCKS + "/analyzer_"); - } - }, - ESCRITOIRE(TileEscritoire.class, "Escritoire") { - @Nullable - @Override - public IBlockRenderer getRenderer() { - return Proxies.render.getRenderEscritoire(); - } - }; - - public static final BlockCoreType[] VALUES = values(); - - private final String teIdent; - private final Class teClass; - - BlockCoreType(Class teClass, String teName) { - this.teIdent = "forestry." + teName; - this.teClass = teClass; - } - - @Override - public int getMeta() { - return ordinal(); - } - - @Override - public String getTeIdent() { - return teIdent; - } - - @Override - public Class getTeClass() { - return teClass; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.blocks; + +import forestry.core.config.Constants; +import forestry.core.proxy.Proxies; +import forestry.core.render.IBlockRenderer; +import forestry.core.tiles.TileAnalyzer; +import forestry.core.tiles.TileEscritoire; +import forestry.core.tiles.TileForestry; +import forestry.plugins.PluginApiculture; +import javax.annotation.Nullable; + +public enum BlockCoreType implements IMachinePropertiesTESR { + ANALYZER(TileAnalyzer.class, "Analyzer") { + @Nullable + @Override + public IBlockRenderer getRenderer() { + return PluginApiculture.proxy.getRendererAnalyzer(Constants.TEXTURE_PATH_BLOCKS + "/analyzer_"); + } + }, + ESCRITOIRE(TileEscritoire.class, "Escritoire") { + @Nullable + @Override + public IBlockRenderer getRenderer() { + return Proxies.render.getRenderEscritoire(); + } + }; + + public static final BlockCoreType[] VALUES = values(); + + private final String teIdent; + private final Class teClass; + + BlockCoreType(Class teClass, String teName) { + this.teIdent = "forestry." + teName; + this.teClass = teClass; + } + + @Override + public int getMeta() { + return ordinal(); + } + + @Override + public String getTeIdent() { + return teIdent; + } + + @Override + public Class getTeClass() { + return teClass; + } +} diff --git a/src/main/java/forestry/core/blocks/BlockForestry.java b/src/main/java/forestry/core/blocks/BlockForestry.java index 3fe80f8d1..cc1f21f6e 100644 --- a/src/main/java/forestry/core/blocks/BlockForestry.java +++ b/src/main/java/forestry/core/blocks/BlockForestry.java @@ -10,8 +10,12 @@ ******************************************************************************/ package forestry.core.blocks; -import org.apache.logging.log4j.Level; - +import com.mojang.authlib.GameProfile; +import forestry.core.CreativeTabForestry; +import forestry.core.access.IOwnable; +import forestry.core.access.IRestrictedAccess; +import forestry.core.tiles.TileForestry; +import forestry.core.utils.Log; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; @@ -20,74 +24,66 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; - -import com.mojang.authlib.GameProfile; - -import forestry.core.CreativeTabForestry; -import forestry.core.access.IOwnable; -import forestry.core.access.IRestrictedAccess; -import forestry.core.tiles.TileForestry; -import forestry.core.utils.Log; +import org.apache.logging.log4j.Level; public abstract class BlockForestry extends BlockContainer { - protected BlockForestry(Material material) { - super(material); - setHardness(1.5f); - setCreativeTab(CreativeTabForestry.tabForestry); - } + protected BlockForestry(Material material) { + super(material); + setHardness(1.5f); + setCreativeTab(CreativeTabForestry.tabForestry); + } - @Override - public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) { - TileEntity tile = world.getTileEntity(x, y, z); + @Override + public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) { + TileEntity tile = world.getTileEntity(x, y, z); - if (tile instanceof IRestrictedAccess) { - IRestrictedAccess restrictedAccessTile = (IRestrictedAccess) tile; - if (!restrictedAccessTile.getAccessHandler().allowsRemoval(player)) { - return false; - } - } + if (tile instanceof IRestrictedAccess) { + IRestrictedAccess restrictedAccessTile = (IRestrictedAccess) tile; + if (!restrictedAccessTile.getAccessHandler().allowsRemoval(player)) { + return false; + } + } - return super.removedByPlayer(world, player, x, y, z); - } + return super.removedByPlayer(world, player, x, y, z); + } - @Override - public void onBlockPlacedBy(World world, int i, int j, int k, EntityLivingBase entityLiving, ItemStack itemstack) { + @Override + public void onBlockPlacedBy(World world, int i, int j, int k, EntityLivingBase entityLiving, ItemStack itemstack) { - if (world.isRemote) { - return; - } + if (world.isRemote) { + return; + } - if (entityLiving instanceof EntityPlayer) { - TileEntity tile = world.getTileEntity(i, j, k); + if (entityLiving instanceof EntityPlayer) { + TileEntity tile = world.getTileEntity(i, j, k); - IOwnable ownable; + IOwnable ownable; - if (tile instanceof IRestrictedAccess) { - ownable = ((IRestrictedAccess) tile).getAccessHandler(); - } else if (tile instanceof IOwnable) { - ownable = (IOwnable) tile; - } else { - return; - } + if (tile instanceof IRestrictedAccess) { + ownable = ((IRestrictedAccess) tile).getAccessHandler(); + } else if (tile instanceof IOwnable) { + ownable = (IOwnable) tile; + } else { + return; + } - EntityPlayer player = (EntityPlayer) entityLiving; - GameProfile gameProfile = player.getGameProfile(); - ownable.setOwner(gameProfile); - } - } - - @Override - public void onNeighborBlockChange(World world, int x, int y, int z, Block block) { - try { - TileEntity tile = world.getTileEntity(x, y, z); - if (tile instanceof TileForestry) { - ((TileForestry) tile).onNeighborBlockChange(block); - } - } catch (StackOverflowError error) { - Log.logThrowable(Level.ERROR, "Stack Overflow Error in BlockMachine.onNeighborBlockChange()", 10, error); - throw error; - } - } + EntityPlayer player = (EntityPlayer) entityLiving; + GameProfile gameProfile = player.getGameProfile(); + ownable.setOwner(gameProfile); + } + } + @Override + public void onNeighborBlockChange(World world, int x, int y, int z, Block block) { + try { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile instanceof TileForestry) { + ((TileForestry) tile).onNeighborBlockChange(block); + } + } catch (StackOverflowError error) { + Log.logThrowable(Level.ERROR, "Stack Overflow Error in BlockMachine.onNeighborBlockChange()", 10, error); + throw error; + } + } } diff --git a/src/main/java/forestry/core/blocks/BlockRegistry.java b/src/main/java/forestry/core/blocks/BlockRegistry.java index 56d0165bd..a91e99a36 100644 --- a/src/main/java/forestry/core/blocks/BlockRegistry.java +++ b/src/main/java/forestry/core/blocks/BlockRegistry.java @@ -1,37 +1,35 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.blocks; - -import net.minecraft.block.Block; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.oredict.OreDictionary; - -import cpw.mods.fml.common.registry.GameRegistry; - -import forestry.core.utils.StringUtil; -import forestry.plugins.PluginManager; - -public abstract class BlockRegistry { - protected static T registerBlock(T block, Class itemClass, String name, Object... itemCtorArgs) { - if (PluginManager.getStage() != PluginManager.Stage.SETUP) { - throw new RuntimeException("Tried to register Block outside of Setup"); - } - block.setBlockName("for." + name); - GameRegistry.registerBlock(block, itemClass, StringUtil.cleanBlockName(block), itemCtorArgs); - return block; - } - - protected static void registerOreDictWildcard(String oreDictName, Block block) { - OreDictionary.registerOre(oreDictName, new ItemStack(block, 1, OreDictionary.WILDCARD_VALUE)); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.blocks; + +import cpw.mods.fml.common.registry.GameRegistry; +import forestry.core.utils.StringUtil; +import forestry.plugins.PluginManager; +import net.minecraft.block.Block; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; + +public abstract class BlockRegistry { + protected static T registerBlock( + T block, Class itemClass, String name, Object... itemCtorArgs) { + if (PluginManager.getStage() != PluginManager.Stage.SETUP) { + throw new RuntimeException("Tried to register Block outside of Setup"); + } + block.setBlockName("for." + name); + GameRegistry.registerBlock(block, itemClass, StringUtil.cleanBlockName(block), itemCtorArgs); + return block; + } + + protected static void registerOreDictWildcard(String oreDictName, Block block) { + OreDictionary.registerOre(oreDictName, new ItemStack(block, 1, OreDictionary.WILDCARD_VALUE)); + } +} diff --git a/src/main/java/forestry/core/blocks/BlockRegistryCore.java b/src/main/java/forestry/core/blocks/BlockRegistryCore.java index d80ad3818..5873dd146 100644 --- a/src/main/java/forestry/core/blocks/BlockRegistryCore.java +++ b/src/main/java/forestry/core/blocks/BlockRegistryCore.java @@ -1,50 +1,48 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.blocks; - -import net.minecraft.init.Blocks; - -import net.minecraftforge.oredict.OreDictionary; - -import forestry.core.items.ItemBlockForestry; -import forestry.core.items.ItemBlockTyped; - -public class BlockRegistryCore extends BlockRegistry { - public final BlockCore core; - public final BlockSoil soil; - public final BlockResourceOre resources; - public final BlockResourceStorage resourceStorage; - - public BlockRegistryCore() { - core = registerBlock(new BlockCore(), ItemBlockForestry.class, "core"); - - soil = registerBlock(new BlockSoil(), ItemBlockTyped.class, "soil"); - soil.setHarvestLevel("shovel", 0, 0); - soil.setHarvestLevel("shovel", 0, 1); - - resources = registerBlock(new BlockResourceOre(), ItemBlockForestry.class, "resources"); - resources.setHarvestLevel("pickaxe", 1); - OreDictionary.registerOre("oreApatite", resources.get(BlockResourceOre.ResourceType.APATITE, 1)); - OreDictionary.registerOre("oreCopper", resources.get(BlockResourceOre.ResourceType.COPPER, 1)); - OreDictionary.registerOre("oreTin", resources.get(BlockResourceOre.ResourceType.TIN, 1)); - - resourceStorage = registerBlock(new BlockResourceStorage(), ItemBlockForestry.class, "resourceStorage"); - resourceStorage.setHarvestLevel("pickaxe", 0); - OreDictionary.registerOre("blockApatite", resourceStorage.get(BlockResourceStorage.ResourceType.APATITE)); - OreDictionary.registerOre("blockCopper", resourceStorage.get(BlockResourceStorage.ResourceType.COPPER)); - OreDictionary.registerOre("blockTin", resourceStorage.get(BlockResourceStorage.ResourceType.TIN)); - OreDictionary.registerOre("blockBronze", resourceStorage.get(BlockResourceStorage.ResourceType.BRONZE)); - - // register some common oreDict names for our recipes - OreDictionary.registerOre("chestWood", Blocks.chest); - OreDictionary.registerOre("craftingTableWood", Blocks.crafting_table); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.blocks; + +import forestry.core.items.ItemBlockForestry; +import forestry.core.items.ItemBlockTyped; +import net.minecraft.init.Blocks; +import net.minecraftforge.oredict.OreDictionary; + +public class BlockRegistryCore extends BlockRegistry { + public final BlockCore core; + public final BlockSoil soil; + public final BlockResourceOre resources; + public final BlockResourceStorage resourceStorage; + + public BlockRegistryCore() { + core = registerBlock(new BlockCore(), ItemBlockForestry.class, "core"); + + soil = registerBlock(new BlockSoil(), ItemBlockTyped.class, "soil"); + soil.setHarvestLevel("shovel", 0, 0); + soil.setHarvestLevel("shovel", 0, 1); + + resources = registerBlock(new BlockResourceOre(), ItemBlockForestry.class, "resources"); + resources.setHarvestLevel("pickaxe", 1); + OreDictionary.registerOre("oreApatite", resources.get(BlockResourceOre.ResourceType.APATITE, 1)); + OreDictionary.registerOre("oreCopper", resources.get(BlockResourceOre.ResourceType.COPPER, 1)); + OreDictionary.registerOre("oreTin", resources.get(BlockResourceOre.ResourceType.TIN, 1)); + + resourceStorage = registerBlock(new BlockResourceStorage(), ItemBlockForestry.class, "resourceStorage"); + resourceStorage.setHarvestLevel("pickaxe", 0); + OreDictionary.registerOre("blockApatite", resourceStorage.get(BlockResourceStorage.ResourceType.APATITE)); + OreDictionary.registerOre("blockCopper", resourceStorage.get(BlockResourceStorage.ResourceType.COPPER)); + OreDictionary.registerOre("blockTin", resourceStorage.get(BlockResourceStorage.ResourceType.TIN)); + OreDictionary.registerOre("blockBronze", resourceStorage.get(BlockResourceStorage.ResourceType.BRONZE)); + + // register some common oreDict names for our recipes + OreDictionary.registerOre("chestWood", Blocks.chest); + OreDictionary.registerOre("craftingTableWood", Blocks.crafting_table); + } +} diff --git a/src/main/java/forestry/core/blocks/BlockResourceOre.java b/src/main/java/forestry/core/blocks/BlockResourceOre.java index 88a39b054..7553fc356 100644 --- a/src/main/java/forestry/core/blocks/BlockResourceOre.java +++ b/src/main/java/forestry/core/blocks/BlockResourceOre.java @@ -10,9 +10,13 @@ ******************************************************************************/ package forestry.core.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.CreativeTabForestry; +import forestry.core.render.TextureManager; +import forestry.plugins.PluginCore; import java.util.ArrayList; import java.util.List; - import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -23,102 +27,95 @@ import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.CreativeTabForestry; -import forestry.core.render.TextureManager; -import forestry.plugins.PluginCore; - public class BlockResourceOre extends Block { - public enum ResourceType { - APATITE, - COPPER, - TIN; + public enum ResourceType { + APATITE, + COPPER, + TIN; - public static final ResourceType[] VALUES = values(); + public static final ResourceType[] VALUES = values(); - @SideOnly(Side.CLIENT) - public IIcon icon; - } + @SideOnly(Side.CLIENT) + public IIcon icon; + } - public BlockResourceOre() { - super(Material.rock); - setHardness(3F); - setResistance(5F); - setCreativeTab(CreativeTabForestry.tabForestry); - } + public BlockResourceOre() { + super(Material.rock); + setHardness(3F); + setResistance(5F); + setCreativeTab(CreativeTabForestry.tabForestry); + } - @Override - public void dropBlockAsItemWithChance(World world, int x, int y, int z, int metadata, float par6, int par7) { - super.dropBlockAsItemWithChance(world, x, y, z, metadata, par6, par7); + @Override + public void dropBlockAsItemWithChance(World world, int x, int y, int z, int metadata, float par6, int par7) { + super.dropBlockAsItemWithChance(world, x, y, z, metadata, par6, par7); - if (metadata == 0) { - this.dropXpOnBlockBreak(world, x, y, z, MathHelper.getRandomIntegerInRange(world.rand, 1, 4)); - } - } + if (metadata == 0) { + this.dropXpOnBlockBreak(world, x, y, z, MathHelper.getRandomIntegerInRange(world.rand, 1, 4)); + } + } - @Override - public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - ArrayList drops = new ArrayList<>(); + @Override + public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + ArrayList drops = new ArrayList<>(); - if (metadata == ResourceType.APATITE.ordinal()) { - int fortuneModifier = world.rand.nextInt(fortune + 2) - 1; - if (fortuneModifier < 0) { - fortuneModifier = 0; - } + if (metadata == ResourceType.APATITE.ordinal()) { + int fortuneModifier = world.rand.nextInt(fortune + 2) - 1; + if (fortuneModifier < 0) { + fortuneModifier = 0; + } - int amount = (2 + world.rand.nextInt(5)) * (fortuneModifier + 1); - if (amount > 0) { - drops.add(PluginCore.items.apatite.getItemStack(amount)); - } - } else { - drops.add(new ItemStack(this, 1, metadata)); - } + int amount = (2 + world.rand.nextInt(5)) * (fortuneModifier + 1); + if (amount > 0) { + drops.add(PluginCore.items.apatite.getItemStack(amount)); + } + } else { + drops.add(new ItemStack(this, 1, metadata)); + } - return drops; - } + return drops; + } - @Override - public int getDamageValue(World world, int x, int y, int z) { - return world.getBlockMetadata(x, y, z); - } + @Override + public int getDamageValue(World world, int x, int y, int z) { + return world.getBlockMetadata(x, y, z); + } - @Override - public int damageDropped(int meta) { - return meta; - } + @Override + public int damageDropped(int meta) { + return meta; + } - // / CREATIVE INVENTORY - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { - for (ResourceType resourceType : ResourceType.values()) { - ItemStack stack = get(resourceType, 1); - itemList.add(stack); - } - } + // / CREATIVE INVENTORY + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { + for (ResourceType resourceType : ResourceType.values()) { + ItemStack stack = get(resourceType, 1); + itemList.add(stack); + } + } - /* ICONS */ - @Override - @SideOnly(Side.CLIENT) - public void registerBlockIcons(IIconRegister register) { - ResourceType.APATITE.icon = TextureManager.registerTex(register, "ores/apatite"); - ResourceType.COPPER.icon = TextureManager.registerTex(register, "ores/copper"); - ResourceType.TIN.icon = TextureManager.registerTex(register, "ores/tin"); - } + /* ICONS */ + @Override + @SideOnly(Side.CLIENT) + public void registerBlockIcons(IIconRegister register) { + ResourceType.APATITE.icon = TextureManager.registerTex(register, "ores/apatite"); + ResourceType.COPPER.icon = TextureManager.registerTex(register, "ores/copper"); + ResourceType.TIN.icon = TextureManager.registerTex(register, "ores/tin"); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(int i, int meta) { - if (meta < 0 || meta >= ResourceType.VALUES.length) { - return null; - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(int i, int meta) { + if (meta < 0 || meta >= ResourceType.VALUES.length) { + return null; + } - return ResourceType.VALUES[meta].icon; - } + return ResourceType.VALUES[meta].icon; + } - public ItemStack get(ResourceType type, int amount) { - return new ItemStack(this, amount, type.ordinal()); - } + public ItemStack get(ResourceType type, int amount) { + return new ItemStack(this, amount, type.ordinal()); + } } diff --git a/src/main/java/forestry/core/blocks/BlockResourceStorage.java b/src/main/java/forestry/core/blocks/BlockResourceStorage.java index 9c138ed92..92f96169b 100644 --- a/src/main/java/forestry/core/blocks/BlockResourceStorage.java +++ b/src/main/java/forestry/core/blocks/BlockResourceStorage.java @@ -1,7 +1,10 @@ package forestry.core.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.CreativeTabForestry; +import forestry.core.render.TextureManager; import java.util.List; - import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -10,66 +13,60 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.CreativeTabForestry; -import forestry.core.render.TextureManager; - public class BlockResourceStorage extends Block { - public enum ResourceType { - APATITE, - COPPER, - TIN, - BRONZE; + public enum ResourceType { + APATITE, + COPPER, + TIN, + BRONZE; - public static final ResourceType[] VALUES = values(); + public static final ResourceType[] VALUES = values(); - @SideOnly(Side.CLIENT) - public IIcon icon; - } + @SideOnly(Side.CLIENT) + public IIcon icon; + } - public BlockResourceStorage() { - super(Material.iron); - setHardness(3F); - setResistance(5F); - setCreativeTab(CreativeTabForestry.tabForestry); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubBlocks(Item item, CreativeTabs creativeTabs, List itemList) { - for (ResourceType resourceType : ResourceType.values()) { - ItemStack stack = get(resourceType); - itemList.add(stack); - } - } + public BlockResourceStorage() { + super(Material.iron); + setHardness(3F); + setResistance(5F); + setCreativeTab(CreativeTabForestry.tabForestry); + } - @Override - public int damageDropped(int damage) { - return damage; - } - - @Override - @SideOnly(Side.CLIENT) - public void registerBlockIcons(IIconRegister register) { - ResourceType.APATITE.icon = TextureManager.registerTex(register, "storage/apatite"); - ResourceType.COPPER.icon = TextureManager.registerTex(register, "storage/copper"); - ResourceType.TIN.icon = TextureManager.registerTex(register, "storage/tin"); - ResourceType.BRONZE.icon = TextureManager.registerTex(register, "storage/bronze"); - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubBlocks(Item item, CreativeTabs creativeTabs, List itemList) { + for (ResourceType resourceType : ResourceType.values()) { + ItemStack stack = get(resourceType); + itemList.add(stack); + } + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(int i, int meta) { - if (meta < 0 || meta >= ResourceType.VALUES.length) { - return null; - } + @Override + public int damageDropped(int damage) { + return damage; + } - return ResourceType.VALUES[meta].icon; - } + @Override + @SideOnly(Side.CLIENT) + public void registerBlockIcons(IIconRegister register) { + ResourceType.APATITE.icon = TextureManager.registerTex(register, "storage/apatite"); + ResourceType.COPPER.icon = TextureManager.registerTex(register, "storage/copper"); + ResourceType.TIN.icon = TextureManager.registerTex(register, "storage/tin"); + ResourceType.BRONZE.icon = TextureManager.registerTex(register, "storage/bronze"); + } - public ItemStack get(ResourceType type) { - return new ItemStack(this, 1, type.ordinal()); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(int i, int meta) { + if (meta < 0 || meta >= ResourceType.VALUES.length) { + return null; + } + + return ResourceType.VALUES[meta].icon; + } + + public ItemStack get(ResourceType type) { + return new ItemStack(this, 1, type.ordinal()); + } } diff --git a/src/main/java/forestry/core/blocks/BlockSoil.java b/src/main/java/forestry/core/blocks/BlockSoil.java index f8e811a73..1d9dacb10 100644 --- a/src/main/java/forestry/core/blocks/BlockSoil.java +++ b/src/main/java/forestry/core/blocks/BlockSoil.java @@ -10,10 +10,15 @@ ******************************************************************************/ package forestry.core.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.CreativeTabForestry; +import forestry.core.config.Constants; +import forestry.core.render.TextureManager; +import forestry.plugins.PluginCore; import java.util.ArrayList; import java.util.List; import java.util.Random; - import net.minecraft.block.Block; import net.minecraft.block.IGrowable; import net.minecraft.block.material.Material; @@ -25,252 +30,248 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.common.EnumPlantType; import net.minecraftforge.common.IPlantable; import net.minecraftforge.common.util.ForgeDirection; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.CreativeTabForestry; -import forestry.core.config.Constants; -import forestry.core.render.TextureManager; -import forestry.plugins.PluginCore; - /** * Humus, bog earth, peat */ public class BlockSoil extends Block implements IItemTyped { - public enum SoilType { - HUMUS, BOG_EARTH, PEAT - } + public enum SoilType { + HUMUS, + BOG_EARTH, + PEAT + } - private static final int degradeDelimiter = 3; + private static final int degradeDelimiter = 3; - public BlockSoil() { - super(Material.sand); - setTickRandomly(true); - setHardness(0.5f); - setStepSound(soundTypeGrass); - setCreativeTab(CreativeTabForestry.tabForestry); - } + public BlockSoil() { + super(Material.sand); + setTickRandomly(true); + setHardness(0.5f); + setStepSound(soundTypeGrass); + setCreativeTab(CreativeTabForestry.tabForestry); + } - @Override - public int tickRate(World world) { - return 500; - } + @Override + public int tickRate(World world) { + return 500; + } - @Override - public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - ArrayList ret = new ArrayList<>(); + @Override + public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + ArrayList ret = new ArrayList<>(); - SoilType type = getTypeFromMeta(metadata); + SoilType type = getTypeFromMeta(metadata); - if (type == SoilType.PEAT) { - ret.add(PluginCore.items.peat.getItemStack()); - ret.add(new ItemStack(Blocks.dirt)); - } else if (type == SoilType.HUMUS) { - ret.add(new ItemStack(Blocks.dirt)); - } else { - ret.add(new ItemStack(this, 1, SoilType.BOG_EARTH.ordinal())); - } + if (type == SoilType.PEAT) { + ret.add(PluginCore.items.peat.getItemStack()); + ret.add(new ItemStack(Blocks.dirt)); + } else if (type == SoilType.HUMUS) { + ret.add(new ItemStack(Blocks.dirt)); + } else { + ret.add(new ItemStack(this, 1, SoilType.BOG_EARTH.ordinal())); + } - return ret; - } + return ret; + } - @Override - public int getDamageValue(World world, int x, int y, int z) { - return (world.getBlockMetadata(x, y, z) & 0x03); - } + @Override + public int getDamageValue(World world, int x, int y, int z) { + return (world.getBlockMetadata(x, y, z) & 0x03); + } - @Override - public void updateTick(World world, int i, int j, int k, Random random) { - if (world.isRemote) { - return; - } + @Override + public void updateTick(World world, int i, int j, int k, Random random) { + if (world.isRemote) { + return; + } - int meta = world.getBlockMetadata(i, j, k); + int meta = world.getBlockMetadata(i, j, k); - SoilType type = getTypeFromMeta(meta); + SoilType type = getTypeFromMeta(meta); - if (type == SoilType.HUMUS) { - updateTickHumus(world, i, j, k); - } else if (type == SoilType.BOG_EARTH) { - updateTickBogEarth(world, i, j, k); - } - } + if (type == SoilType.HUMUS) { + updateTickHumus(world, i, j, k); + } else if (type == SoilType.BOG_EARTH) { + updateTickBogEarth(world, i, j, k); + } + } - private static void updateTickHumus(World world, int i, int j, int k) { - if (isEnrooted(world, i, j, k)) { - degradeSoil(world, i, j, k); - } - } + private static void updateTickHumus(World world, int i, int j, int k) { + if (isEnrooted(world, i, j, k)) { + degradeSoil(world, i, j, k); + } + } - private static void updateTickBogEarth(World world, int i, int j, int k) { - if (isMoistened(world, i, j, k)) { - matureBog(world, i, j, k); - } - } + private static void updateTickBogEarth(World world, int i, int j, int k) { + if (isMoistened(world, i, j, k)) { + matureBog(world, i, j, k); + } + } - private static boolean isEnrooted(World world, int x, int y, int z) { - for (int i = -1; i < 2; i++) { - for (int j = -1; j < 2; j++) { - Block block = world.getBlock(x + i, y + 1, z + j); - if (block == Blocks.log || block == Blocks.sapling || block instanceof IGrowable) { - // We are not returning true if we are the base of a sapling. - return !(i == 0 && j == 0); - } - } - } + private static boolean isEnrooted(World world, int x, int y, int z) { + for (int i = -1; i < 2; i++) { + for (int j = -1; j < 2; j++) { + Block block = world.getBlock(x + i, y + 1, z + j); + if (block == Blocks.log || block == Blocks.sapling || block instanceof IGrowable) { + // We are not returning true if we are the base of a sapling. + return !(i == 0 && j == 0); + } + } + } - return false; - } + return false; + } - /** - * If a tree or sapling is in the vicinity, there is a chance, that the soil will degrade. - */ - private static void degradeSoil(World world, int x, int y, int z) { + /** + * If a tree or sapling is in the vicinity, there is a chance, that the soil will degrade. + */ + private static void degradeSoil(World world, int x, int y, int z) { - if (world.rand.nextInt(140) != 0) { - return; - } + if (world.rand.nextInt(140) != 0) { + return; + } - int meta = world.getBlockMetadata(x, y, z); + int meta = world.getBlockMetadata(x, y, z); - // Unpack first - int type = meta & 0x03; - int grade = meta >> 2; + // Unpack first + int type = meta & 0x03; + int grade = meta >> 2; - // Increment (de)gradation - grade++; + // Increment (de)gradation + grade++; - // Repackage in format TTGG - meta = (grade << 2 | type); + // Repackage in format TTGG + meta = (grade << 2 | type); - if (grade >= degradeDelimiter) { - world.setBlock(x, y, z, Blocks.sand, 0, Constants.FLAG_BLOCK_SYNCH); - } else { - world.setBlockMetadataWithNotify(x, y, z, meta, Constants.FLAG_BLOCK_SYNCH); - } - world.markBlockForUpdate(x, y, z); - } + if (grade >= degradeDelimiter) { + world.setBlock(x, y, z, Blocks.sand, 0, Constants.FLAG_BLOCK_SYNCH); + } else { + world.setBlockMetadataWithNotify(x, y, z, meta, Constants.FLAG_BLOCK_SYNCH); + } + world.markBlockForUpdate(x, y, z); + } - private static boolean isMoistened(World world, int x, int y, int z) { + private static boolean isMoistened(World world, int x, int y, int z) { - for (int i = -2; i < 3; i++) { - for (int j = -2; j < 3; j++) { - Block block = world.getBlock(x + i, y, z + j); - if (block == Blocks.water || block == Blocks.flowing_water) { - return true; - } - } - } + for (int i = -2; i < 3; i++) { + for (int j = -2; j < 3; j++) { + Block block = world.getBlock(x + i, y, z + j); + if (block == Blocks.water || block == Blocks.flowing_water) { + return true; + } + } + } - return false; - } + return false; + } - private static void matureBog(World world, int i, int j, int k) { + private static void matureBog(World world, int i, int j, int k) { - if (world.rand.nextInt(13) != 0) { - return; - } + if (world.rand.nextInt(13) != 0) { + return; + } - int meta = world.getBlockMetadata(i, j, k); + int meta = world.getBlockMetadata(i, j, k); - // Unpack first + // Unpack first - int type = meta & 0x03; - int maturity = meta >> 2; + int type = meta & 0x03; + int maturity = meta >> 2; - if (maturity >= degradeDelimiter) { - return; - } + if (maturity >= degradeDelimiter) { + return; + } - // Increment (de)gradation - maturity++; + // Increment (de)gradation + maturity++; - meta = (maturity << 2 | type); - world.setBlockMetadataWithNotify(i, j, k, meta, Constants.FLAG_BLOCK_SYNCH); - world.markBlockForUpdate(i, j, k); - } + meta = (maturity << 2 | type); + world.setBlockMetadataWithNotify(i, j, k, meta, Constants.FLAG_BLOCK_SYNCH); + world.markBlockForUpdate(i, j, k); + } - @Override - public boolean canSustainPlant(IBlockAccess world, int x, int y, int z, ForgeDirection direction, IPlantable plant) { - EnumPlantType plantType = plant.getPlantType(world, x, y, z); - if (plantType != EnumPlantType.Crop && plantType != EnumPlantType.Plains) { - return false; - } + @Override + public boolean canSustainPlant( + IBlockAccess world, int x, int y, int z, ForgeDirection direction, IPlantable plant) { + EnumPlantType plantType = plant.getPlantType(world, x, y, z); + if (plantType != EnumPlantType.Crop && plantType != EnumPlantType.Plains) { + return false; + } - int meta = world.getBlockMetadata(x, y, z); - SoilType type = getTypeFromMeta(meta); + int meta = world.getBlockMetadata(x, y, z); + SoilType type = getTypeFromMeta(meta); - return type == SoilType.HUMUS; - } + return type == SoilType.HUMUS; + } - @Override - protected boolean canSilkHarvest() { - return false; - } + @Override + protected boolean canSilkHarvest() { + return false; + } - public SoilType getTypeFromMeta(int meta) { - int type = meta & 0x03; - int maturity = meta >> 2; + public SoilType getTypeFromMeta(int meta) { + int type = meta & 0x03; + int maturity = meta >> 2; - if (type == 1) { - if (maturity < degradeDelimiter) { - return SoilType.BOG_EARTH; - } else { - return SoilType.PEAT; - } - } else { - return SoilType.HUMUS; - } - } + if (type == 1) { + if (maturity < degradeDelimiter) { + return SoilType.BOG_EARTH; + } else { + return SoilType.PEAT; + } + } else { + return SoilType.HUMUS; + } + } - // / CREATIVE INVENTORY - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { - itemList.add(new ItemStack(this, 1, 0)); - itemList.add(new ItemStack(this, 1, 1)); - } + // / CREATIVE INVENTORY + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { + itemList.add(new ItemStack(this, 1, 0)); + itemList.add(new ItemStack(this, 1, 1)); + } - /* ICONS */ - @SideOnly(Side.CLIENT) - private IIcon iconHumus; - @SideOnly(Side.CLIENT) - private IIcon iconBogEarth; - @SideOnly(Side.CLIENT) - private IIcon iconPeat; + /* ICONS */ + @SideOnly(Side.CLIENT) + private IIcon iconHumus; - @Override - @SideOnly(Side.CLIENT) - public void registerBlockIcons(IIconRegister register) { - iconHumus = TextureManager.registerTex(register, "soil/humus"); - iconBogEarth = TextureManager.registerTex(register, "soil/bog"); - iconPeat = TextureManager.registerTex(register, "soil/peat"); - } + @SideOnly(Side.CLIENT) + private IIcon iconBogEarth; - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(int side, int meta) { + @SideOnly(Side.CLIENT) + private IIcon iconPeat; - SoilType type = getTypeFromMeta(meta); + @Override + @SideOnly(Side.CLIENT) + public void registerBlockIcons(IIconRegister register) { + iconHumus = TextureManager.registerTex(register, "soil/humus"); + iconBogEarth = TextureManager.registerTex(register, "soil/bog"); + iconPeat = TextureManager.registerTex(register, "soil/peat"); + } - switch (type) { - case HUMUS: - return iconHumus; - case BOG_EARTH: - return iconBogEarth; - case PEAT: - return iconPeat; - } - return null; - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(int side, int meta) { - public ItemStack get(SoilType soilType, int amount) { - return new ItemStack(this, amount, soilType.ordinal()); - } + SoilType type = getTypeFromMeta(meta); + + switch (type) { + case HUMUS: + return iconHumus; + case BOG_EARTH: + return iconBogEarth; + case PEAT: + return iconPeat; + } + return null; + } + + public ItemStack get(SoilType soilType, int amount) { + return new ItemStack(this, amount, soilType.ordinal()); + } } diff --git a/src/main/java/forestry/core/blocks/BlockStructure.java b/src/main/java/forestry/core/blocks/BlockStructure.java index 7c8640840..9fca08181 100644 --- a/src/main/java/forestry/core/blocks/BlockStructure.java +++ b/src/main/java/forestry/core/blocks/BlockStructure.java @@ -10,6 +10,13 @@ ******************************************************************************/ package forestry.core.blocks; +import com.mojang.authlib.GameProfile; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.api.multiblock.IMultiblockController; +import forestry.core.circuits.ISocketable; +import forestry.core.multiblock.MultiblockTileEntityForestry; +import forestry.core.multiblock.MultiblockUtil; +import forestry.core.utils.InventoryUtil; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.EntityLivingBase; @@ -21,112 +28,104 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -import com.mojang.authlib.GameProfile; - -import forestry.api.multiblock.IMultiblockComponent; -import forestry.api.multiblock.IMultiblockController; -import forestry.core.circuits.ISocketable; -import forestry.core.multiblock.MultiblockTileEntityForestry; -import forestry.core.multiblock.MultiblockUtil; -import forestry.core.utils.InventoryUtil; - public abstract class BlockStructure extends BlockForestry { - protected BlockStructure(Material material) { - super(material); - setHardness(1.0f); - } + protected BlockStructure(Material material) { + super(material); + setHardness(1.0f); + } - @Override - public boolean canSilkHarvest() { - return false; - } + @Override + public boolean canSilkHarvest() { + return false; + } - private long previousMessageTick = 0; + private long previousMessageTick = 0; - @Override - public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) { - if (player.isSneaking()) { - return false; - } + @Override + public boolean onBlockActivated( + World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) { + if (player.isSneaking()) { + return false; + } - TileEntity tile = world.getTileEntity(x, y, z); - if (!(tile instanceof MultiblockTileEntityForestry)) { - return false; - } + TileEntity tile = world.getTileEntity(x, y, z); + if (!(tile instanceof MultiblockTileEntityForestry)) { + return false; + } - MultiblockTileEntityForestry part = (MultiblockTileEntityForestry) tile; - IMultiblockController controller = part.getMultiblockLogic().getController(); + MultiblockTileEntityForestry part = (MultiblockTileEntityForestry) tile; + IMultiblockController controller = part.getMultiblockLogic().getController(); - // If the player's hands are empty and they right-click on a multiblock, they get a - // multiblock-debugging message if the machine is not assembled. - if (player.getCurrentEquippedItem() == null && !controller.isAssembled()) { - if (controller != null) { - String validationError = controller.getLastValidationError(); - if (validationError != null) { - long tick = world.getTotalWorldTime(); - if (tick > previousMessageTick + 20) { - player.addChatMessage(new ChatComponentText(validationError)); - previousMessageTick = tick; - } - return true; - } - } else { - player.addChatMessage(new ChatComponentText(StatCollector.translateToLocal("for.multiblock.error.notConnected"))); - return true; - } - } + // If the player's hands are empty and they right-click on a multiblock, they get a + // multiblock-debugging message if the machine is not assembled. + if (player.getCurrentEquippedItem() == null && !controller.isAssembled()) { + if (controller != null) { + String validationError = controller.getLastValidationError(); + if (validationError != null) { + long tick = world.getTotalWorldTime(); + if (tick > previousMessageTick + 20) { + player.addChatMessage(new ChatComponentText(validationError)); + previousMessageTick = tick; + } + return true; + } + } else { + player.addChatMessage( + new ChatComponentText(StatCollector.translateToLocal("for.multiblock.error.notConnected"))); + return true; + } + } - // Don't open the GUI if the multiblock isn't assembled - if (controller == null || !controller.isAssembled()) { - return false; - } + // Don't open the GUI if the multiblock isn't assembled + if (controller == null || !controller.isAssembled()) { + return false; + } - if (!world.isRemote) { - part.openGui(player); - } - return true; - } + if (!world.isRemote) { + part.openGui(player); + } + return true; + } - @Override - public void onBlockPlacedBy(World world, int i, int j, int k, EntityLivingBase entityLiving, ItemStack itemstack) { - if (world.isRemote) { - return; - } + @Override + public void onBlockPlacedBy(World world, int i, int j, int k, EntityLivingBase entityLiving, ItemStack itemstack) { + if (world.isRemote) { + return; + } - if (entityLiving instanceof EntityPlayer) { - TileEntity tile = world.getTileEntity(i, j, k); + if (entityLiving instanceof EntityPlayer) { + TileEntity tile = world.getTileEntity(i, j, k); - if (tile instanceof MultiblockTileEntityForestry) { - EntityPlayer player = (EntityPlayer) entityLiving; - GameProfile gameProfile = player.getGameProfile(); - ((MultiblockTileEntityForestry) tile).setOwner(gameProfile); - } - } - } + if (tile instanceof MultiblockTileEntityForestry) { + EntityPlayer player = (EntityPlayer) entityLiving; + GameProfile gameProfile = player.getGameProfile(); + ((MultiblockTileEntityForestry) tile).setOwner(gameProfile); + } + } + } - @Override - public void breakBlock(World world, int x, int y, int z, Block block, int meta) { + @Override + public void breakBlock(World world, int x, int y, int z, Block block, int meta) { - if (world.isRemote) { - return; - } + if (world.isRemote) { + return; + } - TileEntity tile = world.getTileEntity(x, y, z); - if (tile instanceof IMultiblockComponent) { - IMultiblockComponent part = (IMultiblockComponent) tile; - - // drop inventory if we're the last part remaining - if (MultiblockUtil.getNeighboringParts(world, part).size() == 0) { - if (tile instanceof IInventory) { - InventoryUtil.dropInventory((IInventory) tile, world, x, y, z); - } - if (tile instanceof ISocketable) { - InventoryUtil.dropSockets((ISocketable) tile, world, x, y, z); - } - } - } - super.breakBlock(world, x, y, z, block, meta); - } + TileEntity tile = world.getTileEntity(x, y, z); + if (tile instanceof IMultiblockComponent) { + IMultiblockComponent part = (IMultiblockComponent) tile; + // drop inventory if we're the last part remaining + if (MultiblockUtil.getNeighboringParts(world, part).size() == 0) { + if (tile instanceof IInventory) { + InventoryUtil.dropInventory((IInventory) tile, world, x, y, z); + } + if (tile instanceof ISocketable) { + InventoryUtil.dropSockets((ISocketable) tile, world, x, y, z); + } + } + } + super.breakBlock(world, x, y, z, block, meta); + } } diff --git a/src/main/java/forestry/core/blocks/IItemTyped.java b/src/main/java/forestry/core/blocks/IItemTyped.java index fc731a6d1..ddeb97f4d 100644 --- a/src/main/java/forestry/core/blocks/IItemTyped.java +++ b/src/main/java/forestry/core/blocks/IItemTyped.java @@ -1,5 +1,5 @@ -package forestry.core.blocks; - -public interface IItemTyped { - Enum getTypeFromMeta(int meta); -} +package forestry.core.blocks; + +public interface IItemTyped { + Enum getTypeFromMeta(int meta); +} diff --git a/src/main/java/forestry/core/blocks/IMachineProperties.java b/src/main/java/forestry/core/blocks/IMachineProperties.java index cf433c41b..c9d63a001 100644 --- a/src/main/java/forestry/core/blocks/IMachineProperties.java +++ b/src/main/java/forestry/core/blocks/IMachineProperties.java @@ -1,21 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.blocks; - -import forestry.core.tiles.TileForestry; - -public interface IMachineProperties { - int getMeta(); - - String getTeIdent(); - - Class getTeClass(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.blocks; + +import forestry.core.tiles.TileForestry; + +public interface IMachineProperties { + int getMeta(); + + String getTeIdent(); + + Class getTeClass(); +} diff --git a/src/main/java/forestry/core/blocks/IMachinePropertiesTESR.java b/src/main/java/forestry/core/blocks/IMachinePropertiesTESR.java index 677e997ba..d900902f0 100644 --- a/src/main/java/forestry/core/blocks/IMachinePropertiesTESR.java +++ b/src/main/java/forestry/core/blocks/IMachinePropertiesTESR.java @@ -1,17 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.blocks; - -import forestry.core.render.IBlockRenderer; - -public interface IMachinePropertiesTESR extends IMachineProperties { - IBlockRenderer getRenderer(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.blocks; + +import forestry.core.render.IBlockRenderer; + +public interface IMachinePropertiesTESR extends IMachineProperties { + IBlockRenderer getRenderer(); +} diff --git a/src/main/java/forestry/core/circuits/Circuit.java b/src/main/java/forestry/core/circuits/Circuit.java index 3e0066cf5..efd58773d 100755 --- a/src/main/java/forestry/core/circuits/Circuit.java +++ b/src/main/java/forestry/core/circuits/Circuit.java @@ -10,96 +10,95 @@ ******************************************************************************/ package forestry.core.circuits; -import java.util.List; - import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.ICircuit; import forestry.core.utils.StringUtil; +import java.util.List; public abstract class Circuit implements ICircuit { - private final String uid; - private final boolean requiresDiscovery; - private int limit = 1; + private final String uid; + private final boolean requiresDiscovery; + private int limit = 1; - protected Circuit(String uid, boolean requiresDiscovery) { - this.uid = uid; - this.requiresDiscovery = requiresDiscovery; + protected Circuit(String uid, boolean requiresDiscovery) { + this.uid = uid; + this.requiresDiscovery = requiresDiscovery; - ChipsetManager.circuitRegistry.registerCircuit(this); - } + ChipsetManager.circuitRegistry.registerCircuit(this); + } - protected void setLimit(int limit) { - this.limit = limit; - } + protected void setLimit(int limit) { + this.limit = limit; + } - @Override - public String getUID() { - return "forestry." + this.uid; - } + @Override + public String getUID() { + return "forestry." + this.uid; + } - @Override - public int getLimit() { - return this.limit; - } + @Override + public int getLimit() { + return this.limit; + } - @Override - public boolean requiresDiscovery() { - return this.requiresDiscovery; - } + @Override + public boolean requiresDiscovery() { + return this.requiresDiscovery; + } - @Override - public String getName() { - return "circuit." + this.uid; - } + @Override + public String getName() { + return "circuit." + this.uid; + } - @Override - public void addTooltip(List list) { - list.add(StringUtil.localize(getName())); + @Override + public void addTooltip(List list) { + list.add(StringUtil.localize(getName())); - int i = 1; - while (true) { - String unlocalizedDescription = getName() + ".description." + i; - String description = StringUtil.localize(unlocalizedDescription); - if (description.endsWith(unlocalizedDescription)) { - break; - } - list.add(" - " + description); - i++; - } - } + int i = 1; + while (true) { + String unlocalizedDescription = getName() + ".description." + i; + String description = StringUtil.localize(unlocalizedDescription); + if (description.endsWith(unlocalizedDescription)) { + break; + } + list.add(" - " + description); + i++; + } + } - public static ICircuit energyElectricChoke1; - public static ICircuit energyElectricEfficiency1; - public static ICircuit energyElectricBoost1; - public static ICircuit energyElectricBoost2; + public static ICircuit energyElectricChoke1; + public static ICircuit energyElectricEfficiency1; + public static ICircuit energyElectricBoost1; + public static ICircuit energyElectricBoost2; - public static ICircuit farmArborealManaged; - public static ICircuit farmShroomManaged; - public static ICircuit farmCerealManaged; - public static ICircuit farmVegetableManaged; - public static ICircuit farmPeatManaged; - public static ICircuit farmSucculentManaged; - public static ICircuit farmPoaleManaged; - public static ICircuit farmFungal; - public static ICircuit farmInfernalManaged; - public static ICircuit farmGourdManaged; + public static ICircuit farmArborealManaged; + public static ICircuit farmShroomManaged; + public static ICircuit farmCerealManaged; + public static ICircuit farmVegetableManaged; + public static ICircuit farmPeatManaged; + public static ICircuit farmSucculentManaged; + public static ICircuit farmPoaleManaged; + public static ICircuit farmFungal; + public static ICircuit farmInfernalManaged; + public static ICircuit farmGourdManaged; - public static ICircuit farmShroomManual; - public static ICircuit farmCerealManual; - public static ICircuit farmVegetableManual; - public static ICircuit farmPeatManual; - public static ICircuit farmSucculentManual; - public static ICircuit farmPoalesManual; - public static ICircuit farmGourdManual; - public static ICircuit farmCocoaManual; + public static ICircuit farmShroomManual; + public static ICircuit farmCerealManual; + public static ICircuit farmVegetableManual; + public static ICircuit farmPeatManual; + public static ICircuit farmSucculentManual; + public static ICircuit farmPoalesManual; + public static ICircuit farmGourdManual; + public static ICircuit farmCocoaManual; - public static ICircuit farmIC2CropsManual; - public static ICircuit farmOrchardManual; - public static ICircuit farmRubberManual; - public static ICircuit farmEnderManaged; + public static ICircuit farmIC2CropsManual; + public static ICircuit farmOrchardManual; + public static ICircuit farmRubberManual; + public static ICircuit farmEnderManaged; - public static ICircuit machineSpeedUpgrade1; - public static ICircuit machineSpeedUpgrade2; - public static ICircuit machineEfficiencyUpgrade1; + public static ICircuit machineSpeedUpgrade1; + public static ICircuit machineSpeedUpgrade2; + public static ICircuit machineEfficiencyUpgrade1; } diff --git a/src/main/java/forestry/core/circuits/CircuitBoard.java b/src/main/java/forestry/core/circuits/CircuitBoard.java index 2119ef0d1..badbac572 100755 --- a/src/main/java/forestry/core/circuits/CircuitBoard.java +++ b/src/main/java/forestry/core/circuits/CircuitBoard.java @@ -10,12 +10,6 @@ ******************************************************************************/ package forestry.core.circuits; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumChatFormatting; - import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.ICircuit; import forestry.api.circuits.ICircuitBoard; @@ -23,152 +17,155 @@ import forestry.api.circuits.ICircuitLayout; import forestry.api.circuits.ICircuitSocketType; import forestry.core.proxy.Proxies; import forestry.core.utils.StringUtil; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumChatFormatting; public class CircuitBoard implements ICircuitBoard { - private EnumCircuitBoardType type; - private ICircuitLayout layout; - private ICircuit[] circuits; + private EnumCircuitBoardType type; + private ICircuitLayout layout; + private ICircuit[] circuits; - public CircuitBoard(EnumCircuitBoardType type, ICircuitLayout layout, ICircuit[] circuits) { - this.type = type; - this.layout = layout; - this.circuits = circuits; - } + public CircuitBoard(EnumCircuitBoardType type, ICircuitLayout layout, ICircuit[] circuits) { + this.type = type; + this.layout = layout; + this.circuits = circuits; + } - public CircuitBoard(NBTTagCompound nbttagcompound) { - readFromNBT(nbttagcompound); - } + public CircuitBoard(NBTTagCompound nbttagcompound) { + readFromNBT(nbttagcompound); + } - @Override - public int getPrimaryColor() { - return type.getPrimaryColor(); - } + @Override + public int getPrimaryColor() { + return type.getPrimaryColor(); + } - @Override - public int getSecondaryColor() { - return type.getSecondaryColor(); - } + @Override + public int getSecondaryColor() { + return type.getSecondaryColor(); + } - @Override - public void addTooltip(List list) { - if (layout != null) { - list.add(EnumChatFormatting.GOLD + layout.getUsage() + ":"); - } + @Override + public void addTooltip(List list) { + if (layout != null) { + list.add(EnumChatFormatting.GOLD + layout.getUsage() + ":"); + } - List extendedTooltip = new ArrayList<>(); - for (ICircuit circuit : circuits) { - if (circuit != null) { - circuit.addTooltip(extendedTooltip); - } - } + List extendedTooltip = new ArrayList<>(); + for (ICircuit circuit : circuits) { + if (circuit != null) { + circuit.addTooltip(extendedTooltip); + } + } - if (Proxies.common.isShiftDown() || extendedTooltip.size() <= 4) { - list.addAll(extendedTooltip); - } else { - list.add(EnumChatFormatting.ITALIC + "<" + StringUtil.localize("gui.tooltip.tmi") + ">"); - } - } + if (Proxies.common.isShiftDown() || extendedTooltip.size() <= 4) { + list.addAll(extendedTooltip); + } else { + list.add(EnumChatFormatting.ITALIC + "<" + StringUtil.localize("gui.tooltip.tmi") + ">"); + } + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { - type = EnumCircuitBoardType.values()[nbttagcompound.getShort("T")]; + type = EnumCircuitBoardType.values()[nbttagcompound.getShort("T")]; - // Layout - if (nbttagcompound.hasKey("LY")) { - layout = ChipsetManager.circuitRegistry.getLayout(nbttagcompound.getString("LY")); - } - if (layout == null) { - ChipsetManager.circuitRegistry.getDefaultLayout(); - } + // Layout + if (nbttagcompound.hasKey("LY")) { + layout = ChipsetManager.circuitRegistry.getLayout(nbttagcompound.getString("LY")); + } + if (layout == null) { + ChipsetManager.circuitRegistry.getDefaultLayout(); + } - circuits = new ICircuit[4]; + circuits = new ICircuit[4]; - for (int i = 0; i < 4; i++) { - if (!nbttagcompound.hasKey("CA.I" + i)) { - continue; - } - ICircuit circuit = ChipsetManager.circuitRegistry.getCircuit(nbttagcompound.getString("CA.I" + i)); - if (circuit != null) { - circuits[i] = circuit; - } - } - } + for (int i = 0; i < 4; i++) { + if (!nbttagcompound.hasKey("CA.I" + i)) { + continue; + } + ICircuit circuit = ChipsetManager.circuitRegistry.getCircuit(nbttagcompound.getString("CA.I" + i)); + if (circuit != null) { + circuits[i] = circuit; + } + } + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setShort("T", (short) type.ordinal()); + nbttagcompound.setShort("T", (short) type.ordinal()); - // Layout - if (layout != null) { - nbttagcompound.setString("LY", layout.getUID()); - } + // Layout + if (layout != null) { + nbttagcompound.setString("LY", layout.getUID()); + } - // Circuits - for (int i = 0; i < circuits.length; i++) { - ICircuit circuit = circuits[i]; - if (circuit == null) { - continue; - } + // Circuits + for (int i = 0; i < circuits.length; i++) { + ICircuit circuit = circuits[i]; + if (circuit == null) { + continue; + } - nbttagcompound.setString("CA.I" + i, circuit.getUID()); - } + nbttagcompound.setString("CA.I" + i, circuit.getUID()); + } + } - } + @Override + public void onInsertion(Object tile) { + for (int i = 0; i < circuits.length; i++) { + ICircuit circuit = circuits[i]; + if (circuit == null) { + continue; + } + circuit.onInsertion(i, tile); + } + } - @Override - public void onInsertion(Object tile) { - for (int i = 0; i < circuits.length; i++) { - ICircuit circuit = circuits[i]; - if (circuit == null) { - continue; - } - circuit.onInsertion(i, tile); - } - } + @Override + public void onLoad(Object tile) { + for (int i = 0; i < circuits.length; i++) { + ICircuit circuit = circuits[i]; + if (circuit == null) { + continue; + } + circuit.onLoad(i, tile); + } + } - @Override - public void onLoad(Object tile) { - for (int i = 0; i < circuits.length; i++) { - ICircuit circuit = circuits[i]; - if (circuit == null) { - continue; - } - circuit.onLoad(i, tile); - } - } + @Override + public void onRemoval(Object tile) { + for (int i = 0; i < circuits.length; i++) { + ICircuit circuit = circuits[i]; + if (circuit == null) { + continue; + } + circuit.onRemoval(i, tile); + } + } - @Override - public void onRemoval(Object tile) { - for (int i = 0; i < circuits.length; i++) { - ICircuit circuit = circuits[i]; - if (circuit == null) { - continue; - } - circuit.onRemoval(i, tile); - } - } + @Override + public void onTick(Object tile) { + for (int i = 0; i < circuits.length; i++) { + ICircuit circuit = circuits[i]; + if (circuit == null) { + continue; + } + circuit.onTick(i, tile); + } + } - @Override - public void onTick(Object tile) { - for (int i = 0; i < circuits.length; i++) { - ICircuit circuit = circuits[i]; - if (circuit == null) { - continue; - } - circuit.onTick(i, tile); - } - } + @Override + public ICircuit[] getCircuits() { + return circuits; + } - @Override - public ICircuit[] getCircuits() { - return circuits; - } - - @Override - public ICircuitSocketType getSocketType() { - return layout.getSocketType(); - } + @Override + public ICircuitSocketType getSocketType() { + return layout.getSocketType(); + } } diff --git a/src/main/java/forestry/core/circuits/CircuitId.java b/src/main/java/forestry/core/circuits/CircuitId.java index 4be8cb99d..4cf188ba4 100755 --- a/src/main/java/forestry/core/circuits/CircuitId.java +++ b/src/main/java/forestry/core/circuits/CircuitId.java @@ -11,9 +11,9 @@ package forestry.core.circuits; public class CircuitId { - public static final int ELECTRIC_CHOKE_I = 1; - public static final int FIRE_DAMPENER_I = 2; - public static final int ELECTRIC_EFFICIENCY_I = 3; - public static final int ELECTRIC_BOOST_I = 4; - public static final int ELECTRIC_BOOST_II = 5; + public static final int ELECTRIC_CHOKE_I = 1; + public static final int FIRE_DAMPENER_I = 2; + public static final int ELECTRIC_EFFICIENCY_I = 3; + public static final int ELECTRIC_BOOST_I = 4; + public static final int ELECTRIC_BOOST_II = 5; } diff --git a/src/main/java/forestry/core/circuits/CircuitLayout.java b/src/main/java/forestry/core/circuits/CircuitLayout.java index f15cbb7e4..1ec698290 100755 --- a/src/main/java/forestry/core/circuits/CircuitLayout.java +++ b/src/main/java/forestry/core/circuits/CircuitLayout.java @@ -16,31 +16,31 @@ import forestry.core.utils.StringUtil; public class CircuitLayout implements ICircuitLayout { - private final String uid; - private final ICircuitSocketType socketType; + private final String uid; + private final ICircuitSocketType socketType; - public CircuitLayout(String uid, ICircuitSocketType socketType) { - this.uid = uid; - this.socketType = socketType; - } + public CircuitLayout(String uid, ICircuitSocketType socketType) { + this.uid = uid; + this.socketType = socketType; + } - @Override - public String getUID() { - return "forestry." + this.uid; - } + @Override + public String getUID() { + return "forestry." + this.uid; + } - @Override - public String getName() { - return StringUtil.localize("circuit.layout." + this.uid + ".name"); - } + @Override + public String getName() { + return StringUtil.localize("circuit.layout." + this.uid + ".name"); + } - @Override - public String getUsage() { - return StringUtil.localize("circuit.layout." + this.uid + ".usage"); - } + @Override + public String getUsage() { + return StringUtil.localize("circuit.layout." + this.uid + ".usage"); + } - @Override - public ICircuitSocketType getSocketType() { - return socketType; - } + @Override + public ICircuitSocketType getSocketType() { + return socketType; + } } diff --git a/src/main/java/forestry/core/circuits/CircuitLibrary.java b/src/main/java/forestry/core/circuits/CircuitLibrary.java index 5dde1a6b1..5757a98a9 100755 --- a/src/main/java/forestry/core/circuits/CircuitLibrary.java +++ b/src/main/java/forestry/core/circuits/CircuitLibrary.java @@ -10,23 +10,19 @@ ******************************************************************************/ package forestry.core.circuits; +import forestry.api.circuits.ICircuitLibrary; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.WorldSavedData; -import forestry.api.circuits.ICircuitLibrary; - public class CircuitLibrary extends WorldSavedData implements ICircuitLibrary { - public CircuitLibrary(String par1Str) { - super(par1Str); - } + public CircuitLibrary(String par1Str) { + super(par1Str); + } - @Override - public void readFromNBT(NBTTagCompound var1) { - } - - @Override - public void writeToNBT(NBTTagCompound var1) { - } + @Override + public void readFromNBT(NBTTagCompound var1) {} + @Override + public void writeToNBT(NBTTagCompound var1) {} } diff --git a/src/main/java/forestry/core/circuits/CircuitRecipe.java b/src/main/java/forestry/core/circuits/CircuitRecipe.java index 17dc0721f..38c4dd0ea 100644 --- a/src/main/java/forestry/core/circuits/CircuitRecipe.java +++ b/src/main/java/forestry/core/circuits/CircuitRecipe.java @@ -1,45 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.circuits; - -import net.minecraft.item.ItemStack; - -import forestry.api.circuits.ICircuit; -import forestry.api.circuits.ICircuitLayout; - -public class CircuitRecipe { - - private final ICircuitLayout layout; - private final ItemStack resource; - private final ICircuit circuit; - - public CircuitRecipe(ICircuitLayout layout, ItemStack resource, ICircuit circuit) { - this.resource = resource; - this.layout = layout; - this.circuit = circuit; - } - - public boolean matches(ICircuitLayout layout, ItemStack itemstack) { - if (!this.layout.getUID().equals(layout.getUID())) { - return false; - } - - return itemstack.isItemEqual(resource); - } - - public ICircuit getCircuit() { - return circuit; - } - - public ItemStack getResource() { - return resource; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.circuits; + +import forestry.api.circuits.ICircuit; +import forestry.api.circuits.ICircuitLayout; +import net.minecraft.item.ItemStack; + +public class CircuitRecipe { + + private final ICircuitLayout layout; + private final ItemStack resource; + private final ICircuit circuit; + + public CircuitRecipe(ICircuitLayout layout, ItemStack resource, ICircuit circuit) { + this.resource = resource; + this.layout = layout; + this.circuit = circuit; + } + + public boolean matches(ICircuitLayout layout, ItemStack itemstack) { + if (!this.layout.getUID().equals(layout.getUID())) { + return false; + } + + return itemstack.isItemEqual(resource); + } + + public ICircuit getCircuit() { + return circuit; + } + + public ItemStack getResource() { + return resource; + } +} diff --git a/src/main/java/forestry/core/circuits/CircuitRegistry.java b/src/main/java/forestry/core/circuits/CircuitRegistry.java index 9d754d1c8..f000cca9f 100755 --- a/src/main/java/forestry/core/circuits/CircuitRegistry.java +++ b/src/main/java/forestry/core/circuits/CircuitRegistry.java @@ -10,13 +10,6 @@ ******************************************************************************/ package forestry.core.circuits; -import java.util.LinkedHashMap; -import java.util.Map; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - import forestry.api.circuits.CircuitSocketType; import forestry.api.circuits.ICircuit; import forestry.api.circuits.ICircuitBoard; @@ -24,92 +17,98 @@ import forestry.api.circuits.ICircuitLayout; import forestry.api.circuits.ICircuitLibrary; import forestry.api.circuits.ICircuitRegistry; import forestry.plugins.PluginCore; +import java.util.LinkedHashMap; +import java.util.Map; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; public class CircuitRegistry implements ICircuitRegistry { - public static final ICircuitLayout DUMMY_LAYOUT = new CircuitLayout("dummy", CircuitSocketType.NONE); - private static final Map DUMMY_MAP = new LinkedHashMap<>(); - private final Map layoutMap = new LinkedHashMap<>(); - private final Map circuitMap = new LinkedHashMap<>(); + public static final ICircuitLayout DUMMY_LAYOUT = new CircuitLayout("dummy", CircuitSocketType.NONE); + private static final Map DUMMY_MAP = new LinkedHashMap<>(); + private final Map layoutMap = new LinkedHashMap<>(); + private final Map circuitMap = new LinkedHashMap<>(); - static { - DUMMY_MAP.put("dummy", DUMMY_LAYOUT); - } + static { + DUMMY_MAP.put("dummy", DUMMY_LAYOUT); + } - @Override - public ICircuitLibrary getCircuitLibrary(World world, String playername) { - CircuitLibrary library = (CircuitLibrary) world.loadItemData(CircuitLibrary.class, "CircuitLibrary_" + playername); + @Override + public ICircuitLibrary getCircuitLibrary(World world, String playername) { + CircuitLibrary library = + (CircuitLibrary) world.loadItemData(CircuitLibrary.class, "CircuitLibrary_" + playername); - if (library == null) { - library = new CircuitLibrary(playername); - world.setItemData("CircuitLibrary_" + playername, library); - } + if (library == null) { + library = new CircuitLibrary(playername); + world.setItemData("CircuitLibrary_" + playername, library); + } - return library; - } + return library; + } - /* CIRCUIT LAYOUTS */ - @Override - public ICircuitLayout getDefaultLayout() { - if (layoutMap.containsKey("forestry.engine.tin")) { - return layoutMap.get("forestry.engine.tin"); - } else if (!layoutMap.isEmpty()) { - return layoutMap.values().iterator().next(); - } else { - return DUMMY_LAYOUT; - } - } + /* CIRCUIT LAYOUTS */ + @Override + public ICircuitLayout getDefaultLayout() { + if (layoutMap.containsKey("forestry.engine.tin")) { + return layoutMap.get("forestry.engine.tin"); + } else if (!layoutMap.isEmpty()) { + return layoutMap.values().iterator().next(); + } else { + return DUMMY_LAYOUT; + } + } - @Override - public Map getRegisteredLayouts() { - if (layoutMap.isEmpty()) { - return DUMMY_MAP; - } - return layoutMap; - } + @Override + public Map getRegisteredLayouts() { + if (layoutMap.isEmpty()) { + return DUMMY_MAP; + } + return layoutMap; + } - @Override - public void registerLayout(ICircuitLayout layout) { - layoutMap.put(layout.getUID(), layout); - } + @Override + public void registerLayout(ICircuitLayout layout) { + layoutMap.put(layout.getUID(), layout); + } - @Override - public ICircuitLayout getLayout(String uid) { - if (layoutMap.containsKey(uid)) { - return layoutMap.get(uid); - } else { - return null; - } - } + @Override + public ICircuitLayout getLayout(String uid) { + if (layoutMap.containsKey(uid)) { + return layoutMap.get(uid); + } else { + return null; + } + } - /* CIRCUITS */ - @Override - public Map getRegisteredCircuits() { - return circuitMap; - } + /* CIRCUITS */ + @Override + public Map getRegisteredCircuits() { + return circuitMap; + } - @Override - public void registerCircuit(ICircuit circuit) { - circuitMap.put(circuit.getUID(), circuit); - } + @Override + public void registerCircuit(ICircuit circuit) { + circuitMap.put(circuit.getUID(), circuit); + } - @Override - public ICircuit getCircuit(String uid) { - return circuitMap.get(uid); - } + @Override + public ICircuit getCircuit(String uid) { + return circuitMap.get(uid); + } - @Override - public boolean isChipset(ItemStack itemstack) { - return itemstack != null && itemstack.getItem() == PluginCore.items.circuitboards; - } + @Override + public boolean isChipset(ItemStack itemstack) { + return itemstack != null && itemstack.getItem() == PluginCore.items.circuitboards; + } - @Override - public ICircuitBoard getCircuitboard(ItemStack itemstack) { - NBTTagCompound nbttagcompound = itemstack.getTagCompound(); - if (nbttagcompound == null) { - return null; - } + @Override + public ICircuitBoard getCircuitboard(ItemStack itemstack) { + NBTTagCompound nbttagcompound = itemstack.getTagCompound(); + if (nbttagcompound == null) { + return null; + } - return new CircuitBoard(nbttagcompound); - } + return new CircuitBoard(nbttagcompound); + } } diff --git a/src/main/java/forestry/core/circuits/ContainerSolderingIron.java b/src/main/java/forestry/core/circuits/ContainerSolderingIron.java index fca543ad1..9cd404017 100755 --- a/src/main/java/forestry/core/circuits/ContainerSolderingIron.java +++ b/src/main/java/forestry/core/circuits/ContainerSolderingIron.java @@ -10,9 +10,6 @@ ******************************************************************************/ package forestry.core.circuits; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; - import forestry.api.circuits.ICircuitLayout; import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.IGuiSelectable; @@ -24,58 +21,62 @@ import forestry.core.network.IForestryPacketServer; import forestry.core.network.packets.PacketGuiLayoutSelect; import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.proxy.Proxies; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; -public class ContainerSolderingIron extends ContainerItemInventory implements IGuiSelectable { +public class ContainerSolderingIron extends ContainerItemInventory + implements IGuiSelectable { - public ContainerSolderingIron(EntityPlayer player, ItemInventorySolderingIron inventory) { - super(inventory, player.inventory, 8, 123); + public ContainerSolderingIron(EntityPlayer player, ItemInventorySolderingIron inventory) { + super(inventory, player.inventory, 8, 123); - // Input - this.addSlotToContainer(new SlotFiltered(inventory, 0, 152, 12)); + // Input + this.addSlotToContainer(new SlotFiltered(inventory, 0, 152, 12)); - // Output - this.addSlotToContainer(new SlotOutput(inventory, 1, 152, 92)); + // Output + this.addSlotToContainer(new SlotOutput(inventory, 1, 152, 92)); - // Ingredients - this.addSlotToContainer(new SlotFiltered(inventory, 2, 12, 32)); - this.addSlotToContainer(new SlotFiltered(inventory, 3, 12, 52)); - this.addSlotToContainer(new SlotFiltered(inventory, 4, 12, 72)); - this.addSlotToContainer(new SlotFiltered(inventory, 5, 12, 92)); - } + // Ingredients + this.addSlotToContainer(new SlotFiltered(inventory, 2, 12, 32)); + this.addSlotToContainer(new SlotFiltered(inventory, 3, 12, 52)); + this.addSlotToContainer(new SlotFiltered(inventory, 4, 12, 72)); + this.addSlotToContainer(new SlotFiltered(inventory, 5, 12, 92)); + } - public ICircuitLayout getLayout() { - return inventory.getLayout(); - } + public ICircuitLayout getLayout() { + return inventory.getLayout(); + } - public static void advanceSelection(int index) { - sendSelectionChange(index, 0); - } + public static void advanceSelection(int index) { + sendSelectionChange(index, 0); + } - public static void regressSelection(int index) { - sendSelectionChange(index, 1); - } + public static void regressSelection(int index) { + sendSelectionChange(index, 1); + } - private static void sendSelectionChange(int index, int advance) { - IForestryPacketServer packet = new PacketGuiSelectRequest(index, advance); - Proxies.net.sendToServer(packet); - } + private static void sendSelectionChange(int index, int advance) { + IForestryPacketServer packet = new PacketGuiSelectRequest(index, advance); + Proxies.net.sendToServer(packet); + } - @Override - public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { + @Override + public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { - if (packet.getSecondaryIndex() == 0) { - if (packet.getPrimaryIndex() == 0) { - inventory.advanceLayout(); - } - } else if (packet.getPrimaryIndex() == 0) { - inventory.regressLayout(); - } + if (packet.getSecondaryIndex() == 0) { + if (packet.getPrimaryIndex() == 0) { + inventory.advanceLayout(); + } + } else if (packet.getPrimaryIndex() == 0) { + inventory.regressLayout(); + } - IForestryPacketClient packetResponse = new PacketGuiLayoutSelect(inventory.getLayout().getUID()); - Proxies.net.sendToPlayer(packetResponse, player); - } + IForestryPacketClient packetResponse = + new PacketGuiLayoutSelect(inventory.getLayout().getUID()); + Proxies.net.sendToPlayer(packetResponse, player); + } - public void setLayout(String layoutUID) { - inventory.setLayout(layoutUID); - } + public void setLayout(String layoutUID) { + inventory.setLayout(layoutUID); + } } diff --git a/src/main/java/forestry/core/circuits/EnumCircuitBoardType.java b/src/main/java/forestry/core/circuits/EnumCircuitBoardType.java index 9fc24e09c..b20303959 100755 --- a/src/main/java/forestry/core/circuits/EnumCircuitBoardType.java +++ b/src/main/java/forestry/core/circuits/EnumCircuitBoardType.java @@ -11,28 +11,30 @@ package forestry.core.circuits; public enum EnumCircuitBoardType { - BASIC((short) 1, 0x191919, 0x6dcff6), ENHANCED((short) 2, 0x191919, 0xcb7c32), REFINED((short) 3, 0x191919, 0xc9c9c9), INTRICATE((short) 4, 0x191919, - 0xe2cb6b); + BASIC((short) 1, 0x191919, 0x6dcff6), + ENHANCED((short) 2, 0x191919, 0xcb7c32), + REFINED((short) 3, 0x191919, 0xc9c9c9), + INTRICATE((short) 4, 0x191919, 0xe2cb6b); - private final short sockets; - private final int primaryColor; - private final int secondaryColor; + private final short sockets; + private final int primaryColor; + private final int secondaryColor; - EnumCircuitBoardType(short sockets, int primaryColor, int secondaryColor) { - this.sockets = sockets; - this.primaryColor = primaryColor; - this.secondaryColor = secondaryColor; - } + EnumCircuitBoardType(short sockets, int primaryColor, int secondaryColor) { + this.sockets = sockets; + this.primaryColor = primaryColor; + this.secondaryColor = secondaryColor; + } - public short getSockets() { - return sockets; - } + public short getSockets() { + return sockets; + } - public int getPrimaryColor() { - return primaryColor; - } + public int getPrimaryColor() { + return primaryColor; + } - public int getSecondaryColor() { - return secondaryColor; - } + public int getSecondaryColor() { + return secondaryColor; + } } diff --git a/src/main/java/forestry/core/circuits/GuiSolderingIron.java b/src/main/java/forestry/core/circuits/GuiSolderingIron.java index a270cea63..4f8ee4a4f 100755 --- a/src/main/java/forestry/core/circuits/GuiSolderingIron.java +++ b/src/main/java/forestry/core/circuits/GuiSolderingIron.java @@ -10,12 +10,6 @@ ******************************************************************************/ package forestry.core.circuits; -import java.util.Locale; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - import forestry.api.circuits.CircuitSocketType; import forestry.api.circuits.ICircuitLayout; import forestry.api.circuits.ICircuitSocketType; @@ -24,72 +18,80 @@ import forestry.core.config.Constants; import forestry.core.gui.GuiForestry; import forestry.core.inventory.ItemInventorySolderingIron; import forestry.core.utils.StringUtil; +import java.util.Locale; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; public class GuiSolderingIron extends GuiForestry { - public GuiSolderingIron(EntityPlayer player, ItemInventorySolderingIron inventory) { - super(Constants.TEXTURE_PATH_GUI + "/solder.png", new ContainerSolderingIron(player, inventory), inventory); + public GuiSolderingIron(EntityPlayer player, ItemInventorySolderingIron inventory) { + super(Constants.TEXTURE_PATH_GUI + "/solder.png", new ContainerSolderingIron(player, inventory), inventory); - xSize = 176; - ySize = 205; - } + xSize = 176; + ySize = 205; + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - ICircuitLayout layout = ((ContainerSolderingIron) inventorySlots).getLayout(); - String title = layout.getName(); - fontRendererObj.drawString(title, guiLeft + 8 + textLayout.getCenteredOffset(title, 138), guiTop + 16, fontColor.get("gui.screen")); + ICircuitLayout layout = ((ContainerSolderingIron) inventorySlots).getLayout(); + String title = layout.getName(); + fontRendererObj.drawString( + title, + guiLeft + 8 + textLayout.getCenteredOffset(title, 138), + guiTop + 16, + fontColor.get("gui.screen")); - for (int i = 0; i < 4; i++) { - String description; - ItemStack tube = inventory.getStackInSlot(i + 2); - CircuitRecipe recipe = SolderManager.getMatchingRecipe(layout, tube); - if (recipe == null) { - description = "(" + StringUtil.localize("gui.noeffect") + ")"; - } else { - description = StringUtil.localize(recipe.getCircuit().getName()) + " (" + recipe.getCircuit().getLimit() + ")"; - } + for (int i = 0; i < 4; i++) { + String description; + ItemStack tube = inventory.getStackInSlot(i + 2); + CircuitRecipe recipe = SolderManager.getMatchingRecipe(layout, tube); + if (recipe == null) { + description = "(" + StringUtil.localize("gui.noeffect") + ")"; + } else { + description = StringUtil.localize(recipe.getCircuit().getName()) + " (" + + recipe.getCircuit().getLimit() + ")"; + } - int row = i * 20; - fontRendererObj.drawString(description, guiLeft + 32, guiTop + 36 + row, fontColor.get("gui.screen")); + int row = i * 20; + fontRendererObj.drawString(description, guiLeft + 32, guiTop + 36 + row, fontColor.get("gui.screen")); - if (tube == null) { - try { - ICircuitSocketType socketType = layout.getSocketType(); - if (CircuitSocketType.FARM.equals(socketType)) { - FarmDirection farmDirection = FarmDirection.values()[i]; - String farmDirectionString = farmDirection.toString().toLowerCase(Locale.ENGLISH); - String localizedDirection = StringUtil.localize("gui.solder." + farmDirectionString); - fontRendererObj.drawString(localizedDirection, guiLeft + 17, guiTop + 36 + row, fontColor.get("gui.screen")); - } - } catch (Throwable ignored) { - // older circuit layouts do not have getSocketType() - } - } - } - } + if (tube == null) { + try { + ICircuitSocketType socketType = layout.getSocketType(); + if (CircuitSocketType.FARM.equals(socketType)) { + FarmDirection farmDirection = FarmDirection.values()[i]; + String farmDirectionString = farmDirection.toString().toLowerCase(Locale.ENGLISH); + String localizedDirection = StringUtil.localize("gui.solder." + farmDirectionString); + fontRendererObj.drawString( + localizedDirection, guiLeft + 17, guiTop + 36 + row, fontColor.get("gui.screen")); + } + } catch (Throwable ignored) { + // older circuit layouts do not have getSocketType() + } + } + } + } - @SuppressWarnings("unchecked") - @Override - public void initGui() { - super.initGui(); + @SuppressWarnings("unchecked") + @Override + public void initGui() { + super.initGui(); - buttonList.add(new GuiButton(1, guiLeft + 12, guiTop + 10, 12, 18, "<")); - buttonList.add(new GuiButton(2, guiLeft + 130, guiTop + 10, 12, 18, ">")); + buttonList.add(new GuiButton(1, guiLeft + 12, guiTop + 10, 12, 18, "<")); + buttonList.add(new GuiButton(2, guiLeft + 130, guiTop + 10, 12, 18, ">")); + } - } - - @Override - protected void actionPerformed(GuiButton guibutton) { - super.actionPerformed(guibutton); - - if (guibutton.id == 1) { - ContainerSolderingIron.regressSelection(0); - } else if (guibutton.id == 2) { - ContainerSolderingIron.advanceSelection(0); - } - } + @Override + protected void actionPerformed(GuiButton guibutton) { + super.actionPerformed(guibutton); + if (guibutton.id == 1) { + ContainerSolderingIron.regressSelection(0); + } else if (guibutton.id == 2) { + ContainerSolderingIron.advanceSelection(0); + } + } } diff --git a/src/main/java/forestry/core/circuits/ISocketable.java b/src/main/java/forestry/core/circuits/ISocketable.java index 714f07c6f..b329a65c9 100644 --- a/src/main/java/forestry/core/circuits/ISocketable.java +++ b/src/main/java/forestry/core/circuits/ISocketable.java @@ -10,16 +10,15 @@ ******************************************************************************/ package forestry.core.circuits; +import forestry.api.circuits.ICircuitSocketType; import net.minecraft.item.ItemStack; -import forestry.api.circuits.ICircuitSocketType; - public interface ISocketable { - int getSocketCount(); + int getSocketCount(); - ItemStack getSocket(int slot); + ItemStack getSocket(int slot); - void setSocket(int slot, ItemStack stack); + void setSocket(int slot, ItemStack stack); - ICircuitSocketType getSocketType(); + ICircuitSocketType getSocketType(); } diff --git a/src/main/java/forestry/core/circuits/ISolderingIron.java b/src/main/java/forestry/core/circuits/ISolderingIron.java index ab86ce4cc..016cc7b37 100755 --- a/src/main/java/forestry/core/circuits/ISolderingIron.java +++ b/src/main/java/forestry/core/circuits/ISolderingIron.java @@ -10,6 +10,4 @@ ******************************************************************************/ package forestry.core.circuits; -public interface ISolderingIron { - -} +public interface ISolderingIron {} diff --git a/src/main/java/forestry/core/circuits/ISpeedUpgradable.java b/src/main/java/forestry/core/circuits/ISpeedUpgradable.java index b6afc836e..de874c3ef 100644 --- a/src/main/java/forestry/core/circuits/ISpeedUpgradable.java +++ b/src/main/java/forestry/core/circuits/ISpeedUpgradable.java @@ -1,15 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.circuits; - -public interface ISpeedUpgradable { - void applySpeedUpgrade(double speedChange, double powerChange); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.circuits; + +public interface ISpeedUpgradable { + void applySpeedUpgrade(double speedChange, double powerChange); +} diff --git a/src/main/java/forestry/core/circuits/ItemCircuitBoard.java b/src/main/java/forestry/core/circuits/ItemCircuitBoard.java index 48962f8c0..b82536bed 100755 --- a/src/main/java/forestry/core/circuits/ItemCircuitBoard.java +++ b/src/main/java/forestry/core/circuits/ItemCircuitBoard.java @@ -10,89 +10,87 @@ ******************************************************************************/ package forestry.core.circuits; -import java.util.List; -import java.util.Locale; - -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.ICircuit; import forestry.api.circuits.ICircuitBoard; import forestry.api.circuits.ICircuitLayout; import forestry.core.items.ItemForestryMultiPass; import forestry.plugins.PluginCore; +import java.util.List; +import java.util.Locale; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; public class ItemCircuitBoard extends ItemForestryMultiPass { - public ItemCircuitBoard() { - super(); - setHasSubtypes(true); - } + public ItemCircuitBoard() { + super(); + setHasSubtypes(true); + } - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - itemList.add(createCircuitboard(EnumCircuitBoardType.BASIC, null, new ICircuit[]{})); - itemList.add(createCircuitboard(EnumCircuitBoardType.ENHANCED, null, new ICircuit[]{})); - itemList.add(createCircuitboard(EnumCircuitBoardType.REFINED, null, new ICircuit[]{})); - itemList.add(createCircuitboard(EnumCircuitBoardType.INTRICATE, null, new ICircuit[]{})); - } + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + itemList.add(createCircuitboard(EnumCircuitBoardType.BASIC, null, new ICircuit[] {})); + itemList.add(createCircuitboard(EnumCircuitBoardType.ENHANCED, null, new ICircuit[] {})); + itemList.add(createCircuitboard(EnumCircuitBoardType.REFINED, null, new ICircuit[] {})); + itemList.add(createCircuitboard(EnumCircuitBoardType.INTRICATE, null, new ICircuit[] {})); + } - /** - * @return true if the item's stackTagCompound needs to be synchronized over SMP. - */ - @Override - public boolean getShareTag() { - return true; - } + /** + * @return true if the item's stackTagCompound needs to be synchronized over SMP. + */ + @Override + public boolean getShareTag() { + return true; + } - @Override - public int getColorFromItemStack(ItemStack itemstack, int pass) { - EnumCircuitBoardType type = EnumCircuitBoardType.values()[itemstack.getItemDamage()]; - if (pass == 0) { - return type.getPrimaryColor(); - } else { - return type.getSecondaryColor(); - } - } + @Override + public int getColorFromItemStack(ItemStack itemstack, int pass) { + EnumCircuitBoardType type = EnumCircuitBoardType.values()[itemstack.getItemDamage()]; + if (pass == 0) { + return type.getPrimaryColor(); + } else { + return type.getSecondaryColor(); + } + } - @Override - public String getUnlocalizedName(ItemStack stack) { - EnumCircuitBoardType type = EnumCircuitBoardType.values()[stack.getItemDamage()]; - return "item.for.circuitboard." + type.toString().toLowerCase(Locale.ENGLISH); - } + @Override + public String getUnlocalizedName(ItemStack stack) { + EnumCircuitBoardType type = EnumCircuitBoardType.values()[stack.getItemDamage()]; + return "item.for.circuitboard." + type.toString().toLowerCase(Locale.ENGLISH); + } - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { - ICircuitBoard circuitboard = ChipsetManager.circuitRegistry.getCircuitboard(itemstack); - if (circuitboard != null) { - circuitboard.addTooltip(list); - } - } + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { + ICircuitBoard circuitboard = ChipsetManager.circuitRegistry.getCircuitboard(itemstack); + if (circuitboard != null) { + circuitboard.addTooltip(list); + } + } - public static ItemStack createCircuitboard(EnumCircuitBoardType type, ICircuitLayout layout, ICircuit[] circuits) { - ItemStack chipset = PluginCore.items.circuitboards.get(type); - saveChipset(chipset, new CircuitBoard(type, layout, circuits)); - return chipset; - } + public static ItemStack createCircuitboard(EnumCircuitBoardType type, ICircuitLayout layout, ICircuit[] circuits) { + ItemStack chipset = PluginCore.items.circuitboards.get(type); + saveChipset(chipset, new CircuitBoard(type, layout, circuits)); + return chipset; + } - private static void saveChipset(ItemStack itemstack, ICircuitBoard circuitboard) { - if (circuitboard == null) { - itemstack.setTagCompound(null); - return; - } + private static void saveChipset(ItemStack itemstack, ICircuitBoard circuitboard) { + if (circuitboard == null) { + itemstack.setTagCompound(null); + return; + } - NBTTagCompound nbttagcompound = new NBTTagCompound(); - circuitboard.writeToNBT(nbttagcompound); - itemstack.setTagCompound(nbttagcompound); - } + NBTTagCompound nbttagcompound = new NBTTagCompound(); + circuitboard.writeToNBT(nbttagcompound); + itemstack.setTagCompound(nbttagcompound); + } - public ItemStack get(EnumCircuitBoardType type) { - return new ItemStack(this, 1, type.ordinal()); - } + public ItemStack get(EnumCircuitBoardType type) { + return new ItemStack(this, 1, type.ordinal()); + } } diff --git a/src/main/java/forestry/core/circuits/SolderManager.java b/src/main/java/forestry/core/circuits/SolderManager.java index e07215e61..51f470b92 100644 --- a/src/main/java/forestry/core/circuits/SolderManager.java +++ b/src/main/java/forestry/core/circuits/SolderManager.java @@ -1,60 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.circuits; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.item.ItemStack; - -import forestry.api.circuits.ICircuit; -import forestry.api.circuits.ICircuitLayout; -import forestry.api.circuits.ISolderManager; - -public class SolderManager implements ISolderManager { - private static final List recipes = new ArrayList<>(); - - @Override - public void addRecipe(ICircuitLayout layout, ItemStack resource, ICircuit circuit) { - if (layout == null) { - throw new IllegalArgumentException("layout may not be null"); - } - if (resource == null) { - throw new IllegalArgumentException("resource may not be null"); - } - if (circuit == null) { - throw new IllegalArgumentException("circuit may not be null"); - } - recipes.add(new CircuitRecipe(layout, resource, circuit)); - } - - public static ICircuit getCircuit(ICircuitLayout layout, ItemStack resource) { - CircuitRecipe circuitRecipe = getMatchingRecipe(layout, resource); - if (circuitRecipe == null) { - return null; - } - return circuitRecipe.getCircuit(); - } - - public static CircuitRecipe getMatchingRecipe(ICircuitLayout layout, ItemStack resource) { - if (layout == null || resource == null) { - return null; - } - - for (CircuitRecipe recipe : recipes) { - if (recipe.matches(layout, resource)) { - return recipe; - } - } - - return null; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.circuits; + +import forestry.api.circuits.ICircuit; +import forestry.api.circuits.ICircuitLayout; +import forestry.api.circuits.ISolderManager; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.item.ItemStack; + +public class SolderManager implements ISolderManager { + private static final List recipes = new ArrayList<>(); + + @Override + public void addRecipe(ICircuitLayout layout, ItemStack resource, ICircuit circuit) { + if (layout == null) { + throw new IllegalArgumentException("layout may not be null"); + } + if (resource == null) { + throw new IllegalArgumentException("resource may not be null"); + } + if (circuit == null) { + throw new IllegalArgumentException("circuit may not be null"); + } + recipes.add(new CircuitRecipe(layout, resource, circuit)); + } + + public static ICircuit getCircuit(ICircuitLayout layout, ItemStack resource) { + CircuitRecipe circuitRecipe = getMatchingRecipe(layout, resource); + if (circuitRecipe == null) { + return null; + } + return circuitRecipe.getCircuit(); + } + + public static CircuitRecipe getMatchingRecipe(ICircuitLayout layout, ItemStack resource) { + if (layout == null || resource == null) { + return null; + } + + for (CircuitRecipe recipe : recipes) { + if (recipe.matches(layout, resource)) { + return recipe; + } + } + + return null; + } +} diff --git a/src/main/java/forestry/core/commands/CommandHelpers.java b/src/main/java/forestry/core/commands/CommandHelpers.java index b4f091bcd..162d8f1c4 100644 --- a/src/main/java/forestry/core/commands/CommandHelpers.java +++ b/src/main/java/forestry/core/commands/CommandHelpers.java @@ -10,10 +10,10 @@ ******************************************************************************/ package forestry.core.commands; +import forestry.core.utils.StringUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.command.WrongUsageException; @@ -25,159 +25,166 @@ import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; import net.minecraft.world.World; -import forestry.core.utils.StringUtil; - /** * @author CovertJaguar */ public class CommandHelpers { - public static World getWorld(ICommandSender sender, IForestryCommand command, String[] args, int worldArgIndex) { - // Handle passed in world argument - if (worldArgIndex < args.length) { - try { - int dim = Integer.parseInt(args[worldArgIndex]); - World world = MinecraftServer.getServer().worldServerForDimension(dim); - if (world != null) { - return world; - } - } catch (Exception ex) { - throwWrongUsage(sender, command); - } - } - return getWorld(sender, command); - } + public static World getWorld(ICommandSender sender, IForestryCommand command, String[] args, int worldArgIndex) { + // Handle passed in world argument + if (worldArgIndex < args.length) { + try { + int dim = Integer.parseInt(args[worldArgIndex]); + World world = MinecraftServer.getServer().worldServerForDimension(dim); + if (world != null) { + return world; + } + } catch (Exception ex) { + throwWrongUsage(sender, command); + } + } + return getWorld(sender, command); + } - public static World getWorld(ICommandSender sender, IForestryCommand command) { - return sender.getEntityWorld(); - } + public static World getWorld(ICommandSender sender, IForestryCommand command) { + return sender.getEntityWorld(); + } - public static EntityPlayerMP getPlayer(ICommandSender sender, String playerName) { - return CommandBase.getPlayer(sender, playerName); - } + public static EntityPlayerMP getPlayer(ICommandSender sender, String playerName) { + return CommandBase.getPlayer(sender, playerName); + } - public static String[] getPlayers() { - return MinecraftServer.getServer().getAllUsernames(); - } + public static String[] getPlayers() { + return MinecraftServer.getServer().getAllUsernames(); + } - public static void sendLocalizedChatMessage(ICommandSender sender, String locTag, Object... args) { - sender.addChatMessage(new ChatComponentTranslation(locTag, args)); - } + public static void sendLocalizedChatMessage(ICommandSender sender, String locTag, Object... args) { + sender.addChatMessage(new ChatComponentTranslation(locTag, args)); + } - public static void sendLocalizedChatMessage(ICommandSender sender, ChatStyle chatStyle, String locTag, Object... args) { - ChatComponentTranslation chat = new ChatComponentTranslation(locTag, args); - chat.setChatStyle(chatStyle); - sender.addChatMessage(chat); - } + public static void sendLocalizedChatMessage( + ICommandSender sender, ChatStyle chatStyle, String locTag, Object... args) { + ChatComponentTranslation chat = new ChatComponentTranslation(locTag, args); + chat.setChatStyle(chatStyle); + sender.addChatMessage(chat); + } - /** - * Avoid using this function if at all possible. Commands are processed on the server, - * which has no localization information. - * - * StringUtil.localize() is NOT a valid alternative for sendLocalizedChatMessage(). - * Messages will not be localized properly if you use StringUtil.localize(). - */ - public static void sendChatMessage(ICommandSender sender, String message) { - sender.addChatMessage(new ChatComponentText(message)); - } + /** + * Avoid using this function if at all possible. Commands are processed on the server, + * which has no localization information. + * + * StringUtil.localize() is NOT a valid alternative for sendLocalizedChatMessage(). + * Messages will not be localized properly if you use StringUtil.localize(). + */ + public static void sendChatMessage(ICommandSender sender, String message) { + sender.addChatMessage(new ChatComponentText(message)); + } - public static void throwWrongUsage(ICommandSender sender, IForestryCommand command) throws WrongUsageException { - throw new WrongUsageException(StringUtil.localizeAndFormat("chat.help", command.getCommandUsage(sender))); - } + public static void throwWrongUsage(ICommandSender sender, IForestryCommand command) throws WrongUsageException { + throw new WrongUsageException(StringUtil.localizeAndFormat("chat.help", command.getCommandUsage(sender))); + } - public static void processChildCommand(ICommandSender sender, SubCommand child, String[] args) { - if (!sender.canCommandSenderUseCommand(child.getPermissionLevel(), child.getFullCommandString())) { - throw new WrongUsageException(StringUtil.localize("chat.command.noperms")); - } - String[] newargs = new String[args.length - 1]; - System.arraycopy(args, 1, newargs, 0, newargs.length); - child.processCommand(sender, newargs); - } + public static void processChildCommand(ICommandSender sender, SubCommand child, String[] args) { + if (!sender.canCommandSenderUseCommand(child.getPermissionLevel(), child.getFullCommandString())) { + throw new WrongUsageException(StringUtil.localize("chat.command.noperms")); + } + String[] newargs = new String[args.length - 1]; + System.arraycopy(args, 1, newargs, 0, newargs.length); + child.processCommand(sender, newargs); + } - public static void printHelp(ICommandSender sender, IForestryCommand command) { + public static void printHelp(ICommandSender sender, IForestryCommand command) { - String commandString = command.getFullCommandString().replace(" ", "."); + String commandString = command.getFullCommandString().replace(" ", "."); - ChatStyle header = new ChatStyle(); - header.setColor(EnumChatFormatting.BLUE); - sendLocalizedChatMessage(sender, header, "for.chat.command." + commandString + ".format", command.getFullCommandString()); + ChatStyle header = new ChatStyle(); + header.setColor(EnumChatFormatting.BLUE); + sendLocalizedChatMessage( + sender, header, "for.chat.command." + commandString + ".format", command.getFullCommandString()); - ChatStyle body = new ChatStyle(); - body.setColor(EnumChatFormatting.GRAY); + ChatStyle body = new ChatStyle(); + body.setColor(EnumChatFormatting.GRAY); - List commandAliases = command.getCommandAliases(); - if (commandAliases.size() > 0) { - sendLocalizedChatMessage(sender, body, "for.chat.command.aliases", commandAliases.toString().replace("[", "").replace("]", "")); - } + List commandAliases = command.getCommandAliases(); + if (commandAliases.size() > 0) { + sendLocalizedChatMessage( + sender, + body, + "for.chat.command.aliases", + commandAliases.toString().replace("[", "").replace("]", "")); + } - int permLevel = command.getPermissionLevel(); - if (permLevel > 0) { - sendLocalizedChatMessage(sender, body, "for.chat.command.permlevel", permLevel); - } + int permLevel = command.getPermissionLevel(); + if (permLevel > 0) { + sendLocalizedChatMessage(sender, body, "for.chat.command.permlevel", permLevel); + } - sendLocalizedChatMessage(sender, body, "for.chat.command." + commandString + ".help"); + sendLocalizedChatMessage(sender, body, "for.chat.command." + commandString + ".help"); - if (!command.getChildren().isEmpty()) { - sendLocalizedChatMessage(sender, "for.chat.command.list"); - for (SubCommand child : command.getChildren()) { - sendLocalizedChatMessage(sender, "for.chat.command." + child.getFullCommandString().replace(" ", ".") + ".desc", child.getCommandName()); - } - } - } + if (!command.getChildren().isEmpty()) { + sendLocalizedChatMessage(sender, "for.chat.command.list"); + for (SubCommand child : command.getChildren()) { + sendLocalizedChatMessage( + sender, + "for.chat.command." + child.getFullCommandString().replace(" ", ".") + ".desc", + child.getCommandName()); + } + } + } - public static boolean processStandardCommands(ICommandSender sender, IForestryCommand command, String[] args) { - if (args.length >= 1) { - if (args[0].equals("help")) { - command.printHelp(sender); - return true; - } - for (SubCommand child : command.getChildren()) { - if (matches(args[0], child)) { - processChildCommand(sender, child, args); - return true; - } - } - } - return false; - } + public static boolean processStandardCommands(ICommandSender sender, IForestryCommand command, String[] args) { + if (args.length >= 1) { + if (args[0].equals("help")) { + command.printHelp(sender); + return true; + } + for (SubCommand child : command.getChildren()) { + if (matches(args[0], child)) { + processChildCommand(sender, child, args); + return true; + } + } + } + return false; + } - public static boolean matches(String commandName, IForestryCommand command) { - if (commandName.equals(command.getCommandName())) { - return true; - } else if (command.getCommandAliases() != null) { - for (String alias : command.getCommandAliases()) { - if (commandName.equals(alias)) { - return true; - } - } - } - return false; - } + public static boolean matches(String commandName, IForestryCommand command) { + if (commandName.equals(command.getCommandName())) { + return true; + } else if (command.getCommandAliases() != null) { + for (String alias : command.getCommandAliases()) { + if (commandName.equals(alias)) { + return true; + } + } + } + return false; + } - @SuppressWarnings("unchecked") - public static List getListOfStringsMatchingLastWord(String[] strings, String... lastWords) { - return CommandBase.getListOfStringsMatchingLastWord(strings, lastWords); - } + @SuppressWarnings("unchecked") + public static List getListOfStringsMatchingLastWord(String[] strings, String... lastWords) { + return CommandBase.getListOfStringsMatchingLastWord(strings, lastWords); + } - public static List addStandardTabCompletionOptions(IForestryCommand command, ICommandSender sender, String[] incomplete) { - if (incomplete.length > 1) { - String commandName = incomplete[0]; - for (SubCommand child : command.getChildren()) { - if (CommandHelpers.matches(commandName, child)) { - String[] incompleteRemaining = Arrays.copyOfRange(incomplete, 1, incomplete.length); - return child.addTabCompletionOptions(sender, incompleteRemaining); - } - } - } + public static List addStandardTabCompletionOptions( + IForestryCommand command, ICommandSender sender, String[] incomplete) { + if (incomplete.length > 1) { + String commandName = incomplete[0]; + for (SubCommand child : command.getChildren()) { + if (CommandHelpers.matches(commandName, child)) { + String[] incompleteRemaining = Arrays.copyOfRange(incomplete, 1, incomplete.length); + return child.addTabCompletionOptions(sender, incompleteRemaining); + } + } + } - List commandNames = new ArrayList<>(); - for (SubCommand child : command.getChildren()) { - commandNames.add(child.getCommandName()); - } - commandNames.add("help"); - - String[] commandNamesArr = commandNames.toArray(new String[commandNames.size()]); - return CommandHelpers.getListOfStringsMatchingLastWord(incomplete, commandNamesArr); - } + List commandNames = new ArrayList<>(); + for (SubCommand child : command.getChildren()) { + commandNames.add(child.getCommandName()); + } + commandNames.add("help"); + String[] commandNamesArr = commandNames.toArray(new String[commandNames.size()]); + return CommandHelpers.getListOfStringsMatchingLastWord(incomplete, commandNamesArr); + } } diff --git a/src/main/java/forestry/core/commands/CommandMode.java b/src/main/java/forestry/core/commands/CommandMode.java index ee3c2cc16..98f6e1d0c 100644 --- a/src/main/java/forestry/core/commands/CommandMode.java +++ b/src/main/java/forestry/core/commands/CommandMode.java @@ -12,9 +12,9 @@ package forestry.core.commands; public class CommandMode extends SubCommand { - public CommandMode(ICommandModeHelper modeHelper) { - super("mode"); - addChildCommand(new CommandModeInfo(modeHelper)); - addChildCommand(new CommandModeSet(modeHelper)); - } + public CommandMode(ICommandModeHelper modeHelper) { + super("mode"); + addChildCommand(new CommandModeInfo(modeHelper)); + addChildCommand(new CommandModeSet(modeHelper)); + } } diff --git a/src/main/java/forestry/core/commands/CommandModeInfo.java b/src/main/java/forestry/core/commands/CommandModeInfo.java index 042638445..d3ef554d9 100644 --- a/src/main/java/forestry/core/commands/CommandModeInfo.java +++ b/src/main/java/forestry/core/commands/CommandModeInfo.java @@ -11,66 +11,65 @@ package forestry.core.commands; import java.util.List; - -import org.apache.commons.lang3.StringUtils; - import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; import net.minecraft.world.World; +import org.apache.commons.lang3.StringUtils; public class CommandModeInfo extends SubCommand { - private final String[] modeStringArr; - private final String helpString; - private final ICommandModeHelper modeHelper; + private final String[] modeStringArr; + private final String helpString; + private final ICommandModeHelper modeHelper; - public CommandModeInfo(ICommandModeHelper modeHelper) { - super("info"); + public CommandModeInfo(ICommandModeHelper modeHelper) { + super("info"); - this.modeHelper = modeHelper; - modeStringArr = modeHelper.getModeNames(); - helpString = StringUtils.join(modeStringArr, ", "); - } + this.modeHelper = modeHelper; + modeStringArr = modeHelper.getModeNames(); + helpString = StringUtils.join(modeStringArr, ", "); + } - @Override - public void processSubCommand(ICommandSender sender, String[] args) { - if (args.length <= 0) { - printHelp(sender); - return; - } + @Override + public void processSubCommand(ICommandSender sender, String[] args) { + if (args.length <= 0) { + printHelp(sender); + return; + } - String modeName = modeHelper.getModeNameMatching(args[0]); + String modeName = modeHelper.getModeNameMatching(args[0]); - if (modeName == null) { - CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.mode.info.error", args[0]); - printHelp(sender); - return; - } + if (modeName == null) { + CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.mode.info.error", args[0]); + printHelp(sender); + return; + } - ChatStyle green = new ChatStyle(); - green.setColor(EnumChatFormatting.GREEN); - CommandHelpers.sendLocalizedChatMessage(sender, green, modeName); + ChatStyle green = new ChatStyle(); + green.setColor(EnumChatFormatting.GREEN); + CommandHelpers.sendLocalizedChatMessage(sender, green, modeName); - for (String desc : modeHelper.getDescription(modeName)) { - CommandHelpers.sendLocalizedChatMessage(sender, "for." + desc); - } - } + for (String desc : modeHelper.getDescription(modeName)) { + CommandHelpers.sendLocalizedChatMessage(sender, "for." + desc); + } + } - @Override - public void printHelp(ICommandSender sender) { - super.printHelp(sender); + @Override + public void printHelp(ICommandSender sender) { + super.printHelp(sender); - World world = CommandHelpers.getWorld(sender, this); + World world = CommandHelpers.getWorld(sender, this); - String modeName = modeHelper.getModeName(world); - String worldName = String.valueOf(world.getWorldInfo().getSaveVersion()); + String modeName = modeHelper.getModeName(world); + String worldName = String.valueOf(world.getWorldInfo().getSaveVersion()); - CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.mode.info.current", modeName, worldName); - CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.mode.info.available", helpString); - } + CommandHelpers.sendLocalizedChatMessage( + sender, "for.chat.command.forestry.mode.info.current", modeName, worldName); + CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.mode.info.available", helpString); + } - @Override - public List addTabCompletionOptions(ICommandSender sender, String[] incomplete) { - return CommandHelpers.getListOfStringsMatchingLastWord(incomplete, modeStringArr); - } + @Override + public List addTabCompletionOptions(ICommandSender sender, String[] incomplete) { + return CommandHelpers.getListOfStringsMatchingLastWord(incomplete, modeStringArr); + } } diff --git a/src/main/java/forestry/core/commands/CommandModeSet.java b/src/main/java/forestry/core/commands/CommandModeSet.java index 42198a64c..5beaff5df 100644 --- a/src/main/java/forestry/core/commands/CommandModeSet.java +++ b/src/main/java/forestry/core/commands/CommandModeSet.java @@ -11,52 +11,50 @@ package forestry.core.commands; import java.util.List; - import net.minecraft.command.ICommandSender; import net.minecraft.world.World; public final class CommandModeSet extends SubCommand { - private final String[] modeStringArr; - private final ICommandModeHelper modeSetter; + private final String[] modeStringArr; + private final ICommandModeHelper modeSetter; - public CommandModeSet(ICommandModeHelper modeSetter) { - super("set"); - setPermLevel(PermLevel.ADMIN); + public CommandModeSet(ICommandModeHelper modeSetter) { + super("set"); + setPermLevel(PermLevel.ADMIN); - this.modeSetter = modeSetter; - modeStringArr = modeSetter.getModeNames(); + this.modeSetter = modeSetter; + modeStringArr = modeSetter.getModeNames(); + } - } + @Override + public void processSubCommand(ICommandSender sender, String[] args) { + if (args.length == 0 || args.length > 2) { + printHelp(sender); + return; + } - @Override - public void processSubCommand(ICommandSender sender, String[] args) { - if (args.length == 0 || args.length > 2) { - printHelp(sender); - return; - } + World world; + if (args.length == 2) { + world = CommandHelpers.getWorld(sender, this, args, 0); + } else { + world = CommandHelpers.getWorld(sender, this); + } - World world; - if (args.length == 2) { - world = CommandHelpers.getWorld(sender, this, args, 0); - } else { - world = CommandHelpers.getWorld(sender, this); - } + String desired = args[args.length - 1]; - String desired = args[args.length - 1]; + String modeName = modeSetter.getModeNameMatching(desired); + if (modeName == null) { + CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.mode.set.error", desired); + printHelp(sender); + return; + } - String modeName = modeSetter.getModeNameMatching(desired); - if (modeName == null) { - CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.mode.set.error", desired); - printHelp(sender); - return; - } + modeSetter.setMode(world, modeName); + CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.mode.set.success", modeName); + } - modeSetter.setMode(world, modeName); - CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.mode.set.success", modeName); - } - - @Override - public List addTabCompletionOptions(ICommandSender sender, String[] incomplete) { - return CommandHelpers.getListOfStringsMatchingLastWord(incomplete, modeStringArr); - } + @Override + public List addTabCompletionOptions(ICommandSender sender, String[] incomplete) { + return CommandHelpers.getListOfStringsMatchingLastWord(incomplete, modeStringArr); + } } diff --git a/src/main/java/forestry/core/commands/CommandPlugins.java b/src/main/java/forestry/core/commands/CommandPlugins.java index f46e4b943..2e881583c 100644 --- a/src/main/java/forestry/core/commands/CommandPlugins.java +++ b/src/main/java/forestry/core/commands/CommandPlugins.java @@ -10,118 +10,115 @@ ******************************************************************************/ package forestry.core.commands; -import net.minecraft.command.CommandException; -import net.minecraft.command.ICommandSender; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.StatCollector; - import forestry.core.utils.StringUtil; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; import forestry.plugins.PluginManager; +import net.minecraft.command.CommandException; +import net.minecraft.command.ICommandSender; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.StatCollector; /** * @author CovertJaguar */ public class CommandPlugins extends SubCommand { - public CommandPlugins() { - super("plugins"); - addAlias("plug"); - addChildCommand(new CommandPluginsInfo()); - } + public CommandPlugins() { + super("plugins"); + addAlias("plug"); + addChildCommand(new CommandPluginsInfo()); + } - @Override - public void processSubCommand(ICommandSender sender, String[] args) { - if (args.length == 0) { - listPluginsForSender(sender); - } else { - CommandHelpers.throwWrongUsage(sender, this); - } - } + @Override + public void processSubCommand(ICommandSender sender, String[] args) { + if (args.length == 0) { + listPluginsForSender(sender); + } else { + CommandHelpers.throwWrongUsage(sender, this); + } + } - private static void listPluginsForSender(ICommandSender sender) { - StringBuilder pluginList = new StringBuilder(); - for (PluginManager.Module pluginModule : PluginManager.getLoadedModules()) { - if (pluginList.length() > 0) { - pluginList.append(", "); - } - pluginList.append(makeListEntry(pluginModule.instance())); - } - CommandHelpers.sendChatMessage(sender, pluginList.toString()); - } + private static void listPluginsForSender(ICommandSender sender) { + StringBuilder pluginList = new StringBuilder(); + for (PluginManager.Module pluginModule : PluginManager.getLoadedModules()) { + if (pluginList.length() > 0) { + pluginList.append(", "); + } + pluginList.append(makeListEntry(pluginModule.instance())); + } + CommandHelpers.sendChatMessage(sender, pluginList.toString()); + } - private static String makeListEntry(ForestryPlugin plugin) { - String entry = plugin.isAvailable() ? EnumChatFormatting.GREEN.toString() : EnumChatFormatting.RED.toString(); + private static String makeListEntry(ForestryPlugin plugin) { + String entry = plugin.isAvailable() ? EnumChatFormatting.GREEN.toString() : EnumChatFormatting.RED.toString(); - Plugin info = plugin.getClass().getAnnotation(Plugin.class); - if (info != null) { - entry += info.pluginID(); - if (!info.version().isEmpty()) { - entry += " (" + info.version() + ")"; - } - } else { - entry += "???"; - } + Plugin info = plugin.getClass().getAnnotation(Plugin.class); + if (info != null) { + entry += info.pluginID(); + if (!info.version().isEmpty()) { + entry += " (" + info.version() + ")"; + } + } else { + entry += "???"; + } - return entry; - } + return entry; + } - public static class CommandPluginsInfo extends SubCommand { + public static class CommandPluginsInfo extends SubCommand { - public CommandPluginsInfo() { - super("info"); - addAlias("i"); - } + public CommandPluginsInfo() { + super("info"); + addAlias("i"); + } - @Override - public void processSubCommand(ICommandSender sender, String[] args) { - if (args.length == 1) { - listPluginInfoForSender(sender, args[0]); - } else { - CommandHelpers.throwWrongUsage(sender, this); - } - } + @Override + public void processSubCommand(ICommandSender sender, String[] args) { + if (args.length == 1) { + listPluginInfoForSender(sender, args[0]); + } else { + CommandHelpers.throwWrongUsage(sender, this); + } + } - private static void listPluginInfoForSender(ICommandSender sender, String plugin) { - ForestryPlugin found = null; - for (PluginManager.Module pluginModule : PluginManager.getLoadedModules()) { - Plugin info = pluginModule.instance().getClass().getAnnotation(Plugin.class); - if (info == null) { - continue; - } + private static void listPluginInfoForSender(ICommandSender sender, String plugin) { + ForestryPlugin found = null; + for (PluginManager.Module pluginModule : PluginManager.getLoadedModules()) { + Plugin info = pluginModule.instance().getClass().getAnnotation(Plugin.class); + if (info == null) { + continue; + } - if ((info.pluginID().equalsIgnoreCase(plugin) || info.name().equalsIgnoreCase(plugin))) { - found = pluginModule.instance(); - break; - } - } + if ((info.pluginID().equalsIgnoreCase(plugin) || info.name().equalsIgnoreCase(plugin))) { + found = pluginModule.instance(); + break; + } + } - if (found == null) { - throw new CommandException(StringUtil.localizeAndFormat("chat.plugins.error", plugin)); - } + if (found == null) { + throw new CommandException(StringUtil.localizeAndFormat("chat.plugins.error", plugin)); + } - EnumChatFormatting formatting = found.isAvailable() ? EnumChatFormatting.GREEN : EnumChatFormatting.RED; - - Plugin info = found.getClass().getAnnotation(Plugin.class); - if (info != null) { - CommandHelpers.sendChatMessage(sender, formatting + "Plugin: " + info.name()); - if (!info.version().isEmpty()) { - CommandHelpers.sendChatMessage(sender, EnumChatFormatting.BLUE + "Version: " + info.version()); - } - if (!info.author().isEmpty()) { - CommandHelpers.sendChatMessage(sender, EnumChatFormatting.BLUE + "Author(s): " + info.author()); - } - if (!info.url().isEmpty()) { - CommandHelpers.sendChatMessage(sender, EnumChatFormatting.BLUE + "URL: " + info.url()); - } - if (!info.unlocalizedDescription().isEmpty()) { - CommandHelpers.sendChatMessage(sender, StatCollector.translateToLocal(info.unlocalizedDescription())); - } - } - - } - - } + EnumChatFormatting formatting = found.isAvailable() ? EnumChatFormatting.GREEN : EnumChatFormatting.RED; + Plugin info = found.getClass().getAnnotation(Plugin.class); + if (info != null) { + CommandHelpers.sendChatMessage(sender, formatting + "Plugin: " + info.name()); + if (!info.version().isEmpty()) { + CommandHelpers.sendChatMessage(sender, EnumChatFormatting.BLUE + "Version: " + info.version()); + } + if (!info.author().isEmpty()) { + CommandHelpers.sendChatMessage(sender, EnumChatFormatting.BLUE + "Author(s): " + info.author()); + } + if (!info.url().isEmpty()) { + CommandHelpers.sendChatMessage(sender, EnumChatFormatting.BLUE + "URL: " + info.url()); + } + if (!info.unlocalizedDescription().isEmpty()) { + CommandHelpers.sendChatMessage( + sender, StatCollector.translateToLocal(info.unlocalizedDescription())); + } + } + } + } } diff --git a/src/main/java/forestry/core/commands/CommandSaveStats.java b/src/main/java/forestry/core/commands/CommandSaveStats.java index e3a0810f0..377d2fdfd 100644 --- a/src/main/java/forestry/core/commands/CommandSaveStats.java +++ b/src/main/java/forestry/core/commands/CommandSaveStats.java @@ -10,6 +10,13 @@ ******************************************************************************/ package forestry.core.commands; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAlleleSpecies; +import forestry.api.genetics.IBreedingTracker; +import forestry.core.config.Constants; +import forestry.core.config.Version; +import forestry.core.proxy.Proxies; +import forestry.core.utils.StringUtil; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; @@ -21,167 +28,177 @@ import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Locale; - import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAlleleSpecies; -import forestry.api.genetics.IBreedingTracker; -import forestry.core.config.Constants; -import forestry.core.config.Version; -import forestry.core.proxy.Proxies; -import forestry.core.utils.StringUtil; - public final class CommandSaveStats extends SubCommand { - private static final String discoveredSymbol; - private static final String blacklistedSymbol; - private static final String notCountedSymbol; + private static final String discoveredSymbol; + private static final String blacklistedSymbol; + private static final String notCountedSymbol; - static { - discoveredSymbol = StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.discovered.symbol"); - blacklistedSymbol = StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.blacklisted.symbol"); - notCountedSymbol = StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.notCounted.symbol"); - } + static { + discoveredSymbol = StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.discovered.symbol"); + blacklistedSymbol = + StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.blacklisted.symbol"); + notCountedSymbol = StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.notCounted.symbol"); + } - private final IStatsSaveHelper saveHelper; - private final ICommandModeHelper modeHelper; + private final IStatsSaveHelper saveHelper; + private final ICommandModeHelper modeHelper; - public CommandSaveStats(IStatsSaveHelper saveHelper, ICommandModeHelper modeHelper) { - super("save"); - this.saveHelper = saveHelper; - this.modeHelper = modeHelper; - } + public CommandSaveStats(IStatsSaveHelper saveHelper, ICommandModeHelper modeHelper) { + super("save"); + this.saveHelper = saveHelper; + this.modeHelper = modeHelper; + } - @Override - public List addTabCompletionOptions(ICommandSender sender, String[] parameters) { - return CommandHelpers.getListOfStringsMatchingLastWord(parameters, CommandHelpers.getPlayers()); - } + @Override + public List addTabCompletionOptions(ICommandSender sender, String[] parameters) { + return CommandHelpers.getListOfStringsMatchingLastWord(parameters, CommandHelpers.getPlayers()); + } - @Override - public void processSubCommand(ICommandSender sender, String[] args) { - if (args.length > 1) { - printHelp(sender); - return; - } + @Override + public void processSubCommand(ICommandSender sender, String[] args) { + if (args.length > 1) { + printHelp(sender); + return; + } - String newLine = System.getProperty("line.separator"); - World world = CommandHelpers.getWorld(sender, this); + String newLine = System.getProperty("line.separator"); + World world = CommandHelpers.getWorld(sender, this); - EntityPlayerMP player; - if (args.length > 0) { - player = CommandHelpers.getPlayer(sender, args[0]); - } else { - player = CommandHelpers.getPlayer(sender, sender.getCommandSenderName()); - } + EntityPlayerMP player; + if (args.length > 0) { + player = CommandHelpers.getPlayer(sender, args[0]); + } else { + player = CommandHelpers.getPlayer(sender, sender.getCommandSenderName()); + } - Collection statistics = new ArrayList<>(); + Collection statistics = new ArrayList<>(); - String date = DateFormat.getInstance().format(new Date()); - statistics.add(StatCollector.translateToLocalFormatted(saveHelper.getUnlocalizedSaveStatsString(), player.getDisplayName(), date)); - statistics.add(""); - statistics.add(StatCollector.translateToLocalFormatted("for.chat.command.forestry.stats.save.mode", modeHelper.getModeName(world))); - statistics.add(""); + String date = DateFormat.getInstance().format(new Date()); + statistics.add(StatCollector.translateToLocalFormatted( + saveHelper.getUnlocalizedSaveStatsString(), player.getDisplayName(), date)); + statistics.add(""); + statistics.add(StatCollector.translateToLocalFormatted( + "for.chat.command.forestry.stats.save.mode", modeHelper.getModeName(world))); + statistics.add(""); - IBreedingTracker tracker = saveHelper.getBreedingTracker(world, player.getGameProfile()); - if (tracker == null) { - statistics.add(StatCollector.translateToLocal("for.chat.command.forestry.stats.save.error4")); - } else { - saveHelper.addExtraInfo(statistics, tracker); + IBreedingTracker tracker = saveHelper.getBreedingTracker(world, player.getGameProfile()); + if (tracker == null) { + statistics.add(StatCollector.translateToLocal("for.chat.command.forestry.stats.save.error4")); + } else { + saveHelper.addExtraInfo(statistics, tracker); - Collection species = saveHelper.getSpecies(); + Collection species = saveHelper.getSpecies(); - String speciesCount = StatCollector.translateToLocal("for.gui.speciescount"); - String speciesCountLine = String.format("%s (%s):", speciesCount, species.size()); - statistics.add(speciesCountLine); - statistics.add(StringUtil.line(speciesCountLine.length())); + String speciesCount = StatCollector.translateToLocal("for.gui.speciescount"); + String speciesCountLine = String.format("%s (%s):", speciesCount, species.size()); + statistics.add(speciesCountLine); + statistics.add(StringUtil.line(speciesCountLine.length())); - statistics.add(discoveredSymbol + ": " + StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.discovered")); - statistics.add(blacklistedSymbol + ": " + StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.blacklisted")); - statistics.add(notCountedSymbol + ": " + StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.notCounted")); - statistics.add(""); + statistics.add(discoveredSymbol + ": " + + StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.discovered")); + statistics.add(blacklistedSymbol + ": " + + StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.blacklisted")); + statistics.add(notCountedSymbol + ": " + + StatCollector.translateToLocal("for.chat.command.forestry.stats.save.key.notCounted")); + statistics.add(""); - String header = generateSpeciesListHeader(); - statistics.add(header); + String header = generateSpeciesListHeader(); + statistics.add(header); - statistics.add(StringUtil.line(header.length())); - statistics.add(""); + statistics.add(StringUtil.line(header.length())); + statistics.add(""); - for (IAlleleSpecies allele : species) { - statistics.add(generateSpeciesListEntry(allele, tracker)); - } - } + for (IAlleleSpecies allele : species) { + statistics.add(generateSpeciesListEntry(allele, tracker)); + } + } - File file = new File(Proxies.common.getForestryRoot(), "config/" + Constants.MOD.toLowerCase(Locale.ENGLISH) + "/stats/" + player.getDisplayName() + '-' + saveHelper.getFileSuffix() + ".log"); - try { - File folder = file.getParentFile(); - if (folder != null && !folder.exists()) { - boolean success = file.getParentFile().mkdirs(); - if (!success) { - CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.stats.save.error1"); - return; - } - } + File file = new File( + Proxies.common.getForestryRoot(), + "config/" + Constants.MOD.toLowerCase(Locale.ENGLISH) + "/stats/" + player.getDisplayName() + '-' + + saveHelper.getFileSuffix() + ".log"); + try { + File folder = file.getParentFile(); + if (folder != null && !folder.exists()) { + boolean success = file.getParentFile().mkdirs(); + if (!success) { + CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.stats.save.error1"); + return; + } + } - if (!file.exists() && !file.createNewFile()) { - CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.stats.save.error1"); - return; - } + if (!file.exists() && !file.createNewFile()) { + CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.stats.save.error1"); + return; + } - if (!file.canWrite()) { - CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.stats.save.error2"); - return; - } + if (!file.canWrite()) { + CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.stats.save.error2"); + return; + } - FileOutputStream fileout = new FileOutputStream(file); - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fileout, "UTF-8")); + FileOutputStream fileout = new FileOutputStream(file); + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fileout, "UTF-8")); - writer.write("# " + Constants.MOD + newLine + "# " + Version.getVersion() + newLine); + writer.write("# " + Constants.MOD + newLine + "# " + Version.getVersion() + newLine); - for (String line : statistics) { - writer.write(line + newLine); - } + for (String line : statistics) { + writer.write(line + newLine); + } - writer.close(); + writer.close(); - } catch (IOException ex) { - CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.stats.save.error3"); - ex.printStackTrace(); - return; - } + } catch (IOException ex) { + CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.stats.save.error3"); + ex.printStackTrace(); + return; + } - CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.stats.save.saved", player.getDisplayName()); - } + CommandHelpers.sendLocalizedChatMessage( + sender, "for.chat.command.forestry.stats.save.saved", player.getDisplayName()); + } - private static String generateSpeciesListHeader() { - String authority = StatCollector.translateToLocal("for.gui.alyzer.authority"); - String species = StatCollector.translateToLocal("for.gui.species"); - return speciesListEntry(discoveredSymbol, blacklistedSymbol, notCountedSymbol, "UID", species, authority); - } + private static String generateSpeciesListHeader() { + String authority = StatCollector.translateToLocal("for.gui.alyzer.authority"); + String species = StatCollector.translateToLocal("for.gui.species"); + return speciesListEntry(discoveredSymbol, blacklistedSymbol, notCountedSymbol, "UID", species, authority); + } - private static String generateSpeciesListEntry(IAlleleSpecies species, IBreedingTracker tracker) { - String discovered = ""; - if (tracker.isDiscovered(species)) { - discovered = discoveredSymbol; - } + private static String generateSpeciesListEntry(IAlleleSpecies species, IBreedingTracker tracker) { + String discovered = ""; + if (tracker.isDiscovered(species)) { + discovered = discoveredSymbol; + } - String blacklisted = ""; - if (AlleleManager.alleleRegistry.isBlacklisted(species.getUID())) { - blacklisted = blacklistedSymbol; - } + String blacklisted = ""; + if (AlleleManager.alleleRegistry.isBlacklisted(species.getUID())) { + blacklisted = blacklistedSymbol; + } - String notCounted = ""; - if (!species.isCounted()) { - notCounted = notCountedSymbol; - } + String notCounted = ""; + if (!species.isCounted()) { + notCounted = notCountedSymbol; + } - return speciesListEntry(discovered, blacklisted, notCounted, species.getUID(), species.getName(), species.getAuthority()); - } + return speciesListEntry( + discovered, blacklisted, notCounted, species.getUID(), species.getName(), species.getAuthority()); + } - private static String speciesListEntry(String discovered, String blacklisted, String notCounted, String UID, String speciesName, String authority) { - return String.format("[ %-2s ] [ %-2s ] [ %-2s ]\t%-40s %-20s %-20s", discovered, blacklisted, notCounted, UID, speciesName, authority); - } + private static String speciesListEntry( + String discovered, + String blacklisted, + String notCounted, + String UID, + String speciesName, + String authority) { + return String.format( + "[ %-2s ] [ %-2s ] [ %-2s ]\t%-40s %-20s %-20s", + discovered, blacklisted, notCounted, UID, speciesName, authority); + } } diff --git a/src/main/java/forestry/core/commands/CommandVersion.java b/src/main/java/forestry/core/commands/CommandVersion.java index bbe6362e6..6089ac2e3 100644 --- a/src/main/java/forestry/core/commands/CommandVersion.java +++ b/src/main/java/forestry/core/commands/CommandVersion.java @@ -10,37 +10,41 @@ ******************************************************************************/ package forestry.core.commands; +import forestry.core.config.Version; +import forestry.core.proxy.Proxies; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; -import forestry.core.config.Version; -import forestry.core.proxy.Proxies; - /** * @author CovertJaguar */ public class CommandVersion extends SubCommand { - public CommandVersion() { - super("version"); - } + public CommandVersion() { + super("version"); + } - @Override - public void processSubCommand(ICommandSender sender, String[] args) { - ChatStyle style = new ChatStyle(); - if (Version.isOutdated()) { - style.setColor(EnumChatFormatting.RED); - } else { - style.setColor(EnumChatFormatting.GREEN); - } - - CommandHelpers.sendLocalizedChatMessage(sender, style, "for.chat.version", Version.getVersion(), Proxies.common.getMinecraftVersion(), Version.getRecommendedVersion()); - if (Version.isOutdated()) { - for (String updateLine : Version.getChangelog()) { - CommandHelpers.sendChatMessage(sender, EnumChatFormatting.BLUE + updateLine); - } - } - } + @Override + public void processSubCommand(ICommandSender sender, String[] args) { + ChatStyle style = new ChatStyle(); + if (Version.isOutdated()) { + style.setColor(EnumChatFormatting.RED); + } else { + style.setColor(EnumChatFormatting.GREEN); + } + CommandHelpers.sendLocalizedChatMessage( + sender, + style, + "for.chat.version", + Version.getVersion(), + Proxies.common.getMinecraftVersion(), + Version.getRecommendedVersion()); + if (Version.isOutdated()) { + for (String updateLine : Version.getChangelog()) { + CommandHelpers.sendChatMessage(sender, EnumChatFormatting.BLUE + updateLine); + } + } + } } diff --git a/src/main/java/forestry/core/commands/ICommandModeHelper.java b/src/main/java/forestry/core/commands/ICommandModeHelper.java index a2b9e6569..0728ebc43 100644 --- a/src/main/java/forestry/core/commands/ICommandModeHelper.java +++ b/src/main/java/forestry/core/commands/ICommandModeHelper.java @@ -13,13 +13,13 @@ package forestry.core.commands; import net.minecraft.world.World; public interface ICommandModeHelper { - String[] getModeNames(); + String[] getModeNames(); - String getModeNameMatching(String desired); + String getModeNameMatching(String desired); - String getModeName(World world); + String getModeName(World world); - void setMode(World world, String modeName); + void setMode(World world, String modeName); - Iterable getDescription(String modeName); + Iterable getDescription(String modeName); } diff --git a/src/main/java/forestry/core/commands/IForestryCommand.java b/src/main/java/forestry/core/commands/IForestryCommand.java index 81238313a..f6f46625b 100644 --- a/src/main/java/forestry/core/commands/IForestryCommand.java +++ b/src/main/java/forestry/core/commands/IForestryCommand.java @@ -12,7 +12,6 @@ package forestry.core.commands; import java.util.List; import java.util.SortedSet; - import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; @@ -21,14 +20,14 @@ import net.minecraft.command.ICommandSender; */ public interface IForestryCommand extends ICommand { - String getFullCommandString(); + String getFullCommandString(); - @Override - List getCommandAliases(); + @Override + List getCommandAliases(); - int getPermissionLevel(); + int getPermissionLevel(); - SortedSet getChildren(); + SortedSet getChildren(); - void printHelp(ICommandSender sender); + void printHelp(ICommandSender sender); } diff --git a/src/main/java/forestry/core/commands/IStatsSaveHelper.java b/src/main/java/forestry/core/commands/IStatsSaveHelper.java index 192b26b3c..e8699a616 100644 --- a/src/main/java/forestry/core/commands/IStatsSaveHelper.java +++ b/src/main/java/forestry/core/commands/IStatsSaveHelper.java @@ -10,24 +10,21 @@ ******************************************************************************/ package forestry.core.commands; -import java.util.Collection; - -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IBreedingTracker; +import java.util.Collection; +import net.minecraft.world.World; public interface IStatsSaveHelper { - String getUnlocalizedSaveStatsString(); + String getUnlocalizedSaveStatsString(); - void addExtraInfo(Collection statistics, IBreedingTracker breedingTracker); + void addExtraInfo(Collection statistics, IBreedingTracker breedingTracker); - Collection getSpecies(); + Collection getSpecies(); - String getFileSuffix(); + String getFileSuffix(); - IBreedingTracker getBreedingTracker(World world, GameProfile gameProfile); + IBreedingTracker getBreedingTracker(World world, GameProfile gameProfile); } diff --git a/src/main/java/forestry/core/commands/RootCommand.java b/src/main/java/forestry/core/commands/RootCommand.java index bc4d02fd0..e6adc32aa 100644 --- a/src/main/java/forestry/core/commands/RootCommand.java +++ b/src/main/java/forestry/core/commands/RootCommand.java @@ -15,7 +15,6 @@ import java.util.Comparator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; - import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; @@ -24,82 +23,81 @@ import net.minecraft.command.ICommandSender; */ public class RootCommand extends CommandBase implements IForestryCommand { - public static final String ROOT_COMMAND_NAME = "forestry"; - public static final String ROOT_COMMAND_ALIAS = "for"; + public static final String ROOT_COMMAND_NAME = "forestry"; + public static final String ROOT_COMMAND_ALIAS = "for"; - private final SortedSet children = new TreeSet<>(new Comparator() { + private final SortedSet children = new TreeSet<>(new Comparator() { - @Override - public int compare(SubCommand o1, SubCommand o2) { - return o1.compareTo(o2); - } - }); + @Override + public int compare(SubCommand o1, SubCommand o2) { + return o1.compareTo(o2); + } + }); - public void addChildCommand(SubCommand child) { - child.setParent(this); - children.add(child); - } + public void addChildCommand(SubCommand child) { + child.setParent(this); + children.add(child); + } - /* CommandBase */ + /* CommandBase */ - @Override - public String getCommandName() { - return ROOT_COMMAND_NAME; - } + @Override + public String getCommandName() { + return ROOT_COMMAND_NAME; + } - @Override - public String getCommandUsage(ICommandSender sender) { - return "/" + this.getCommandName() + " help"; - } + @Override + public String getCommandUsage(ICommandSender sender) { + return "/" + this.getCommandName() + " help"; + } - @Override - public void processCommand(ICommandSender sender, String[] args) { - if (!CommandHelpers.processStandardCommands(sender, this, args)) { - CommandHelpers.throwWrongUsage(sender, this); - } - } + @Override + public void processCommand(ICommandSender sender, String[] args) { + if (!CommandHelpers.processStandardCommands(sender, this, args)) { + CommandHelpers.throwWrongUsage(sender, this); + } + } - /** - * Used only for CommandBase. - * It gets obfuscated, so the name needs to be different from the one in IForestryCommand. - */ - @Override - public int getRequiredPermissionLevel() { - return getPermissionLevel(); - } + /** + * Used only for CommandBase. + * It gets obfuscated, so the name needs to be different from the one in IForestryCommand. + */ + @Override + public int getRequiredPermissionLevel() { + return getPermissionLevel(); + } - @Override - public List getCommandAliases() { - List aliases = new ArrayList<>(); - aliases.add(ROOT_COMMAND_ALIAS); - return aliases; - } + @Override + public List getCommandAliases() { + List aliases = new ArrayList<>(); + aliases.add(ROOT_COMMAND_ALIAS); + return aliases; + } - @Override - public List addTabCompletionOptions(ICommandSender sender, String[] incomplete) { - return CommandHelpers.addStandardTabCompletionOptions(this, sender, incomplete); - } + @Override + public List addTabCompletionOptions(ICommandSender sender, String[] incomplete) { + return CommandHelpers.addStandardTabCompletionOptions(this, sender, incomplete); + } - /* IForestryCommand */ + /* IForestryCommand */ - @Override - public String getFullCommandString() { - return getCommandName(); - } + @Override + public String getFullCommandString() { + return getCommandName(); + } - @Override - public int getPermissionLevel() { - return 0; - } + @Override + public int getPermissionLevel() { + return 0; + } - @Override - public SortedSet getChildren() { - return children; - } - - @Override - public void printHelp(ICommandSender sender) { - CommandHelpers.printHelp(sender, this); - } + @Override + public SortedSet getChildren() { + return children; + } + @Override + public void printHelp(ICommandSender sender) { + CommandHelpers.printHelp(sender, this); + } } diff --git a/src/main/java/forestry/core/commands/SpeciesNotFoundException.java b/src/main/java/forestry/core/commands/SpeciesNotFoundException.java index c065f249b..c309b2b5c 100644 --- a/src/main/java/forestry/core/commands/SpeciesNotFoundException.java +++ b/src/main/java/forestry/core/commands/SpeciesNotFoundException.java @@ -14,10 +14,9 @@ import net.minecraft.command.CommandException; public class SpeciesNotFoundException extends CommandException { - private static final long serialVersionUID = 1L; - - public SpeciesNotFoundException(String title) { - super("Could not find species with Name or UID %s", title); - } + private static final long serialVersionUID = 1L; + public SpeciesNotFoundException(String title) { + super("Could not find species with Name or UID %s", title); + } } diff --git a/src/main/java/forestry/core/commands/SubCommand.java b/src/main/java/forestry/core/commands/SubCommand.java index d16d58565..a88452feb 100644 --- a/src/main/java/forestry/core/commands/SubCommand.java +++ b/src/main/java/forestry/core/commands/SubCommand.java @@ -10,13 +10,12 @@ ******************************************************************************/ package forestry.core.commands; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; - +import javax.annotation.Nonnull; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; @@ -25,120 +24,118 @@ import net.minecraft.command.ICommandSender; */ public abstract class SubCommand implements IForestryCommand { - public enum PermLevel { + public enum PermLevel { + EVERYONE(0), + ADMIN(2); + public final int permLevel; - EVERYONE(0), ADMIN(2); - public final int permLevel; + PermLevel(int permLevel) { + this.permLevel = permLevel; + } + } - PermLevel(int permLevel) { - this.permLevel = permLevel; - } + private final String name; + private final List aliases = new ArrayList<>(); + private PermLevel permLevel = PermLevel.EVERYONE; + private IForestryCommand parent; + private final SortedSet children = new TreeSet<>(new Comparator() { - } + @Override + public int compare(SubCommand o1, SubCommand o2) { + return o1.compareTo(o2); + } + }); - private final String name; - private final List aliases = new ArrayList<>(); - private PermLevel permLevel = PermLevel.EVERYONE; - private IForestryCommand parent; - private final SortedSet children = new TreeSet<>(new Comparator() { + public SubCommand(String name) { + this.name = name; + } - @Override - public int compare(SubCommand o1, SubCommand o2) { - return o1.compareTo(o2); - } - }); + @Override + public final String getCommandName() { + return name; + } - public SubCommand(String name) { - this.name = name; - } + public SubCommand addChildCommand(SubCommand child) { + child.setParent(this); + children.add(child); + return this; + } - @Override - public final String getCommandName() { - return name; - } + void setParent(IForestryCommand parent) { + this.parent = parent; + } - public SubCommand addChildCommand(SubCommand child) { - child.setParent(this); - children.add(child); - return this; - } + @Override + public SortedSet getChildren() { + return children; + } - void setParent(IForestryCommand parent) { - this.parent = parent; - } + public void addAlias(String alias) { + aliases.add(alias); + } - @Override - public SortedSet getChildren() { - return children; - } + @Override + public List getCommandAliases() { + return aliases; + } - public void addAlias(String alias) { - aliases.add(alias); - } + @Override + public List addTabCompletionOptions(ICommandSender sender, String[] incomplete) { + return CommandHelpers.addStandardTabCompletionOptions(this, sender, incomplete); + } - @Override - public List getCommandAliases() { - return aliases; - } + @Override + public final void processCommand(ICommandSender sender, String[] args) { + if (!CommandHelpers.processStandardCommands(sender, this, args)) { + processSubCommand(sender, args); + } + } - @Override - public List addTabCompletionOptions(ICommandSender sender, String[] incomplete) { - return CommandHelpers.addStandardTabCompletionOptions(this, sender, incomplete); - } + public void processSubCommand(ICommandSender sender, String[] args) { + printHelp(sender); + } - @Override - public final void processCommand(ICommandSender sender, String[] args) { - if (!CommandHelpers.processStandardCommands(sender, this, args)) { - processSubCommand(sender, args); - } - } + public SubCommand setPermLevel(PermLevel permLevel) { + this.permLevel = permLevel; + return this; + } - public void processSubCommand(ICommandSender sender, String[] args) { - printHelp(sender); - } + @Override + public final int getPermissionLevel() { + return permLevel.permLevel; + } - public SubCommand setPermLevel(PermLevel permLevel) { - this.permLevel = permLevel; - return this; - } + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return sender.canCommandSenderUseCommand(getPermissionLevel(), getCommandName()); + } - @Override - public final int getPermissionLevel() { - return permLevel.permLevel; - } + @Override + public boolean isUsernameIndex(String[] args, int index) { + return false; + } - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender) { - return sender.canCommandSenderUseCommand(getPermissionLevel(), getCommandName()); - } + @Override + public String getCommandUsage(ICommandSender sender) { + return "/" + getFullCommandString() + " help"; + } - @Override - public boolean isUsernameIndex(String[] args, int index) { - return false; - } + @Override + public void printHelp(ICommandSender sender) { + CommandHelpers.printHelp(sender, this); + } - @Override - public String getCommandUsage(ICommandSender sender) { - return "/" + getFullCommandString() + " help"; - } + @Override + public String getFullCommandString() { + return parent.getFullCommandString() + " " + getCommandName(); + } - @Override - public void printHelp(ICommandSender sender) { - CommandHelpers.printHelp(sender, this); - } - - @Override - public String getFullCommandString() { - return parent.getFullCommandString() + " " + getCommandName(); - } - - public int compareTo(ICommand command) { - return this.getCommandName().compareTo(command.getCommandName()); - } - - @Override - public int compareTo(@Nonnull Object command) { - return this.compareTo((ICommand) command); - } + public int compareTo(ICommand command) { + return this.getCommandName().compareTo(command.getCommandName()); + } + @Override + public int compareTo(@Nonnull Object command) { + return this.compareTo((ICommand) command); + } } diff --git a/src/main/java/forestry/core/commands/TemplateNotFoundException.java b/src/main/java/forestry/core/commands/TemplateNotFoundException.java index 92b66dc0a..c18e2f49c 100644 --- a/src/main/java/forestry/core/commands/TemplateNotFoundException.java +++ b/src/main/java/forestry/core/commands/TemplateNotFoundException.java @@ -10,16 +10,14 @@ ******************************************************************************/ package forestry.core.commands; -import net.minecraft.command.CommandException; - import forestry.api.genetics.IAlleleSpecies; +import net.minecraft.command.CommandException; public class TemplateNotFoundException extends CommandException { - private static final long serialVersionUID = 1L; - - public TemplateNotFoundException(IAlleleSpecies species) { - super("Could not find template for species %s with UID %s", species.getName(), species.getUID()); - } + private static final long serialVersionUID = 1L; + public TemplateNotFoundException(IAlleleSpecies species) { + super("Could not find template for species %s with UID %s", species.getName(), species.getUID()); + } } diff --git a/src/main/java/forestry/core/config/Config.java b/src/main/java/forestry/core/config/Config.java index 8dd6749e6..44ba82a61 100755 --- a/src/main/java/forestry/core/config/Config.java +++ b/src/main/java/forestry/core/config/Config.java @@ -11,7 +11,11 @@ package forestry.core.config; import com.google.common.collect.LinkedListMultimap; - +import forestry.Forestry; +import forestry.core.fluids.Fluids; +import forestry.core.utils.Log; +import forestry.core.utils.StringUtil; +import forestry.mail.gui.GuiMailboxInfo; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; @@ -21,61 +25,53 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Properties; import java.util.Set; - import net.minecraft.util.StatCollector; - import net.minecraftforge.common.config.Property; -import forestry.Forestry; -import forestry.core.fluids.Fluids; -import forestry.core.utils.Log; -import forestry.core.utils.StringUtil; -import forestry.mail.gui.GuiMailboxInfo; - public class Config { - public static final String CATEGORY_COMMON = "common"; - public static final String CATEGORY_FLUIDS = "fluids"; + public static final String CATEGORY_COMMON = "common"; + public static final String CATEGORY_FLUIDS = "fluids"; - public static LocalizedConfiguration configCommon; - public static LocalizedConfiguration configFluid; + public static LocalizedConfiguration configCommon; + public static LocalizedConfiguration configFluid; - public static String gameMode; + public static String gameMode; - private static final Set disabledStructures = new HashSet<>(); - private static final Set disabledFluids = new HashSet<>(); - private static final Set disabledBlocks = new HashSet<>(); + private static final Set disabledStructures = new HashSet<>(); + private static final Set disabledFluids = new HashSet<>(); + private static final Set disabledBlocks = new HashSet<>(); - public static boolean isDebug = false; + public static boolean isDebug = false; - public static boolean enablePermissions = true; + public static boolean enablePermissions = true; - // Graphics - public static boolean enableParticleFX = true; + // Graphics + public static boolean enableParticleFX = true; - // Genetics - public static boolean clearInvalidChromosomes = false; - public static boolean pollinateVanillaTrees = true; - public static float researchMutationBoostMultiplier = 1.5f; - public static float maxResearchMutationBoostPercent = 5.0f; + // Genetics + public static boolean clearInvalidChromosomes = false; + public static boolean pollinateVanillaTrees = true; + public static float researchMutationBoostMultiplier = 1.5f; + public static float maxResearchMutationBoostPercent = 5.0f; - // Dungeon loot - public static boolean dungeonLootRare = false; + // Dungeon loot + public static boolean dungeonLootRare = false; - // World generation - public static boolean generateApatiteOre = true; - public static boolean generateCopperOre = true; - public static boolean generateTinOre = true; - private static float generateBeehivesAmount = 1.0f; - public static boolean generateBeehivesDebug = false; - public static boolean enableVillagers = true; + // World generation + public static boolean generateApatiteOre = true; + public static boolean generateCopperOre = true; + public static boolean generateTinOre = true; + private static float generateBeehivesAmount = 1.0f; + public static boolean generateBeehivesDebug = false; + public static boolean enableVillagers = true; - // Retrogen - public static boolean doRetrogen = false; - public static boolean forceRetrogen = false; + // Retrogen + public static boolean doRetrogen = false; + public static boolean forceRetrogen = false; - // Performance - public static boolean enableBackpackResupply = true; + // Performance + public static boolean enableBackpackResupply = true; // Optimization public static boolean enableCraftingTimeout = true; @@ -83,256 +79,282 @@ public class Config { public static boolean cacheWorktableRecipes = true; public static boolean promoteWorktableRecipesToFrontOfGlobalRecipemap = true; - // Customization - private static boolean craftingBronzeEnabled = true; + // Customization + private static boolean craftingBronzeEnabled = true; - public static boolean craftingStampsEnabled = true; - public static final ArrayList collectorStamps = new ArrayList<>(); + public static boolean craftingStampsEnabled = true; + public static final ArrayList collectorStamps = new ArrayList<>(); - public static int farmSize = 2; - public static boolean squareFarms = false; - private static boolean enableExUtilEnderLily = true; - private static boolean enableMagicalCropsSupport = true; + public static int farmSize = 2; + public static boolean squareFarms = false; + private static boolean enableExUtilEnderLily = true; + private static boolean enableMagicalCropsSupport = true; - // Mail - public static boolean mailAlertEnabled = true; - public static GuiMailboxInfo.XPosition mailAlertXPosition = GuiMailboxInfo.XPosition.LEFT; - public static GuiMailboxInfo.YPosition mailAlertYPosition = GuiMailboxInfo.YPosition.TOP; + // Mail + public static boolean mailAlertEnabled = true; + public static GuiMailboxInfo.XPosition mailAlertXPosition = GuiMailboxInfo.XPosition.LEFT; + public static GuiMailboxInfo.YPosition mailAlertYPosition = GuiMailboxInfo.YPosition.TOP; - // Gui tabs (Ledger) - public static int guiTabSpeed = 8; + // Gui tabs (Ledger) + public static int guiTabSpeed = 8; - // Hints - public static boolean enableHints = true; - public static final LinkedListMultimap hints = LinkedListMultimap.create(); - public static boolean enableEnergyStat = true; + // Hints + public static boolean enableHints = true; + public static final LinkedListMultimap hints = LinkedListMultimap.create(); + public static boolean enableEnergyStat = true; - public static boolean isStructureEnabled(String uid) { - return !Config.disabledStructures.contains(uid); - } + public static boolean isStructureEnabled(String uid) { + return !Config.disabledStructures.contains(uid); + } - public static boolean isFluidEnabled(Fluids fluids) { - return !Config.disabledFluids.contains(fluids.getTag()); - } + public static boolean isFluidEnabled(Fluids fluids) { + return !Config.disabledFluids.contains(fluids.getTag()); + } - public static boolean isBlockEnabled(String tag) { - return !Config.disabledBlocks.contains(tag); - } + public static boolean isBlockEnabled(String tag) { + return !Config.disabledBlocks.contains(tag); + } - public static boolean isCraftingBronzeEnabled() { - return craftingBronzeEnabled; - } + public static boolean isCraftingBronzeEnabled() { + return craftingBronzeEnabled; + } - public static double getBeehivesAmount() { - return generateBeehivesAmount; - } + public static double getBeehivesAmount() { + return generateBeehivesAmount; + } - public static boolean isExUtilEnderLilyEnabled() { - return enableExUtilEnderLily; - } + public static boolean isExUtilEnderLilyEnabled() { + return enableExUtilEnderLily; + } - public static boolean isMagicalCropsSupportEnabled() { - return enableMagicalCropsSupport; - } + public static boolean isMagicalCropsSupportEnabled() { + return enableMagicalCropsSupport; + } - public static void load() { - File configCommonFile = new File(Forestry.instance.getConfigFolder(), CATEGORY_COMMON + ".cfg"); - loadConfigCommon(configCommonFile); + public static void load() { + File configCommonFile = new File(Forestry.instance.getConfigFolder(), CATEGORY_COMMON + ".cfg"); + loadConfigCommon(configCommonFile); - File configFluidsFile = new File(Forestry.instance.getConfigFolder(), CATEGORY_FLUIDS + ".cfg"); - loadConfigFluids(configFluidsFile); + File configFluidsFile = new File(Forestry.instance.getConfigFolder(), CATEGORY_FLUIDS + ".cfg"); + loadConfigFluids(configFluidsFile); - loadHints(); - } + loadHints(); + } - private static void loadConfigCommon(File configFileCommon) { + private static void loadConfigCommon(File configFileCommon) { - configCommon = new LocalizedConfiguration(configFileCommon, "1.2.0"); + configCommon = new LocalizedConfiguration(configFileCommon, "1.2.0"); - gameMode = configCommon.getStringLocalized("difficulty", "game.mode", "EASY", new String[]{"OP, EASY, NORMAL, HARD"}); + gameMode = configCommon.getStringLocalized( + "difficulty", "game.mode", "EASY", new String[] {"OP, EASY, NORMAL, HARD"}); - boolean recreate = configCommon.getBooleanLocalized("difficulty", "recreate.definitions", true); - if (recreate) { - Log.info("Recreating all gamemode definitions from the defaults. This may be caused by an upgrade"); + boolean recreate = configCommon.getBooleanLocalized("difficulty", "recreate.definitions", true); + if (recreate) { + Log.info("Recreating all gamemode definitions from the defaults. This may be caused by an upgrade"); - String recreateDefinitionsComment = StringUtil.localize("config.difficulty.recreate.definitions.comment"); - Property property = configCommon.get("difficulty", "recreate.definitions", true, recreateDefinitionsComment); - property.set(false); + String recreateDefinitionsComment = StringUtil.localize("config.difficulty.recreate.definitions.comment"); + Property property = + configCommon.get("difficulty", "recreate.definitions", true, recreateDefinitionsComment); + property.set(false); - // Make sure the default mode files are there. + // Make sure the default mode files are there. - File opMode = new File(Forestry.instance.getConfigFolder(), "gamemodes/OP.cfg"); - CopyFileToFS(opMode, "/config/forestry/gamemodes/OP.cfg"); + File opMode = new File(Forestry.instance.getConfigFolder(), "gamemodes/OP.cfg"); + CopyFileToFS(opMode, "/config/forestry/gamemodes/OP.cfg"); - File normalMode = new File(Forestry.instance.getConfigFolder(), "gamemodes/NORMAL.cfg"); - CopyFileToFS(normalMode, "/config/forestry/gamemodes/NORMAL.cfg"); + File normalMode = new File(Forestry.instance.getConfigFolder(), "gamemodes/NORMAL.cfg"); + CopyFileToFS(normalMode, "/config/forestry/gamemodes/NORMAL.cfg"); - File hardMode = new File(Forestry.instance.getConfigFolder(), "gamemodes/HARD.cfg"); - CopyFileToFS(hardMode, "/config/forestry/gamemodes/HARD.cfg"); - } + File hardMode = new File(Forestry.instance.getConfigFolder(), "gamemodes/HARD.cfg"); + CopyFileToFS(hardMode, "/config/forestry/gamemodes/HARD.cfg"); + } - enableParticleFX = configCommon.getBooleanLocalized("performance", "particleFX", enableParticleFX); + enableParticleFX = configCommon.getBooleanLocalized("performance", "particleFX", enableParticleFX); - // RetroGen + // RetroGen - doRetrogen = configCommon.getBooleanLocalized("world.generate.retrogen", "normal", doRetrogen); - forceRetrogen = configCommon.getBooleanLocalized("world.generate.retrogen", "forced", forceRetrogen); + doRetrogen = configCommon.getBooleanLocalized("world.generate.retrogen", "normal", doRetrogen); + forceRetrogen = configCommon.getBooleanLocalized("world.generate.retrogen", "forced", forceRetrogen); - if (forceRetrogen) { - Property property = configCommon.get("world.generate.retrogen", "forced", false); - property.set(false); + if (forceRetrogen) { + Property property = configCommon.get("world.generate.retrogen", "forced", false); + property.set(false); - Log.info("Enabled force retrogen."); - doRetrogen = true; - } else if (doRetrogen) { - Log.info("Enabled retrogen."); - } + Log.info("Enabled force retrogen."); + doRetrogen = true; + } else if (doRetrogen) { + Log.info("Enabled retrogen."); + } - generateBeehivesAmount = configCommon.getFloatLocalized("world.generate.beehives", "amount", generateBeehivesAmount, 0.0f, 10.0f); - generateBeehivesDebug = configCommon.getBooleanLocalized("world.generate.beehives", "debug", generateBeehivesDebug); + generateBeehivesAmount = configCommon.getFloatLocalized( + "world.generate.beehives", "amount", generateBeehivesAmount, 0.0f, 10.0f); + generateBeehivesDebug = + configCommon.getBooleanLocalized("world.generate.beehives", "debug", generateBeehivesDebug); - generateApatiteOre = configCommon.getBooleanLocalized("world.generate.ore", "apatite", generateApatiteOre); - generateCopperOre = configCommon.getBooleanLocalized("world.generate.ore", "copper", generateCopperOre); - generateTinOre = configCommon.getBooleanLocalized("world.generate.ore", "tin", generateTinOre); + generateApatiteOre = configCommon.getBooleanLocalized("world.generate.ore", "apatite", generateApatiteOre); + generateCopperOre = configCommon.getBooleanLocalized("world.generate.ore", "copper", generateCopperOre); + generateTinOre = configCommon.getBooleanLocalized("world.generate.ore", "tin", generateTinOre); - enableVillagers = configCommon.getBooleanLocalized("world.generate", "villagers", enableVillagers); + enableVillagers = configCommon.getBooleanLocalized("world.generate", "villagers", enableVillagers); - craftingBronzeEnabled = configCommon.getBooleanLocalized("crafting", "bronze", craftingBronzeEnabled); - craftingStampsEnabled = configCommon.getBooleanLocalized("crafting.stamps", "enabled", true); + craftingBronzeEnabled = configCommon.getBooleanLocalized("crafting", "bronze", craftingBronzeEnabled); + craftingStampsEnabled = configCommon.getBooleanLocalized("crafting.stamps", "enabled", true); - String[] allStamps = new String[]{"1n", "2n", "5n", "10n", "20n", "50n", "100n"}; - String[] defaultCollectors = new String[]{"20n", "50n", "100n"}; - String[] stamps = configCommon.getStringListLocalized("crafting.stamps", "disabled", defaultCollectors, allStamps); - try { - collectorStamps.addAll(Arrays.asList(stamps)); - } catch (Exception ex) { - Log.warning("Failed to read config for 'crafting.stamps.disabled', setting to default."); - Property property = configCommon.get("crafting.stamps", "disabled", defaultCollectors); - property.setToDefault(); - collectorStamps.addAll(Arrays.asList(defaultCollectors)); - } + String[] allStamps = new String[] {"1n", "2n", "5n", "10n", "20n", "50n", "100n"}; + String[] defaultCollectors = new String[] {"20n", "50n", "100n"}; + String[] stamps = + configCommon.getStringListLocalized("crafting.stamps", "disabled", defaultCollectors, allStamps); + try { + collectorStamps.addAll(Arrays.asList(stamps)); + } catch (Exception ex) { + Log.warning("Failed to read config for 'crafting.stamps.disabled', setting to default."); + Property property = configCommon.get("crafting.stamps", "disabled", defaultCollectors); + property.setToDefault(); + collectorStamps.addAll(Arrays.asList(defaultCollectors)); + } - clearInvalidChromosomes = configCommon.getBooleanLocalized("genetics", "clear.invalid.chromosomes", clearInvalidChromosomes); - pollinateVanillaTrees = configCommon.getBooleanLocalized("genetics", "pollinate.vanilla.trees", pollinateVanillaTrees); - researchMutationBoostMultiplier = configCommon.getFloatLocalized("genetics.research.boost", "multiplier", researchMutationBoostMultiplier, 1.0f, 1000.f); - maxResearchMutationBoostPercent = configCommon.getFloatLocalized("genetics.research.boost", "max.percent", maxResearchMutationBoostPercent, 0.0f, 100.0f); + clearInvalidChromosomes = + configCommon.getBooleanLocalized("genetics", "clear.invalid.chromosomes", clearInvalidChromosomes); + pollinateVanillaTrees = + configCommon.getBooleanLocalized("genetics", "pollinate.vanilla.trees", pollinateVanillaTrees); + researchMutationBoostMultiplier = configCommon.getFloatLocalized( + "genetics.research.boost", "multiplier", researchMutationBoostMultiplier, 1.0f, 1000.f); + maxResearchMutationBoostPercent = configCommon.getFloatLocalized( + "genetics.research.boost", "max.percent", maxResearchMutationBoostPercent, 0.0f, 100.0f); - dungeonLootRare = configCommon.getBooleanLocalized("difficulty", "loot.rare", dungeonLootRare); + dungeonLootRare = configCommon.getBooleanLocalized("difficulty", "loot.rare", dungeonLootRare); - enableBackpackResupply = configCommon.getBooleanLocalized("performance", "backpacks.resupply", enableBackpackResupply); + enableBackpackResupply = + configCommon.getBooleanLocalized("performance", "backpacks.resupply", enableBackpackResupply); - enableCraftingTimeout = configCommon.getBooleanLocalized("optimization","enable.crafting.timeout", enableCraftingTimeout); - craftingTimeout = configCommon.getIntLocalized("optimization","crafting.timeout",craftingTimeout, 50, 2000 ); // min 50ms, default 200ms, max 2000 ms. Integer.MAX_VALUE is ~ 2100 ms because of multiplication by 1,000,000 - cacheWorktableRecipes = configCommon.getBooleanLocalized("optimization","cache.worktable.recipes", cacheWorktableRecipes); - promoteWorktableRecipesToFrontOfGlobalRecipemap = configCommon.getBooleanLocalized("optimization","promote.worktable.recipes",promoteWorktableRecipesToFrontOfGlobalRecipemap); + enableCraftingTimeout = + configCommon.getBooleanLocalized("optimization", "enable.crafting.timeout", enableCraftingTimeout); + craftingTimeout = configCommon.getIntLocalized( + "optimization", + "crafting.timeout", + craftingTimeout, + 50, + 2000); // min 50ms, default 200ms, max 2000 ms. Integer.MAX_VALUE is ~ 2100 ms because of multiplication + // by 1,000,000 + cacheWorktableRecipes = + configCommon.getBooleanLocalized("optimization", "cache.worktable.recipes", cacheWorktableRecipes); + promoteWorktableRecipesToFrontOfGlobalRecipemap = configCommon.getBooleanLocalized( + "optimization", "promote.worktable.recipes", promoteWorktableRecipesToFrontOfGlobalRecipemap); - // move legacy mail property - configCommon.moveProperty("tweaks.gui", "mail.alert", "tweaks.gui.mail.alert"); - configCommon.renameProperty("tweaks.gui.mail.alert", "mail.alert", "enabled"); + // move legacy mail property + configCommon.moveProperty("tweaks.gui", "mail.alert", "tweaks.gui.mail.alert"); + configCommon.renameProperty("tweaks.gui.mail.alert", "mail.alert", "enabled"); - mailAlertEnabled = configCommon.getBooleanLocalized("tweaks.gui.mail.alert", "enabled", mailAlertEnabled); - mailAlertXPosition = configCommon.getEnumLocalized("tweaks.gui.mail.alert", "xPosition", mailAlertXPosition, GuiMailboxInfo.XPosition.values()); - mailAlertYPosition = configCommon.getEnumLocalized("tweaks.gui.mail.alert", "yPosition", mailAlertYPosition, GuiMailboxInfo.YPosition.values()); + mailAlertEnabled = configCommon.getBooleanLocalized("tweaks.gui.mail.alert", "enabled", mailAlertEnabled); + mailAlertXPosition = configCommon.getEnumLocalized( + "tweaks.gui.mail.alert", "xPosition", mailAlertXPosition, GuiMailboxInfo.XPosition.values()); + mailAlertYPosition = configCommon.getEnumLocalized( + "tweaks.gui.mail.alert", "yPosition", mailAlertYPosition, GuiMailboxInfo.YPosition.values()); - guiTabSpeed = configCommon.getIntLocalized("tweaks.gui.tabs", "speed", guiTabSpeed, 1, 50); - enableHints = configCommon.getBooleanLocalized("tweaks.gui.tabs", "hints", enableHints); - enableEnergyStat = configCommon.getBooleanLocalized("tweaks.gui.tabs", "energy", enableEnergyStat); + guiTabSpeed = configCommon.getIntLocalized("tweaks.gui.tabs", "speed", guiTabSpeed, 1, 50); + enableHints = configCommon.getBooleanLocalized("tweaks.gui.tabs", "hints", enableHints); + enableEnergyStat = configCommon.getBooleanLocalized("tweaks.gui.tabs", "energy", enableEnergyStat); - enablePermissions = configCommon.getBooleanLocalized("tweaks", "permissions", enablePermissions); + enablePermissions = configCommon.getBooleanLocalized("tweaks", "permissions", enablePermissions); - farmSize = configCommon.getIntLocalized("tweaks.farms", "size", farmSize, 1, 3); - squareFarms = configCommon.getBooleanLocalized("tweaks.farms", "square", squareFarms); - enableExUtilEnderLily = configCommon.getBooleanLocalized("tweaks.farms", "enderlily", enableExUtilEnderLily); - enableMagicalCropsSupport = configCommon.getBooleanLocalized("tweaks.farms", "magicalcrops", enableMagicalCropsSupport); + farmSize = configCommon.getIntLocalized("tweaks.farms", "size", farmSize, 1, 3); + squareFarms = configCommon.getBooleanLocalized("tweaks.farms", "square", squareFarms); + enableExUtilEnderLily = configCommon.getBooleanLocalized("tweaks.farms", "enderlily", enableExUtilEnderLily); + enableMagicalCropsSupport = + configCommon.getBooleanLocalized("tweaks.farms", "magicalcrops", enableMagicalCropsSupport); - String[] availableStructures = new String[]{"alveary3x3", "farm3x3", "farm3x4", "farm3x5", "farm4x4", "farm5x5"}; - String[] disabledStructureArray = disabledStructures.toArray(new String[disabledStructures.size()]); - disabledStructureArray = configCommon.getStringListLocalized("structures", "disabled", disabledStructureArray, availableStructures); + String[] availableStructures = + new String[] {"alveary3x3", "farm3x3", "farm3x4", "farm3x5", "farm4x4", "farm5x5"}; + String[] disabledStructureArray = disabledStructures.toArray(new String[disabledStructures.size()]); + disabledStructureArray = configCommon.getStringListLocalized( + "structures", "disabled", disabledStructureArray, availableStructures); - disabledStructures.addAll(Arrays.asList(disabledStructureArray)); - for (String str : disabledStructures) { - Log.finer("Disabled structure '%s'.", str); - } + disabledStructures.addAll(Arrays.asList(disabledStructureArray)); + for (String str : disabledStructures) { + Log.finer("Disabled structure '%s'.", str); + } - isDebug = configCommon.getBooleanLocalized("debug", "enabled", isDebug); + isDebug = configCommon.getBooleanLocalized("debug", "enabled", isDebug); - configCommon.save(); - } + configCommon.save(); + } - private static void loadConfigFluids(File configFile) { - configFluid = new LocalizedConfiguration(configFile, "1.0.0"); + private static void loadConfigFluids(File configFile) { + configFluid = new LocalizedConfiguration(configFile, "1.0.0"); - for (Fluids fluid : Fluids.forestryFluids) { - String fluidName = StatCollector.translateToLocal("fluid." + fluid.getTag()); + for (Fluids fluid : Fluids.forestryFluids) { + String fluidName = StatCollector.translateToLocal("fluid." + fluid.getTag()); - boolean enabledFluid = !Config.disabledFluids.contains(fluid.getTag()); - String enableFluidComment = StringUtil.localizeAndFormatRaw("for.config.fluids.enable.format", fluidName); - enabledFluid = configFluid.getBoolean("enableFluid", fluid.getTag(), enabledFluid, enableFluidComment); - if (!enabledFluid) { - Config.disabledFluids.add(fluid.getTag()); - } + boolean enabledFluid = !Config.disabledFluids.contains(fluid.getTag()); + String enableFluidComment = StringUtil.localizeAndFormatRaw("for.config.fluids.enable.format", fluidName); + enabledFluid = configFluid.getBoolean("enableFluid", fluid.getTag(), enabledFluid, enableFluidComment); + if (!enabledFluid) { + Config.disabledFluids.add(fluid.getTag()); + } - boolean enabledFluidBlock = !Config.disabledBlocks.contains(fluid.getTag()); - String enableFluidBlockComment = StringUtil.localizeAndFormatRaw("for.config.fluid.blocks.enable.format", fluidName); - enabledFluidBlock = configFluid.getBoolean("enableFluidBlock", fluid.getTag(), enabledFluidBlock, enableFluidBlockComment); - if (!enabledFluidBlock) { - Config.disabledBlocks.add(fluid.getTag()); - } - } + boolean enabledFluidBlock = !Config.disabledBlocks.contains(fluid.getTag()); + String enableFluidBlockComment = + StringUtil.localizeAndFormatRaw("for.config.fluid.blocks.enable.format", fluidName); + enabledFluidBlock = configFluid.getBoolean( + "enableFluidBlock", fluid.getTag(), enabledFluidBlock, enableFluidBlockComment); + if (!enabledFluidBlock) { + Config.disabledBlocks.add(fluid.getTag()); + } + } - configFluid.save(); - } + configFluid.save(); + } - private static void CopyFileToFS(File destination, String resourcePath) { - InputStream stream = Config.class.getResourceAsStream(resourcePath); - OutputStream outstream; - int readBytes; - byte[] buffer = new byte[4096]; - try { + private static void CopyFileToFS(File destination, String resourcePath) { + InputStream stream = Config.class.getResourceAsStream(resourcePath); + OutputStream outstream; + int readBytes; + byte[] buffer = new byte[4096]; + try { - if (destination.getParentFile() != null) { - destination.getParentFile().mkdirs(); - } + if (destination.getParentFile() != null) { + destination.getParentFile().mkdirs(); + } - if (!destination.exists() && !destination.createNewFile()) { - return; - } + if (!destination.exists() && !destination.createNewFile()) { + return; + } - outstream = new FileOutputStream(destination); - while ((readBytes = stream.read(buffer)) > 0) { - outstream.write(buffer, 0, readBytes); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } + outstream = new FileOutputStream(destination); + while ((readBytes = stream.read(buffer)) > 0) { + outstream.write(buffer, 0, readBytes); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } - private static void loadHints() { + private static void loadHints() { - Properties prop = new Properties(); + Properties prop = new Properties(); - try { - InputStream hintStream = Config.class.getResourceAsStream("/config/forestry/hints.properties"); - prop.load(hintStream); - } catch (Exception ex) { - ex.printStackTrace(); - } + try { + InputStream hintStream = Config.class.getResourceAsStream("/config/forestry/hints.properties"); + prop.load(hintStream); + } catch (Exception ex) { + ex.printStackTrace(); + } - for (String key : prop.stringPropertyNames()) { - String[] parsedHints = parseHints(prop.getProperty(key)); - if (parsedHints != null) { - for (String parsedHint : parsedHints) { - hints.put(key, parsedHint); - } - } - } - } + for (String key : prop.stringPropertyNames()) { + String[] parsedHints = parseHints(prop.getProperty(key)); + if (parsedHints != null) { + for (String parsedHint : parsedHints) { + hints.put(key, parsedHint); + } + } + } + } - private static String[] parseHints(String list) { - if (list.isEmpty()) { - return new String[0]; - } else { - return list.split("[;]+"); - } - } + private static String[] parseHints(String list) { + if (list.isEmpty()) { + return new String[0]; + } else { + return list.split("[;]+"); + } + } } diff --git a/src/main/java/forestry/core/config/Constants.java b/src/main/java/forestry/core/config/Constants.java index 0834ad07a..77081be8b 100644 --- a/src/main/java/forestry/core/config/Constants.java +++ b/src/main/java/forestry/core/config/Constants.java @@ -13,132 +13,132 @@ package forestry.core.config; import forestry.api.core.IForestryConstants; public class Constants implements IForestryConstants { - // System - public static final String MOD = "Forestry"; - public static final String ID = "forestry"; - public static final String VERSION = "GRADLETOKEN_VERSION"; - public static final String URL = "http://forestry.sengir.net/"; + // System + public static final String MOD = "Forestry"; + public static final String ID = "forestry"; + public static final String VERSION = "GRADLETOKEN_VERSION"; + public static final String URL = "http://forestry.sengir.net/"; - public static final int FLAG_BLOCK_UPDATE = 1; - public static final int FLAG_BLOCK_SYNCH = 2; - public static final int FLAG_BLOCK_SYNCH_AND_UPDATE = FLAG_BLOCK_UPDATE + FLAG_BLOCK_SYNCH; + public static final int FLAG_BLOCK_UPDATE = 1; + public static final int FLAG_BLOCK_SYNCH = 2; + public static final int FLAG_BLOCK_SYNCH_AND_UPDATE = FLAG_BLOCK_UPDATE + FLAG_BLOCK_SYNCH; - public static final int BUCKET_VOLUME = 1000; - public static final int FLUID_PER_HONEY_DROP = 100; + public static final int BUCKET_VOLUME = 1000; + public static final int FLUID_PER_HONEY_DROP = 100; - public static final int[] FACINGS = {0, 1, 2, 3, 4, 5}; - public static final int[] SLOTS_NONE = new int[0]; - public static final String[] EMPTY_STRINGS = new String[0]; + public static final int[] FACINGS = {0, 1, 2, 3, 4, 5}; + public static final int[] SLOTS_NONE = new int[0]; + public static final String[] EMPTY_STRINGS = new String[0]; - // Textures - public static final String TEXTURE_PATH_GUI = "textures/gui"; - public static final String TEXTURE_PATH_BLOCKS = "textures/blocks"; - public static final String TEXTURE_PATH_ITEMS = "textures/items"; - public static final String TEXTURE_PATH_ENTITIES = "textures/entity"; + // Textures + public static final String TEXTURE_PATH_GUI = "textures/gui"; + public static final String TEXTURE_PATH_BLOCKS = "textures/blocks"; + public static final String TEXTURE_PATH_ITEMS = "textures/items"; + public static final String TEXTURE_PATH_ENTITIES = "textures/entity"; - public static final String TEXTURE_APIARIST_ARMOR_PRIMARY = TEXTURE_PATH_ITEMS + "/apiarist_armor_1.png"; - public static final String TEXTURE_APIARIST_ARMOR_SECONDARY = TEXTURE_PATH_ITEMS + "/apiarist_armor_2.png"; - public static final String TEXTURE_NATURALIST_ARMOR_PRIMARY = TEXTURE_PATH_ITEMS + "/naturalist_armor_1.png"; - public static final String TEXTURE_SKIN_BEEKPEEPER = TEXTURE_PATH_ENTITIES + "/beekeeper.png"; - public static final String TEXTURE_SKIN_LUMBERJACK = TEXTURE_PATH_ENTITIES + "/lumberjack.png"; + public static final String TEXTURE_APIARIST_ARMOR_PRIMARY = TEXTURE_PATH_ITEMS + "/apiarist_armor_1.png"; + public static final String TEXTURE_APIARIST_ARMOR_SECONDARY = TEXTURE_PATH_ITEMS + "/apiarist_armor_2.png"; + public static final String TEXTURE_NATURALIST_ARMOR_PRIMARY = TEXTURE_PATH_ITEMS + "/naturalist_armor_1.png"; + public static final String TEXTURE_SKIN_BEEKPEEPER = TEXTURE_PATH_ENTITIES + "/beekeeper.png"; + public static final String TEXTURE_SKIN_LUMBERJACK = TEXTURE_PATH_ENTITIES + "/lumberjack.png"; - // Villagers - public static final int ID_VILLAGER_BEEKEEPER = 80; - public static final int ID_VILLAGER_LUMBERJACK = 81; + // Villagers + public static final int ID_VILLAGER_BEEKEEPER = 80; + public static final int ID_VILLAGER_LUMBERJACK = 81; - // Village Chest Gen hook - public static final String CHEST_GEN_HOOK_NATURALIST_CHEST = "naturalistChest"; + // Village Chest Gen hook + public static final String CHEST_GEN_HOOK_NATURALIST_CHEST = "naturalistChest"; - // Item Ids + // Item Ids - public static final int SLOTS_BACKPACK_DEFAULT = 15; - public static final int SLOTS_BACKPACK_T2 = 45; - public static final int SLOTS_BACKPACK_APIARIST = 125; + public static final int SLOTS_BACKPACK_DEFAULT = 15; + public static final int SLOTS_BACKPACK_T2 = 45; + public static final int SLOTS_BACKPACK_APIARIST = 125; - // Food stuff - public static final int FOOD_AMBROSIA_HEAL = 8; - public static final int FOOD_JUICE_HEAL = 2; - public static final float FOOD_JUICE_SATURATION = 0.2f; - public static final int FOOD_HONEY_HEAL = 2; - public static final float FOOD_HONEY_SATURATION = 0.2f; + // Food stuff + public static final int FOOD_AMBROSIA_HEAL = 8; + public static final int FOOD_JUICE_HEAL = 2; + public static final float FOOD_JUICE_SATURATION = 0.2f; + public static final int FOOD_HONEY_HEAL = 2; + public static final float FOOD_HONEY_SATURATION = 0.2f; - public static final int APIARY_MIN_LEVEL_LIGHT = 11; - public static final int APIARY_BREEDING_TIME = 100; + public static final int APIARY_MIN_LEVEL_LIGHT = 11; + public static final int APIARY_BREEDING_TIME = 100; - // Energy - public static final int ENGINE_TANK_CAPACITY = 10 * BUCKET_VOLUME; - public static final int ENGINE_CYCLE_DURATION_WATER = 1000; - public static final int ENGINE_CYCLE_DURATION_JUICE = 2500; - public static final int ENGINE_CYCLE_DURATION_HONEY = 2500; - public static final int ENGINE_CYCLE_DURATION_MILK = 10000; - public static final int ENGINE_CYCLE_DURATION_SEED_OIL = 2500; - public static final int ENGINE_CYCLE_DURATION_BIOMASS = 2500; - public static final int ENGINE_CYCLE_DURATION_ETHANOL = 15000; - public static final int ENGINE_FUEL_VALUE_WATER = 10; - public static final int ENGINE_FUEL_VALUE_JUICE = 10; - public static final int ENGINE_FUEL_VALUE_HONEY = 20; - public static final int ENGINE_FUEL_VALUE_MILK = 10; - public static final int ENGINE_FUEL_VALUE_SEED_OIL = 30; - public static final int ENGINE_FUEL_VALUE_BIOMASS = 50; - public static final int ENGINE_HEAT_VALUE_LAVA = 20; + // Energy + public static final int ENGINE_TANK_CAPACITY = 10 * BUCKET_VOLUME; + public static final int ENGINE_CYCLE_DURATION_WATER = 1000; + public static final int ENGINE_CYCLE_DURATION_JUICE = 2500; + public static final int ENGINE_CYCLE_DURATION_HONEY = 2500; + public static final int ENGINE_CYCLE_DURATION_MILK = 10000; + public static final int ENGINE_CYCLE_DURATION_SEED_OIL = 2500; + public static final int ENGINE_CYCLE_DURATION_BIOMASS = 2500; + public static final int ENGINE_CYCLE_DURATION_ETHANOL = 15000; + public static final int ENGINE_FUEL_VALUE_WATER = 10; + public static final int ENGINE_FUEL_VALUE_JUICE = 10; + public static final int ENGINE_FUEL_VALUE_HONEY = 20; + public static final int ENGINE_FUEL_VALUE_MILK = 10; + public static final int ENGINE_FUEL_VALUE_SEED_OIL = 30; + public static final int ENGINE_FUEL_VALUE_BIOMASS = 50; + public static final int ENGINE_HEAT_VALUE_LAVA = 20; - public static final float ENGINE_PISTON_SPEED_MAX = 0.08f; + public static final float ENGINE_PISTON_SPEED_MAX = 0.08f; - public static final int ENGINE_BRONZE_HEAT_MAX = 10000; - public static final int ENGINE_BRONZE_HEAT_LOSS_COOL = 2; - public static final int ENGINE_BRONZE_HEAT_LOSS_OPERATING = 1; - public static final int ENGINE_BRONZE_HEAT_LOSS_OVERHEATING = 5; - public static final int ENGINE_BRONZE_HEAT_GENERATION_ENERGY = 1; + public static final int ENGINE_BRONZE_HEAT_MAX = 10000; + public static final int ENGINE_BRONZE_HEAT_LOSS_COOL = 2; + public static final int ENGINE_BRONZE_HEAT_LOSS_OPERATING = 1; + public static final int ENGINE_BRONZE_HEAT_LOSS_OVERHEATING = 5; + public static final int ENGINE_BRONZE_HEAT_GENERATION_ENERGY = 1; - public static final int ENGINE_COPPER_CYCLE_DURATION_PEAT = 5000; - public static final int ENGINE_COPPER_FUEL_VALUE_PEAT = 10; - public static final int ENGINE_COPPER_CYCLE_DURATION_BITUMINOUS_PEAT = 6000; - public static final int ENGINE_COPPER_FUEL_VALUE_BITUMINOUS_PEAT = 20; - public static final int ENGINE_COPPER_HEAT_MAX = 10000; - public static final int ENGINE_COPPER_ASH_FOR_ITEM = 7500; + public static final int ENGINE_COPPER_CYCLE_DURATION_PEAT = 5000; + public static final int ENGINE_COPPER_FUEL_VALUE_PEAT = 10; + public static final int ENGINE_COPPER_CYCLE_DURATION_BITUMINOUS_PEAT = 6000; + public static final int ENGINE_COPPER_FUEL_VALUE_BITUMINOUS_PEAT = 20; + public static final int ENGINE_COPPER_HEAT_MAX = 10000; + public static final int ENGINE_COPPER_ASH_FOR_ITEM = 7500; - public static final int ENGINE_ELECTRIC_HEAT_MAX = 3000; - public static final int ENGINE_TIN_EU_FOR_CYCLE = 5; //Reduced from 6 to 5, as per the 4 RF to 1 EU ratio - public static final int ENGINE_TIN_ENERGY_PER_CYCLE = 20; - public static final int ENGINE_TIN_MAX_EU_STORED = 2 * ENGINE_TIN_EU_FOR_CYCLE; - public static final int ENGINE_TIN_MAX_EU_BATTERY = 100; + public static final int ENGINE_ELECTRIC_HEAT_MAX = 3000; + public static final int ENGINE_TIN_EU_FOR_CYCLE = 5; // Reduced from 6 to 5, as per the 4 RF to 1 EU ratio + public static final int ENGINE_TIN_ENERGY_PER_CYCLE = 20; + public static final int ENGINE_TIN_MAX_EU_STORED = 2 * ENGINE_TIN_EU_FOR_CYCLE; + public static final int ENGINE_TIN_MAX_EU_BATTERY = 100; - // Factory - public static final int PROCESSOR_TANK_CAPACITY = 10 * BUCKET_VOLUME; + // Factory + public static final int PROCESSOR_TANK_CAPACITY = 10 * BUCKET_VOLUME; - public static final int MACHINE_MAX_ENERGY = 5000; + public static final int MACHINE_MAX_ENERGY = 5000; - public static final int RAINMAKER_RAIN_DURATION_IODINE = 10000; + public static final int RAINMAKER_RAIN_DURATION_IODINE = 10000; - public static final int STILL_DESTILLATION_DURATION = 100; - public static final int STILL_DESTILLATION_INPUT = 10; - public static final int STILL_DESTILLATION_OUTPUT = 3; + public static final int STILL_DESTILLATION_DURATION = 100; + public static final int STILL_DESTILLATION_INPUT = 10; + public static final int STILL_DESTILLATION_OUTPUT = 3; - public static final int BOTTLER_FILLING_TIME = 20; - public static final int BOTTLER_FUELCAN_VOLUME = 2000; + public static final int BOTTLER_FILLING_TIME = 20; + public static final int BOTTLER_FUELCAN_VOLUME = 2000; - public static final float ICE_COOLING_MULTIPLIER = 6f; // multiple of water's cooling value + public static final float ICE_COOLING_MULTIPLIER = 6f; // multiple of water's cooling value - // Storage - public static final int RAINTANK_TANK_CAPACITY = 30 * BUCKET_VOLUME; - public static final int RAINTANK_AMOUNT_PER_UPDATE = 10; - public static final int RAINTANK_FILLING_TIME = 12; - public static final int CARPENTER_CRATING_CYCLES = 5; - public static final int CARPENTER_UNCRATING_CYCLES = 5; - public static final int CARPENTER_CRATING_LIQUID_QUANTITY = 100; + // Storage + public static final int RAINTANK_TANK_CAPACITY = 30 * BUCKET_VOLUME; + public static final int RAINTANK_AMOUNT_PER_UPDATE = 10; + public static final int RAINTANK_FILLING_TIME = 12; + public static final int CARPENTER_CRATING_CYCLES = 5; + public static final int CARPENTER_UNCRATING_CYCLES = 5; + public static final int CARPENTER_CRATING_LIQUID_QUANTITY = 100; - @Override - public int getApicultureVillagerID() { - return ID_VILLAGER_BEEKEEPER; - } + @Override + public int getApicultureVillagerID() { + return ID_VILLAGER_BEEKEEPER; + } - @Override - public int getArboricultureVillagerID() { - return ID_VILLAGER_LUMBERJACK; - } + @Override + public int getArboricultureVillagerID() { + return ID_VILLAGER_LUMBERJACK; + } - @Override - public String getVillagerChestGenKey() { - return CHEST_GEN_HOOK_NATURALIST_CHEST; - } + @Override + public String getVillagerChestGenKey() { + return CHEST_GEN_HOOK_NATURALIST_CHEST; + } } diff --git a/src/main/java/forestry/core/config/ForestryGuiConfig.java b/src/main/java/forestry/core/config/ForestryGuiConfig.java index cef80c28a..1446c5e13 100644 --- a/src/main/java/forestry/core/config/ForestryGuiConfig.java +++ b/src/main/java/forestry/core/config/ForestryGuiConfig.java @@ -1,49 +1,46 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.config; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import net.minecraft.client.gui.GuiScreen; - -import net.minecraftforge.common.config.ConfigCategory; -import net.minecraftforge.common.config.ConfigElement; - -import cpw.mods.fml.client.config.GuiConfig; -import cpw.mods.fml.client.config.IConfigElement; - -public class ForestryGuiConfig extends GuiConfig { - - public ForestryGuiConfig(GuiScreen parent) { - super(parent, getConfigCategories(), Constants.MOD, true, true, Constants.MOD); - } - - private static List getConfigCategories() { - List configElements = new ArrayList<>(); - - List commonCategoryNames = Arrays.asList("crafting", "difficulty", "genetics", "performance", "structures", "tweaks", "world"); - for (String categoryName : commonCategoryNames) { - ConfigCategory category = Config.configCommon.getCategory(categoryName); - configElements.add(new ConfigElement(category)); - } - - List fluidCategoryNames = Arrays.asList("enableFluid", "enableFluidBlock"); - for (String categoryName : fluidCategoryNames) { - ConfigCategory category = Config.configFluid.getCategory(categoryName); - configElements.add(new ConfigElement(category)); - } - - return configElements; - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.config; + +import cpw.mods.fml.client.config.GuiConfig; +import cpw.mods.fml.client.config.IConfigElement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.common.config.ConfigCategory; +import net.minecraftforge.common.config.ConfigElement; + +public class ForestryGuiConfig extends GuiConfig { + + public ForestryGuiConfig(GuiScreen parent) { + super(parent, getConfigCategories(), Constants.MOD, true, true, Constants.MOD); + } + + private static List getConfigCategories() { + List configElements = new ArrayList<>(); + + List commonCategoryNames = + Arrays.asList("crafting", "difficulty", "genetics", "performance", "structures", "tweaks", "world"); + for (String categoryName : commonCategoryNames) { + ConfigCategory category = Config.configCommon.getCategory(categoryName); + configElements.add(new ConfigElement(category)); + } + + List fluidCategoryNames = Arrays.asList("enableFluid", "enableFluidBlock"); + for (String categoryName : fluidCategoryNames) { + ConfigCategory category = Config.configFluid.getCategory(categoryName); + configElements.add(new ConfigElement(category)); + } + + return configElements; + } +} diff --git a/src/main/java/forestry/core/config/ForestryGuiConfigFactory.java b/src/main/java/forestry/core/config/ForestryGuiConfigFactory.java index 82eeeebaf..316c124f8 100644 --- a/src/main/java/forestry/core/config/ForestryGuiConfigFactory.java +++ b/src/main/java/forestry/core/config/ForestryGuiConfigFactory.java @@ -1,40 +1,36 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.config; - -import java.util.Set; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; - -import cpw.mods.fml.client.IModGuiFactory; - -public class ForestryGuiConfigFactory implements IModGuiFactory { - @Override - public void initialize(Minecraft minecraftInstance) { - - } - - @Override - public Class mainConfigGuiClass() { - return ForestryGuiConfig.class; - } - - @Override - public Set runtimeGuiCategories() { - return null; - } - - @Override - public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) { - return null; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.config; + +import cpw.mods.fml.client.IModGuiFactory; +import java.util.Set; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; + +public class ForestryGuiConfigFactory implements IModGuiFactory { + @Override + public void initialize(Minecraft minecraftInstance) {} + + @Override + public Class mainConfigGuiClass() { + return ForestryGuiConfig.class; + } + + @Override + public Set runtimeGuiCategories() { + return null; + } + + @Override + public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) { + return null; + } +} diff --git a/src/main/java/forestry/core/config/GameMode.java b/src/main/java/forestry/core/config/GameMode.java index f88d2e6e5..21385ff7e 100644 --- a/src/main/java/forestry/core/config/GameMode.java +++ b/src/main/java/forestry/core/config/GameMode.java @@ -10,182 +10,179 @@ ******************************************************************************/ package forestry.core.config; -import java.io.File; -import java.util.HashMap; -import java.util.Map; - -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - import forestry.Forestry; import forestry.api.core.IGameMode; import forestry.core.blocks.BlockSoil; import forestry.core.utils.Log; import forestry.plugins.PluginCore; import forestry.plugins.PluginFluids; +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; public class GameMode implements IGameMode { - private static final String GAMEMODE_KEY = "gamemode"; - private String identifier = "EASY"; - private final String category; + private static final String GAMEMODE_KEY = "gamemode"; + private String identifier = "EASY"; + private final String category; - private final Map booleanSettings = new HashMap<>(); - private final Map integerSettings = new HashMap<>(); - private final Map floatSettings = new HashMap<>(); - private final Map stackSettings = new HashMap<>(); + private final Map booleanSettings = new HashMap<>(); + private final Map integerSettings = new HashMap<>(); + private final Map floatSettings = new HashMap<>(); + private final Map stackSettings = new HashMap<>(); - private static final float ENERGY_DEMAND_MODIFIER = 1.0f; - private static final float FUEL_MODIFIER = 1.0f; + private static final float ENERGY_DEMAND_MODIFIER = 1.0f; + private static final float FUEL_MODIFIER = 1.0f; - private static final int FARM_FERTILIZER_VALUE = 2000; + private static final int FARM_FERTILIZER_VALUE = 2000; - private final ItemStack recipeFertilizerOutputApatite = PluginCore.items.fertilizerCompound.getItemStack(8); - private final ItemStack recipeFertilizerOutputAsh = PluginCore.items.fertilizerCompound.getItemStack(16); - private final ItemStack recipeCompostOutputWheat = PluginCore.items.fertilizerBio.getItemStack(4); - private final ItemStack recipeCompostOutputAsh = PluginCore.items.fertilizerBio.getItemStack(1); + private final ItemStack recipeFertilizerOutputApatite = PluginCore.items.fertilizerCompound.getItemStack(8); + private final ItemStack recipeFertilizerOutputAsh = PluginCore.items.fertilizerCompound.getItemStack(16); + private final ItemStack recipeCompostOutputWheat = PluginCore.items.fertilizerBio.getItemStack(4); + private final ItemStack recipeCompostOutputAsh = PluginCore.items.fertilizerBio.getItemStack(1); - private final ItemStack recipeHumusOutputFertilizer = PluginCore.blocks.soil.get(BlockSoil.SoilType.HUMUS, 8); - private final ItemStack recipeHumusOutputCompost = PluginCore.blocks.soil.get(BlockSoil.SoilType.HUMUS, 8); + private final ItemStack recipeHumusOutputFertilizer = PluginCore.blocks.soil.get(BlockSoil.SoilType.HUMUS, 8); + private final ItemStack recipeHumusOutputCompost = PluginCore.blocks.soil.get(BlockSoil.SoilType.HUMUS, 8); - private final ItemStack recipeBogEarthOutputBucket = PluginCore.blocks.soil.get(BlockSoil.SoilType.BOG_EARTH, 6); - private final ItemStack recipeBogEarthOutputCans = PluginCore.blocks.soil.get(BlockSoil.SoilType.BOG_EARTH, 8); + private final ItemStack recipeBogEarthOutputBucket = PluginCore.blocks.soil.get(BlockSoil.SoilType.BOG_EARTH, 6); + private final ItemStack recipeBogEarthOutputCans = PluginCore.blocks.soil.get(BlockSoil.SoilType.BOG_EARTH, 8); - private final ItemStack recipeCanOutput = PluginFluids.items.canEmpty.getItemStack(12); - private final ItemStack recipeCapsuleOutput = PluginFluids.items.waxCapsuleEmpty.getItemStack(4); - private final ItemStack recipeRefractoryOutput = PluginFluids.items.refractoryEmpty.getItemStack(4); + private final ItemStack recipeCanOutput = PluginFluids.items.canEmpty.getItemStack(12); + private final ItemStack recipeCapsuleOutput = PluginFluids.items.waxCapsuleEmpty.getItemStack(4); + private final ItemStack recipeRefractoryOutput = PluginFluids.items.refractoryEmpty.getItemStack(4); - private static final int FERMENTATION_DURATION_FERTILIZER = 200; - private static final int FERMENTATION_DURATION_COMPOST = 250; + private static final int FERMENTATION_DURATION_FERTILIZER = 200; + private static final int FERMENTATION_DURATION_COMPOST = 250; - private static final int FERMENTED_CYCLE_FERTILIZER = 56; - private static final int FERMENTED_CYCLE_COMPOST = 48; + private static final int FERMENTED_CYCLE_FERTILIZER = 56; + private static final int FERMENTED_CYCLE_COMPOST = 48; - private static final int FERMENTED_SAPLING = 250; - private static final int FERMENTED_CACTI = 50; - private static final int FERMENTED_WHEAT = 50; - private static final int FERMENTED_CANE = 50; - private static final int FERMENTED_MUSHROOM = 50; + private static final int FERMENTED_SAPLING = 250; + private static final int FERMENTED_CACTI = 50; + private static final int FERMENTED_WHEAT = 50; + private static final int FERMENTED_CANE = 50; + private static final int FERMENTED_MUSHROOM = 50; - private static final int SQUEEZED_LIQUID_SEED = 10; - private static final int SQUEEZED_LIQUID_APPLE = 200; - private static final int SQUEEZED_MULCH_APPLE = 20; + private static final int SQUEEZED_LIQUID_SEED = 10; + private static final int SQUEEZED_LIQUID_APPLE = 200; + private static final int SQUEEZED_MULCH_APPLE = 20; - public GameMode(String identifier) { + public GameMode(String identifier) { - this.identifier = identifier; - this.category = "gamemodes/" + identifier; + this.identifier = identifier; + this.category = "gamemodes/" + identifier; - File configFile = new File(Forestry.instance.getConfigFolder(), category + ".cfg"); + File configFile = new File(Forestry.instance.getConfigFolder(), category + ".cfg"); - LocalizedConfiguration config = new LocalizedConfiguration(configFile, "1.0.0"); + LocalizedConfiguration config = new LocalizedConfiguration(configFile, "1.0.0"); - initSettingFloat(config, "energy", "demand.modifier", ENERGY_DEMAND_MODIFIER); - initSettingBoolean(config, "energy", "engine.clockwork", true); + initSettingFloat(config, "energy", "demand.modifier", ENERGY_DEMAND_MODIFIER); + initSettingBoolean(config, "energy", "engine.clockwork", true); - initSettingInt(config, "farms", "fertilizer.value", FARM_FERTILIZER_VALUE); + initSettingInt(config, "farms", "fertilizer.value", FARM_FERTILIZER_VALUE); - initSettingFloat(config, "fuel.ethanol", "generator", FUEL_MODIFIER); - initSettingFloat(config, "fuel.ethanol", "combustion", FUEL_MODIFIER); - initSettingFloat(config, "fuel.biomass", "generator", FUEL_MODIFIER); - initSettingFloat(config, "fuel.biomass", "biogas", FUEL_MODIFIER); + initSettingFloat(config, "fuel.ethanol", "generator", FUEL_MODIFIER); + initSettingFloat(config, "fuel.ethanol", "combustion", FUEL_MODIFIER); + initSettingFloat(config, "fuel.biomass", "generator", FUEL_MODIFIER); + initSettingFloat(config, "fuel.biomass", "biogas", FUEL_MODIFIER); - initSettingStack(config, "recipe.output.fertilizer", "apatite", recipeFertilizerOutputApatite); - initSettingStack(config, "recipe.output.fertilizer", "ash", recipeFertilizerOutputAsh); - initSettingStack(config, "recipe.output.compost", "wheat", recipeCompostOutputWheat); - initSettingStack(config, "recipe.output.compost", "ash", recipeCompostOutputAsh); - initSettingStack(config, "recipe.output.humus", "fertilizer", recipeHumusOutputFertilizer); - initSettingStack(config, "recipe.output.humus", "compost", recipeHumusOutputCompost); - initSettingStack(config, "recipe.output.bogearth", "bucket", recipeBogEarthOutputBucket); - initSettingStack(config, "recipe.output.bogearth", "can", recipeBogEarthOutputCans); - initSettingStack(config, "recipe.output", "can", recipeCanOutput); - initSettingStack(config, "recipe.output", "capsule", recipeCapsuleOutput); - initSettingStack(config, "recipe.output", "refractory", recipeRefractoryOutput); + initSettingStack(config, "recipe.output.fertilizer", "apatite", recipeFertilizerOutputApatite); + initSettingStack(config, "recipe.output.fertilizer", "ash", recipeFertilizerOutputAsh); + initSettingStack(config, "recipe.output.compost", "wheat", recipeCompostOutputWheat); + initSettingStack(config, "recipe.output.compost", "ash", recipeCompostOutputAsh); + initSettingStack(config, "recipe.output.humus", "fertilizer", recipeHumusOutputFertilizer); + initSettingStack(config, "recipe.output.humus", "compost", recipeHumusOutputCompost); + initSettingStack(config, "recipe.output.bogearth", "bucket", recipeBogEarthOutputBucket); + initSettingStack(config, "recipe.output.bogearth", "can", recipeBogEarthOutputCans); + initSettingStack(config, "recipe.output", "can", recipeCanOutput); + initSettingStack(config, "recipe.output", "capsule", recipeCapsuleOutput); + initSettingStack(config, "recipe.output", "refractory", recipeRefractoryOutput); - initSettingInt(config, "fermenter.cycles", "fertilizer", FERMENTATION_DURATION_FERTILIZER); - initSettingInt(config, "fermenter.cycles", "compost", FERMENTATION_DURATION_COMPOST); + initSettingInt(config, "fermenter.cycles", "fertilizer", FERMENTATION_DURATION_FERTILIZER); + initSettingInt(config, "fermenter.cycles", "compost", FERMENTATION_DURATION_COMPOST); - initSettingInt(config, "fermenter.value", "fertilizer", FERMENTED_CYCLE_FERTILIZER); - initSettingInt(config, "fermenter.value", "compost", FERMENTED_CYCLE_COMPOST); + initSettingInt(config, "fermenter.value", "fertilizer", FERMENTED_CYCLE_FERTILIZER); + initSettingInt(config, "fermenter.value", "compost", FERMENTED_CYCLE_COMPOST); - initSettingInt(config, "fermenter.yield", "sapling", FERMENTED_SAPLING); - initSettingInt(config, "fermenter.yield", "cactus", FERMENTED_CACTI); - initSettingInt(config, "fermenter.yield", "wheat", FERMENTED_WHEAT); - initSettingInt(config, "fermenter.yield", "cane", FERMENTED_CANE); - initSettingInt(config, "fermenter.yield", "mushroom", FERMENTED_MUSHROOM); + initSettingInt(config, "fermenter.yield", "sapling", FERMENTED_SAPLING); + initSettingInt(config, "fermenter.yield", "cactus", FERMENTED_CACTI); + initSettingInt(config, "fermenter.yield", "wheat", FERMENTED_WHEAT); + initSettingInt(config, "fermenter.yield", "cane", FERMENTED_CANE); + initSettingInt(config, "fermenter.yield", "mushroom", FERMENTED_MUSHROOM); - initSettingInt(config, "squeezer.liquid", "seed", SQUEEZED_LIQUID_SEED); - initSettingInt(config, "squeezer.liquid", "apple", SQUEEZED_LIQUID_APPLE); + initSettingInt(config, "squeezer.liquid", "seed", SQUEEZED_LIQUID_SEED); + initSettingInt(config, "squeezer.liquid", "apple", SQUEEZED_LIQUID_APPLE); - initSettingInt(config, "squeezer.mulch", "apple", SQUEEZED_MULCH_APPLE); + initSettingInt(config, "squeezer.mulch", "apple", SQUEEZED_MULCH_APPLE); - config.save(); - } + config.save(); + } - private void initSettingFloat(LocalizedConfiguration config, String category, String name, float defaultValue) { - String fullName = category + '.' + name; - float floatValue = config.getFloatLocalized(GAMEMODE_KEY + '.' + category, name, defaultValue, 0.0f, 10.0f); - floatSettings.put(fullName, floatValue); - } + private void initSettingFloat(LocalizedConfiguration config, String category, String name, float defaultValue) { + String fullName = category + '.' + name; + float floatValue = config.getFloatLocalized(GAMEMODE_KEY + '.' + category, name, defaultValue, 0.0f, 10.0f); + floatSettings.put(fullName, floatValue); + } - private void initSettingInt(LocalizedConfiguration config, String category, String key, int defaultValue) { - String fullKey = category + '.' + key; - int intValue = config.getIntLocalized(GAMEMODE_KEY + '.' + category, key, defaultValue, 0, 2000); - integerSettings.put(fullKey, intValue); - } + private void initSettingInt(LocalizedConfiguration config, String category, String key, int defaultValue) { + String fullKey = category + '.' + key; + int intValue = config.getIntLocalized(GAMEMODE_KEY + '.' + category, key, defaultValue, 0, 2000); + integerSettings.put(fullKey, intValue); + } - private void initSettingStack(LocalizedConfiguration config, String category, String key, ItemStack defaultValue) { - String fullKey = category + '.' + key; - int stackSize = config.getIntLocalized(GAMEMODE_KEY + '.' + category, key, defaultValue.stackSize, 0, 64); - ItemStack changed = defaultValue.copy(); - changed.stackSize = stackSize; - stackSettings.put(fullKey, changed); - } + private void initSettingStack(LocalizedConfiguration config, String category, String key, ItemStack defaultValue) { + String fullKey = category + '.' + key; + int stackSize = config.getIntLocalized(GAMEMODE_KEY + '.' + category, key, defaultValue.stackSize, 0, 64); + ItemStack changed = defaultValue.copy(); + changed.stackSize = stackSize; + stackSettings.put(fullKey, changed); + } - private void initSettingBoolean(LocalizedConfiguration config, String category, String key, boolean defaultValue) { - String fullKey = category + '.' + key; - boolean booleanValue = config.getBooleanLocalized(GAMEMODE_KEY + '.' + category, key, defaultValue); - booleanSettings.put(fullKey, booleanValue); - } + private void initSettingBoolean(LocalizedConfiguration config, String category, String key, boolean defaultValue) { + String fullKey = category + '.' + key; + boolean booleanValue = config.getBooleanLocalized(GAMEMODE_KEY + '.' + category, key, defaultValue); + booleanSettings.put(fullKey, booleanValue); + } - @Override - public int getIntegerSetting(String ident) { - if (integerSettings.containsKey(ident)) { - return integerSettings.get(ident); - } - Log.warning("No such setting: " + ident); - return -1; - } + @Override + public int getIntegerSetting(String ident) { + if (integerSettings.containsKey(ident)) { + return integerSettings.get(ident); + } + Log.warning("No such setting: " + ident); + return -1; + } - @Override - public float getFloatSetting(String ident) { - if (floatSettings.containsKey(ident)) { - return floatSettings.get(ident); - } - Log.warning("No such setting: " + ident); - return 1; - } + @Override + public float getFloatSetting(String ident) { + if (floatSettings.containsKey(ident)) { + return floatSettings.get(ident); + } + Log.warning("No such setting: " + ident); + return 1; + } - @Override - public boolean getBooleanSetting(String ident) { - if (booleanSettings.containsKey(ident)) { - return booleanSettings.get(ident); - } - Log.warning("No such setting: " + ident); - return false; - } + @Override + public boolean getBooleanSetting(String ident) { + if (booleanSettings.containsKey(ident)) { + return booleanSettings.get(ident); + } + Log.warning("No such setting: " + ident); + return false; + } - @Override - public ItemStack getStackSetting(String ident) { - if (stackSettings.containsKey(ident)) { - return stackSettings.get(ident); - } - Log.warning("No such setting: " + ident); - return new ItemStack(Items.apple, 1); - } - - @Override - public String getIdentifier() { - return identifier; - } + @Override + public ItemStack getStackSetting(String ident) { + if (stackSettings.containsKey(ident)) { + return stackSettings.get(ident); + } + Log.warning("No such setting: " + ident); + return new ItemStack(Items.apple, 1); + } + @Override + public String getIdentifier() { + return identifier; + } } diff --git a/src/main/java/forestry/core/config/LocalizedConfiguration.java b/src/main/java/forestry/core/config/LocalizedConfiguration.java index 6758aa3e5..74f759935 100644 --- a/src/main/java/forestry/core/config/LocalizedConfiguration.java +++ b/src/main/java/forestry/core/config/LocalizedConfiguration.java @@ -1,149 +1,149 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.config; - -import java.io.File; -import java.util.Arrays; - -import net.minecraft.util.StatCollector; - -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.common.config.Property; - -public class LocalizedConfiguration extends Configuration { - - public LocalizedConfiguration(File file, String configVersion) { - super(file, configVersion); - } - - public Configuration setCategoryLanguageKey(String categoryName) { - String categoryKey = "for.config" + categoryName; - return super.setCategoryLanguageKey(categoryName, categoryKey); - } - - public boolean getBoolean(String category, String name, boolean defaultValue, String comment) { - Property prop = this.get(category, name, defaultValue); - prop.comment = comment + " [default: " + defaultValue + "]"; - return prop.getBoolean(defaultValue); - } - - public boolean getBooleanLocalized(String category, String name, boolean defaultValue) { - String langKey = "for.config." + category + '.' + name; - String commentKey = langKey + '.' + "comment"; - String comment = ""; - if (StatCollector.canTranslate(commentKey)) { - comment = StatCollector.translateToLocal(commentKey); - } - return getBoolean(name, category, defaultValue, comment, langKey); - } - - public String getStringLocalized(String category, String name, String defaultValue) { - String langKey = "for.config." + category + '.' + name; - String commentKey = langKey + '.' + "comment"; - String comment = ""; - if (StatCollector.canTranslate(commentKey)) { - comment = StatCollector.translateToLocal(commentKey); - } - return getString(name, category, defaultValue, comment, langKey); - } - - public String getStringLocalized(String category, String name, String defaultValue, String[] validValues) { - String langKey = "for.config." + category + '.' + name; - String commentKey = langKey + '.' + "comment"; - String comment = ""; - if (StatCollector.canTranslate(commentKey)) { - comment = StatCollector.translateToLocal(commentKey); - } - - Property prop = this.get(category, name, defaultValue); - prop.setValidValues(validValues); - prop.setLanguageKey(langKey); - prop.comment = comment + " [default: " + defaultValue + "] [valid: " + Arrays.toString(prop.getValidValues()) + "]"; - return prop.getString(); - } - - public > T getEnumLocalized(String category, String name, T defaultValue, T[] validEnumValues) { - String langKey = "for.config." + category + '.' + name; - String commentKey = langKey + '.' + "comment"; - String comment = ""; - if (StatCollector.canTranslate(commentKey)) { - comment = StatCollector.translateToLocal(commentKey); - } - - Property prop = this.get(category, name, defaultValue.name()); - - String[] validValues = new String[validEnumValues.length]; - for (int i = 0; i < validEnumValues.length; i++) { - T enumValue = validEnumValues[i]; - validValues[i] = enumValue.name(); - } - - prop.setValidValues(validValues); - prop.setLanguageKey(langKey); - prop.comment = comment + " [default: " + defaultValue + "] [valid: " + Arrays.toString(prop.getValidValues()) + "]"; - String stringValue = prop.getString(); - - T enumValue = defaultValue; - for (int i = 0; i < validValues.length; i++) { - if (stringValue.equals(validValues[i])) { - enumValue = validEnumValues[i]; - } - } - - return enumValue; - } - - public String[] getStringListLocalized(String category, String name, String[] defaultValue) { - String langKey = "for.config." + category + '.' + name; - String commentKey = langKey + '.' + "comment"; - String comment = ""; - if (StatCollector.canTranslate(commentKey)) { - comment = StatCollector.translateToLocal(commentKey); - } - return super.getStringList(name, category, defaultValue, comment); - } - - public String[] getStringListLocalized(String category, String name, String[] defaultValue, String[] validValues) { - String langKey = "for.config." + category + '.' + name; - String commentKey = langKey + '.' + "comment"; - String comment = ""; - if (StatCollector.canTranslate(commentKey)) { - comment = StatCollector.translateToLocal(commentKey); - } - - Property prop = this.get(category, name, defaultValue); - prop.setLanguageKey(langKey); - prop.setValidValues(validValues); - prop.comment = comment + " [default: " + Arrays.toString(defaultValue) + "] [valid: " + Arrays.toString(prop.getValidValues()) + "]"; - return prop.getStringList(); - } - - public float getFloatLocalized(String category, String name, float defaultValue, float minValue, float maxValue) { - String langKey = "for.config." + category + '.' + name; - String commentKey = langKey + '.' + "comment"; - String comment = ""; - if (StatCollector.canTranslate(commentKey)) { - comment = StatCollector.translateToLocal(commentKey); - } - return getFloat(name, category, defaultValue, minValue, maxValue, comment, langKey); - } - - public int getIntLocalized(String category, String name, int defaultValue, int minValue, int maxValue) { - String langKey = "for.config." + category + '.' + name; - String commentKey = langKey + '.' + "comment"; - String comment = ""; - if (StatCollector.canTranslate(commentKey)) { - comment = StatCollector.translateToLocal(commentKey); - } - return getInt(name, category, defaultValue, minValue, maxValue, comment, langKey); - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.config; + +import java.io.File; +import java.util.Arrays; +import net.minecraft.util.StatCollector; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; + +public class LocalizedConfiguration extends Configuration { + + public LocalizedConfiguration(File file, String configVersion) { + super(file, configVersion); + } + + public Configuration setCategoryLanguageKey(String categoryName) { + String categoryKey = "for.config" + categoryName; + return super.setCategoryLanguageKey(categoryName, categoryKey); + } + + public boolean getBoolean(String category, String name, boolean defaultValue, String comment) { + Property prop = this.get(category, name, defaultValue); + prop.comment = comment + " [default: " + defaultValue + "]"; + return prop.getBoolean(defaultValue); + } + + public boolean getBooleanLocalized(String category, String name, boolean defaultValue) { + String langKey = "for.config." + category + '.' + name; + String commentKey = langKey + '.' + "comment"; + String comment = ""; + if (StatCollector.canTranslate(commentKey)) { + comment = StatCollector.translateToLocal(commentKey); + } + return getBoolean(name, category, defaultValue, comment, langKey); + } + + public String getStringLocalized(String category, String name, String defaultValue) { + String langKey = "for.config." + category + '.' + name; + String commentKey = langKey + '.' + "comment"; + String comment = ""; + if (StatCollector.canTranslate(commentKey)) { + comment = StatCollector.translateToLocal(commentKey); + } + return getString(name, category, defaultValue, comment, langKey); + } + + public String getStringLocalized(String category, String name, String defaultValue, String[] validValues) { + String langKey = "for.config." + category + '.' + name; + String commentKey = langKey + '.' + "comment"; + String comment = ""; + if (StatCollector.canTranslate(commentKey)) { + comment = StatCollector.translateToLocal(commentKey); + } + + Property prop = this.get(category, name, defaultValue); + prop.setValidValues(validValues); + prop.setLanguageKey(langKey); + prop.comment = + comment + " [default: " + defaultValue + "] [valid: " + Arrays.toString(prop.getValidValues()) + "]"; + return prop.getString(); + } + + public > T getEnumLocalized(String category, String name, T defaultValue, T[] validEnumValues) { + String langKey = "for.config." + category + '.' + name; + String commentKey = langKey + '.' + "comment"; + String comment = ""; + if (StatCollector.canTranslate(commentKey)) { + comment = StatCollector.translateToLocal(commentKey); + } + + Property prop = this.get(category, name, defaultValue.name()); + + String[] validValues = new String[validEnumValues.length]; + for (int i = 0; i < validEnumValues.length; i++) { + T enumValue = validEnumValues[i]; + validValues[i] = enumValue.name(); + } + + prop.setValidValues(validValues); + prop.setLanguageKey(langKey); + prop.comment = + comment + " [default: " + defaultValue + "] [valid: " + Arrays.toString(prop.getValidValues()) + "]"; + String stringValue = prop.getString(); + + T enumValue = defaultValue; + for (int i = 0; i < validValues.length; i++) { + if (stringValue.equals(validValues[i])) { + enumValue = validEnumValues[i]; + } + } + + return enumValue; + } + + public String[] getStringListLocalized(String category, String name, String[] defaultValue) { + String langKey = "for.config." + category + '.' + name; + String commentKey = langKey + '.' + "comment"; + String comment = ""; + if (StatCollector.canTranslate(commentKey)) { + comment = StatCollector.translateToLocal(commentKey); + } + return super.getStringList(name, category, defaultValue, comment); + } + + public String[] getStringListLocalized(String category, String name, String[] defaultValue, String[] validValues) { + String langKey = "for.config." + category + '.' + name; + String commentKey = langKey + '.' + "comment"; + String comment = ""; + if (StatCollector.canTranslate(commentKey)) { + comment = StatCollector.translateToLocal(commentKey); + } + + Property prop = this.get(category, name, defaultValue); + prop.setLanguageKey(langKey); + prop.setValidValues(validValues); + prop.comment = comment + " [default: " + Arrays.toString(defaultValue) + "] [valid: " + + Arrays.toString(prop.getValidValues()) + "]"; + return prop.getStringList(); + } + + public float getFloatLocalized(String category, String name, float defaultValue, float minValue, float maxValue) { + String langKey = "for.config." + category + '.' + name; + String commentKey = langKey + '.' + "comment"; + String comment = ""; + if (StatCollector.canTranslate(commentKey)) { + comment = StatCollector.translateToLocal(commentKey); + } + return getFloat(name, category, defaultValue, minValue, maxValue, comment, langKey); + } + + public int getIntLocalized(String category, String name, int defaultValue, int minValue, int maxValue) { + String langKey = "for.config." + category + '.' + name; + String commentKey = langKey + '.' + "comment"; + String comment = ""; + if (StatCollector.canTranslate(commentKey)) { + comment = StatCollector.translateToLocal(commentKey); + } + return getInt(name, category, defaultValue, minValue, maxValue, comment, langKey); + } +} diff --git a/src/main/java/forestry/core/config/SessionVars.java b/src/main/java/forestry/core/config/SessionVars.java index 623d41872..13054d72a 100755 --- a/src/main/java/forestry/core/config/SessionVars.java +++ b/src/main/java/forestry/core/config/SessionVars.java @@ -13,32 +13,32 @@ package forestry.core.config; import java.util.HashMap; public class SessionVars { - - private static final HashMap stringVars = new HashMap<>(); - - private static Class openedLedger; - public static void setOpenedLedger(Class ledgerClass) { - openedLedger = ledgerClass; - } + private static final HashMap stringVars = new HashMap<>(); - public static Class getOpenedLedger() { - return openedLedger; - } - - public static void setStringVar(String ident, String val) { - stringVars.put(ident, val); - } - - public static String getStringVar(String ident) { - if (stringVars.containsKey(ident)) { - return stringVars.get(ident); - } - - return null; - } - - public static void clearStringVar(String ident) { - stringVars.remove(ident); - } + private static Class openedLedger; + + public static void setOpenedLedger(Class ledgerClass) { + openedLedger = ledgerClass; + } + + public static Class getOpenedLedger() { + return openedLedger; + } + + public static void setStringVar(String ident, String val) { + stringVars.put(ident, val); + } + + public static String getStringVar(String ident) { + if (stringVars.containsKey(ident)) { + return stringVars.get(ident); + } + + return null; + } + + public static void clearStringVar(String ident) { + stringVars.remove(ident); + } } diff --git a/src/main/java/forestry/core/config/Version.java b/src/main/java/forestry/core/config/Version.java index 8f9ab3d99..ba7ec45e4 100755 --- a/src/main/java/forestry/core/config/Version.java +++ b/src/main/java/forestry/core/config/Version.java @@ -10,23 +10,20 @@ ******************************************************************************/ package forestry.core.config; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.versioning.DefaultArtifactVersion; +import forestry.Forestry; +import forestry.core.proxy.Proxies; +import forestry.core.utils.Log; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; - import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.versioning.DefaultArtifactVersion; - -import forestry.Forestry; -import forestry.core.proxy.Proxies; -import forestry.core.utils.Log; - /** * With permission from pahimar. * @@ -34,147 +31,157 @@ import forestry.core.utils.Log; */ public class Version { - public enum EnumUpdateState { + public enum EnumUpdateState { + CURRENT, + OUTDATED, + CONNECTION_ERROR + } - CURRENT, OUTDATED, CONNECTION_ERROR - } + public static final String VERSION = "@VERSION@"; + public static final String BUILD_NUMBER = "@BUILD_NUMBER@"; + public static final String[] FAILED_CHANGELOG = + new String[] {String.format("Unable to retrieve changelog for %s", Constants.MOD)}; + private static final String REMOTE_VERSION_FILE = "http://bit.ly/forestryver"; + private static final String REMOTE_CHANGELOG_ROOT = "https://dl.dropbox.com/u/44760587/forestry/changelog/"; + public static EnumUpdateState currentVersion = EnumUpdateState.CURRENT; + private static String recommendedVersion; + private static String[] cachedChangelog = FAILED_CHANGELOG; - public static final String VERSION = "@VERSION@"; - public static final String BUILD_NUMBER = "@BUILD_NUMBER@"; - public static final String[] FAILED_CHANGELOG = new String[]{String.format("Unable to retrieve changelog for %s", Constants.MOD)}; - private static final String REMOTE_VERSION_FILE = "http://bit.ly/forestryver"; - private static final String REMOTE_CHANGELOG_ROOT = "https://dl.dropbox.com/u/44760587/forestry/changelog/"; - public static EnumUpdateState currentVersion = EnumUpdateState.CURRENT; - private static String recommendedVersion; - private static String[] cachedChangelog = FAILED_CHANGELOG; + public static String getVersion() { + return VERSION + " (" + BUILD_NUMBER + ")"; + } - public static String getVersion() { - return VERSION + " (" + BUILD_NUMBER + ")"; - } + public static boolean isOutdated() { + return currentVersion == EnumUpdateState.OUTDATED; + } - public static boolean isOutdated() { - return currentVersion == EnumUpdateState.OUTDATED; - } + public static boolean needsUpdateNoticeAndMarkAsSeen() { + if (!isOutdated()) { + return false; + } - public static boolean needsUpdateNoticeAndMarkAsSeen() { - if (!isOutdated()) { - return false; - } + File versionFile = new File(Forestry.instance.getConfigFolder(), Config.CATEGORY_COMMON + ".cfg"); + Configuration config = new Configuration(versionFile); + Property property = config.get("version", "seen", VERSION); + property.comment = + "indicates the last version the user has been informed about and will suppress further notices on it."; + String seenVersion = property.getString(); - File versionFile = new File(Forestry.instance.getConfigFolder(), Config.CATEGORY_COMMON + ".cfg"); - Configuration config = new Configuration(versionFile); - Property property = config.get("version", "seen", VERSION); - property.comment = "indicates the last version the user has been informed about and will suppress further notices on it."; - String seenVersion = property.getString(); + if (recommendedVersion == null || recommendedVersion.equals(seenVersion)) { + return false; + } - if (recommendedVersion == null || recommendedVersion.equals(seenVersion)) { - return false; - } + property.set(recommendedVersion); + config.save(); + return true; + } - property.set(recommendedVersion); - config.save(); - return true; - } + public static String getRecommendedVersion() { + return recommendedVersion; + } - public static String getRecommendedVersion() { - return recommendedVersion; - } + private static class VersionChecker extends Thread { - private static class VersionChecker extends Thread { + @Override + public void run() { + try { + String location = REMOTE_VERSION_FILE; + HttpURLConnection conn = null; + while (location != null && !location.isEmpty()) { + URL url = new URL(location); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestProperty( + "User-Agent", + "Mozilla/5.0 (Windows; U; Windows NT 6.0; ru; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)"); + conn.connect(); + location = conn.getHeaderField("Location"); + } - @Override - public void run() { - try { - String location = REMOTE_VERSION_FILE; - HttpURLConnection conn = null; - while (location != null && !location.isEmpty()) { - URL url = new URL(location); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestProperty("User-Agent", - "Mozilla/5.0 (Windows; U; Windows NT 6.0; ru; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)"); - conn.connect(); - location = conn.getHeaderField("Location"); - } + BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); - BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + String mcVersion = Proxies.common.getMinecraftVersion(); + while ((line = reader.readLine()) != null) { + if (line.startsWith(mcVersion) && line.contains(Constants.MOD)) { + String[] tokens = line.split(":"); + recommendedVersion = tokens[2]; + } + } - String line; - String mcVersion = Proxies.common.getMinecraftVersion(); - while ((line = reader.readLine()) != null) { - if (line.startsWith(mcVersion) && line.contains(Constants.MOD)) { - String[] tokens = line.split(":"); - recommendedVersion = tokens[2]; - } - } + if (recommendedVersion == null) { + return; + } - if (recommendedVersion == null) { - return; - } + int result = FMLCommonHandler.instance() + .findContainerFor(Forestry.instance) + .getProcessedVersion() + .compareTo(new DefaultArtifactVersion(recommendedVersion)); + if (result >= 0) { + Log.finer("Using the latest version [" + VERSION + " (build:" + BUILD_NUMBER + ")] for Minecraft " + + mcVersion); + currentVersion = EnumUpdateState.CURRENT; + return; + } - int result = FMLCommonHandler.instance().findContainerFor(Forestry.instance).getProcessedVersion().compareTo(new DefaultArtifactVersion(recommendedVersion)); - if (result >= 0) { - Log.finer("Using the latest version [" + VERSION + " (build:" + BUILD_NUMBER + ")] for Minecraft " + mcVersion); - currentVersion = EnumUpdateState.CURRENT; - return; - } + cachedChangelog = grabChangelog(recommendedVersion); - cachedChangelog = grabChangelog(recommendedVersion); + Log.warning("Using outdated version [" + VERSION + " (build:" + BUILD_NUMBER + ")] for Minecraft " + + mcVersion + ". Consider updating."); + currentVersion = EnumUpdateState.OUTDATED; - Log.warning("Using outdated version [" + VERSION + " (build:" + BUILD_NUMBER + ")] for Minecraft " + mcVersion + ". Consider updating."); - currentVersion = EnumUpdateState.OUTDATED; + } catch (Exception e) { + // e.printStackTrace(); + Log.warning("Unable to read from remote version authority."); + currentVersion = EnumUpdateState.CONNECTION_ERROR; + } + } + } - } catch (Exception e) { - // e.printStackTrace(); - Log.warning("Unable to read from remote version authority."); - currentVersion = EnumUpdateState.CONNECTION_ERROR; - } - } - } + public static void versionCheck() { + new VersionChecker().start(); + } - public static void versionCheck() { - new VersionChecker().start(); - } + public static String[] getChangelog() { + return cachedChangelog; + } - public static String[] getChangelog() { - return cachedChangelog; - } + public static String[] grabChangelog(String version) { - public static String[] grabChangelog(String version) { + try { + String location = REMOTE_CHANGELOG_ROOT + version; + HttpURLConnection conn; + do { + URL url = new URL(location); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestProperty( + "User-Agent", + "Mozilla/5.0 (Windows; U; Windows NT 6.0; ru; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)"); + conn.connect(); + location = conn.getHeaderField("Location"); + } while (location != null && !location.isEmpty()); - try { - String location = REMOTE_CHANGELOG_ROOT + version; - HttpURLConnection conn; - do { - URL url = new URL(location); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestProperty("User-Agent", - "Mozilla/5.0 (Windows; U; Windows NT 6.0; ru; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)"); - conn.connect(); - location = conn.getHeaderField("Location"); - } while (location != null && !location.isEmpty()); + BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); - BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + ArrayList changelog = new ArrayList<>(); + while ((line = reader.readLine()) != null) { + if (line.startsWith("#")) { + continue; + } + if (line.isEmpty()) { + continue; + } - String line; - ArrayList changelog = new ArrayList<>(); - while ((line = reader.readLine()) != null) { - if (line.startsWith("#")) { - continue; - } - if (line.isEmpty()) { - continue; - } + changelog.add(line); + } - changelog.add(line); - } + return changelog.toArray(new String[changelog.size()]); - return changelog.toArray(new String[changelog.size()]); + } catch (Exception ex) { + // ex.printStackTrace(); + Log.warning("Unable to read changelog from remote site."); + } - } catch (Exception ex) { - // ex.printStackTrace(); - Log.warning("Unable to read changelog from remote site."); - } - - return new String[]{String.format("Unable to retrieve changelog for %s %s", Constants.MOD, version)}; - } + return new String[] {String.format("Unable to retrieve changelog for %s %s", Constants.MOD, version)}; + } } diff --git a/src/main/java/forestry/core/entities/EntityFXColoredDropParticle.java b/src/main/java/forestry/core/entities/EntityFXColoredDropParticle.java index 725377058..07c3ddc0c 100644 --- a/src/main/java/forestry/core/entities/EntityFXColoredDropParticle.java +++ b/src/main/java/forestry/core/entities/EntityFXColoredDropParticle.java @@ -1,84 +1,93 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.entities; - -import net.minecraft.block.BlockLiquid; -import net.minecraft.block.material.Material; -import net.minecraft.client.particle.EntityFX; -import net.minecraft.util.MathHelper; -import net.minecraft.world.World; - -public class EntityFXColoredDropParticle extends EntityFX { - - /** - * The height of the current bob - */ - private int bobTimer; - - public EntityFXColoredDropParticle(World world, double x, double y, double z, float red, float green, float blue) { - super(world, x, y, z); - this.particleRed = red; - this.particleGreen = green; - this.particleBlue = blue; - - this.setParticleTextureIndex(113); - this.setSize(0.01F, 0.01F); - this.particleGravity = 0.06F; - this.bobTimer = 40; - this.particleMaxAge = (int) (64.0D / (Math.random() * 0.8D + 0.2D)); - } - - /** - * Called to update the entity's position/logic. - */ - public void onUpdate() { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - - this.motionY -= (double) this.particleGravity; - - if (this.bobTimer-- > 0) { - this.motionX *= 0.02D; - this.motionY *= 0.02D; - this.motionZ *= 0.02D; - this.setParticleTextureIndex(113); - } else { - this.setParticleTextureIndex(112); - } - - this.moveEntity(this.motionX, this.motionY, this.motionZ); - this.motionX *= 0.9800000190734863D; - this.motionY *= 0.9800000190734863D; - this.motionZ *= 0.9800000190734863D; - - if (this.particleMaxAge-- <= 0) { - this.setDead(); - } - - if (this.onGround) { - this.setParticleTextureIndex(114); - - this.motionX *= 0.699999988079071D; - this.motionZ *= 0.699999988079071D; - } - - Material material = this.worldObj.getBlock(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.posY), MathHelper.floor_double(this.posZ)).getMaterial(); - - if (material.isLiquid() || material.isSolid()) { - double d0 = (double) ((float) (MathHelper.floor_double(this.posY) + 1) - BlockLiquid.getLiquidHeightPercent(this.worldObj.getBlockMetadata(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.posY), MathHelper.floor_double(this.posZ)))); - - if (this.posY < d0) { - this.setDead(); - } - } - } -} \ No newline at end of file +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.entities; + +import net.minecraft.block.BlockLiquid; +import net.minecraft.block.material.Material; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.util.MathHelper; +import net.minecraft.world.World; + +public class EntityFXColoredDropParticle extends EntityFX { + + /** + * The height of the current bob + */ + private int bobTimer; + + public EntityFXColoredDropParticle(World world, double x, double y, double z, float red, float green, float blue) { + super(world, x, y, z); + this.particleRed = red; + this.particleGreen = green; + this.particleBlue = blue; + + this.setParticleTextureIndex(113); + this.setSize(0.01F, 0.01F); + this.particleGravity = 0.06F; + this.bobTimer = 40; + this.particleMaxAge = (int) (64.0D / (Math.random() * 0.8D + 0.2D)); + } + + /** + * Called to update the entity's position/logic. + */ + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + + this.motionY -= (double) this.particleGravity; + + if (this.bobTimer-- > 0) { + this.motionX *= 0.02D; + this.motionY *= 0.02D; + this.motionZ *= 0.02D; + this.setParticleTextureIndex(113); + } else { + this.setParticleTextureIndex(112); + } + + this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.motionX *= 0.9800000190734863D; + this.motionY *= 0.9800000190734863D; + this.motionZ *= 0.9800000190734863D; + + if (this.particleMaxAge-- <= 0) { + this.setDead(); + } + + if (this.onGround) { + this.setParticleTextureIndex(114); + + this.motionX *= 0.699999988079071D; + this.motionZ *= 0.699999988079071D; + } + + Material material = this.worldObj + .getBlock( + MathHelper.floor_double(this.posX), + MathHelper.floor_double(this.posY), + MathHelper.floor_double(this.posZ)) + .getMaterial(); + + if (material.isLiquid() || material.isSolid()) { + double d0 = (double) ((float) (MathHelper.floor_double(this.posY) + 1) + - BlockLiquid.getLiquidHeightPercent(this.worldObj.getBlockMetadata( + MathHelper.floor_double(this.posX), + MathHelper.floor_double(this.posY), + MathHelper.floor_double(this.posZ)))); + + if (this.posY < d0) { + this.setDead(); + } + } + } +} diff --git a/src/main/java/forestry/core/entities/EntityFXHoneydust.java b/src/main/java/forestry/core/entities/EntityFXHoneydust.java index 6282979da..44ad33be5 100644 --- a/src/main/java/forestry/core/entities/EntityFXHoneydust.java +++ b/src/main/java/forestry/core/entities/EntityFXHoneydust.java @@ -15,14 +15,14 @@ import net.minecraft.world.World; public class EntityFXHoneydust extends EntityReddustFX { - public EntityFXHoneydust(World world, double d, double d1, double d2, float f, float f1, float f2) { - this(world, d, d1, d2, 1.0F, f, f1, f2); - } + public EntityFXHoneydust(World world, double d, double d1, double d2, float f, float f1, float f2) { + this(world, d, d1, d2, 1.0F, f, f1, f2); + } - public EntityFXHoneydust(World world, double d, double d1, double d2, float f, float f1, float f2, float f3) { - super(world, d, d1, d2, f, f1, f2, f3); - particleRed = 0.9F + (world.rand.nextFloat() * 0.2F); - particleGreen = 0.75F + (world.rand.nextFloat() * 0.2F); - particleBlue = 0F + (world.rand.nextFloat() * 0.2F); - } + public EntityFXHoneydust(World world, double d, double d1, double d2, float f, float f1, float f2, float f3) { + super(world, d, d1, d2, f, f1, f2, f3); + particleRed = 0.9F + (world.rand.nextFloat() * 0.2F); + particleGreen = 0.75F + (world.rand.nextFloat() * 0.2F); + particleBlue = 0F + (world.rand.nextFloat() * 0.2F); + } } diff --git a/src/main/java/forestry/core/entities/EntityFXIgnition.java b/src/main/java/forestry/core/entities/EntityFXIgnition.java index 61ac5d808..d2668681d 100644 --- a/src/main/java/forestry/core/entities/EntityFXIgnition.java +++ b/src/main/java/forestry/core/entities/EntityFXIgnition.java @@ -1,87 +1,94 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.entities; - -import net.minecraft.client.particle.EntityFX; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.world.World; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class EntityFXIgnition extends EntityFX { - private final float ignitionParticleScale; - - public EntityFXIgnition(World world, double x, double y, double z) { - super(world, x, y, z, 0, 0, 0); - this.motionX *= 0.8; - this.motionY *= 0.8; - this.motionZ *= 0.8; - this.motionY = (double) (this.rand.nextFloat() * 0.4F + 0.05F); - this.particleRed = this.particleGreen = this.particleBlue = 1.0F; - this.particleScale *= (this.rand.nextFloat() / 2) + 0.3F; - this.ignitionParticleScale = this.particleScale; - this.particleMaxAge = (int) (16.0 / (Math.random() * 0.8 + 0.2)); - this.noClip = false; - this.setParticleTextureIndex(49); - } - - public int getBrightnessForRender(float p_70070_1_) { - int i = super.getBrightnessForRender(p_70070_1_); - short short1 = 240; - int j = i >> 16 & 255; - return short1 | j << 16; - } - - /** - * Gets how bright this entity is. - */ - public float getBrightness(float p_70013_1_) { - return 1.0F; - } - - public void renderParticle(Tessellator p_70539_1_, float p_70539_2_, float p_70539_3_, float p_70539_4_, float p_70539_5_, float p_70539_6_, float p_70539_7_) { - float f6 = ((float) this.particleAge + p_70539_2_) / (float) this.particleMaxAge; - this.particleScale = this.ignitionParticleScale * (1.0F - f6 * f6); - super.renderParticle(p_70539_1_, p_70539_2_, p_70539_3_, p_70539_4_, p_70539_5_, p_70539_6_, p_70539_7_); - } - - /** - * Called to update the entity's position/logic. - */ - public void onUpdate() { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - - if (this.particleAge++ >= this.particleMaxAge) { - this.setDead(); - } - - float f = (float) this.particleAge / (float) this.particleMaxAge; - - if (this.rand.nextFloat() > (f * 2)) { - this.worldObj.spawnParticle("smoke", this.posX, this.posY, this.posZ, this.motionX, this.motionY, this.motionZ); - } - - this.motionY -= 0.03D; - this.moveEntity(this.motionX, this.motionY, this.motionZ); - this.motionX *= 0.999D; - this.motionY *= 0.999D; - this.motionZ *= 0.999D; - - if (this.onGround) { - this.motionX *= 0.7; - this.motionZ *= 0.7; - } - } -} \ No newline at end of file +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.entities; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.world.World; + +@SideOnly(Side.CLIENT) +public class EntityFXIgnition extends EntityFX { + private final float ignitionParticleScale; + + public EntityFXIgnition(World world, double x, double y, double z) { + super(world, x, y, z, 0, 0, 0); + this.motionX *= 0.8; + this.motionY *= 0.8; + this.motionZ *= 0.8; + this.motionY = (double) (this.rand.nextFloat() * 0.4F + 0.05F); + this.particleRed = this.particleGreen = this.particleBlue = 1.0F; + this.particleScale *= (this.rand.nextFloat() / 2) + 0.3F; + this.ignitionParticleScale = this.particleScale; + this.particleMaxAge = (int) (16.0 / (Math.random() * 0.8 + 0.2)); + this.noClip = false; + this.setParticleTextureIndex(49); + } + + public int getBrightnessForRender(float p_70070_1_) { + int i = super.getBrightnessForRender(p_70070_1_); + short short1 = 240; + int j = i >> 16 & 255; + return short1 | j << 16; + } + + /** + * Gets how bright this entity is. + */ + public float getBrightness(float p_70013_1_) { + return 1.0F; + } + + public void renderParticle( + Tessellator p_70539_1_, + float p_70539_2_, + float p_70539_3_, + float p_70539_4_, + float p_70539_5_, + float p_70539_6_, + float p_70539_7_) { + float f6 = ((float) this.particleAge + p_70539_2_) / (float) this.particleMaxAge; + this.particleScale = this.ignitionParticleScale * (1.0F - f6 * f6); + super.renderParticle(p_70539_1_, p_70539_2_, p_70539_3_, p_70539_4_, p_70539_5_, p_70539_6_, p_70539_7_); + } + + /** + * Called to update the entity's position/logic. + */ + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + + if (this.particleAge++ >= this.particleMaxAge) { + this.setDead(); + } + + float f = (float) this.particleAge / (float) this.particleMaxAge; + + if (this.rand.nextFloat() > (f * 2)) { + this.worldObj.spawnParticle( + "smoke", this.posX, this.posY, this.posZ, this.motionX, this.motionY, this.motionZ); + } + + this.motionY -= 0.03D; + this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.motionX *= 0.999D; + this.motionY *= 0.999D; + this.motionZ *= 0.999D; + + if (this.onGround) { + this.motionX *= 0.7; + this.motionZ *= 0.7; + } + } +} diff --git a/src/main/java/forestry/core/entities/EntityFXSnow.java b/src/main/java/forestry/core/entities/EntityFXSnow.java index c46f1854e..c1b7b086a 100644 --- a/src/main/java/forestry/core/entities/EntityFXSnow.java +++ b/src/main/java/forestry/core/entities/EntityFXSnow.java @@ -17,57 +17,111 @@ import net.minecraft.world.World; public class EntityFXSnow extends EntityFX { - public static IIcon icons[]; + public static IIcon icons[]; - public EntityFXSnow(World world, double x, double y, double z) { - super(world, x, y, z, 0.0D, 0.0D, 0.0D); + public EntityFXSnow(World world, double x, double y, double z) { + super(world, x, y, z, 0.0D, 0.0D, 0.0D); - this.setParticleIcon(icons[rand.nextInt(icons.length)]); - this.particleScale *= 0.5F; - this.particleMaxAge = (int) (40.0D / (Math.random() * 0.8D + 0.2D)); - this.noClip = true; + this.setParticleIcon(icons[rand.nextInt(icons.length)]); + this.particleScale *= 0.5F; + this.particleMaxAge = (int) (40.0D / (Math.random() * 0.8D + 0.2D)); + this.noClip = true; - this.motionX *= 0.01D; - this.motionY *= -0.4D; - this.motionZ *= 0.01D; - } + this.motionX *= 0.01D; + this.motionY *= -0.4D; + this.motionZ *= 0.01D; + } - @Override - public int getFXLayer() { - return 2; - } + @Override + public int getFXLayer() { + return 2; + } - @Override - public void renderParticle(Tessellator tess, float timeStep, float rotationX, float rotationXZ, float rotationZ, float rotationYZ, float rotationXY) { - double x = (this.prevPosX + (this.posX - this.prevPosX) * timeStep - interpPosX); - double y = (this.prevPosY + (this.posY - this.prevPosY) * timeStep - interpPosY); - double z = (this.prevPosZ + (this.posZ - this.prevPosZ) * timeStep - interpPosZ); + @Override + public void renderParticle( + Tessellator tess, + float timeStep, + float rotationX, + float rotationXZ, + float rotationZ, + float rotationYZ, + float rotationXY) { + double x = (this.prevPosX + (this.posX - this.prevPosX) * timeStep - interpPosX); + double y = (this.prevPosY + (this.posY - this.prevPosY) * timeStep - interpPosY); + double z = (this.prevPosZ + (this.posZ - this.prevPosZ) * timeStep - interpPosZ); - float minU = this.particleTextureIndexX / 16.0F; - float maxU = minU + 0.0624375F; - float minV = this.particleTextureIndexY / 16.0F; - float maxV = minV + 0.0624375F; - float scale = 0.1F * this.particleScale; + float minU = this.particleTextureIndexX / 16.0F; + float maxU = minU + 0.0624375F; + float minV = this.particleTextureIndexY / 16.0F; + float maxV = minV + 0.0624375F; + float scale = 0.1F * this.particleScale; - if (this.particleIcon != null) { - minU = this.particleIcon.getMinU(); - maxU = this.particleIcon.getMaxU(); - minV = this.particleIcon.getMinV(); - maxV = this.particleIcon.getMaxV(); - } + if (this.particleIcon != null) { + minU = this.particleIcon.getMinU(); + maxU = this.particleIcon.getMaxU(); + minV = this.particleIcon.getMinV(); + maxV = this.particleIcon.getMaxV(); + } - tess.setColorRGBA_F(this.particleRed, this.particleGreen, this.particleBlue, this.particleAlpha); + tess.setColorRGBA_F(this.particleRed, this.particleGreen, this.particleBlue, this.particleAlpha); - for (int i = 0; i < 5; i++) { - renderParticle(tess, x, y, z, rotationX, rotationXZ, rotationZ, rotationYZ, rotationXY, minU, maxU, minV, maxV, scale); - } - } + for (int i = 0; i < 5; i++) { + renderParticle( + tess, + x, + y, + z, + rotationX, + rotationXZ, + rotationZ, + rotationYZ, + rotationXY, + minU, + maxU, + minV, + maxV, + scale); + } + } - private static void renderParticle(Tessellator tess, double x, double y, double z, float rotationX, float rotationXZ, float rotationZ, float rotationYZ, float rotationXY, - float minU, float maxU, float minV, float maxV, float scale) { - tess.addVertexWithUV((x - rotationX * scale - rotationYZ * scale), (y - rotationXZ * scale), (z - rotationZ * scale - rotationXY * scale), maxU, maxV); - tess.addVertexWithUV((x - rotationX * scale + rotationYZ * scale), (y + rotationXZ * scale), (z - rotationZ * scale + rotationXY * scale), maxU, minV); - tess.addVertexWithUV((x + rotationX * scale + rotationYZ * scale), (y + rotationXZ * scale), (z + rotationZ * scale + rotationXY * scale), minU, minV); - tess.addVertexWithUV((x + rotationX * scale - rotationYZ * scale), (y - rotationXZ * scale), (z + rotationZ * scale - rotationXY * scale), minU, maxV); - } + private static void renderParticle( + Tessellator tess, + double x, + double y, + double z, + float rotationX, + float rotationXZ, + float rotationZ, + float rotationYZ, + float rotationXY, + float minU, + float maxU, + float minV, + float maxV, + float scale) { + tess.addVertexWithUV( + (x - rotationX * scale - rotationYZ * scale), + (y - rotationXZ * scale), + (z - rotationZ * scale - rotationXY * scale), + maxU, + maxV); + tess.addVertexWithUV( + (x - rotationX * scale + rotationYZ * scale), + (y + rotationXZ * scale), + (z - rotationZ * scale + rotationXY * scale), + maxU, + minV); + tess.addVertexWithUV( + (x + rotationX * scale + rotationYZ * scale), + (y + rotationXZ * scale), + (z + rotationZ * scale + rotationXY * scale), + minU, + minV); + tess.addVertexWithUV( + (x + rotationX * scale - rotationYZ * scale), + (y - rotationXZ * scale), + (z + rotationZ * scale - rotationXY * scale), + minU, + maxV); + } } diff --git a/src/main/java/forestry/core/entities/EntityMinecartContainerForestry.java b/src/main/java/forestry/core/entities/EntityMinecartContainerForestry.java index 6c259f9bb..a74f94ce9 100644 --- a/src/main/java/forestry/core/entities/EntityMinecartContainerForestry.java +++ b/src/main/java/forestry/core/entities/EntityMinecartContainerForestry.java @@ -1,167 +1,165 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.entities; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - -import forestry.core.inventory.IInventoryAdapter; -import forestry.core.tiles.IFilterSlotDelegate; -import forestry.core.utils.InventoryUtil; - -public abstract class EntityMinecartContainerForestry extends EntityMinecartForestry implements ISidedInventory, IFilterSlotDelegate { - /** - * When set to true, the minecart will drop all items when setDead() is called. When false (such as when travelling - * dimensions) it preserves its contents. - */ - private boolean dropContentsWhenDead = true; - - @SuppressWarnings("unused") - public EntityMinecartContainerForestry(World world) { - super(world); - } - - public EntityMinecartContainerForestry(World world, double posX, double posY, double posZ) { - super(world, posX, posY, posZ); - } - - @Override - protected void readEntityFromNBT(NBTTagCompound nbtTagCompound) { - super.readEntityFromNBT(nbtTagCompound); - getInternalInventory().readFromNBT(nbtTagCompound); - } - - @Override - protected void writeEntityToNBT(NBTTagCompound nbtTagCompound) { - super.writeEntityToNBT(nbtTagCompound); - getInternalInventory().writeToNBT(nbtTagCompound); - } - - @Override - public void setDead() { - if (dropContentsWhenDead && !worldObj.isRemote) { - InventoryUtil.dropInventory(getInternalInventory(), worldObj, posX, posY, posZ); - } - super.setDead(); - } - - @Override - protected void applyDrag() { - int redstoneLevel = 15 - Container.calcRedstoneFromInventory(this); - double drag = 0.98F + (float) redstoneLevel * 0.001F; - this.motionX *= drag; - this.motionY *= 0.0D; - this.motionZ *= drag; - } - - @Override - public void travelToDimension(int dimensionId) { - dropContentsWhenDead = false; - super.travelToDimension(dimensionId); - } - - /* IInventory */ - @Override - public boolean isUseableByPlayer(EntityPlayer player) { - return !isDead && player.getDistanceSqToEntity(this) <= 64.0D; - } - - @Override - public int getSizeInventory() { - return getInternalInventory().getSizeInventory(); - } - - @Override - public final ItemStack getStackInSlot(int slotIndex) { - return getInternalInventory().getStackInSlot(slotIndex); - } - - @Override - public ItemStack decrStackSize(int slotIndex, int amount) { - return getInternalInventory().decrStackSize(slotIndex, amount); - } - - @Override - public final ItemStack getStackInSlotOnClosing(int slotIndex) { - return getInternalInventory().getStackInSlotOnClosing(slotIndex); - } - - @Override - public void setInventorySlotContents(int slotIndex, ItemStack itemstack) { - getInternalInventory().setInventorySlotContents(slotIndex, itemstack); - } - - @Override - public final int getInventoryStackLimit() { - return getInternalInventory().getInventoryStackLimit(); - } - - @Override - public final void openInventory() { - getInternalInventory().openInventory(); - } - - @Override - public final void closeInventory() { - getInternalInventory().closeInventory(); - } - - @Override - public final String getInventoryName() { - return getInternalInventory().getInventoryName(); - } - - @Override - public final boolean hasCustomInventoryName() { - return false; // stop RailCraft from rendering a halo text of the inventory name - } - - @Override - public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { - return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); - } - - @Override - public final boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return getInternalInventory().canSlotAccept(slotIndex, itemStack); - } - - @Override - public boolean isLocked(int slotIndex) { - return getInternalInventory().isLocked(slotIndex); - } - - @Override - public int[] getAccessibleSlotsFromSide(int side) { - return getInternalInventory().getAccessibleSlotsFromSide(side); - } - - @Override - public boolean canInsertItem(int slot, ItemStack stack, int side) { - return getInternalInventory().canInsertItem(slot, stack, side); - } - - @Override - public boolean canExtractItem(int slot, ItemStack stack, int side) { - return getInternalInventory().canExtractItem(slot, stack, side); - } - - @Override - public void markDirty() { - - } - - protected abstract IInventoryAdapter getInternalInventory(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.entities; + +import forestry.core.inventory.IInventoryAdapter; +import forestry.core.tiles.IFilterSlotDelegate; +import forestry.core.utils.InventoryUtil; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +public abstract class EntityMinecartContainerForestry extends EntityMinecartForestry + implements ISidedInventory, IFilterSlotDelegate { + /** + * When set to true, the minecart will drop all items when setDead() is called. When false (such as when travelling + * dimensions) it preserves its contents. + */ + private boolean dropContentsWhenDead = true; + + @SuppressWarnings("unused") + public EntityMinecartContainerForestry(World world) { + super(world); + } + + public EntityMinecartContainerForestry(World world, double posX, double posY, double posZ) { + super(world, posX, posY, posZ); + } + + @Override + protected void readEntityFromNBT(NBTTagCompound nbtTagCompound) { + super.readEntityFromNBT(nbtTagCompound); + getInternalInventory().readFromNBT(nbtTagCompound); + } + + @Override + protected void writeEntityToNBT(NBTTagCompound nbtTagCompound) { + super.writeEntityToNBT(nbtTagCompound); + getInternalInventory().writeToNBT(nbtTagCompound); + } + + @Override + public void setDead() { + if (dropContentsWhenDead && !worldObj.isRemote) { + InventoryUtil.dropInventory(getInternalInventory(), worldObj, posX, posY, posZ); + } + super.setDead(); + } + + @Override + protected void applyDrag() { + int redstoneLevel = 15 - Container.calcRedstoneFromInventory(this); + double drag = 0.98F + (float) redstoneLevel * 0.001F; + this.motionX *= drag; + this.motionY *= 0.0D; + this.motionZ *= drag; + } + + @Override + public void travelToDimension(int dimensionId) { + dropContentsWhenDead = false; + super.travelToDimension(dimensionId); + } + + /* IInventory */ + @Override + public boolean isUseableByPlayer(EntityPlayer player) { + return !isDead && player.getDistanceSqToEntity(this) <= 64.0D; + } + + @Override + public int getSizeInventory() { + return getInternalInventory().getSizeInventory(); + } + + @Override + public final ItemStack getStackInSlot(int slotIndex) { + return getInternalInventory().getStackInSlot(slotIndex); + } + + @Override + public ItemStack decrStackSize(int slotIndex, int amount) { + return getInternalInventory().decrStackSize(slotIndex, amount); + } + + @Override + public final ItemStack getStackInSlotOnClosing(int slotIndex) { + return getInternalInventory().getStackInSlotOnClosing(slotIndex); + } + + @Override + public void setInventorySlotContents(int slotIndex, ItemStack itemstack) { + getInternalInventory().setInventorySlotContents(slotIndex, itemstack); + } + + @Override + public final int getInventoryStackLimit() { + return getInternalInventory().getInventoryStackLimit(); + } + + @Override + public final void openInventory() { + getInternalInventory().openInventory(); + } + + @Override + public final void closeInventory() { + getInternalInventory().closeInventory(); + } + + @Override + public final String getInventoryName() { + return getInternalInventory().getInventoryName(); + } + + @Override + public final boolean hasCustomInventoryName() { + return false; // stop RailCraft from rendering a halo text of the inventory name + } + + @Override + public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { + return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); + } + + @Override + public final boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return getInternalInventory().canSlotAccept(slotIndex, itemStack); + } + + @Override + public boolean isLocked(int slotIndex) { + return getInternalInventory().isLocked(slotIndex); + } + + @Override + public int[] getAccessibleSlotsFromSide(int side) { + return getInternalInventory().getAccessibleSlotsFromSide(side); + } + + @Override + public boolean canInsertItem(int slot, ItemStack stack, int side) { + return getInternalInventory().canInsertItem(slot, stack, side); + } + + @Override + public boolean canExtractItem(int slot, ItemStack stack, int side) { + return getInternalInventory().canExtractItem(slot, stack, side); + } + + @Override + public void markDirty() {} + + protected abstract IInventoryAdapter getInternalInventory(); +} diff --git a/src/main/java/forestry/core/entities/EntityMinecartForestry.java b/src/main/java/forestry/core/entities/EntityMinecartForestry.java index 347cb1f09..523711d32 100644 --- a/src/main/java/forestry/core/entities/EntityMinecartForestry.java +++ b/src/main/java/forestry/core/entities/EntityMinecartForestry.java @@ -1,135 +1,131 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.entities; - -import net.minecraft.block.Block; -import net.minecraft.entity.item.EntityMinecart; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.DamageSource; -import net.minecraft.util.StatCollector; -import net.minecraft.world.World; - -import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.entity.minecart.MinecartInteractEvent; - -import forestry.core.access.AccessHandler; -import forestry.core.access.EnumAccess; -import forestry.core.access.IAccessHandler; -import forestry.core.access.IRestrictedAccess; -import forestry.core.gui.GuiHandler; -import forestry.core.gui.IGuiHandlerEntity; -import forestry.core.gui.IHintSource; -import forestry.core.tiles.ITitled; - -public abstract class EntityMinecartForestry extends EntityMinecart implements ITitled, IRestrictedAccess, IHintSource, IGuiHandlerEntity { - private final AccessHandler accessHandler = new AccessHandler(this); - - @SuppressWarnings("unused") - public EntityMinecartForestry(World world) { - super(world); - setHasDisplayTile(true); - } - - public EntityMinecartForestry(World world, double posX, double posY, double posZ) { - super(world, posX, posY, posZ); - setHasDisplayTile(true); - } - - @Override - public final boolean interactFirst(EntityPlayer player) { - if (MinecraftForge.EVENT_BUS.post(new MinecartInteractEvent(this, player))) { - return true; - } - - if (!worldObj.isRemote) { - GuiHandler.openGui(player, this); - } - return true; - } - - public void setOwner(GameProfile owner) { - accessHandler.setOwner(owner); - } - - @Override - public int getMinecartType() { - return -1; - } - - @Override - protected void readEntityFromNBT(NBTTagCompound nbtTagCompound) { - super.readEntityFromNBT(nbtTagCompound); - accessHandler.readFromNBT(nbtTagCompound); - } - - @Override - protected void writeEntityToNBT(NBTTagCompound nbtTagCompound) { - super.writeEntityToNBT(nbtTagCompound); - accessHandler.writeToNBT(nbtTagCompound); - } - - /* EntityMinecart */ - @Override - public boolean canBeRidden() { - return false; - } - - // cart contents - @Override - public abstract Block func_145820_n(); - - // cart contents meta - @Override - public abstract int getDisplayTileData(); - - // cart itemStack - @Override - public abstract ItemStack getCartItem(); - - @Override - public void killMinecart(DamageSource damageSource) { - super.killMinecart(damageSource); - entityDropItem(new ItemStack(func_145820_n(), 1, getDisplayTileData()), 0.0F); - } - - // fix cart contents rendering as black in the End dimension - @Override - public float getBrightness(float p_70013_1_) { - return 1.0f; - } - - @Override - public String getCommandSenderName() { - return StatCollector.translateToLocal(getUnlocalizedTitle()); - } - - /* ITitled */ - @Override - public String getUnlocalizedTitle() { - ItemStack cartItem = getCartItem(); - return cartItem.getUnlocalizedName() + ".name"; - } - - /* IRestrictedAccess */ - @Override - public IAccessHandler getAccessHandler() { - return accessHandler; - } - - @Override - public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.entities; + +import com.mojang.authlib.GameProfile; +import forestry.core.access.AccessHandler; +import forestry.core.access.EnumAccess; +import forestry.core.access.IAccessHandler; +import forestry.core.access.IRestrictedAccess; +import forestry.core.gui.GuiHandler; +import forestry.core.gui.IGuiHandlerEntity; +import forestry.core.gui.IHintSource; +import forestry.core.tiles.ITitled; +import net.minecraft.block.Block; +import net.minecraft.entity.item.EntityMinecart; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.DamageSource; +import net.minecraft.util.StatCollector; +import net.minecraft.world.World; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.entity.minecart.MinecartInteractEvent; + +public abstract class EntityMinecartForestry extends EntityMinecart + implements ITitled, IRestrictedAccess, IHintSource, IGuiHandlerEntity { + private final AccessHandler accessHandler = new AccessHandler(this); + + @SuppressWarnings("unused") + public EntityMinecartForestry(World world) { + super(world); + setHasDisplayTile(true); + } + + public EntityMinecartForestry(World world, double posX, double posY, double posZ) { + super(world, posX, posY, posZ); + setHasDisplayTile(true); + } + + @Override + public final boolean interactFirst(EntityPlayer player) { + if (MinecraftForge.EVENT_BUS.post(new MinecartInteractEvent(this, player))) { + return true; + } + + if (!worldObj.isRemote) { + GuiHandler.openGui(player, this); + } + return true; + } + + public void setOwner(GameProfile owner) { + accessHandler.setOwner(owner); + } + + @Override + public int getMinecartType() { + return -1; + } + + @Override + protected void readEntityFromNBT(NBTTagCompound nbtTagCompound) { + super.readEntityFromNBT(nbtTagCompound); + accessHandler.readFromNBT(nbtTagCompound); + } + + @Override + protected void writeEntityToNBT(NBTTagCompound nbtTagCompound) { + super.writeEntityToNBT(nbtTagCompound); + accessHandler.writeToNBT(nbtTagCompound); + } + + /* EntityMinecart */ + @Override + public boolean canBeRidden() { + return false; + } + + // cart contents + @Override + public abstract Block func_145820_n(); + + // cart contents meta + @Override + public abstract int getDisplayTileData(); + + // cart itemStack + @Override + public abstract ItemStack getCartItem(); + + @Override + public void killMinecart(DamageSource damageSource) { + super.killMinecart(damageSource); + entityDropItem(new ItemStack(func_145820_n(), 1, getDisplayTileData()), 0.0F); + } + + // fix cart contents rendering as black in the End dimension + @Override + public float getBrightness(float p_70013_1_) { + return 1.0f; + } + + @Override + public String getCommandSenderName() { + return StatCollector.translateToLocal(getUnlocalizedTitle()); + } + + /* ITitled */ + @Override + public String getUnlocalizedTitle() { + ItemStack cartItem = getCartItem(); + return cartItem.getUnlocalizedName() + ".name"; + } + + /* IRestrictedAccess */ + @Override + public IAccessHandler getAccessHandler() { + return accessHandler; + } + + @Override + public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) {} +} diff --git a/src/main/java/forestry/core/entities/EntitySelector.java b/src/main/java/forestry/core/entities/EntitySelector.java index 47963c211..f529995bc 100644 --- a/src/main/java/forestry/core/entities/EntitySelector.java +++ b/src/main/java/forestry/core/entities/EntitySelector.java @@ -1,34 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.entities; - -import net.minecraft.command.IEntitySelector; -import net.minecraft.entity.Entity; - -public abstract class EntitySelector implements IEntitySelector { - private final Class entityClass; - - protected EntitySelector(Class entityClass) { - this.entityClass = entityClass; - } - - public Class getEntityClass() { - return entityClass; - } - - @Override - public final boolean isEntityApplicable(Entity entity) { - T castEntity = entityClass.cast(entity); - return isEntityApplicableTyped(castEntity); - } - - protected abstract boolean isEntityApplicableTyped(T entity); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.entities; + +import net.minecraft.command.IEntitySelector; +import net.minecraft.entity.Entity; + +public abstract class EntitySelector implements IEntitySelector { + private final Class entityClass; + + protected EntitySelector(Class entityClass) { + this.entityClass = entityClass; + } + + public Class getEntityClass() { + return entityClass; + } + + @Override + public final boolean isEntityApplicable(Entity entity) { + T castEntity = entityClass.cast(entity); + return isEntityApplicableTyped(castEntity); + } + + protected abstract boolean isEntityApplicableTyped(T entity); +} diff --git a/src/main/java/forestry/core/errors/EnumErrorCode.java b/src/main/java/forestry/core/errors/EnumErrorCode.java index 42eb0b0fd..6c129842a 100644 --- a/src/main/java/forestry/core/errors/EnumErrorCode.java +++ b/src/main/java/forestry/core/errors/EnumErrorCode.java @@ -5,143 +5,152 @@ ******************************************************************************/ package forestry.core.errors; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.util.IIcon; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.core.ForestryAPI; import forestry.api.core.IErrorState; import forestry.core.config.Constants; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.util.IIcon; public enum EnumErrorCode implements IErrorState { + @Deprecated + UNKNOWN("unknown"), // Congratulations, you found a glitch. + @Deprecated + WRONGSTACKSIZE("wrongStacksize"), // Only single items can be used here. + @Deprecated + NODISPOSAL("noDisposal"), // Insufficient space to dispose of waste products. + @Deprecated + INVALIDBIOME("invalidBiome"), // Machine or inhabitants cannot work in this biome. - @Deprecated - UNKNOWN("unknown"), // Congratulations, you found a glitch. - @Deprecated - WRONGSTACKSIZE("wrongStacksize"), // Only single items can be used here. - @Deprecated - NODISPOSAL("noDisposal"), // Insufficient space to dispose of waste products. - @Deprecated - INVALIDBIOME("invalidBiome"), // Machine or inhabitants cannot work in this biome. + // Bees + TOO_HOT("tooHot"), // The bees are melting in the heat here and unable to work. Use the habitat locator to find a + // cooler climate. + TOO_COLD("tooCold"), // The bees are huddled together to survive the freezing cold here. Use the habitat locator to + // find a warmer climate. + TOO_HUMID( + "tooHumid"), // The damp climate here has made the bees' wings too damp to fly. Use the habitat locator to + // find a dryer climate. + TOO_ARID( + "tooArid", + "invalidBiome"), // The dry climate here has made the bees parched and unable do work. Use the habitat + // locator to find a wetter climate. + IS_RAINING("isRaining"), // Only tolerant fliers can work in the rain. + NOT_GLOOMY("notGloomy"), // The bees can only work in darkness. + NOT_BRIGHT("notLucid"), // The bees have trouble navigating in the dark. + NOT_DAY("notDay"), // The bees can only work during the daytime. + NOT_NIGHT("notNight"), // The bees can only work during the night. + NO_FLOWER("noFlower"), // Hive members are not finding the right flowers. Use the Beealyzer to discover their flower + // preference. + NO_QUEEN("noQueen"), // Supply this hive with a queen or a princess and a drone. + NO_DRONE("noDrone"), // Mating requires a drone present. + NO_SKY("noSky"), // The hive requires direct sunlight from above. - // Bees - TOO_HOT("tooHot"), // The bees are melting in the heat here and unable to work. Use the habitat locator to find a cooler climate. - TOO_COLD("tooCold"), // The bees are huddled together to survive the freezing cold here. Use the habitat locator to find a warmer climate. - TOO_HUMID("tooHumid"), // The damp climate here has made the bees' wings too damp to fly. Use the habitat locator to find a dryer climate. - TOO_ARID("tooArid", "invalidBiome"), // The dry climate here has made the bees parched and unable do work. Use the habitat locator to find a wetter climate. - IS_RAINING("isRaining"), // Only tolerant fliers can work in the rain. - NOT_GLOOMY("notGloomy"), // The bees can only work in darkness. - NOT_BRIGHT("notLucid"), // The bees have trouble navigating in the dark. - NOT_DAY("notDay"), // The bees can only work during the daytime. - NOT_NIGHT("notNight"), // The bees can only work during the night. - NO_FLOWER("noFlower"), // Hive members are not finding the right flowers. Use the Beealyzer to discover their flower preference. - NO_QUEEN("noQueen"), // Supply this hive with a queen or a princess and a drone. - NO_DRONE("noDrone"), // Mating requires a drone present. - NO_SKY("noSky"), // The hive requires direct sunlight from above. + // Machines + NO_RESOURCE("noResource"), // More resources need to be supplied for operation. + NO_RESOURCE_INVENTORY( + "noResourceInventory", + "noResource"), // Resources need to be added to the machine's inventory to craft this recipe. + NO_RESOURCE_LIQUID("noResourceLiquid", "noLiquid"), // More liquid resources need to be supplied for operation. + NO_RECIPE("noRecipe"), // No matching recipe was found for the supplied resources. + NO_SPACE_INVENTORY("noSpace"), // Empty this machine's inventory. + NO_SPACE_TANK("noSpaceTank", "noLiquid"), // Empty this machine's liquid tank. + NO_POWER("noPower"), // This machine requires RF energy from an engine to function. + NO_REDSTONE("noRedstone", "disabled"), // This machine requires a redstone signal to activate it. + DISABLED_BY_REDSTONE("disabledRedstone", "disabled"), // This machine is being disabled by a redstone signal. + NOT_DARK("notDark", "notGloomy"), // A lower light level is required for operation. - // Machines - NO_RESOURCE("noResource"), // More resources need to be supplied for operation. - NO_RESOURCE_INVENTORY("noResourceInventory", "noResource"), // Resources need to be added to the machine's inventory to craft this recipe. - NO_RESOURCE_LIQUID("noResourceLiquid", "noLiquid"), // More liquid resources need to be supplied for operation. - NO_RECIPE("noRecipe"), // No matching recipe was found for the supplied resources. - NO_SPACE_INVENTORY("noSpace"), // Empty this machine's inventory. - NO_SPACE_TANK("noSpaceTank", "noLiquid"), // Empty this machine's liquid tank. - NO_POWER("noPower"), // This machine requires RF energy from an engine to function. - NO_REDSTONE("noRedstone", "disabled"), // This machine requires a redstone signal to activate it. - DISABLED_BY_REDSTONE("disabledRedstone", "disabled"), // This machine is being disabled by a redstone signal. - NOT_DARK("notDark", "notGloomy"), // A lower light level is required for operation. + // Rain Tank + NOT_RAINING("notRaining"), // Operation is only possible when it is raining. + NO_RAIN_BIOME("noRainBiome", "notRaining"), // This location never receives rain. + NO_SKY_RAIN_TANK("noSkyRainTank", "noSky"), // Clear the area above this machine so it can gather rain. - // Rain Tank - NOT_RAINING("notRaining"), // Operation is only possible when it is raining. - NO_RAIN_BIOME("noRainBiome", "notRaining"), // This location never receives rain. - NO_SKY_RAIN_TANK("noSkyRainTank", "noSky"), // Clear the area above this machine so it can gather rain. + // Alyzer + NO_HONEY("noHoney"), // This gadget requires honey drops or honeydew for operation. + NO_SPECIMEN("noSpecimen"), // Supply specimen to analyze. - // Alyzer - NO_HONEY("noHoney"), // This gadget requires honey drops or honeydew for operation. - NO_SPECIMEN("noSpecimen"), // Supply specimen to analyze. + // Engines + FORCED_COOLDOWN("forcedCooldown"), // Engine has overheated and is forced into cooldown. + NO_FUEL("noFuel"), // (Biogas & Peat-fired) Replenish this machine's fuel supplies. + NO_HEAT("noHeat"), // (Biogas engine) Refill the heating tank. + NO_ENERGY_NET("noEnergyNet"), // Your world is barren of any electricity. (Install IndustrialCraft\u00b2.) - // Engines - FORCED_COOLDOWN("forcedCooldown"), // Engine has overheated and is forced into cooldown. - NO_FUEL("noFuel"), // (Biogas & Peat-fired) Replenish this machine's fuel supplies. - NO_HEAT("noHeat"), // (Biogas engine) Refill the heating tank. - NO_ENERGY_NET("noEnergyNet"), // Your world is barren of any electricity. (Install IndustrialCraft\u00b2.) + // Trade Station + NO_STAMPS("noStamps"), // The trade station requires more stamps to pay postage. + NO_PAPER("noPaper"), // The trade station requires more paper to send letters. + NO_SUPPLIES("noSupplies", "noResource"), // The trade station requires more supplies to send. + NO_TRADE("noTrade", "noResource"), // The trade station requires items to Send and Receive. - // Trade Station - NO_STAMPS("noStamps"), // The trade station requires more stamps to pay postage. - NO_PAPER("noPaper"), // The trade station requires more paper to send letters. - NO_SUPPLIES("noSupplies", "noResource"), // The trade station requires more supplies to send. - NO_TRADE("noTrade", "noResource"), // The trade station requires items to Send and Receive. + // Trade Station naming + NOT_ALPHANUMERIC("notAlphaNumeric"), // A Trade Station name must consist of letters and numbers only. + NOT_UNIQUE("notUnique"), // Trade Station names must be unique and this name is already taken. - // Trade Station naming - NOT_ALPHANUMERIC("notAlphaNumeric"), // A Trade Station name must consist of letters and numbers only. - NOT_UNIQUE("notUnique"), // Trade Station names must be unique and this name is already taken. + // Letters + NOT_POST_PAID("notPostpaid", "noStamps"), // Apply more stamps to pay the postal service. + NO_RECIPIENT("noRecipient"), // You need to address your letter to a recipient to send it. - // Letters - NOT_POST_PAID("notPostpaid", "noStamps"), // Apply more stamps to pay the postal service. - NO_RECIPIENT("noRecipient"), // You need to address your letter to a recipient to send it. + // Circuit Boards + NO_CIRCUIT_BOARD("noCircuitBoard"), // Insert a circuit board to solder the selected tubes onto it. + NO_CIRCUIT_LAYOUT("noCircuitLayout"), // No layouts available due to the current game settings. + CIRCUIT_MISMATCH("circuitMismatch"), // Amount of tubes does not match size of circuit board. - // Circuit Boards - NO_CIRCUIT_BOARD("noCircuitBoard"), // Insert a circuit board to solder the selected tubes onto it. - NO_CIRCUIT_LAYOUT("noCircuitLayout"), // No layouts available due to the current game settings. - CIRCUIT_MISMATCH("circuitMismatch"), // Amount of tubes does not match size of circuit board. + // Farms + NO_FERTILIZER("noFertilizer"), // Farms require fertilizer for function. Compost is insufficient. + NO_FARMLAND("noFarmland"), // Smooth sandstone, bricks or stone bricks create a platform the farm will build on. + NO_LIQUID_FARM("noLiquid") // Depending on rainfall, temperature and humidity farms need to be supplied with varying +// amounts of water. +; - // Farms - NO_FERTILIZER("noFertilizer"), // Farms require fertilizer for function. Compost is insufficient. - NO_FARMLAND("noFarmland"), // Smooth sandstone, bricks or stone bricks create a platform the farm will build on. - NO_LIQUID_FARM("noLiquid") // Depending on rainfall, temperature and humidity farms need to be supplied with varying amounts of water. - ; + private final String name; + private final String iconName; - private final String name; - private final String iconName; - @SideOnly(Side.CLIENT) - private IIcon icon; + @SideOnly(Side.CLIENT) + private IIcon icon; - EnumErrorCode(String name) { - this(name, name); - } + EnumErrorCode(String name) { + this(name, name); + } - EnumErrorCode(String name, String iconName) { - this.name = name; - this.iconName = iconName; - } + EnumErrorCode(String name, String iconName) { + this.name = name; + this.iconName = iconName; + } - @Override - public String getDescription() { - return "errors." + name + ".desc"; - } + @Override + public String getDescription() { + return "errors." + name + ".desc"; + } - @Override - public String getHelp() { - return "errors." + name + ".help"; - } + @Override + public String getHelp() { + return "errors." + name + ".help"; + } - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - icon = register.registerIcon("forestry:errors/" + iconName); - } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + icon = register.registerIcon("forestry:errors/" + iconName); + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon() { - return icon; - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon() { + return icon; + } - @Override - public short getID() { - return (short) ordinal(); - } + @Override + public short getID() { + return (short) ordinal(); + } - @Override - public String getUniqueName() { - return Constants.MOD + ":" + name; - } + @Override + public String getUniqueName() { + return Constants.MOD + ":" + name; + } - public static void init() { - for (IErrorState code : values()) { - ForestryAPI.errorStateRegistry.registerErrorState(code); - } - } + public static void init() { + for (IErrorState code : values()) { + ForestryAPI.errorStateRegistry.registerErrorState(code); + } + } } diff --git a/src/main/java/forestry/core/errors/ErrorLogic.java b/src/main/java/forestry/core/errors/ErrorLogic.java index 3df6b9b3a..3106eef93 100644 --- a/src/main/java/forestry/core/errors/ErrorLogic.java +++ b/src/main/java/forestry/core/errors/ErrorLogic.java @@ -1,75 +1,73 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.errors; - -import com.google.common.collect.ImmutableSet; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; - -import forestry.api.core.ForestryAPI; -import forestry.api.core.IErrorLogic; -import forestry.api.core.IErrorState; - -public class ErrorLogic implements IErrorLogic { - private final Set errorStates = new HashSet<>(); - - @Override - public final boolean setCondition(boolean condition, IErrorState errorState) { - if (condition) { - errorStates.add(errorState); - } else { - errorStates.remove(errorState); - } - return condition; - } - - public final boolean contains(IErrorState state) { - return errorStates.contains(state); - } - - public final boolean hasErrors() { - return errorStates.size() > 0; - } - - @Override - public final ImmutableSet getErrorStates() { - return ImmutableSet.copyOf(errorStates); - } - - @Override - public void clearErrors() { - errorStates.clear(); - } - - @Override - public void writeData(DataOutputStream data) throws IOException { - data.writeShort(errorStates.size()); - for (IErrorState errorState : errorStates) { - data.writeShort(errorState.getID()); - } - } - - @Override - public void readData(DataInputStream data) throws IOException { - clearErrors(); - - short errorStateCount = data.readShort(); - for (int i = 0; i < errorStateCount; i++) { - short errorStateId = data.readShort(); - IErrorState errorState = ForestryAPI.errorStateRegistry.getErrorState(errorStateId); - errorStates.add(errorState); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.errors; + +import com.google.common.collect.ImmutableSet; +import forestry.api.core.ForestryAPI; +import forestry.api.core.IErrorLogic; +import forestry.api.core.IErrorState; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; + +public class ErrorLogic implements IErrorLogic { + private final Set errorStates = new HashSet<>(); + + @Override + public final boolean setCondition(boolean condition, IErrorState errorState) { + if (condition) { + errorStates.add(errorState); + } else { + errorStates.remove(errorState); + } + return condition; + } + + public final boolean contains(IErrorState state) { + return errorStates.contains(state); + } + + public final boolean hasErrors() { + return errorStates.size() > 0; + } + + @Override + public final ImmutableSet getErrorStates() { + return ImmutableSet.copyOf(errorStates); + } + + @Override + public void clearErrors() { + errorStates.clear(); + } + + @Override + public void writeData(DataOutputStream data) throws IOException { + data.writeShort(errorStates.size()); + for (IErrorState errorState : errorStates) { + data.writeShort(errorState.getID()); + } + } + + @Override + public void readData(DataInputStream data) throws IOException { + clearErrors(); + + short errorStateCount = data.readShort(); + for (int i = 0; i < errorStateCount; i++) { + short errorStateId = data.readShort(); + IErrorState errorState = ForestryAPI.errorStateRegistry.getErrorState(errorStateId); + errorStates.add(errorState); + } + } +} diff --git a/src/main/java/forestry/core/errors/ErrorStateRegistry.java b/src/main/java/forestry/core/errors/ErrorStateRegistry.java index f2abf1451..6fe5726f6 100644 --- a/src/main/java/forestry/core/errors/ErrorStateRegistry.java +++ b/src/main/java/forestry/core/errors/ErrorStateRegistry.java @@ -12,86 +12,83 @@ package forestry.core.errors; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; - +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.core.IErrorLogic; +import forestry.api.core.IErrorState; +import forestry.api.core.IErrorStateRegistry; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; - import net.minecraft.client.renderer.texture.IIconRegister; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.core.IErrorLogic; -import forestry.api.core.IErrorState; -import forestry.api.core.IErrorStateRegistry; - /** * * @author CovertJaguar */ public class ErrorStateRegistry implements IErrorStateRegistry { - private static final BiMap states = HashBiMap.create(); - private static final Map stateNames = new HashMap<>(); - private static final Set stateView = Collections.unmodifiableSet(states.inverse().keySet()); + private static final BiMap states = HashBiMap.create(); + private static final Map stateNames = new HashMap<>(); + private static final Set stateView = + Collections.unmodifiableSet(states.inverse().keySet()); - @Override - public void registerErrorState(IErrorState state) { - if (states.containsKey(state.getID())) { - throw new RuntimeException("Forestry Error State does not possess a unique id."); - } + @Override + public void registerErrorState(IErrorState state) { + if (states.containsKey(state.getID())) { + throw new RuntimeException("Forestry Error State does not possess a unique id."); + } - states.put(state.getID(), state); - addStateName(state, state.getUniqueName()); - } + states.put(state.getID(), state); + addStateName(state, state.getUniqueName()); + } - @Override - public void addAlias(IErrorState state, String name) { - if (!states.values().contains(state)) { - throw new RuntimeException("Forestry Error State did not exist while trying to register alias."); - } + @Override + public void addAlias(IErrorState state, String name) { + if (!states.values().contains(state)) { + throw new RuntimeException("Forestry Error State did not exist while trying to register alias."); + } - addStateName(state, name); - } + addStateName(state, name); + } - private static void addStateName(IErrorState state, String name) { - if (!name.contains(":")) { - throw new RuntimeException("Forestry Error State name must be in the format :."); - } + private static void addStateName(IErrorState state, String name) { + if (!name.contains(":")) { + throw new RuntimeException("Forestry Error State name must be in the format :."); + } - if (stateNames.containsKey(name)) { - throw new RuntimeException("Forestry Error State does not possess a unique name."); - } + if (stateNames.containsKey(name)) { + throw new RuntimeException("Forestry Error State does not possess a unique name."); + } - stateNames.put(name, state); - } + stateNames.put(name, state); + } - @Override - public IErrorState getErrorState(short id) { - return states.get(id); - } + @Override + public IErrorState getErrorState(short id) { + return states.get(id); + } - @Override - public IErrorState getErrorState(String name) { - return stateNames.get(name); - } + @Override + public IErrorState getErrorState(String name) { + return stateNames.get(name); + } - @Override - public Set getErrorStates() { - return stateView; - } + @Override + public Set getErrorStates() { + return stateView; + } - @Override - public IErrorLogic createErrorLogic() { - return new ErrorLogic(); - } + @Override + public IErrorLogic createErrorLogic() { + return new ErrorLogic(); + } - @SideOnly(Side.CLIENT) - public static void initIcons(IIconRegister register) { - for (IErrorState code : states.values()) { - code.registerIcons(register); - } - } + @SideOnly(Side.CLIENT) + public static void initIcons(IIconRegister register) { + for (IErrorState code : states.values()) { + code.registerIcons(register); + } + } } diff --git a/src/main/java/forestry/core/errors/FakeErrorLogic.java b/src/main/java/forestry/core/errors/FakeErrorLogic.java index b1982801c..eabaa5923 100644 --- a/src/main/java/forestry/core/errors/FakeErrorLogic.java +++ b/src/main/java/forestry/core/errors/FakeErrorLogic.java @@ -1,64 +1,54 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.errors; - -import com.google.common.collect.ImmutableSet; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import forestry.api.core.IErrorLogic; -import forestry.api.core.IErrorState; - -public class FakeErrorLogic implements IErrorLogic { - - public static final FakeErrorLogic instance = new FakeErrorLogic(); - - private FakeErrorLogic() { - - } - - @Override - public boolean setCondition(boolean condition, IErrorState errorState) { - return false; - } - - @Override - public boolean contains(IErrorState state) { - return false; - } - - @Override - public boolean hasErrors() { - return true; - } - - @Override - public void clearErrors() { - - } - - @Override - public void writeData(DataOutputStream data) throws IOException { - - } - - @Override - public void readData(DataInputStream data) throws IOException { - - } - - @Override - public ImmutableSet getErrorStates() { - return ImmutableSet.of(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.errors; + +import com.google.common.collect.ImmutableSet; +import forestry.api.core.IErrorLogic; +import forestry.api.core.IErrorState; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +public class FakeErrorLogic implements IErrorLogic { + + public static final FakeErrorLogic instance = new FakeErrorLogic(); + + private FakeErrorLogic() {} + + @Override + public boolean setCondition(boolean condition, IErrorState errorState) { + return false; + } + + @Override + public boolean contains(IErrorState state) { + return false; + } + + @Override + public boolean hasErrors() { + return true; + } + + @Override + public void clearErrors() {} + + @Override + public void writeData(DataOutputStream data) throws IOException {} + + @Override + public void readData(DataInputStream data) throws IOException {} + + @Override + public ImmutableSet getErrorStates() { + return ImmutableSet.of(); + } +} diff --git a/src/main/java/forestry/core/errors/FakeErrorSource.java b/src/main/java/forestry/core/errors/FakeErrorSource.java index 4952014d1..95f56b2c1 100644 --- a/src/main/java/forestry/core/errors/FakeErrorSource.java +++ b/src/main/java/forestry/core/errors/FakeErrorSource.java @@ -1,29 +1,26 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.errors; - -import com.google.common.collect.ImmutableSet; - -import forestry.api.core.IErrorSource; -import forestry.api.core.IErrorState; - -public class FakeErrorSource implements IErrorSource { - public static final FakeErrorSource instance = new FakeErrorSource(); - - private FakeErrorSource() { - - } - - @Override - public ImmutableSet getErrorStates() { - return ImmutableSet.of(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.errors; + +import com.google.common.collect.ImmutableSet; +import forestry.api.core.IErrorSource; +import forestry.api.core.IErrorState; + +public class FakeErrorSource implements IErrorSource { + public static final FakeErrorSource instance = new FakeErrorSource(); + + private FakeErrorSource() {} + + @Override + public ImmutableSet getErrorStates() { + return ImmutableSet.of(); + } +} diff --git a/src/main/java/forestry/core/fluids/BlockForestryFluid.java b/src/main/java/forestry/core/fluids/BlockForestryFluid.java index 29dfe769d..8d2028629 100644 --- a/src/main/java/forestry/core/fluids/BlockForestryFluid.java +++ b/src/main/java/forestry/core/fluids/BlockForestryFluid.java @@ -1,249 +1,249 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.fluids; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.block.material.Material; -import net.minecraft.client.Minecraft; -import net.minecraft.client.particle.EntityFX; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.client.resources.IResourceManager; -import net.minecraft.init.Blocks; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.IIcon; -import net.minecraft.util.ResourceLocation; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.BlockFluidClassic; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; - -import cpw.mods.fml.client.FMLClientHandler; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.config.Constants; -import forestry.core.entities.EntityFXColoredDropParticle; -import forestry.core.render.TextureManager; - -public class BlockForestryFluid extends BlockFluidClassic { - - private final boolean flammable; - private final int flammability; - private final Color color; - - @SideOnly(Side.CLIENT) - private List icons; - - public BlockForestryFluid(Fluids forestryFluid) { - this(forestryFluid, 0, false); - } - - public BlockForestryFluid(Fluids forestryFluid, int flammability, boolean flammable) { - this(forestryFluid.getFluid(), flammability, flammable, forestryFluid.getColor()); - } - - private BlockForestryFluid(Fluid fluid, int flammability, boolean flammable, Color color) { - super(fluid, Material.water); - - setDensity(fluid.getDensity()); - - this.flammability = flammability; - this.flammable = flammable; - - this.color = color; - } - - @Override - public boolean canDrain(World world, int x, int y, int z) { - return true; - } - - @Override - public Fluid getFluid() { - return FluidRegistry.getFluid(fluidName); - } - - @Override - public IIcon getIcon(int side, int meta) { - if (side == 0 || side == 1 || this.icons.size() == 1) { - return this.icons.get(0); - } else { - return this.icons.get(1); - } - } - - @Override - @SideOnly(Side.CLIENT) - public void registerBlockIcons(IIconRegister iconRegister) { - - this.icons = new ArrayList<>(2); - - String still = "liquid/" + fluidName + "_still"; - this.icons.add(TextureManager.registerTex(iconRegister, still)); - - if (flowTextureExists()) { - String flow = "liquid/" + fluidName + "_flow"; - this.icons.add(TextureManager.registerTex(iconRegister, flow)); - } - } - - @SideOnly(Side.CLIENT) - private boolean flowTextureExists() { - try { - ResourceLocation resourceLocation = new ResourceLocation(Constants.ID, "textures/blocks/liquid/" + fluidName + "_flow.png"); - IResourceManager resourceManager = Minecraft.getMinecraft().getResourceManager(); - return resourceManager.getResource(resourceLocation) != null; - } catch (java.lang.Exception e) { - return false; - } - } - - @Override - @SideOnly(Side.CLIENT) - public void randomDisplayTick(World world, int x, int y, int z, Random rand) { - if (rand.nextInt(10) == 0 && World.doesBlockHaveSolidTopSurface(world, x, y - 1, z) && !world.getBlock(x, y - 2, z).getMaterial().blocksMovement()) { - double px = (double) ((float) x + rand.nextFloat()); - double py = (double) y - 1.05D; - double pz = (double) ((float) z + rand.nextFloat()); - - EntityFX fx = new EntityFXColoredDropParticle(world, px, py, pz, color.getRed(), color.getGreen(), color.getBlue()); - FMLClientHandler.instance().getClient().effectRenderer.addEffect(fx); - } - } - - @Override - public boolean canDisplace(IBlockAccess world, int x, int y, int z) { - if (world.getBlock(x, y, z).getMaterial().isLiquid()) { - return false; - } - return super.canDisplace(world, x, y, z); - } - - @Override - public boolean displaceIfPossible(World world, int x, int y, int z) { - if (world.getBlock(x, y, z).getMaterial().isLiquid()) { - return false; - } - return super.displaceIfPossible(world, x, y, z); - } - - @Override - public int getFireSpreadSpeed(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return flammable ? 30 : 0; - } - - @Override - public int getFlammability(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return flammability; - } - - private static boolean isFlammable(IBlockAccess world, int x, int y, int z) { - return world.getBlock(x, y, z).isFlammable(world, x, y, z, ForgeDirection.UNKNOWN); - } - - @Override - public boolean isFlammable(IBlockAccess world, int x, int y, int z, ForgeDirection face) { - return flammable; - } - - @Override - public boolean isFireSource(World world, int x, int y, int z, ForgeDirection side) { - return flammable && flammability == 0; - } - - public Color getColor() { - return color; - } - - @Override - public Material getMaterial() { - // Fahrenheit 451 = 505.928 Kelvin - // The temperature at which book-paper catches fire, and burns. - if (temperature > 505) { - return Material.lava; - } else { - return super.getMaterial(); - } - } - - @Override - public void updateTick(World world, int x, int y, int z, Random rand) { - super.updateTick(world, x, y, z, rand); - - // Start fires if the fluid is lava-like - if (getMaterial() == Material.lava) { - int rangeUp = rand.nextInt(3); - - for (int i = 0; i < rangeUp; ++i) { - x += rand.nextInt(3) - 1; - ++y; - z += rand.nextInt(3) - 1; - Block block = world.getBlock(x, y, z); - - if (block.getMaterial() == Material.air) { - if (isNeighborFlammable(world, x, y, z)) { - world.setBlock(x, y, z, Blocks.fire); - return; - } - } else if (block.getMaterial().blocksMovement()) { - return; - } - } - - if (rangeUp == 0) { - int startX = x; - int startZ = z; - - for (int i = 0; i < 3; ++i) { - x = startX + rand.nextInt(3) - 1; - z = startZ + rand.nextInt(3) - 1; - - if (world.isAirBlock(x, y + 1, z) && isFlammable(world, x, y, z)) { - world.setBlock(x, y + 1, z, Blocks.fire); - } - } - } - } - - // explode if very flammable and near fire - int flammability = getFlammability(world, x, y, z, ForgeDirection.UNKNOWN); - if (flammability > 0) { - // Explosion size is determined by flammability, up to size 4. - float explosionSize = 4F * flammability / 300F; - if (explosionSize > 1.0 && isNearFire(world, x, y, z)) { - world.setBlock(x, y, z, Blocks.fire); - world.newExplosion(null, x, y, z, explosionSize, true, true); - } - } - } - - private static boolean isNeighborFlammable(World world, int x, int y, int z) { - return isFlammable(world, x - 1, y, z) || - isFlammable(world, x + 1, y, z) || - isFlammable(world, x, y, z - 1) || - isFlammable(world, x, y, z + 1) || - isFlammable(world, x, y - 1, z) || - isFlammable(world, x, y + 1, z); - } - - private static boolean isNearFire(World world, int x, int y, int z) { - AxisAlignedBB boundingBox = AxisAlignedBB.getBoundingBox(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1); - return world.func_147470_e(boundingBox); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.fluids; + +import cpw.mods.fml.client.FMLClientHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.config.Constants; +import forestry.core.entities.EntityFXColoredDropParticle; +import forestry.core.render.TextureManager; +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.client.Minecraft; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.client.resources.IResourceManager; +import net.minecraft.init.Blocks; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.IIcon; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.BlockFluidClassic; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; + +public class BlockForestryFluid extends BlockFluidClassic { + + private final boolean flammable; + private final int flammability; + private final Color color; + + @SideOnly(Side.CLIENT) + private List icons; + + public BlockForestryFluid(Fluids forestryFluid) { + this(forestryFluid, 0, false); + } + + public BlockForestryFluid(Fluids forestryFluid, int flammability, boolean flammable) { + this(forestryFluid.getFluid(), flammability, flammable, forestryFluid.getColor()); + } + + private BlockForestryFluid(Fluid fluid, int flammability, boolean flammable, Color color) { + super(fluid, Material.water); + + setDensity(fluid.getDensity()); + + this.flammability = flammability; + this.flammable = flammable; + + this.color = color; + } + + @Override + public boolean canDrain(World world, int x, int y, int z) { + return true; + } + + @Override + public Fluid getFluid() { + return FluidRegistry.getFluid(fluidName); + } + + @Override + public IIcon getIcon(int side, int meta) { + if (side == 0 || side == 1 || this.icons.size() == 1) { + return this.icons.get(0); + } else { + return this.icons.get(1); + } + } + + @Override + @SideOnly(Side.CLIENT) + public void registerBlockIcons(IIconRegister iconRegister) { + + this.icons = new ArrayList<>(2); + + String still = "liquid/" + fluidName + "_still"; + this.icons.add(TextureManager.registerTex(iconRegister, still)); + + if (flowTextureExists()) { + String flow = "liquid/" + fluidName + "_flow"; + this.icons.add(TextureManager.registerTex(iconRegister, flow)); + } + } + + @SideOnly(Side.CLIENT) + private boolean flowTextureExists() { + try { + ResourceLocation resourceLocation = + new ResourceLocation(Constants.ID, "textures/blocks/liquid/" + fluidName + "_flow.png"); + IResourceManager resourceManager = Minecraft.getMinecraft().getResourceManager(); + return resourceManager.getResource(resourceLocation) != null; + } catch (java.lang.Exception e) { + return false; + } + } + + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(World world, int x, int y, int z, Random rand) { + if (rand.nextInt(10) == 0 + && World.doesBlockHaveSolidTopSurface(world, x, y - 1, z) + && !world.getBlock(x, y - 2, z).getMaterial().blocksMovement()) { + double px = (double) ((float) x + rand.nextFloat()); + double py = (double) y - 1.05D; + double pz = (double) ((float) z + rand.nextFloat()); + + EntityFX fx = new EntityFXColoredDropParticle( + world, px, py, pz, color.getRed(), color.getGreen(), color.getBlue()); + FMLClientHandler.instance().getClient().effectRenderer.addEffect(fx); + } + } + + @Override + public boolean canDisplace(IBlockAccess world, int x, int y, int z) { + if (world.getBlock(x, y, z).getMaterial().isLiquid()) { + return false; + } + return super.canDisplace(world, x, y, z); + } + + @Override + public boolean displaceIfPossible(World world, int x, int y, int z) { + if (world.getBlock(x, y, z).getMaterial().isLiquid()) { + return false; + } + return super.displaceIfPossible(world, x, y, z); + } + + @Override + public int getFireSpreadSpeed(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return flammable ? 30 : 0; + } + + @Override + public int getFlammability(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return flammability; + } + + private static boolean isFlammable(IBlockAccess world, int x, int y, int z) { + return world.getBlock(x, y, z).isFlammable(world, x, y, z, ForgeDirection.UNKNOWN); + } + + @Override + public boolean isFlammable(IBlockAccess world, int x, int y, int z, ForgeDirection face) { + return flammable; + } + + @Override + public boolean isFireSource(World world, int x, int y, int z, ForgeDirection side) { + return flammable && flammability == 0; + } + + public Color getColor() { + return color; + } + + @Override + public Material getMaterial() { + // Fahrenheit 451 = 505.928 Kelvin + // The temperature at which book-paper catches fire, and burns. + if (temperature > 505) { + return Material.lava; + } else { + return super.getMaterial(); + } + } + + @Override + public void updateTick(World world, int x, int y, int z, Random rand) { + super.updateTick(world, x, y, z, rand); + + // Start fires if the fluid is lava-like + if (getMaterial() == Material.lava) { + int rangeUp = rand.nextInt(3); + + for (int i = 0; i < rangeUp; ++i) { + x += rand.nextInt(3) - 1; + ++y; + z += rand.nextInt(3) - 1; + Block block = world.getBlock(x, y, z); + + if (block.getMaterial() == Material.air) { + if (isNeighborFlammable(world, x, y, z)) { + world.setBlock(x, y, z, Blocks.fire); + return; + } + } else if (block.getMaterial().blocksMovement()) { + return; + } + } + + if (rangeUp == 0) { + int startX = x; + int startZ = z; + + for (int i = 0; i < 3; ++i) { + x = startX + rand.nextInt(3) - 1; + z = startZ + rand.nextInt(3) - 1; + + if (world.isAirBlock(x, y + 1, z) && isFlammable(world, x, y, z)) { + world.setBlock(x, y + 1, z, Blocks.fire); + } + } + } + } + + // explode if very flammable and near fire + int flammability = getFlammability(world, x, y, z, ForgeDirection.UNKNOWN); + if (flammability > 0) { + // Explosion size is determined by flammability, up to size 4. + float explosionSize = 4F * flammability / 300F; + if (explosionSize > 1.0 && isNearFire(world, x, y, z)) { + world.setBlock(x, y, z, Blocks.fire); + world.newExplosion(null, x, y, z, explosionSize, true, true); + } + } + } + + private static boolean isNeighborFlammable(World world, int x, int y, int z) { + return isFlammable(world, x - 1, y, z) + || isFlammable(world, x + 1, y, z) + || isFlammable(world, x, y, z - 1) + || isFlammable(world, x, y, z + 1) + || isFlammable(world, x, y - 1, z) + || isFlammable(world, x, y + 1, z); + } + + private static boolean isNearFire(World world, int x, int y, int z) { + AxisAlignedBB boundingBox = AxisAlignedBB.getBoundingBox(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1); + return world.func_147470_e(boundingBox); + } +} diff --git a/src/main/java/forestry/core/fluids/FakeTankManager.java b/src/main/java/forestry/core/fluids/FakeTankManager.java index 81914910d..51b769aaf 100644 --- a/src/main/java/forestry/core/fluids/FakeTankManager.java +++ b/src/main/java/forestry/core/fluids/FakeTankManager.java @@ -1,88 +1,75 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.fluids; - -import java.util.List; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.ICrafting; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidTank; - -import forestry.core.fluids.tanks.FakeTank; - -public class FakeTankManager implements ITankManager { - public static final FakeTankManager instance = new FakeTankManager(); - - private FakeTankManager() { - - } - - @Override - public void containerAdded(Container container, ICrafting player) { - - } - - @Override - public void updateGuiData(Container container, List crafters) { - - } - - @Override - public void containerRemoved(Container container) { - - } - - @Override - public IFluidTank getTank(int tankIndex) { - return FakeTank.INSTANCE; - } - - @Override - public void processTankUpdate(int tankIndex, FluidStack contents) { - - } - - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return FakeTank.INSTANCE.fill(resource, doFill); - } - - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return FakeTank.INSTANCE.drain(resource.amount, doDrain); - } - - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return FakeTank.INSTANCE.drain(maxDrain, doDrain); - } - - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return false; - } - - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return false; - } - - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return FakeTank.INFO; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.fluids; + +import forestry.core.fluids.tanks.FakeTank; +import java.util.List; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidTank; + +public class FakeTankManager implements ITankManager { + public static final FakeTankManager instance = new FakeTankManager(); + + private FakeTankManager() {} + + @Override + public void containerAdded(Container container, ICrafting player) {} + + @Override + public void updateGuiData(Container container, List crafters) {} + + @Override + public void containerRemoved(Container container) {} + + @Override + public IFluidTank getTank(int tankIndex) { + return FakeTank.INSTANCE; + } + + @Override + public void processTankUpdate(int tankIndex, FluidStack contents) {} + + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return FakeTank.INSTANCE.fill(resource, doFill); + } + + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return FakeTank.INSTANCE.drain(resource.amount, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return FakeTank.INSTANCE.drain(maxDrain, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return false; + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return false; + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return FakeTank.INFO; + } +} diff --git a/src/main/java/forestry/core/fluids/FakeTankUpdateHandler.java b/src/main/java/forestry/core/fluids/FakeTankUpdateHandler.java index b474deb01..cc196d5fa 100644 --- a/src/main/java/forestry/core/fluids/FakeTankUpdateHandler.java +++ b/src/main/java/forestry/core/fluids/FakeTankUpdateHandler.java @@ -1,27 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.fluids; - -import forestry.core.fluids.tanks.StandardTank; - -public class FakeTankUpdateHandler implements ITankUpdateHandler { - - public static final FakeTankUpdateHandler instance = new FakeTankUpdateHandler(); - - private FakeTankUpdateHandler() { - - } - - @Override - public void updateTankLevels(StandardTank tank) { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.fluids; + +import forestry.core.fluids.tanks.StandardTank; + +public class FakeTankUpdateHandler implements ITankUpdateHandler { + + public static final FakeTankUpdateHandler instance = new FakeTankUpdateHandler(); + + private FakeTankUpdateHandler() {} + + @Override + public void updateTankLevels(StandardTank tank) {} +} diff --git a/src/main/java/forestry/core/fluids/FluidHelper.java b/src/main/java/forestry/core/fluids/FluidHelper.java index e06077391..99b16aa91 100644 --- a/src/main/java/forestry/core/fluids/FluidHelper.java +++ b/src/main/java/forestry/core/fluids/FluidHelper.java @@ -10,14 +10,16 @@ ******************************************************************************/ package forestry.core.fluids; +import forestry.core.config.Constants; +import forestry.core.utils.InventoryUtil; +import forestry.core.utils.ItemStackUtil; +import forestry.plugins.PluginFluids; import java.util.ArrayList; import java.util.List; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; - import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry; @@ -26,391 +28,404 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.IFluidContainerItem; import net.minecraftforge.fluids.IFluidHandler; -import forestry.core.config.Constants; -import forestry.core.utils.InventoryUtil; -import forestry.core.utils.ItemStackUtil; -import forestry.plugins.PluginFluids; - /** * @author CovertJaguar */ public final class FluidHelper { - private FluidHelper() { - } - - public static boolean handleRightClick(IFluidHandler tank, ForgeDirection side, EntityPlayer player, boolean fill, boolean drain) { - if (player == null) { - return false; - } - ItemStack current = player.inventory.getCurrentItem(); - if (current != null) { - - FluidStack liquid = getFluidStackInContainer(current); - - if (fill && liquid != null) { - int canUseAmount = tank.fill(side, liquid, false); - if (canUseAmount == 0) { - return false; - } - - ItemStack drainedContainer = getDrainedContainer(current, canUseAmount); - if (ItemStackUtil.isIdenticalItem(current, drainedContainer)) { - return false; - } - - int usedAmount = tank.fill(side, liquid, true); - if (usedAmount > 0) { - if (!player.capabilities.isCreativeMode) { - if (current.stackSize > 1) { - player.inventory.decrStackSize(player.inventory.currentItem, 1); - if (drainedContainer != null && !player.inventory.addItemStackToInventory(drainedContainer)) { - player.dropPlayerItemWithRandomChoice(drainedContainer, false); - } - } else { - player.inventory.setInventorySlotContents(player.inventory.currentItem, drainedContainer); - } - player.inventory.markDirty(); - } - return true; - } - - } else if (drain) { - - FluidStack available = tank.drain(side, Integer.MAX_VALUE, false); - if (available != null) { - ItemStack filled = getFilledContainer(available, current); - - liquid = getFluidStackInContainer(filled); - if (liquid != null) { - - if (current.stackSize > 1) { - if (!player.inventory.addItemStackToInventory(filled)) { - return false; - } - player.inventory.setInventorySlotContents(player.inventory.currentItem, InventoryUtil.depleteItem(current)); - player.inventory.markDirty(); - } else { - player.inventory.setInventorySlotContents(player.inventory.currentItem, InventoryUtil.depleteItem(current)); - player.inventory.setInventorySlotContents(player.inventory.currentItem, filled); - player.inventory.markDirty(); - } - - tank.drain(side, liquid.amount, true); - return true; - } - } - } - } - return false; - } - - public static boolean areFluidStacksEqual(FluidStack fluidStack1, FluidStack fluidStack2) { - if (fluidStack1 == null) { - return fluidStack2 == null; - } else { - return fluidStack1.isFluidStackIdentical(fluidStack2); - } - } - - public enum FillStatus { - SUCCESS, INVALID_INPUT, NO_FLUID, NO_SPACE - } - - public static FillStatus fillContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot, Fluid fluidToFill) { - return fillContainers(fluidHandler, inv, inputSlot, outputSlot, fluidToFill, true); - } - - public static FillStatus fillContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot, Fluid fluidToFill, boolean doFill) { - if (fluidToFill == null) { - return FillStatus.INVALID_INPUT; - } - - ItemStack input = inv.getStackInSlot(inputSlot); - if (input == null) { - return FillStatus.INVALID_INPUT; - } - ItemStack output = inv.getStackInSlot(outputSlot); - - int containerCapacity = getFluidCapacity(fluidToFill, input); - if (containerCapacity <= 0) { - return FillStatus.INVALID_INPUT; - } - - int fillAmount = containerCapacity; - if (input.getItem() instanceof IFluidContainerItem) { - fillAmount = Math.min(Constants.BUCKET_VOLUME, containerCapacity); - } - - FluidStack canDrain = fluidHandler.drain(ForgeDirection.UNKNOWN, new FluidStack(fluidToFill, fillAmount), false); - if (canDrain == null || canDrain.amount == 0) { - return FillStatus.NO_FLUID; - } - - ItemStack filled = getFilledContainer(canDrain, input); - if (filled == null) { - return FillStatus.NO_FLUID; // standard containers will not fill if there isn't enough fluid - } - - FluidStack fluidInContainer = getFluidStackInContainer(filled); - if (fluidInContainer == null) { - return FillStatus.INVALID_INPUT; - } - boolean moveToOutput = (fluidInContainer.amount >= containerCapacity); - if (moveToOutput) { - if ((output != null) && (output.stackSize >= output.getMaxStackSize() || !InventoryUtil.isItemEqual(filled, output))) { - return FillStatus.NO_SPACE; - } - } else { - if (input.stackSize > 1) { - return FillStatus.NO_SPACE; - } - } - - if (doFill) { - fluidHandler.drain(ForgeDirection.UNKNOWN, canDrain, true); - if (moveToOutput) { - if (output == null) { - inv.setInventorySlotContents(outputSlot, filled); - } else { - output.stackSize++; - } - inv.decrStackSize(inputSlot, 1); - } else { - inv.setInventorySlotContents(inputSlot, filled); - } - } - - return FillStatus.SUCCESS; - } - - public static boolean drainContainers(IFluidHandler fluidHandler, IInventory inv, int slot) { - return drainContainers(fluidHandler, inv, slot, slot); - } - - public static boolean drainContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot) { - ItemStack input = inv.getStackInSlot(inputSlot); - ItemStack output = inv.getStackInSlot(outputSlot); - - if (input == null) { - return false; - } - - FluidStack fluidInContainer = getFluidStackInContainer(input); - if (fluidInContainer == null) { - return false; - } - - if (input.getItem() instanceof IFluidContainerItem) { - if (fluidInContainer.amount > Constants.BUCKET_VOLUME) { - fluidInContainer.amount = Constants.BUCKET_VOLUME; - } - } - - int used = fluidHandler.fill(ForgeDirection.UNKNOWN, fluidInContainer, false); - - ItemStack drainedItem = getDrainedContainer(input, used); - if (ItemStack.areItemStacksEqual(input, drainedItem)) { - return false; - } - - // consume forestry containers if there is only one slot - if (outputSlot == inputSlot && drainedItem != null) { - Item item = drainedItem.getItem(); - if (PluginFluids.items.canEmpty == item || PluginFluids.items.waxCapsuleEmpty == item || PluginFluids.items.refractoryEmpty == item) { - drainedItem = null; - } - } - - if (!hasRoomForDrainedContainer(input, output, drainedItem, inputSlot, outputSlot)) { - return false; - } - - fluidHandler.fill(ForgeDirection.UNKNOWN, fluidInContainer, true); - - if (drainedItem != null) { - if (outputSlot == inputSlot) { - inv.setInventorySlotContents(outputSlot, drainedItem); - return true; - } - - if (output == null) { - inv.setInventorySlotContents(outputSlot, drainedItem); - } else { - output.stackSize++; - } - } - inv.decrStackSize(inputSlot, 1); - return true; - } - - private static boolean hasRoomForDrainedContainer(ItemStack input, ItemStack output, ItemStack drainedItem, int inputSlot, int outputSlot) { - if (output == null || drainedItem == null) { - return true; - } - - if (outputSlot == inputSlot) { - return input.stackSize == 1; - } - - if (!ItemStackUtil.isIdenticalItem(output, drainedItem)) { - return false; - } - - return output.stackSize + drainedItem.stackSize <= output.getMaxStackSize(); - } - - public static boolean isEmptyContainer(ItemStack empty) { - Item item = empty.getItem(); - if (item instanceof IFluidContainerItem) { - IFluidContainerItem containerItem = (IFluidContainerItem) item; - FluidStack fluid = containerItem.getFluid(empty); - return fluid == null || fluid.amount == 0; - } - - return FluidContainerRegistry.isEmptyContainer(empty); - } - - public static boolean isFillableContainer(ItemStack container) { - FluidStack fluid = getFluidStackInContainer(container); - if (fluid == null || fluid.amount == 0) { - return isEmptyContainer(container); - } - - int capacity = getFluidCapacity(fluid.getFluid(), container); - return fluid.amount < capacity; - } - - public static ItemStack getDrainedContainer(ItemStack container, int drainAmount) { - if (container == null) { - return null; - } - - if (drainAmount == 0) { - return container; - } - - Item item = container.getItem(); - if (item == null) { - return null; - } - - if (item instanceof IFluidContainerItem) { - ItemStack drained = container.copy(); - drained.stackSize = 1; - IFluidContainerItem containerItem = (IFluidContainerItem) item; - containerItem.drain(drained, drainAmount, true); - return drained; - } else { - int capacity = FluidContainerRegistry.getContainerCapacity(container); - if (capacity > 0) { - if (drainAmount < capacity) { - return container; - } - return FluidContainerRegistry.drainFluidContainer(container); - } - } - - return null; - } - - public static ItemStack getEmptyContainer(ItemStack container) { - if (container == null) { - return null; - } - FluidStack fluidStack = FluidHelper.getFluidStackInContainer(container); - if (fluidStack == null) { - return null; - } - - return FluidHelper.getDrainedContainer(container, fluidStack.amount); - } - - public static List getAllFilledContainers(ItemStack empty) { - List filledContainers = new ArrayList<>(); - for (Fluid fluid : FluidRegistry.getRegisteredFluids().values()) { - ItemStack filledContainer = getFilledContainer(fluid, empty); - if (filledContainer != null) { - filledContainers.add(filledContainer); - } - } - return filledContainers; - } - - public static ItemStack getFilledContainer(Fluid fluid, ItemStack empty) { - if (fluid == null) { - return null; - } - - FluidStack fluidToFill = new FluidStack(fluid, Integer.MAX_VALUE); - - return getFilledContainer(fluidToFill, empty); - } - - public static ItemStack getFilledContainer(FluidStack liquid, ItemStack empty) { - if (liquid == null || empty == null) { - return null; - } - - Item item = empty.getItem(); - if (item instanceof IFluidContainerItem) { - ItemStack full = ItemStackUtil.createSplitStack(empty, 1); - IFluidContainerItem containerItem = (IFluidContainerItem) item; - containerItem.fill(full, liquid, true); - return full; - } - - return FluidContainerRegistry.fillFluidContainer(liquid, empty); - } - - public static FluidStack getFluidStackInContainer(ItemStack stack) { - if (stack == null) { - return null; - } - Item item = stack.getItem(); - if (item instanceof IFluidContainerItem) { - IFluidContainerItem containerItem = (IFluidContainerItem) item; - return containerItem.getFluid(stack); - } - - return FluidContainerRegistry.getFluidForFilledItem(stack); - } - - public static Fluid getFluidInContainer(ItemStack stack) { - FluidStack fluidStack = getFluidStackInContainer(stack); - return fluidStack != null ? fluidStack.getFluid() : null; - } - - public static boolean containsFluidStack(ItemStack stack, FluidStack fluidStack) { - Item item = stack.getItem(); - if (item instanceof IFluidContainerItem) { - IFluidContainerItem containerItem = (IFluidContainerItem) item; - FluidStack contained = containerItem.getFluid(stack); - return contained != null && contained.containsFluid(fluidStack); - } - - return FluidContainerRegistry.containsFluid(stack, fluidStack); - } - - public static boolean containsFluid(ItemStack stack, Fluid fluid) { - return containsFluidStack(stack, new FluidStack(fluid, 1)); - } - - public static int getFluidCapacity(Fluid fluid, ItemStack container) { - if (container == null) { - return 0; - } - Item item = container.getItem(); - if (item instanceof IFluidContainerItem) { - IFluidContainerItem containerItem = (IFluidContainerItem) item; - return containerItem.getCapacity(container); - } - - if (fluid == null) { - return FluidContainerRegistry.getContainerCapacity(container); - } else { - return FluidContainerRegistry.getContainerCapacity(new FluidStack(fluid, Constants.BUCKET_VOLUME), container); - } - } - + private FluidHelper() {} + + public static boolean handleRightClick( + IFluidHandler tank, ForgeDirection side, EntityPlayer player, boolean fill, boolean drain) { + if (player == null) { + return false; + } + ItemStack current = player.inventory.getCurrentItem(); + if (current != null) { + + FluidStack liquid = getFluidStackInContainer(current); + + if (fill && liquid != null) { + int canUseAmount = tank.fill(side, liquid, false); + if (canUseAmount == 0) { + return false; + } + + ItemStack drainedContainer = getDrainedContainer(current, canUseAmount); + if (ItemStackUtil.isIdenticalItem(current, drainedContainer)) { + return false; + } + + int usedAmount = tank.fill(side, liquid, true); + if (usedAmount > 0) { + if (!player.capabilities.isCreativeMode) { + if (current.stackSize > 1) { + player.inventory.decrStackSize(player.inventory.currentItem, 1); + if (drainedContainer != null + && !player.inventory.addItemStackToInventory(drainedContainer)) { + player.dropPlayerItemWithRandomChoice(drainedContainer, false); + } + } else { + player.inventory.setInventorySlotContents(player.inventory.currentItem, drainedContainer); + } + player.inventory.markDirty(); + } + return true; + } + + } else if (drain) { + + FluidStack available = tank.drain(side, Integer.MAX_VALUE, false); + if (available != null) { + ItemStack filled = getFilledContainer(available, current); + + liquid = getFluidStackInContainer(filled); + if (liquid != null) { + + if (current.stackSize > 1) { + if (!player.inventory.addItemStackToInventory(filled)) { + return false; + } + player.inventory.setInventorySlotContents( + player.inventory.currentItem, InventoryUtil.depleteItem(current)); + player.inventory.markDirty(); + } else { + player.inventory.setInventorySlotContents( + player.inventory.currentItem, InventoryUtil.depleteItem(current)); + player.inventory.setInventorySlotContents(player.inventory.currentItem, filled); + player.inventory.markDirty(); + } + + tank.drain(side, liquid.amount, true); + return true; + } + } + } + } + return false; + } + + public static boolean areFluidStacksEqual(FluidStack fluidStack1, FluidStack fluidStack2) { + if (fluidStack1 == null) { + return fluidStack2 == null; + } else { + return fluidStack1.isFluidStackIdentical(fluidStack2); + } + } + + public enum FillStatus { + SUCCESS, + INVALID_INPUT, + NO_FLUID, + NO_SPACE + } + + public static FillStatus fillContainers( + IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot, Fluid fluidToFill) { + return fillContainers(fluidHandler, inv, inputSlot, outputSlot, fluidToFill, true); + } + + public static FillStatus fillContainers( + IFluidHandler fluidHandler, + IInventory inv, + int inputSlot, + int outputSlot, + Fluid fluidToFill, + boolean doFill) { + if (fluidToFill == null) { + return FillStatus.INVALID_INPUT; + } + + ItemStack input = inv.getStackInSlot(inputSlot); + if (input == null) { + return FillStatus.INVALID_INPUT; + } + ItemStack output = inv.getStackInSlot(outputSlot); + + int containerCapacity = getFluidCapacity(fluidToFill, input); + if (containerCapacity <= 0) { + return FillStatus.INVALID_INPUT; + } + + int fillAmount = containerCapacity; + if (input.getItem() instanceof IFluidContainerItem) { + fillAmount = Math.min(Constants.BUCKET_VOLUME, containerCapacity); + } + + FluidStack canDrain = + fluidHandler.drain(ForgeDirection.UNKNOWN, new FluidStack(fluidToFill, fillAmount), false); + if (canDrain == null || canDrain.amount == 0) { + return FillStatus.NO_FLUID; + } + + ItemStack filled = getFilledContainer(canDrain, input); + if (filled == null) { + return FillStatus.NO_FLUID; // standard containers will not fill if there isn't enough fluid + } + + FluidStack fluidInContainer = getFluidStackInContainer(filled); + if (fluidInContainer == null) { + return FillStatus.INVALID_INPUT; + } + boolean moveToOutput = (fluidInContainer.amount >= containerCapacity); + if (moveToOutput) { + if ((output != null) + && (output.stackSize >= output.getMaxStackSize() || !InventoryUtil.isItemEqual(filled, output))) { + return FillStatus.NO_SPACE; + } + } else { + if (input.stackSize > 1) { + return FillStatus.NO_SPACE; + } + } + + if (doFill) { + fluidHandler.drain(ForgeDirection.UNKNOWN, canDrain, true); + if (moveToOutput) { + if (output == null) { + inv.setInventorySlotContents(outputSlot, filled); + } else { + output.stackSize++; + } + inv.decrStackSize(inputSlot, 1); + } else { + inv.setInventorySlotContents(inputSlot, filled); + } + } + + return FillStatus.SUCCESS; + } + + public static boolean drainContainers(IFluidHandler fluidHandler, IInventory inv, int slot) { + return drainContainers(fluidHandler, inv, slot, slot); + } + + public static boolean drainContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot) { + ItemStack input = inv.getStackInSlot(inputSlot); + ItemStack output = inv.getStackInSlot(outputSlot); + + if (input == null) { + return false; + } + + FluidStack fluidInContainer = getFluidStackInContainer(input); + if (fluidInContainer == null) { + return false; + } + + if (input.getItem() instanceof IFluidContainerItem) { + if (fluidInContainer.amount > Constants.BUCKET_VOLUME) { + fluidInContainer.amount = Constants.BUCKET_VOLUME; + } + } + + int used = fluidHandler.fill(ForgeDirection.UNKNOWN, fluidInContainer, false); + + ItemStack drainedItem = getDrainedContainer(input, used); + if (ItemStack.areItemStacksEqual(input, drainedItem)) { + return false; + } + + // consume forestry containers if there is only one slot + if (outputSlot == inputSlot && drainedItem != null) { + Item item = drainedItem.getItem(); + if (PluginFluids.items.canEmpty == item + || PluginFluids.items.waxCapsuleEmpty == item + || PluginFluids.items.refractoryEmpty == item) { + drainedItem = null; + } + } + + if (!hasRoomForDrainedContainer(input, output, drainedItem, inputSlot, outputSlot)) { + return false; + } + + fluidHandler.fill(ForgeDirection.UNKNOWN, fluidInContainer, true); + + if (drainedItem != null) { + if (outputSlot == inputSlot) { + inv.setInventorySlotContents(outputSlot, drainedItem); + return true; + } + + if (output == null) { + inv.setInventorySlotContents(outputSlot, drainedItem); + } else { + output.stackSize++; + } + } + inv.decrStackSize(inputSlot, 1); + return true; + } + + private static boolean hasRoomForDrainedContainer( + ItemStack input, ItemStack output, ItemStack drainedItem, int inputSlot, int outputSlot) { + if (output == null || drainedItem == null) { + return true; + } + + if (outputSlot == inputSlot) { + return input.stackSize == 1; + } + + if (!ItemStackUtil.isIdenticalItem(output, drainedItem)) { + return false; + } + + return output.stackSize + drainedItem.stackSize <= output.getMaxStackSize(); + } + + public static boolean isEmptyContainer(ItemStack empty) { + Item item = empty.getItem(); + if (item instanceof IFluidContainerItem) { + IFluidContainerItem containerItem = (IFluidContainerItem) item; + FluidStack fluid = containerItem.getFluid(empty); + return fluid == null || fluid.amount == 0; + } + + return FluidContainerRegistry.isEmptyContainer(empty); + } + + public static boolean isFillableContainer(ItemStack container) { + FluidStack fluid = getFluidStackInContainer(container); + if (fluid == null || fluid.amount == 0) { + return isEmptyContainer(container); + } + + int capacity = getFluidCapacity(fluid.getFluid(), container); + return fluid.amount < capacity; + } + + public static ItemStack getDrainedContainer(ItemStack container, int drainAmount) { + if (container == null) { + return null; + } + + if (drainAmount == 0) { + return container; + } + + Item item = container.getItem(); + if (item == null) { + return null; + } + + if (item instanceof IFluidContainerItem) { + ItemStack drained = container.copy(); + drained.stackSize = 1; + IFluidContainerItem containerItem = (IFluidContainerItem) item; + containerItem.drain(drained, drainAmount, true); + return drained; + } else { + int capacity = FluidContainerRegistry.getContainerCapacity(container); + if (capacity > 0) { + if (drainAmount < capacity) { + return container; + } + return FluidContainerRegistry.drainFluidContainer(container); + } + } + + return null; + } + + public static ItemStack getEmptyContainer(ItemStack container) { + if (container == null) { + return null; + } + FluidStack fluidStack = FluidHelper.getFluidStackInContainer(container); + if (fluidStack == null) { + return null; + } + + return FluidHelper.getDrainedContainer(container, fluidStack.amount); + } + + public static List getAllFilledContainers(ItemStack empty) { + List filledContainers = new ArrayList<>(); + for (Fluid fluid : FluidRegistry.getRegisteredFluids().values()) { + ItemStack filledContainer = getFilledContainer(fluid, empty); + if (filledContainer != null) { + filledContainers.add(filledContainer); + } + } + return filledContainers; + } + + public static ItemStack getFilledContainer(Fluid fluid, ItemStack empty) { + if (fluid == null) { + return null; + } + + FluidStack fluidToFill = new FluidStack(fluid, Integer.MAX_VALUE); + + return getFilledContainer(fluidToFill, empty); + } + + public static ItemStack getFilledContainer(FluidStack liquid, ItemStack empty) { + if (liquid == null || empty == null) { + return null; + } + + Item item = empty.getItem(); + if (item instanceof IFluidContainerItem) { + ItemStack full = ItemStackUtil.createSplitStack(empty, 1); + IFluidContainerItem containerItem = (IFluidContainerItem) item; + containerItem.fill(full, liquid, true); + return full; + } + + return FluidContainerRegistry.fillFluidContainer(liquid, empty); + } + + public static FluidStack getFluidStackInContainer(ItemStack stack) { + if (stack == null) { + return null; + } + Item item = stack.getItem(); + if (item instanceof IFluidContainerItem) { + IFluidContainerItem containerItem = (IFluidContainerItem) item; + return containerItem.getFluid(stack); + } + + return FluidContainerRegistry.getFluidForFilledItem(stack); + } + + public static Fluid getFluidInContainer(ItemStack stack) { + FluidStack fluidStack = getFluidStackInContainer(stack); + return fluidStack != null ? fluidStack.getFluid() : null; + } + + public static boolean containsFluidStack(ItemStack stack, FluidStack fluidStack) { + Item item = stack.getItem(); + if (item instanceof IFluidContainerItem) { + IFluidContainerItem containerItem = (IFluidContainerItem) item; + FluidStack contained = containerItem.getFluid(stack); + return contained != null && contained.containsFluid(fluidStack); + } + + return FluidContainerRegistry.containsFluid(stack, fluidStack); + } + + public static boolean containsFluid(ItemStack stack, Fluid fluid) { + return containsFluidStack(stack, new FluidStack(fluid, 1)); + } + + public static int getFluidCapacity(Fluid fluid, ItemStack container) { + if (container == null) { + return 0; + } + Item item = container.getItem(); + if (item instanceof IFluidContainerItem) { + IFluidContainerItem containerItem = (IFluidContainerItem) item; + return containerItem.getCapacity(container); + } + + if (fluid == null) { + return FluidContainerRegistry.getContainerCapacity(container); + } else { + return FluidContainerRegistry.getContainerCapacity( + new FluidStack(fluid, Constants.BUCKET_VOLUME), container); + } + } } diff --git a/src/main/java/forestry/core/fluids/Fluids.java b/src/main/java/forestry/core/fluids/Fluids.java index 79bbb74bd..51b74f656 100644 --- a/src/main/java/forestry/core/fluids/Fluids.java +++ b/src/main/java/forestry/core/fluids/Fluids.java @@ -1,432 +1,401 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.fluids; - -import javax.annotation.Nonnull; -import java.awt.Color; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.commons.lang3.text.WordUtils; - -import net.minecraft.block.Block; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - -import forestry.core.config.Constants; -import forestry.core.items.EnumContainerType; -import forestry.core.items.ItemLiquidContainer; - -public enum Fluids { - - ETHANOL(new Color(255, 111, 0), 790, 1000) { - @Override - public String getTag() { - return "bioethanol"; - } - - @Override - public Block makeBlock() { - return new BlockForestryFluid(this, 300, true); - } - - @Override - public EnumSet getContainerTypes() { - return EnumSet.of( - EnumContainerType.BUCKET, - EnumContainerType.CAN, - EnumContainerType.CAPSULE, - EnumContainerType.REFRACTORY - ); - } - }, - BIOMASS(new Color(100, 132, 41), 400, 6560) { - @Override - public Block makeBlock() { - return new BlockForestryFluid(this, 100, true); - } - - @Override - public EnumSet getContainerTypes() { - return EnumSet.of( - EnumContainerType.BUCKET, - EnumContainerType.CAN, - EnumContainerType.CAPSULE, - EnumContainerType.REFRACTORY - ); - } - }, - GLASS(new Color(164, 164, 164), 2400, 10000) { - @Override - public int getTemperature() { - return 1200; - } - - @Override - public Block makeBlock() { - return new BlockForestryFluid(this, 0, true); - } - - @Override - public EnumSet getContainerTypes() { - return EnumSet.of( - EnumContainerType.BUCKET - ); - } - }, - HONEY(new Color(255, 196, 35), 1420, 73600) { - @Override - public String getTag() { - return "for.honey"; - } - - @Override - public Block makeBlock() { - return new BlockForestryFluid(this); - } - - @Override - public EnumSet getContainerTypes() { - return EnumSet.of( - EnumContainerType.BUCKET, - EnumContainerType.CAN, - EnumContainerType.CAPSULE, - EnumContainerType.REFRACTORY - ); - } - - @Override - public void setProperties(ItemLiquidContainer liquidContainer) { - if (liquidContainer.getType() != EnumContainerType.BUCKET) { - liquidContainer.setDrink(Constants.FOOD_HONEY_HEAL, Constants.FOOD_HONEY_SATURATION); - } - } - }, - LEGACY_HONEY(new Color(255, 196, 35)) { - @Override - public String getTag() { - return "honey"; - } - }, - ICE(new Color(175, 242, 255), 920, 1000) { - @Override - public int getTemperature() { - return 265; - } - - @Override - public Block makeBlock() { - return new BlockForestryFluid(this); - } - - @Override - public EnumSet getContainerTypes() { - return EnumSet.of( - EnumContainerType.BUCKET, - EnumContainerType.CAN, - EnumContainerType.CAPSULE, - EnumContainerType.REFRACTORY - ); - } - }, - JUICE(new Color(168, 201, 114)) { - @Override - public Block makeBlock() { - return new BlockForestryFluid(this); - } - - @Override - public EnumSet getContainerTypes() { - return EnumSet.of( - EnumContainerType.BUCKET, - EnumContainerType.CAN, - EnumContainerType.CAPSULE, - EnumContainerType.REFRACTORY - ); - } - - @Override - public void setProperties(ItemLiquidContainer liquidContainer) { - if (liquidContainer.getType() != EnumContainerType.BUCKET) { - liquidContainer.setDrink(Constants.FOOD_JUICE_HEAL, Constants.FOOD_JUICE_SATURATION); - } - } - }, - MILK(new Color(255, 255, 255), 1030, 3000) { - @Override - public Block makeBlock() { - return new BlockForestryFluid(this); - } - - @Override - public List getOtherContainers() { - return Collections.singletonList( - new ItemStack(Items.milk_bucket) - ); - } - }, - SEEDOIL("SeedOil", new Color(255, 255, 168), 885, 5000) { - @Override - public Block makeBlock() { - return new BlockForestryFluid(this, 2, true); - } - - @Override - public EnumSet getContainerTypes() { - return EnumSet.of( - EnumContainerType.BUCKET, - EnumContainerType.CAN, - EnumContainerType.CAPSULE, - EnumContainerType.REFRACTORY - ); - } - }, - SHORT_MEAD("ShortMead", new Color(239, 154, 56), 1000, 1200) { - @Override - public String getTag() { - return "short.mead"; - } - - @Override - public Block makeBlock() { - return new BlockForestryFluid(this); - } - - @Override - public EnumSet getContainerTypes() { - return EnumSet.of( - EnumContainerType.BUCKET, - EnumContainerType.CAN, - EnumContainerType.CAPSULE, - EnumContainerType.REFRACTORY - ); - } - }, - MEAD("Mead", new Color(202, 102, 0), 1000, 1200) { - @Override - public String getTag() { - return "mead"; - } - - @Override - public Block makeBlock() { - return new BlockForestryFluid(this); - } - - @Override - public EnumSet getContainerTypes() { - return EnumSet.of( - EnumContainerType.BUCKET, - EnumContainerType.CAN, - EnumContainerType.CAPSULE, - EnumContainerType.REFRACTORY - ); - } - }, - // Vanilla - WATER(new Color(0x2432ec)) { - @Override - public EnumSet getContainerTypes() { - return EnumSet.of( - EnumContainerType.CAN, - EnumContainerType.CAPSULE, - EnumContainerType.REFRACTORY - ); - } - }, - LAVA(new Color(0xfd461f)) { - @Override - public EnumSet getContainerTypes() { - return EnumSet.of( - EnumContainerType.CAN, - EnumContainerType.REFRACTORY - ); - } - }, - // BuildCraft - FUEL(new Color(0xffff00)) { - @Override - public EnumSet getContainerTypes() { - return EnumSet.of( - EnumContainerType.CAN, - EnumContainerType.CAPSULE, - EnumContainerType.REFRACTORY - ); - } - }, - OIL(new Color(0x404040)) { - @Override - public EnumSet getContainerTypes() { - return EnumSet.of( - EnumContainerType.CAN, - EnumContainerType.CAPSULE, - EnumContainerType.REFRACTORY - ); - } - }, - // Railcraft - CREOSOTE(new Color(0x635c03)), - STEAM(new Color(0x91938F)); - - public static final Fluids[] forestryFluids = {ETHANOL, BIOMASS, GLASS, HONEY, LEGACY_HONEY, ICE, JUICE, MILK, SEEDOIL, SHORT_MEAD, MEAD}; - - private static final Map tagToFluid = new HashMap<>(); - - static { - for (Fluids fluids : Fluids.values()) { - tagToFluid.put(fluids.getTag(), fluids); - } - } - - private final String containerNameKey; - private final String tag; - private final int density, viscosity; - @Nonnull - private final Color color; - - Fluids(@Nonnull Color color) { - this(null, color, 1000, 1000); - } - - Fluids(@Nonnull Color color, int density, int viscosity) { - this(null, color, density, viscosity); - } - - Fluids(String containerNameKey, @Nonnull Color color, int density, int viscosity) { - if (containerNameKey == null) { - containerNameKey = WordUtils.capitalize(toString().toLowerCase(Locale.ENGLISH)); - } - this.containerNameKey = containerNameKey; - this.tag = name().toLowerCase(Locale.ENGLISH); - this.color = color; - this.density = density; - this.viscosity = viscosity; - } - - public int getTemperature() { - return 295; - } - - public String getTag() { - return tag; - } - - public final int getDensity() { - return density; - } - - public final int getViscosity() { - return viscosity; - } - - public final Fluid getFluid() { - return FluidRegistry.getFluid(getTag()); - } - - public final FluidStack getFluid(int mb) { - return FluidRegistry.getFluidStack(getTag(), mb); - } - - public final Block getBlock() { - Fluid fluid = getFluid(); - if (fluid == null) { - return null; - } - return fluid.getBlock(); - } - - @Nonnull - public final Color getColor() { - return color; - } - - public final boolean is(Fluid fluid) { - return getFluid() == fluid; - } - - public final boolean is(FluidStack fluidStack) { - return fluidStack != null && getFluid() == fluidStack.getFluid(); - } - - public final boolean isContained(ItemStack containerStack) { - return containerStack != null && FluidHelper.containsFluid(containerStack, getFluid()); - } - - public static boolean areEqual(Fluid fluid, FluidStack fluidStack) { - if (fluidStack != null && fluid == fluidStack.getFluid()) { - return true; - } - return fluid == null && fluidStack == null; - } - - public static boolean areEqual(FluidStack a, FluidStack b) { - if (a == b) { - return true; - } - if (a == null || b == null) { - return false; - } - return a.isFluidEqual(b); - } - - @Nonnull - public static Color getFluidColor(FluidStack fluidStack) { - if (fluidStack != null) { - Fluid fluid = fluidStack.getFluid(); - if (fluid != null) { - Fluids fluids = tagToFluid.get(fluid.getName()); - if (fluids != null) { - return fluids.getColor(); - } - } - } - - return Fluids.WATER.getColor(); - } - - /** FluidBlock and Container registration */ - public String getContainerNameKey() { - return containerNameKey; - } - - public EnumSet getContainerTypes() { - return EnumSet.noneOf(EnumContainerType.class); - } - - /** - * Add non-forestry containers for this fluid. - */ - public List getOtherContainers() { - return Collections.emptyList(); - } - - /** - * Create a FluidBlock for this fluid. - */ - public Block makeBlock() { - return null; - } - - /** - * Set the properties for an ItemLiquidContainer before it gets registered. - */ - public void setProperties(ItemLiquidContainer liquidContainer) { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.fluids; + +import forestry.core.config.Constants; +import forestry.core.items.EnumContainerType; +import forestry.core.items.ItemLiquidContainer; +import java.awt.Color; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import javax.annotation.Nonnull; +import net.minecraft.block.Block; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import org.apache.commons.lang3.text.WordUtils; + +public enum Fluids { + ETHANOL(new Color(255, 111, 0), 790, 1000) { + @Override + public String getTag() { + return "bioethanol"; + } + + @Override + public Block makeBlock() { + return new BlockForestryFluid(this, 300, true); + } + + @Override + public EnumSet getContainerTypes() { + return EnumSet.of( + EnumContainerType.BUCKET, + EnumContainerType.CAN, + EnumContainerType.CAPSULE, + EnumContainerType.REFRACTORY); + } + }, + BIOMASS(new Color(100, 132, 41), 400, 6560) { + @Override + public Block makeBlock() { + return new BlockForestryFluid(this, 100, true); + } + + @Override + public EnumSet getContainerTypes() { + return EnumSet.of( + EnumContainerType.BUCKET, + EnumContainerType.CAN, + EnumContainerType.CAPSULE, + EnumContainerType.REFRACTORY); + } + }, + GLASS(new Color(164, 164, 164), 2400, 10000) { + @Override + public int getTemperature() { + return 1200; + } + + @Override + public Block makeBlock() { + return new BlockForestryFluid(this, 0, true); + } + + @Override + public EnumSet getContainerTypes() { + return EnumSet.of(EnumContainerType.BUCKET); + } + }, + HONEY(new Color(255, 196, 35), 1420, 73600) { + @Override + public String getTag() { + return "for.honey"; + } + + @Override + public Block makeBlock() { + return new BlockForestryFluid(this); + } + + @Override + public EnumSet getContainerTypes() { + return EnumSet.of( + EnumContainerType.BUCKET, + EnumContainerType.CAN, + EnumContainerType.CAPSULE, + EnumContainerType.REFRACTORY); + } + + @Override + public void setProperties(ItemLiquidContainer liquidContainer) { + if (liquidContainer.getType() != EnumContainerType.BUCKET) { + liquidContainer.setDrink(Constants.FOOD_HONEY_HEAL, Constants.FOOD_HONEY_SATURATION); + } + } + }, + LEGACY_HONEY(new Color(255, 196, 35)) { + @Override + public String getTag() { + return "honey"; + } + }, + ICE(new Color(175, 242, 255), 920, 1000) { + @Override + public int getTemperature() { + return 265; + } + + @Override + public Block makeBlock() { + return new BlockForestryFluid(this); + } + + @Override + public EnumSet getContainerTypes() { + return EnumSet.of( + EnumContainerType.BUCKET, + EnumContainerType.CAN, + EnumContainerType.CAPSULE, + EnumContainerType.REFRACTORY); + } + }, + JUICE(new Color(168, 201, 114)) { + @Override + public Block makeBlock() { + return new BlockForestryFluid(this); + } + + @Override + public EnumSet getContainerTypes() { + return EnumSet.of( + EnumContainerType.BUCKET, + EnumContainerType.CAN, + EnumContainerType.CAPSULE, + EnumContainerType.REFRACTORY); + } + + @Override + public void setProperties(ItemLiquidContainer liquidContainer) { + if (liquidContainer.getType() != EnumContainerType.BUCKET) { + liquidContainer.setDrink(Constants.FOOD_JUICE_HEAL, Constants.FOOD_JUICE_SATURATION); + } + } + }, + MILK(new Color(255, 255, 255), 1030, 3000) { + @Override + public Block makeBlock() { + return new BlockForestryFluid(this); + } + + @Override + public List getOtherContainers() { + return Collections.singletonList(new ItemStack(Items.milk_bucket)); + } + }, + SEEDOIL("SeedOil", new Color(255, 255, 168), 885, 5000) { + @Override + public Block makeBlock() { + return new BlockForestryFluid(this, 2, true); + } + + @Override + public EnumSet getContainerTypes() { + return EnumSet.of( + EnumContainerType.BUCKET, + EnumContainerType.CAN, + EnumContainerType.CAPSULE, + EnumContainerType.REFRACTORY); + } + }, + SHORT_MEAD("ShortMead", new Color(239, 154, 56), 1000, 1200) { + @Override + public String getTag() { + return "short.mead"; + } + + @Override + public Block makeBlock() { + return new BlockForestryFluid(this); + } + + @Override + public EnumSet getContainerTypes() { + return EnumSet.of( + EnumContainerType.BUCKET, + EnumContainerType.CAN, + EnumContainerType.CAPSULE, + EnumContainerType.REFRACTORY); + } + }, + MEAD("Mead", new Color(202, 102, 0), 1000, 1200) { + @Override + public String getTag() { + return "mead"; + } + + @Override + public Block makeBlock() { + return new BlockForestryFluid(this); + } + + @Override + public EnumSet getContainerTypes() { + return EnumSet.of( + EnumContainerType.BUCKET, + EnumContainerType.CAN, + EnumContainerType.CAPSULE, + EnumContainerType.REFRACTORY); + } + }, + // Vanilla + WATER(new Color(0x2432ec)) { + @Override + public EnumSet getContainerTypes() { + return EnumSet.of(EnumContainerType.CAN, EnumContainerType.CAPSULE, EnumContainerType.REFRACTORY); + } + }, + LAVA(new Color(0xfd461f)) { + @Override + public EnumSet getContainerTypes() { + return EnumSet.of(EnumContainerType.CAN, EnumContainerType.REFRACTORY); + } + }, + // BuildCraft + FUEL(new Color(0xffff00)) { + @Override + public EnumSet getContainerTypes() { + return EnumSet.of(EnumContainerType.CAN, EnumContainerType.CAPSULE, EnumContainerType.REFRACTORY); + } + }, + OIL(new Color(0x404040)) { + @Override + public EnumSet getContainerTypes() { + return EnumSet.of(EnumContainerType.CAN, EnumContainerType.CAPSULE, EnumContainerType.REFRACTORY); + } + }, + // Railcraft + CREOSOTE(new Color(0x635c03)), + STEAM(new Color(0x91938F)); + + public static final Fluids[] forestryFluids = { + ETHANOL, BIOMASS, GLASS, HONEY, LEGACY_HONEY, ICE, JUICE, MILK, SEEDOIL, SHORT_MEAD, MEAD + }; + + private static final Map tagToFluid = new HashMap<>(); + + static { + for (Fluids fluids : Fluids.values()) { + tagToFluid.put(fluids.getTag(), fluids); + } + } + + private final String containerNameKey; + private final String tag; + private final int density, viscosity; + + @Nonnull + private final Color color; + + Fluids(@Nonnull Color color) { + this(null, color, 1000, 1000); + } + + Fluids(@Nonnull Color color, int density, int viscosity) { + this(null, color, density, viscosity); + } + + Fluids(String containerNameKey, @Nonnull Color color, int density, int viscosity) { + if (containerNameKey == null) { + containerNameKey = WordUtils.capitalize(toString().toLowerCase(Locale.ENGLISH)); + } + this.containerNameKey = containerNameKey; + this.tag = name().toLowerCase(Locale.ENGLISH); + this.color = color; + this.density = density; + this.viscosity = viscosity; + } + + public int getTemperature() { + return 295; + } + + public String getTag() { + return tag; + } + + public final int getDensity() { + return density; + } + + public final int getViscosity() { + return viscosity; + } + + public final Fluid getFluid() { + return FluidRegistry.getFluid(getTag()); + } + + public final FluidStack getFluid(int mb) { + return FluidRegistry.getFluidStack(getTag(), mb); + } + + public final Block getBlock() { + Fluid fluid = getFluid(); + if (fluid == null) { + return null; + } + return fluid.getBlock(); + } + + @Nonnull + public final Color getColor() { + return color; + } + + public final boolean is(Fluid fluid) { + return getFluid() == fluid; + } + + public final boolean is(FluidStack fluidStack) { + return fluidStack != null && getFluid() == fluidStack.getFluid(); + } + + public final boolean isContained(ItemStack containerStack) { + return containerStack != null && FluidHelper.containsFluid(containerStack, getFluid()); + } + + public static boolean areEqual(Fluid fluid, FluidStack fluidStack) { + if (fluidStack != null && fluid == fluidStack.getFluid()) { + return true; + } + return fluid == null && fluidStack == null; + } + + public static boolean areEqual(FluidStack a, FluidStack b) { + if (a == b) { + return true; + } + if (a == null || b == null) { + return false; + } + return a.isFluidEqual(b); + } + + @Nonnull + public static Color getFluidColor(FluidStack fluidStack) { + if (fluidStack != null) { + Fluid fluid = fluidStack.getFluid(); + if (fluid != null) { + Fluids fluids = tagToFluid.get(fluid.getName()); + if (fluids != null) { + return fluids.getColor(); + } + } + } + + return Fluids.WATER.getColor(); + } + + /** FluidBlock and Container registration */ + public String getContainerNameKey() { + return containerNameKey; + } + + public EnumSet getContainerTypes() { + return EnumSet.noneOf(EnumContainerType.class); + } + + /** + * Add non-forestry containers for this fluid. + */ + public List getOtherContainers() { + return Collections.emptyList(); + } + + /** + * Create a FluidBlock for this fluid. + */ + public Block makeBlock() { + return null; + } + + /** + * Set the properties for an ItemLiquidContainer before it gets registered. + */ + public void setProperties(ItemLiquidContainer liquidContainer) {} +} diff --git a/src/main/java/forestry/core/fluids/ITankManager.java b/src/main/java/forestry/core/fluids/ITankManager.java index 58b16c4d7..220ae2376 100644 --- a/src/main/java/forestry/core/fluids/ITankManager.java +++ b/src/main/java/forestry/core/fluids/ITankManager.java @@ -1,36 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.fluids; - -import java.util.List; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.ICrafting; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidHandler; -import net.minecraftforge.fluids.IFluidTank; - -public interface ITankManager extends IFluidHandler { - void containerAdded(Container container, ICrafting player); - - void updateGuiData(Container container, List crafters); - - void containerRemoved(Container container); - - IFluidTank getTank(int tankIndex); - - /** - * For updating tanks on the client - */ - void processTankUpdate(int tankIndex, FluidStack contents); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.fluids; + +import java.util.List; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.IFluidHandler; +import net.minecraftforge.fluids.IFluidTank; + +public interface ITankManager extends IFluidHandler { + void containerAdded(Container container, ICrafting player); + + void updateGuiData(Container container, List crafters); + + void containerRemoved(Container container); + + IFluidTank getTank(int tankIndex); + + /** + * For updating tanks on the client + */ + void processTankUpdate(int tankIndex, FluidStack contents); +} diff --git a/src/main/java/forestry/core/fluids/ITankUpdateHandler.java b/src/main/java/forestry/core/fluids/ITankUpdateHandler.java index babbfec69..4abcc3cc0 100644 --- a/src/main/java/forestry/core/fluids/ITankUpdateHandler.java +++ b/src/main/java/forestry/core/fluids/ITankUpdateHandler.java @@ -1,17 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.fluids; - -import forestry.core.fluids.tanks.StandardTank; - -public interface ITankUpdateHandler { - void updateTankLevels(StandardTank tank); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.fluids; + +import forestry.core.fluids.tanks.StandardTank; + +public interface ITankUpdateHandler { + void updateTankLevels(StandardTank tank); +} diff --git a/src/main/java/forestry/core/fluids/LiquidRegistryHelper.java b/src/main/java/forestry/core/fluids/LiquidRegistryHelper.java index c5c17d4d8..90f0e9e21 100644 --- a/src/main/java/forestry/core/fluids/LiquidRegistryHelper.java +++ b/src/main/java/forestry/core/fluids/LiquidRegistryHelper.java @@ -10,61 +10,59 @@ ******************************************************************************/ package forestry.core.fluids; -import java.util.EnumMap; - -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemBucket; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidContainerRegistry; -import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; -import net.minecraftforge.fluids.FluidStack; - import forestry.core.config.Constants; import forestry.core.items.EnumContainerType; import forestry.core.items.ItemLiquidContainer; import forestry.core.utils.Log; import forestry.plugins.PluginFluids; +import java.util.EnumMap; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemBucket; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; +import net.minecraftforge.fluids.FluidStack; public class LiquidRegistryHelper { - private static final EnumMap emptyContainers = new EnumMap<>(EnumContainerType.class); + private static final EnumMap emptyContainers = + new EnumMap<>(EnumContainerType.class); - static { - emptyContainers.put(EnumContainerType.CAN, PluginFluids.items.canEmpty); - emptyContainers.put(EnumContainerType.CAPSULE, PluginFluids.items.waxCapsuleEmpty); - emptyContainers.put(EnumContainerType.REFRACTORY, PluginFluids.items.refractoryEmpty); - } + static { + emptyContainers.put(EnumContainerType.CAN, PluginFluids.items.canEmpty); + emptyContainers.put(EnumContainerType.CAPSULE, PluginFluids.items.waxCapsuleEmpty); + emptyContainers.put(EnumContainerType.REFRACTORY, PluginFluids.items.refractoryEmpty); + } - public static void registerLiquidContainer(Fluids fluid, ItemStack filled) { - Item item = filled.getItem(); - ItemStack empty = null; + public static void registerLiquidContainer(Fluids fluid, ItemStack filled) { + Item item = filled.getItem(); + ItemStack empty = null; - if (item.getContainerItem() instanceof ItemBucket) { - empty = new ItemStack(Items.bucket); - } else if (item instanceof ItemLiquidContainer) { - ItemLiquidContainer liquidContainer = (ItemLiquidContainer) item; - EnumContainerType containerType = liquidContainer.getType(); - ItemLiquidContainer emptyContainer = emptyContainers.get(containerType); - empty = emptyContainer.getItemStack(); - } + if (item.getContainerItem() instanceof ItemBucket) { + empty = new ItemStack(Items.bucket); + } else if (item instanceof ItemLiquidContainer) { + ItemLiquidContainer liquidContainer = (ItemLiquidContainer) item; + EnumContainerType containerType = liquidContainer.getType(); + ItemLiquidContainer emptyContainer = emptyContainers.get(containerType); + empty = emptyContainer.getItemStack(); + } - if (empty == null) { - Log.warning("Unable to inject liquid container: " + filled); - } else { - registerLiquidContainer(fluid, Constants.BUCKET_VOLUME, filled, empty); - } - } + if (empty == null) { + Log.warning("Unable to inject liquid container: " + filled); + } else { + registerLiquidContainer(fluid, Constants.BUCKET_VOLUME, filled, empty); + } + } - public static void registerLiquidContainer(Fluids fluid, int volume, ItemStack filled, ItemStack empty) { - FluidStack contained = fluid.getFluid(volume); - if (contained == null) { - throw new IllegalArgumentException(String.format("Attempted to inject a liquid container for the non-existent liquid '%s'.", fluid)); - } - - FluidContainerData container = new FluidContainerData(contained, filled, empty); - FluidContainerRegistry.registerFluidContainer(container); - } + public static void registerLiquidContainer(Fluids fluid, int volume, ItemStack filled, ItemStack empty) { + FluidStack contained = fluid.getFluid(volume); + if (contained == null) { + throw new IllegalArgumentException( + String.format("Attempted to inject a liquid container for the non-existent liquid '%s'.", fluid)); + } + FluidContainerData container = new FluidContainerData(contained, filled, empty); + FluidContainerRegistry.registerFluidContainer(container); + } } diff --git a/src/main/java/forestry/core/fluids/PipetteContents.java b/src/main/java/forestry/core/fluids/PipetteContents.java index ff654ebe3..d747ea7d8 100644 --- a/src/main/java/forestry/core/fluids/PipetteContents.java +++ b/src/main/java/forestry/core/fluids/PipetteContents.java @@ -1,69 +1,66 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.fluids; - -import java.util.List; - -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.core.INBTTagable; - -public class PipetteContents implements INBTTagable { - private FluidStack contents; - - public PipetteContents(NBTTagCompound nbttagcompound) { - if (nbttagcompound != null) { - readFromNBT(nbttagcompound); - } - } - - public FluidStack getContents() { - return contents; - } - - public void setContents(FluidStack contents) { - this.contents = contents; - } - - public boolean isFull() { - if (contents == null) { - return false; - } - - return contents.getFluid().getID() > 0 && contents.amount >= 1000; - } - - public void addTooltip(List list) { - if (contents == null) { - return; - } - - String descr = contents.getFluid().getLocalizedName(contents); - descr += " (" + contents.amount + " mb)"; - - list.add(descr); - } - - /* INBTTagable */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - contents = FluidStack.loadFluidStackFromNBT(nbttagcompound); - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - if (contents != null) { - contents.writeToNBT(nbttagcompound); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.fluids; + +import forestry.api.core.INBTTagable; +import java.util.List; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.FluidStack; + +public class PipetteContents implements INBTTagable { + private FluidStack contents; + + public PipetteContents(NBTTagCompound nbttagcompound) { + if (nbttagcompound != null) { + readFromNBT(nbttagcompound); + } + } + + public FluidStack getContents() { + return contents; + } + + public void setContents(FluidStack contents) { + this.contents = contents; + } + + public boolean isFull() { + if (contents == null) { + return false; + } + + return contents.getFluid().getID() > 0 && contents.amount >= 1000; + } + + public void addTooltip(List list) { + if (contents == null) { + return; + } + + String descr = contents.getFluid().getLocalizedName(contents); + descr += " (" + contents.amount + " mb)"; + + list.add(descr); + } + + /* INBTTagable */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + contents = FluidStack.loadFluidStackFromNBT(nbttagcompound); + } + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + if (contents != null) { + contents.writeToNBT(nbttagcompound); + } + } +} diff --git a/src/main/java/forestry/core/fluids/TankManager.java b/src/main/java/forestry/core/fluids/TankManager.java index 52762a0af..65e8905ac 100644 --- a/src/main/java/forestry/core/fluids/TankManager.java +++ b/src/main/java/forestry/core/fluids/TankManager.java @@ -12,27 +12,6 @@ package forestry.core.fluids; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; - -import javax.annotation.Nonnull; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.ICrafting; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidTank; - import forestry.api.core.INBTTagable; import forestry.core.fluids.tanks.FakeTank; import forestry.core.fluids.tanks.StandardTank; @@ -47,316 +26,333 @@ import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.IRenderableTile; import forestry.core.utils.NBTUtil; import forestry.core.utils.NBTUtil.NBTList; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import javax.annotation.Nonnull; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidTank; /** * @author CovertJaguar */ public class TankManager implements ITankManager, ITankUpdateHandler, IStreamable, INBTTagable { - private final List tanks = new ArrayList<>(); + private final List tanks = new ArrayList<>(); - // for container updates, keeps track of the fluids known to each client (container) - private final Table prevFluidStacks = HashBasedTable.create(); + // for container updates, keeps track of the fluids known to each client (container) + private final Table prevFluidStacks = HashBasedTable.create(); - // tank tile updates, for blocks that show fluid levels on the outside - private final ILiquidTankTile tile; - private final List tankLevels = new ArrayList<>(); + // tank tile updates, for blocks that show fluid levels on the outside + private final ILiquidTankTile tile; + private final List tankLevels = new ArrayList<>(); - public TankManager() { - this.tile = null; - } + public TankManager() { + this.tile = null; + } - public TankManager(ILiquidTankTile tile, StandardTank... tanks) { - this.tile = tile; - addAll(Arrays.asList(tanks)); - } + public TankManager(ILiquidTankTile tile, StandardTank... tanks) { + this.tile = tile; + addAll(Arrays.asList(tanks)); + } - public final boolean addAll(@Nonnull Collection collection) { - boolean addedAll = true; - for (StandardTank tank : collection) { - addedAll &= add(tank); - } - return addedAll; - } + public final boolean addAll(@Nonnull Collection collection) { + boolean addedAll = true; + for (StandardTank tank : collection) { + addedAll &= add(tank); + } + return addedAll; + } - public boolean add(@Nonnull StandardTank tank) { - boolean added = tanks.add(tank); - int index = tanks.indexOf(tank); - tank.setTankUpdateHandler(this); - tank.setTankIndex(index); - tankLevels.add(EnumTankLevel.rateTankLevel(tank)); - return added; - } + public boolean add(@Nonnull StandardTank tank) { + boolean added = tanks.add(tank); + int index = tanks.indexOf(tank); + tank.setTankUpdateHandler(this); + tank.setTankIndex(index); + tankLevels.add(EnumTankLevel.rateTankLevel(tank)); + return added; + } - @Override - public void writeToNBT(NBTTagCompound data) { - NBTTagList tagList = new NBTTagList(); - for (byte slot = 0; slot < tanks.size(); slot++) { - StandardTank tank = tanks.get(slot); - if (tank.getFluid() != null) { - NBTTagCompound tag = new NBTTagCompound(); - tag.setByte("tank", slot); - tank.writeToNBT(tag); - tagList.appendTag(tag); - } - } - data.setTag("tanks", tagList); - } + @Override + public void writeToNBT(NBTTagCompound data) { + NBTTagList tagList = new NBTTagList(); + for (byte slot = 0; slot < tanks.size(); slot++) { + StandardTank tank = tanks.get(slot); + if (tank.getFluid() != null) { + NBTTagCompound tag = new NBTTagCompound(); + tag.setByte("tank", slot); + tank.writeToNBT(tag); + tagList.appendTag(tag); + } + } + data.setTag("tanks", tagList); + } - @Override - public void readFromNBT(NBTTagCompound data) { - NBTList tagList = NBTUtil.getNBTList(data, "tanks", NBTUtil.EnumNBTType.COMPOUND); - for (NBTTagCompound tag : tagList) { - int slot = tag.getByte("tank"); - if (slot >= 0 && slot < tanks.size()) { - StandardTank tank = tanks.get(slot); - tank.readFromNBT(tag); - updateTankLevels(tank, false); - } - } - } + @Override + public void readFromNBT(NBTTagCompound data) { + NBTList tagList = NBTUtil.getNBTList(data, "tanks", NBTUtil.EnumNBTType.COMPOUND); + for (NBTTagCompound tag : tagList) { + int slot = tag.getByte("tank"); + if (slot >= 0 && slot < tanks.size()) { + StandardTank tank = tanks.get(slot); + tank.readFromNBT(tag); + updateTankLevels(tank, false); + } + } + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - for (StandardTank tank : tanks) { - tank.writeData(data); - } - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + for (StandardTank tank : tanks) { + tank.writeData(data); + } + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - for (StandardTank tank : tanks) { - tank.readData(data); - } - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + for (StandardTank tank : tanks) { + tank.readData(data); + } + } - @Override - public void containerAdded(Container container, ICrafting player) { - if (!(player instanceof EntityPlayerMP)) { - return; - } + @Override + public void containerAdded(Container container, ICrafting player) { + if (!(player instanceof EntityPlayerMP)) { + return; + } - List crafters = Collections.singletonList((EntityPlayerMP) player); + List crafters = Collections.singletonList((EntityPlayerMP) player); - for (StandardTank tank : tanks) { - sendTankUpdate(container, tank, crafters); - } - } + for (StandardTank tank : tanks) { + sendTankUpdate(container, tank, crafters); + } + } - @Override - public void containerRemoved(Container container) { - for (StandardTank tank : tanks) { - prevFluidStacks.remove(container, tank.getTankIndex()); - } - } + @Override + public void containerRemoved(Container container) { + for (StandardTank tank : tanks) { + prevFluidStacks.remove(container, tank.getTankIndex()); + } + } - @Override - public void updateGuiData(Container container, List crafters) { - for (StandardTank tank : tanks) { - updateGuiData(container, crafters, tank.getTankIndex()); - } - } + @Override + public void updateGuiData(Container container, List crafters) { + for (StandardTank tank : tanks) { + updateGuiData(container, crafters, tank.getTankIndex()); + } + } - private void updateGuiData(Container container, List crafters, int tankIndex) { - StandardTank tank = tanks.get(tankIndex); - if (tank == null) { - return; - } + private void updateGuiData(Container container, List crafters, int tankIndex) { + StandardTank tank = tanks.get(tankIndex); + if (tank == null) { + return; + } - FluidStack fluidStack = tank.getFluid(); - FluidStack prev = prevFluidStacks.get(container, tankIndex); - if (FluidHelper.areFluidStacksEqual(fluidStack, prev)) { - return; - } + FluidStack fluidStack = tank.getFluid(); + FluidStack prev = prevFluidStacks.get(container, tankIndex); + if (FluidHelper.areFluidStacksEqual(fluidStack, prev)) { + return; + } - sendTankUpdate(container, tank, crafters); - } + sendTankUpdate(container, tank, crafters); + } - private void sendTankUpdate(Container container, StandardTank tank, Iterable crafters) { - int tankIndex = tank.getTankIndex(); - FluidStack fluid = tank.getFluid(); - IForestryPacketClient packet = new PacketTankLevelUpdate(tile, tankIndex, fluid); - for (EntityPlayerMP player : crafters) { - Proxies.net.sendToPlayer(packet, player); - } + private void sendTankUpdate(Container container, StandardTank tank, Iterable crafters) { + int tankIndex = tank.getTankIndex(); + FluidStack fluid = tank.getFluid(); + IForestryPacketClient packet = new PacketTankLevelUpdate(tile, tankIndex, fluid); + for (EntityPlayerMP player : crafters) { + Proxies.net.sendToPlayer(packet, player); + } - if (fluid == null) { - prevFluidStacks.remove(container, tankIndex); - } else { - prevFluidStacks.put(container, tankIndex, fluid.copy()); - } - } + if (fluid == null) { + prevFluidStacks.remove(container, tankIndex); + } else { + prevFluidStacks.put(container, tankIndex, fluid.copy()); + } + } - @Override - public void processTankUpdate(int tankIndex, FluidStack contents) { - if (tankIndex < 0 || tankIndex > tanks.size()) { - return; - } - StandardTank tank = tanks.get(tankIndex); - tank.setFluid(contents); - } + @Override + public void processTankUpdate(int tankIndex, FluidStack contents) { + if (tankIndex < 0 || tankIndex > tanks.size()) { + return; + } + StandardTank tank = tanks.get(tankIndex); + tank.setFluid(contents); + } - @Override - public IFluidTank getTank(int tankIndex) { - return tanks.get(tankIndex); - } + @Override + public IFluidTank getTank(int tankIndex) { + return tanks.get(tankIndex); + } - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - for (StandardTank tank : tanks) { - if (tankAcceptsFluid(tank, resource)) { - return fill(tank.getTankIndex(), resource, doFill); - } - } + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + for (StandardTank tank : tanks) { + if (tankAcceptsFluid(tank, resource)) { + return fill(tank.getTankIndex(), resource, doFill); + } + } - return FakeTank.INSTANCE.fill(resource, doFill); - } + return FakeTank.INSTANCE.fill(resource, doFill); + } - public int fill(int tankIndex, FluidStack resource, boolean doFill) { - if (tankIndex < 0 || tankIndex >= tanks.size() || resource == null) { - return 0; - } + public int fill(int tankIndex, FluidStack resource, boolean doFill) { + if (tankIndex < 0 || tankIndex >= tanks.size() || resource == null) { + return 0; + } - StandardTank tank = tanks.get(tankIndex); - if (!tank.canBeFilledExternally()) { - return 0; - } + StandardTank tank = tanks.get(tankIndex); + if (!tank.canBeFilledExternally()) { + return 0; + } - return tank.fill(resource, doFill); - } + return tank.fill(resource, doFill); + } - @Override - public void updateTankLevels(StandardTank tank) { - updateTankLevels(tank, true); - } + @Override + public void updateTankLevels(StandardTank tank) { + updateTankLevels(tank, true); + } - private void updateTankLevels(StandardTank tank, boolean sendUpdate) { - if (!(tile instanceof IRenderableTile)) { - return; - } + private void updateTankLevels(StandardTank tank, boolean sendUpdate) { + if (!(tile instanceof IRenderableTile)) { + return; + } - int tankIndex = tank.getTankIndex(); - EnumTankLevel tankLevel = EnumTankLevel.rateTankLevel(tank); - if (tankLevel != tankLevels.get(tankIndex)) { - tankLevels.set(tankIndex, tankLevel); - if (sendUpdate) { - PacketTankLevelUpdate tankLevelUpdate = new PacketTankLevelUpdate(tile, tankIndex, tank.getFluid()); - Proxies.net.sendNetworkPacket(tankLevelUpdate, tile.getWorld()); - } - } - } + int tankIndex = tank.getTankIndex(); + EnumTankLevel tankLevel = EnumTankLevel.rateTankLevel(tank); + if (tankLevel != tankLevels.get(tankIndex)) { + tankLevels.set(tankIndex, tankLevel); + if (sendUpdate) { + PacketTankLevelUpdate tankLevelUpdate = new PacketTankLevelUpdate(tile, tankIndex, tank.getFluid()); + Proxies.net.sendNetworkPacket(tankLevelUpdate, tile.getWorld()); + } + } + } - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - for (StandardTank tank : tanks) { - if (tankCanDrain(tank)) { - return drain(tank.getTankIndex(), maxDrain, doDrain); - } - } - return FakeTank.INSTANCE.drain(maxDrain, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + for (StandardTank tank : tanks) { + if (tankCanDrain(tank)) { + return drain(tank.getTankIndex(), maxDrain, doDrain); + } + } + return FakeTank.INSTANCE.drain(maxDrain, doDrain); + } - public FluidStack drain(int tankIndex, int maxDrain, boolean doDrain) { - if (tankIndex < 0 || tankIndex >= tanks.size()) { - return null; - } + public FluidStack drain(int tankIndex, int maxDrain, boolean doDrain) { + if (tankIndex < 0 || tankIndex >= tanks.size()) { + return null; + } - StandardTank tank = tanks.get(tankIndex); - if (!tank.canBeDrainedExternally()) { - return null; - } + StandardTank tank = tanks.get(tankIndex); + if (!tank.canBeDrainedExternally()) { + return null; + } - return tank.drain(maxDrain, doDrain); - } + return tank.drain(maxDrain, doDrain); + } - public FluidStack drain(FluidStack resource, boolean doDrain) { - for (StandardTank tank : tanks) { - if (tankCanDrainFluid(tank, resource)) { - return drain(tank.getTankIndex(), resource.amount, doDrain); - } - } - return null; - } + public FluidStack drain(FluidStack resource, boolean doDrain) { + for (StandardTank tank : tanks) { + if (tankCanDrainFluid(tank, resource)) { + return drain(tank.getTankIndex(), resource.amount, doDrain); + } + } + return null; + } - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return drain(resource, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return drain(resource, doDrain); + } - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return true; - } + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return true; + } - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return true; - } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return true; + } - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection direction) { - FluidTankInfo[] info = new FluidTankInfo[tanks.size()]; - for (int i = 0; i < tanks.size(); i++) { - info[i] = tanks.get(i).getInfo(); - } - return info; - } + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection direction) { + FluidTankInfo[] info = new FluidTankInfo[tanks.size()]; + for (int i = 0; i < tanks.size(); i++) { + info[i] = tanks.get(i).getInfo(); + } + return info; + } - public FluidTankInfo[] getTankInfo() { - return getTankInfo(ForgeDirection.UNKNOWN); - } + public FluidTankInfo[] getTankInfo() { + return getTankInfo(ForgeDirection.UNKNOWN); + } - public FluidTankInfo getTankInfo(int tankIndex) { - return tanks.get(tankIndex).getInfo(); - } + public FluidTankInfo getTankInfo(int tankIndex) { + return tanks.get(tankIndex).getInfo(); + } - public FluidStack getFluid(int tankIndex) { - return tanks.get(tankIndex).getFluid(); - } + public FluidStack getFluid(int tankIndex) { + return tanks.get(tankIndex).getFluid(); + } - public int getFluidAmount(int tankIndex) { - return tanks.get(tankIndex).getFluidAmount(); - } + public int getFluidAmount(int tankIndex) { + return tanks.get(tankIndex).getFluidAmount(); + } - public boolean accepts(Fluid fluid) { - if (fluid == null) { - return false; - } - - for (StandardTank tank : tanks) { - if (tank.accepts(fluid)) { - return true; - } - } + public boolean accepts(Fluid fluid) { + if (fluid == null) { + return false; + } - return false; - } + for (StandardTank tank : tanks) { + if (tank.accepts(fluid)) { + return true; + } + } - private static boolean tankAcceptsFluid(StandardTank tank, FluidStack fluidStack) { - if (fluidStack == null) { - return false; - } - if (!tank.canBeFilledExternally()) { - return false; - } - return tank.fill(fluidStack, false) > 0; - } + return false; + } - private static boolean tankCanDrain(StandardTank tank) { - if (!tank.canBeDrainedExternally()) { - return false; - } - FluidStack drained = tank.drain(1, false); - return drained != null && drained.amount > 0; - } + private static boolean tankAcceptsFluid(StandardTank tank, FluidStack fluidStack) { + if (fluidStack == null) { + return false; + } + if (!tank.canBeFilledExternally()) { + return false; + } + return tank.fill(fluidStack, false) > 0; + } - private static boolean tankCanDrainFluid(StandardTank tank, FluidStack fluidStack) { - if (fluidStack == null) { - return false; - } - if (!Fluids.areEqual(tank.getFluidType(), fluidStack)) { - return false; - } - return tankCanDrain(tank); - } + private static boolean tankCanDrain(StandardTank tank) { + if (!tank.canBeDrainedExternally()) { + return false; + } + FluidStack drained = tank.drain(1, false); + return drained != null && drained.amount > 0; + } + + private static boolean tankCanDrainFluid(StandardTank tank, FluidStack fluidStack) { + if (fluidStack == null) { + return false; + } + if (!Fluids.areEqual(tank.getFluidType(), fluidStack)) { + return false; + } + return tankCanDrain(tank); + } } diff --git a/src/main/java/forestry/core/fluids/tanks/FakeTank.java b/src/main/java/forestry/core/fluids/tanks/FakeTank.java index 96e12f65c..6afc442ae 100644 --- a/src/main/java/forestry/core/fluids/tanks/FakeTank.java +++ b/src/main/java/forestry/core/fluids/tanks/FakeTank.java @@ -18,22 +18,21 @@ import net.minecraftforge.fluids.FluidTankInfo; */ public final class FakeTank extends StandardTank { - public static final FakeTank INSTANCE = new FakeTank(); - public static final FakeTank[] ARRAY = new FakeTank[]{INSTANCE}; - public static final FluidTankInfo[] INFO = new FluidTankInfo[]{INSTANCE.getInfo()}; + public static final FakeTank INSTANCE = new FakeTank(); + public static final FakeTank[] ARRAY = new FakeTank[] {INSTANCE}; + public static final FluidTankInfo[] INFO = new FluidTankInfo[] {INSTANCE.getInfo()}; - private FakeTank() { - super(1); - } + private FakeTank() { + super(1); + } - @Override - public int fill(FluidStack resource, boolean doFill) { - return 0; - } - - @Override - public FluidStack drain(int maxDrain, boolean doDrain) { - return null; - } + @Override + public int fill(FluidStack resource, boolean doFill) { + return 0; + } + @Override + public FluidStack drain(int maxDrain, boolean doDrain) { + return null; + } } diff --git a/src/main/java/forestry/core/fluids/tanks/FilteredTank.java b/src/main/java/forestry/core/fluids/tanks/FilteredTank.java index c63611a9e..dd163a31f 100644 --- a/src/main/java/forestry/core/fluids/tanks/FilteredTank.java +++ b/src/main/java/forestry/core/fluids/tanks/FilteredTank.java @@ -10,94 +10,91 @@ ******************************************************************************/ package forestry.core.fluids.tanks; +import forestry.core.gui.tooltips.ToolTipLine; +import forestry.core.proxy.Proxies; +import forestry.core.utils.StringUtil; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; - import net.minecraft.item.EnumRarity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumChatFormatting; - import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; -import forestry.core.gui.tooltips.ToolTipLine; -import forestry.core.proxy.Proxies; -import forestry.core.utils.StringUtil; - /** * @author CovertJaguar */ public class FilteredTank extends StandardTank { - private final Set filters = new HashSet<>(); // FluidNames + private final Set filters = new HashSet<>(); // FluidNames - public FilteredTank(int capacity, Fluid... filters) { - this(capacity, Arrays.asList(filters), null); - } + public FilteredTank(int capacity, Fluid... filters) { + this(capacity, Arrays.asList(filters), null); + } - public FilteredTank(int capacity, Collection filters) { - this(capacity, filters, null); - } + public FilteredTank(int capacity, Collection filters) { + this(capacity, filters, null); + } - public FilteredTank(int capacity, Collection filters, TileEntity tile) { - super(capacity, tile); - setFilters(filters); - } + public FilteredTank(int capacity, Collection filters, TileEntity tile) { + super(capacity, tile); + setFilters(filters); + } - public void setFilters(Collection filters) { - this.filters.clear(); - for (Fluid fluid : filters) { - this.filters.add(fluid.getName()); - } - } + public void setFilters(Collection filters) { + this.filters.clear(); + for (Fluid fluid : filters) { + this.filters.add(fluid.getName()); + } + } - @Override - public int fill(FluidStack resource, boolean doFill) { - if (liquidMatchesFilter(resource)) { - return super.fill(resource, doFill); - } - return 0; - } + @Override + public int fill(FluidStack resource, boolean doFill) { + if (liquidMatchesFilter(resource)) { + return super.fill(resource, doFill); + } + return 0; + } - @Override - public boolean accepts(Fluid fluid) { - return filters.contains(fluid.getName()); - } + @Override + public boolean accepts(Fluid fluid) { + return filters.contains(fluid.getName()); + } - private boolean liquidMatchesFilter(FluidStack resource) { - if (resource == null || filters == null) { - return false; - } - return filters.contains(resource.getFluid().getName()); - } + private boolean liquidMatchesFilter(FluidStack resource) { + if (resource == null || filters == null) { + return false; + } + return filters.contains(resource.getFluid().getName()); + } - @Override - protected void refreshTooltip() { - if (hasFluid()) { - super.refreshTooltip(); - return; - } + @Override + protected void refreshTooltip() { + if (hasFluid()) { + super.refreshTooltip(); + return; + } - toolTip.clear(); - if (Proxies.common.isShiftDown() || filters.size() < 5) { - for (String filterName : filters) { - Fluid fluidFilter = FluidRegistry.getFluid(filterName); - EnumRarity rarity = fluidFilter.getRarity(); - if (rarity == null) { - rarity = EnumRarity.common; - } - FluidStack filterFluidStack = FluidRegistry.getFluidStack(fluidFilter.getName(), 0); - ToolTipLine name = new ToolTipLine(fluidFilter.getLocalizedName(filterFluidStack), rarity.rarityColor, 2); - toolTip.add(name); - } - } else { - toolTip.add(EnumChatFormatting.ITALIC + "<" + StringUtil.localize("gui.tooltip.tmi") + ">"); - } - - toolTip.add(String.format("%,d", getFluidAmount()) + " / " + String.format("%,d", getCapacity())); - } + toolTip.clear(); + if (Proxies.common.isShiftDown() || filters.size() < 5) { + for (String filterName : filters) { + Fluid fluidFilter = FluidRegistry.getFluid(filterName); + EnumRarity rarity = fluidFilter.getRarity(); + if (rarity == null) { + rarity = EnumRarity.common; + } + FluidStack filterFluidStack = FluidRegistry.getFluidStack(fluidFilter.getName(), 0); + ToolTipLine name = + new ToolTipLine(fluidFilter.getLocalizedName(filterFluidStack), rarity.rarityColor, 2); + toolTip.add(name); + } + } else { + toolTip.add(EnumChatFormatting.ITALIC + "<" + StringUtil.localize("gui.tooltip.tmi") + ">"); + } + toolTip.add(String.format("%,d", getFluidAmount()) + " / " + String.format("%,d", getCapacity())); + } } diff --git a/src/main/java/forestry/core/fluids/tanks/StandardTank.java b/src/main/java/forestry/core/fluids/tanks/StandardTank.java index 27be1cd0f..49267ecbb 100644 --- a/src/main/java/forestry/core/fluids/tanks/StandardTank.java +++ b/src/main/java/forestry/core/fluids/tanks/StandardTank.java @@ -10,17 +10,6 @@ ******************************************************************************/ package forestry.core.fluids.tanks; -import javax.annotation.Nonnull; -import java.io.IOException; -import java.util.Locale; - -import net.minecraft.item.EnumRarity; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTank; - import forestry.core.fluids.FakeTankUpdateHandler; import forestry.core.fluids.FluidHelper; import forestry.core.fluids.ITankUpdateHandler; @@ -30,198 +19,213 @@ import forestry.core.gui.tooltips.ToolTipLine; import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import java.io.IOException; +import java.util.Locale; +import javax.annotation.Nonnull; +import net.minecraft.item.EnumRarity; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTank; /** * @author CovertJaguar */ public class StandardTank extends FluidTank implements IStreamable { - // defines how the tank responds to IFluidHandler requests - public enum TankMode { - DEFAULT, OUTPUT, INPUT, INTERNAL - } + // defines how the tank responds to IFluidHandler requests + public enum TankMode { + DEFAULT, + OUTPUT, + INPUT, + INTERNAL + } - public TankMode tankMode = TankMode.DEFAULT; - private static final int DEFAULT_COLOR = 0xFFFFFF; - @Nonnull - private ITankUpdateHandler tankUpdateHandler = FakeTankUpdateHandler.instance; - private int tankIndex; + public TankMode tankMode = TankMode.DEFAULT; + private static final int DEFAULT_COLOR = 0xFFFFFF; - public StandardTank(int capacity) { - super(capacity); - } + @Nonnull + private ITankUpdateHandler tankUpdateHandler = FakeTankUpdateHandler.instance; - public StandardTank(FluidStack fluid, int capacity) { - this(capacity); - setFluid(fluid); - } + private int tankIndex; - public StandardTank(int capacity, TileEntity tile) { - this(capacity); - this.tile = tile; - } + public StandardTank(int capacity) { + super(capacity); + } - public StandardTank(FluidStack fluid, int capacity, TileEntity tile) { - this(capacity); - this.tile = tile; - setFluid(fluid); - } + public StandardTank(FluidStack fluid, int capacity) { + this(capacity); + setFluid(fluid); + } - public void setTankIndex(int index) { - this.tankIndex = index; - } + public StandardTank(int capacity, TileEntity tile) { + this(capacity); + this.tile = tile; + } - public void setTankUpdateHandler(@Nonnull TankManager tankUpdateHandler) { - this.tankUpdateHandler = tankUpdateHandler; - } + public StandardTank(FluidStack fluid, int capacity, TileEntity tile) { + this(capacity); + this.tile = tile; + setFluid(fluid); + } - public int getTankIndex() { - return tankIndex; - } + public void setTankIndex(int index) { + this.tankIndex = index; + } - public int getColor() { - Fluid f = getFluidType(); - if (f == null) { - return DEFAULT_COLOR; - } - return f.getColor(getFluid()); - } + public void setTankUpdateHandler(@Nonnull TankManager tankUpdateHandler) { + this.tankUpdateHandler = tankUpdateHandler; + } - public boolean isEmpty() { - return getFluid() == null || getFluid().amount <= 0; - } + public int getTankIndex() { + return tankIndex; + } - public boolean isFull() { - return getFluid() != null && getFluid().amount == getCapacity(); - } + public int getColor() { + Fluid f = getFluidType(); + if (f == null) { + return DEFAULT_COLOR; + } + return f.getColor(getFluid()); + } - public int getRemainingSpace() { - return capacity - getFluidAmount(); - } + public boolean isEmpty() { + return getFluid() == null || getFluid().amount <= 0; + } - public Fluid getFluidType() { - return getFluid() != null ? getFluid().getFluid() : null; - } + public boolean isFull() { + return getFluid() != null && getFluid().amount == getCapacity(); + } - @Override - public int fill(final FluidStack resource, final boolean doFill) { - if (resource == null) { - return 0; - } - if (resource.amount <= 0) { - return 0; - } - if (!accepts(resource.getFluid())) { - return 0; - } - int filled = super.fill(resource, doFill); - if (doFill && filled > 0) { - tankUpdateHandler.updateTankLevels(this); - } - return filled; - } + public int getRemainingSpace() { + return capacity - getFluidAmount(); + } - public boolean accepts(Fluid fluid) { - return fluid != null; - } + public Fluid getFluidType() { + return getFluid() != null ? getFluid().getFluid() : null; + } - public boolean canBeFilledExternally() { - switch (tankMode) { - case DEFAULT: - case INPUT: - return true; - } - return false; - } + @Override + public int fill(final FluidStack resource, final boolean doFill) { + if (resource == null) { + return 0; + } + if (resource.amount <= 0) { + return 0; + } + if (!accepts(resource.getFluid())) { + return 0; + } + int filled = super.fill(resource, doFill); + if (doFill && filled > 0) { + tankUpdateHandler.updateTankLevels(this); + } + return filled; + } - public boolean canBeDrainedExternally() { - switch (tankMode) { - case DEFAULT: - case OUTPUT: - return true; - } - return false; - } + public boolean accepts(Fluid fluid) { + return fluid != null; + } - public boolean canFill(Fluid fluid, int amount) { - if (fluid == null) { - return false; - } - FluidStack fluidStack = new FluidStack(fluid, amount); - return canFill(fluidStack); - } + public boolean canBeFilledExternally() { + switch (tankMode) { + case DEFAULT: + case INPUT: + return true; + } + return false; + } - public boolean canFill(FluidStack fluidStack) { - return fill(fluidStack, false) == fluidStack.amount; - } + public boolean canBeDrainedExternally() { + switch (tankMode) { + case DEFAULT: + case OUTPUT: + return true; + } + return false; + } - public boolean canDrain(int amount) { - FluidStack drained = drain(amount, false); - return (drained != null) && (drained.amount == amount); - } + public boolean canFill(Fluid fluid, int amount) { + if (fluid == null) { + return false; + } + FluidStack fluidStack = new FluidStack(fluid, amount); + return canFill(fluidStack); + } - public boolean canDrain(FluidStack toDrain) { - FluidStack drained = drain(toDrain.amount, false); - return FluidHelper.areFluidStacksEqual(drained, toDrain); - } + public boolean canFill(FluidStack fluidStack) { + return fill(fluidStack, false) == fluidStack.amount; + } - @Override - public FluidStack drain(int maxDrain, boolean doDrain) { - if (maxDrain <= 0) { - return null; - } - FluidStack drained = super.drain(maxDrain, doDrain); - if (doDrain && drained != null && drained.amount > 0) { - tankUpdateHandler.updateTankLevels(this); - } - return drained; - } + public boolean canDrain(int amount) { + FluidStack drained = drain(amount, false); + return (drained != null) && (drained.amount == amount); + } - @Override - public String toString() { - return String.format("Tank: %s, %d/%d", fluid != null && fluid.getFluid() != null ? fluid.getFluid().getName() : "Empty", getFluidAmount(), getCapacity()); - } + public boolean canDrain(FluidStack toDrain) { + FluidStack drained = drain(toDrain.amount, false); + return FluidHelper.areFluidStacksEqual(drained, toDrain); + } - public ToolTip getToolTip() { - return toolTip; - } + @Override + public FluidStack drain(int maxDrain, boolean doDrain) { + if (maxDrain <= 0) { + return null; + } + FluidStack drained = super.drain(maxDrain, doDrain); + if (doDrain && drained != null && drained.amount > 0) { + tankUpdateHandler.updateTankLevels(this); + } + return drained; + } - protected boolean hasFluid() { - FluidStack fluid = getFluid(); - return fluid != null && fluid.amount > 0 && fluid.getFluid() != null; - } + @Override + public String toString() { + return String.format( + "Tank: %s, %d/%d", + fluid != null && fluid.getFluid() != null ? fluid.getFluid().getName() : "Empty", + getFluidAmount(), + getCapacity()); + } - protected void refreshTooltip() { - toolTip.clear(); - int amount = 0; - if (hasFluid()) { - Fluid fluidType = getFluidType(); - EnumRarity rarity = fluidType.getRarity(); - if (rarity == null) { - rarity = EnumRarity.common; - } - ToolTipLine fluidName = new ToolTipLine(fluidType.getLocalizedName(getFluid()), rarity.rarityColor, 2); - toolTip.add(fluidName); - amount = getFluid().amount; - } - toolTip.add(new ToolTipLine(String.format(Locale.ENGLISH, "%,d / %,d", amount, getCapacity()))); - } + public ToolTip getToolTip() { + return toolTip; + } - protected final ToolTip toolTip = new ToolTip() { - @Override - public void refresh() { - refreshTooltip(); - } + protected boolean hasFluid() { + FluidStack fluid = getFluid(); + return fluid != null && fluid.amount > 0 && fluid.getFluid() != null; + } - }; + protected void refreshTooltip() { + toolTip.clear(); + int amount = 0; + if (hasFluid()) { + Fluid fluidType = getFluidType(); + EnumRarity rarity = fluidType.getRarity(); + if (rarity == null) { + rarity = EnumRarity.common; + } + ToolTipLine fluidName = new ToolTipLine(fluidType.getLocalizedName(getFluid()), rarity.rarityColor, 2); + toolTip.add(fluidName); + amount = getFluid().amount; + } + toolTip.add(new ToolTipLine(String.format(Locale.ENGLISH, "%,d / %,d", amount, getCapacity()))); + } + protected final ToolTip toolTip = new ToolTip() { + @Override + public void refresh() { + refreshTooltip(); + } + }; - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeFluidStack(fluid); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeFluidStack(fluid); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - fluid = data.readFluidStack(); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + fluid = data.readFluidStack(); + } } diff --git a/src/main/java/forestry/core/genetics/Branch.java b/src/main/java/forestry/core/genetics/Branch.java index 1d598e931..57f186012 100755 --- a/src/main/java/forestry/core/genetics/Branch.java +++ b/src/main/java/forestry/core/genetics/Branch.java @@ -12,8 +12,7 @@ package forestry.core.genetics; public class Branch extends Classification { - public Branch(String uid, String scientific) { - super(EnumClassLevel.GENUS, uid, scientific); - } - + public Branch(String uid, String scientific) { + super(EnumClassLevel.GENUS, uid, scientific); + } } diff --git a/src/main/java/forestry/core/genetics/BreedingTracker.java b/src/main/java/forestry/core/genetics/BreedingTracker.java index 78679c067..ce19724cd 100755 --- a/src/main/java/forestry/core/genetics/BreedingTracker.java +++ b/src/main/java/forestry/core/genetics/BreedingTracker.java @@ -10,24 +10,7 @@ ******************************************************************************/ package forestry.core.genetics; -import javax.annotation.Nullable; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; -import net.minecraft.world.WorldSavedData; - import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.util.FakePlayer; - import forestry.api.core.ForestryEvent; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAlleleSpecies; @@ -37,234 +20,257 @@ import forestry.api.genetics.IMutation; import forestry.api.genetics.ISpeciesRoot; import forestry.core.network.packets.PacketGenomeTrackerSync; import forestry.core.proxy.Proxies; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; +import javax.annotation.Nullable; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import net.minecraft.world.WorldSavedData; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.FakePlayer; public abstract class BreedingTracker extends WorldSavedData implements IBreedingTracker { - private static final String SPECIES_COUNT_KEY = "SpeciesCount"; - private static final String MUTATIONS_COUNT_KEY = "MutationsCount"; - private static final String RESEARCHED_COUNT_KEY = "ResearchedCount"; - private static final String SPECIES_KEY = "SD"; - private static final String MUTATIONS_KEY = "MD"; - private static final String RESEARCHED_KEY = "RD"; - private static final String MODE_NAME_KEY = "BMS"; - private static final String MUTATION_FORMAT = "%s-%s=%s"; - private static final Collection emptyStringCollection = Collections.emptyList(); + private static final String SPECIES_COUNT_KEY = "SpeciesCount"; + private static final String MUTATIONS_COUNT_KEY = "MutationsCount"; + private static final String RESEARCHED_COUNT_KEY = "ResearchedCount"; + private static final String SPECIES_KEY = "SD"; + private static final String MUTATIONS_KEY = "MD"; + private static final String RESEARCHED_KEY = "RD"; + private static final String MODE_NAME_KEY = "BMS"; + private static final String MUTATION_FORMAT = "%s-%s=%s"; + private static final Collection emptyStringCollection = Collections.emptyList(); - public static final String TYPE_KEY = "TYPE"; + public static final String TYPE_KEY = "TYPE"; - private final Set discoveredSpecies = new HashSet<>(); - private final Set discoveredMutations = new HashSet<>(); - private final Set researchedMutations = new HashSet<>(); - private String modeName; + private final Set discoveredSpecies = new HashSet<>(); + private final Set discoveredMutations = new HashSet<>(); + private final Set researchedMutations = new HashSet<>(); + private String modeName; - @Nullable - private GameProfile username; - @Nullable - private World world; + @Nullable + private GameProfile username; - protected BreedingTracker(String s) { - super(s); - } + @Nullable + private World world; - public void setUsername(@Nullable GameProfile username) { - this.username = username; - } + protected BreedingTracker(String s) { + super(s); + } - public void setWorld(@Nullable World world) { - this.world = world; - } + public void setUsername(@Nullable GameProfile username) { + this.username = username; + } - @Override - public String getModeName() { - return modeName; - } + public void setWorld(@Nullable World world) { + this.world = world; + } - @Override - public void setModeName(String name) { - this.modeName = name; - markDirty(); - } + @Override + public String getModeName() { + return modeName; + } - /** - * Returns the common tracker - * - * @param player used to get worldObj - * @return common tracker for this breeding system - */ - protected abstract IBreedingTracker getBreedingTracker(EntityPlayer player); + @Override + public void setModeName(String name) { + this.modeName = name; + markDirty(); + } - /** - * Tag stored in NBT to identify the type of the tracker being synced - */ - protected abstract String speciesRootUID(); + /** + * Returns the common tracker + * + * @param player used to get worldObj + * @return common tracker for this breeding system + */ + protected abstract IBreedingTracker getBreedingTracker(EntityPlayer player); - @Override - public void synchToPlayer(EntityPlayer player) { - if (player instanceof EntityPlayerMP && !(player instanceof FakePlayer)) { - IBreedingTracker breedingTracker = getBreedingTracker(player); - String modeName = breedingTracker.getModeName(); - setModeName(modeName); + /** + * Tag stored in NBT to identify the type of the tracker being synced + */ + protected abstract String speciesRootUID(); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - encodeToNBT(nbttagcompound); - PacketGenomeTrackerSync packet = new PacketGenomeTrackerSync(nbttagcompound); - Proxies.net.sendToPlayer(packet, player); - } - } + @Override + public void synchToPlayer(EntityPlayer player) { + if (player instanceof EntityPlayerMP && !(player instanceof FakePlayer)) { + IBreedingTracker breedingTracker = getBreedingTracker(player); + String modeName = breedingTracker.getModeName(); + setModeName(modeName); - private void syncToPlayer(Collection discoveredSpecies, Collection discoveredMutations, Collection researchedMutations) { - if (world != null && username != null && username.getName() != null) { - EntityPlayer player = world.getPlayerEntityByName(username.getName()); - if (player instanceof EntityPlayerMP && !(player instanceof FakePlayer)) { - IBreedingTracker breedingTracker = getBreedingTracker(player); - String modeName = breedingTracker.getModeName(); - setModeName(modeName); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + encodeToNBT(nbttagcompound); + PacketGenomeTrackerSync packet = new PacketGenomeTrackerSync(nbttagcompound); + Proxies.net.sendToPlayer(packet, player); + } + } - NBTTagCompound nbtTagCompound = new NBTTagCompound(); - writeToNBT(nbtTagCompound, discoveredSpecies, discoveredMutations, researchedMutations); - PacketGenomeTrackerSync packet = new PacketGenomeTrackerSync(nbtTagCompound); - Proxies.net.sendToPlayer(packet, player); - } - } - } + private void syncToPlayer( + Collection discoveredSpecies, + Collection discoveredMutations, + Collection researchedMutations) { + if (world != null && username != null && username.getName() != null) { + EntityPlayer player = world.getPlayerEntityByName(username.getName()); + if (player instanceof EntityPlayerMP && !(player instanceof FakePlayer)) { + IBreedingTracker breedingTracker = getBreedingTracker(player); + String modeName = breedingTracker.getModeName(); + setModeName(modeName); - /* HELPER FUNCTIONS TO PREVENT OBFUSCATION OF INTERFACE METHODS */ - @Override - public void decodeFromNBT(NBTTagCompound nbttagcompound) { - readFromNBT(nbttagcompound); - } + NBTTagCompound nbtTagCompound = new NBTTagCompound(); + writeToNBT(nbtTagCompound, discoveredSpecies, discoveredMutations, researchedMutations); + PacketGenomeTrackerSync packet = new PacketGenomeTrackerSync(nbtTagCompound); + Proxies.net.sendToPlayer(packet, player); + } + } + } - @Override - public void encodeToNBT(NBTTagCompound nbttagcompound) { - writeToNBT(nbttagcompound); - } + /* HELPER FUNCTIONS TO PREVENT OBFUSCATION OF INTERFACE METHODS */ + @Override + public void decodeFromNBT(NBTTagCompound nbttagcompound) { + readFromNBT(nbttagcompound); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { + @Override + public void encodeToNBT(NBTTagCompound nbttagcompound) { + writeToNBT(nbttagcompound); + } - if (nbttagcompound.hasKey(MODE_NAME_KEY)) { - modeName = nbttagcompound.getString(MODE_NAME_KEY); - } + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { - readValuesFromNBT(nbttagcompound, discoveredSpecies, SPECIES_COUNT_KEY, SPECIES_KEY); - readValuesFromNBT(nbttagcompound, discoveredMutations, MUTATIONS_COUNT_KEY, MUTATIONS_KEY); - readValuesFromNBT(nbttagcompound, researchedMutations, RESEARCHED_COUNT_KEY, RESEARCHED_KEY); - } + if (nbttagcompound.hasKey(MODE_NAME_KEY)) { + modeName = nbttagcompound.getString(MODE_NAME_KEY); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - writeToNBT(nbttagcompound, discoveredSpecies, discoveredMutations, researchedMutations); - } + readValuesFromNBT(nbttagcompound, discoveredSpecies, SPECIES_COUNT_KEY, SPECIES_KEY); + readValuesFromNBT(nbttagcompound, discoveredMutations, MUTATIONS_COUNT_KEY, MUTATIONS_KEY); + readValuesFromNBT(nbttagcompound, researchedMutations, RESEARCHED_COUNT_KEY, RESEARCHED_KEY); + } - private void writeToNBT(NBTTagCompound nbtTagCompound, Collection discoveredSpecies, Collection discoveredMutations, Collection researchedMutations) { - if (modeName != null && !modeName.isEmpty()) { - nbtTagCompound.setString(MODE_NAME_KEY, modeName); - } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + writeToNBT(nbttagcompound, discoveredSpecies, discoveredMutations, researchedMutations); + } - nbtTagCompound.setString(TYPE_KEY, speciesRootUID()); + private void writeToNBT( + NBTTagCompound nbtTagCompound, + Collection discoveredSpecies, + Collection discoveredMutations, + Collection researchedMutations) { + if (modeName != null && !modeName.isEmpty()) { + nbtTagCompound.setString(MODE_NAME_KEY, modeName); + } - writeValuesToNBT(nbtTagCompound, discoveredSpecies, SPECIES_COUNT_KEY, SPECIES_KEY); - writeValuesToNBT(nbtTagCompound, discoveredMutations, MUTATIONS_COUNT_KEY, MUTATIONS_KEY); - writeValuesToNBT(nbtTagCompound, researchedMutations, RESEARCHED_COUNT_KEY, RESEARCHED_KEY); - } + nbtTagCompound.setString(TYPE_KEY, speciesRootUID()); - private static void readValuesFromNBT(NBTTagCompound nbttagcompound, Set values, String countKey, String key) { - if (nbttagcompound.hasKey(countKey)) { - final int count = nbttagcompound.getInteger(countKey); - for (int i = 0; i < count; i++) { - String value = nbttagcompound.getString(key + i); - if (value != null && value.length() > 0) { - values.add(value); - } - } - } - } + writeValuesToNBT(nbtTagCompound, discoveredSpecies, SPECIES_COUNT_KEY, SPECIES_KEY); + writeValuesToNBT(nbtTagCompound, discoveredMutations, MUTATIONS_COUNT_KEY, MUTATIONS_KEY); + writeValuesToNBT(nbtTagCompound, researchedMutations, RESEARCHED_COUNT_KEY, RESEARCHED_KEY); + } - private static void writeValuesToNBT(NBTTagCompound nbttagcompound, Collection values, String countKey, String key) { - final int count = values.size(); - nbttagcompound.setInteger(countKey, count); - Iterator iterator = values.iterator(); - for (int i = 0; i < count; i++) { - String value = iterator.next(); - if (value != null && value.length() > 0) { - nbttagcompound.setString(key + i, value); - } - } - } + private static void readValuesFromNBT( + NBTTagCompound nbttagcompound, Set values, String countKey, String key) { + if (nbttagcompound.hasKey(countKey)) { + final int count = nbttagcompound.getInteger(countKey); + for (int i = 0; i < count; i++) { + String value = nbttagcompound.getString(key + i); + if (value != null && value.length() > 0) { + values.add(value); + } + } + } + } - private static String getMutationString(IMutation mutation) { - String species0 = mutation.getAllele0().getUID(); - String species1 = mutation.getAllele1().getUID(); - String resultSpecies = mutation.getTemplate()[0].getUID(); - return String.format(MUTATION_FORMAT, species0, species1, resultSpecies); - } + private static void writeValuesToNBT( + NBTTagCompound nbttagcompound, Collection values, String countKey, String key) { + final int count = values.size(); + nbttagcompound.setInteger(countKey, count); + Iterator iterator = values.iterator(); + for (int i = 0; i < count; i++) { + String value = iterator.next(); + if (value != null && value.length() > 0) { + nbttagcompound.setString(key + i, value); + } + } + } - @Override - public void registerMutation(IMutation mutation) { - String mutationString = getMutationString(mutation); - if (!discoveredMutations.contains(mutationString)) { - discoveredMutations.add(mutationString); - markDirty(); + private static String getMutationString(IMutation mutation) { + String species0 = mutation.getAllele0().getUID(); + String species1 = mutation.getAllele1().getUID(); + String resultSpecies = mutation.getTemplate()[0].getUID(); + return String.format(MUTATION_FORMAT, species0, species1, resultSpecies); + } - ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(speciesRootUID()); - ForestryEvent event = new ForestryEvent.MutationDiscovered(speciesRoot, username, mutation, this); - MinecraftForge.EVENT_BUS.post(event); + @Override + public void registerMutation(IMutation mutation) { + String mutationString = getMutationString(mutation); + if (!discoveredMutations.contains(mutationString)) { + discoveredMutations.add(mutationString); + markDirty(); - syncToPlayer(emptyStringCollection, Collections.singleton(mutationString), emptyStringCollection); - } - } + ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(speciesRootUID()); + ForestryEvent event = new ForestryEvent.MutationDiscovered(speciesRoot, username, mutation, this); + MinecraftForge.EVENT_BUS.post(event); - @Override - public boolean isDiscovered(IMutation mutation) { - String mutationString = getMutationString(mutation); - return discoveredMutations.contains(mutationString) || researchedMutations.contains(mutationString); - } + syncToPlayer(emptyStringCollection, Collections.singleton(mutationString), emptyStringCollection); + } + } - @Override - public boolean isDiscovered(IAlleleSpecies species) { - return discoveredSpecies.contains(species.getUID()); - } + @Override + public boolean isDiscovered(IMutation mutation) { + String mutationString = getMutationString(mutation); + return discoveredMutations.contains(mutationString) || researchedMutations.contains(mutationString); + } - @Override - public int getSpeciesBred() { - return discoveredSpecies.size(); - } + @Override + public boolean isDiscovered(IAlleleSpecies species) { + return discoveredSpecies.contains(species.getUID()); + } - @Override - public void registerBirth(IIndividual individual) { - registerSpecies(individual.getGenome().getPrimary()); - registerSpecies(individual.getGenome().getSecondary()); - } + @Override + public int getSpeciesBred() { + return discoveredSpecies.size(); + } - @Override - public void registerSpecies(IAlleleSpecies species) { - if (!discoveredSpecies.contains(species.getUID())) { - discoveredSpecies.add(species.getUID()); + @Override + public void registerBirth(IIndividual individual) { + registerSpecies(individual.getGenome().getPrimary()); + registerSpecies(individual.getGenome().getSecondary()); + } - ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(speciesRootUID()); - ForestryEvent event = new ForestryEvent.SpeciesDiscovered(speciesRoot, username, species, this); - MinecraftForge.EVENT_BUS.post(event); + @Override + public void registerSpecies(IAlleleSpecies species) { + if (!discoveredSpecies.contains(species.getUID())) { + discoveredSpecies.add(species.getUID()); - syncToPlayer(Collections.singleton(species.getUID()), emptyStringCollection, emptyStringCollection); - } - } + ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(speciesRootUID()); + ForestryEvent event = new ForestryEvent.SpeciesDiscovered(speciesRoot, username, species, this); + MinecraftForge.EVENT_BUS.post(event); - @Override - public void researchMutation(IMutation mutation) { - String mutationString = getMutationString(mutation); - if (!researchedMutations.contains(mutationString)) { - researchedMutations.add(mutationString); - markDirty(); + syncToPlayer(Collections.singleton(species.getUID()), emptyStringCollection, emptyStringCollection); + } + } - registerMutation(mutation); + @Override + public void researchMutation(IMutation mutation) { + String mutationString = getMutationString(mutation); + if (!researchedMutations.contains(mutationString)) { + researchedMutations.add(mutationString); + markDirty(); - syncToPlayer(emptyStringCollection, emptyStringCollection, Collections.singleton(mutationString)); - } - } + registerMutation(mutation); - @Override - public boolean isResearched(IMutation mutation) { - String mutationString = getMutationString(mutation); - return researchedMutations.contains(mutationString); - } + syncToPlayer(emptyStringCollection, emptyStringCollection, Collections.singleton(mutationString)); + } + } + + @Override + public boolean isResearched(IMutation mutation) { + String mutationString = getMutationString(mutation); + return researchedMutations.contains(mutationString); + } } diff --git a/src/main/java/forestry/core/genetics/Chromosome.java b/src/main/java/forestry/core/genetics/Chromosome.java index 950f552ca..d9ad9e25e 100755 --- a/src/main/java/forestry/core/genetics/Chromosome.java +++ b/src/main/java/forestry/core/genetics/Chromosome.java @@ -10,184 +10,180 @@ ******************************************************************************/ package forestry.core.genetics; -import java.util.Random; - -import net.minecraft.nbt.NBTTagCompound; - import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; import forestry.api.genetics.IChromosome; import forestry.core.utils.Log; +import java.util.Random; +import net.minecraft.nbt.NBTTagCompound; public class Chromosome implements IChromosome { - private static final String UID0_TAG = "UID0"; - private static final String UID1_TAG = "UID1"; + private static final String UID0_TAG = "UID0"; + private static final String UID1_TAG = "UID1"; - private IAllele primary; - private IAllele secondary; + private IAllele primary; + private IAllele secondary; - // / CONSTRUCTOR - private Chromosome() { - } + // / CONSTRUCTOR + private Chromosome() {} - public Chromosome(IAllele allele) { - primary = secondary = allele; - } + public Chromosome(IAllele allele) { + primary = secondary = allele; + } - public Chromosome(IAllele primary, IAllele secondary) { - this.primary = primary; - this.secondary = secondary; - } + public Chromosome(IAllele primary, IAllele secondary) { + this.primary = primary; + this.secondary = secondary; + } - // / SAVING & LOADING - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - primary = AlleleManager.alleleRegistry.getAllele(nbttagcompound.getString(UID0_TAG)); - secondary = AlleleManager.alleleRegistry.getAllele(nbttagcompound.getString(UID1_TAG)); - } + // / SAVING & LOADING + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + primary = AlleleManager.alleleRegistry.getAllele(nbttagcompound.getString(UID0_TAG)); + secondary = AlleleManager.alleleRegistry.getAllele(nbttagcompound.getString(UID1_TAG)); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setString(UID0_TAG, primary.getUID()); - nbttagcompound.setString(UID1_TAG, secondary.getUID()); - } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setString(UID0_TAG, primary.getUID()); + nbttagcompound.setString(UID1_TAG, secondary.getUID()); + } - @Override - public IAllele getPrimaryAllele() { - return primary; - } + @Override + public IAllele getPrimaryAllele() { + return primary; + } - @Override - public IAllele getSecondaryAllele() { - return secondary; - } + @Override + public IAllele getSecondaryAllele() { + return secondary; + } - @Override - public IAllele getActiveAllele() { - if (primary == null || secondary == null) { - return null; - } - if (primary.isDominant()) { - return primary; - } - if (secondary.isDominant()) { - return secondary; - } - // Leaves only the case of both being recessive - return primary; - } + @Override + public IAllele getActiveAllele() { + if (primary == null || secondary == null) { + return null; + } + if (primary.isDominant()) { + return primary; + } + if (secondary.isDominant()) { + return secondary; + } + // Leaves only the case of both being recessive + return primary; + } - @Override - public IAllele getInactiveAllele() { - if (!secondary.isDominant()) { - return secondary; - } - if (!primary.isDominant()) { - return primary; - } - // Leaves only the case of both being dominant - return secondary; - } + @Override + public IAllele getInactiveAllele() { + if (!secondary.isDominant()) { + return secondary; + } + if (!primary.isDominant()) { + return primary; + } + // Leaves only the case of both being dominant + return secondary; + } - public IAllele getRandomAllele(Random rand) { - if (rand.nextBoolean()) { - return primary; - } else { - return secondary; - } - } + public IAllele getRandomAllele(Random rand) { + if (rand.nextBoolean()) { + return primary; + } else { + return secondary; + } + } - public boolean overrideInvalidAlleles(IAllele template, Class chromosomeClass) { - boolean foundInvalidAlleles = false; + public boolean overrideInvalidAlleles(IAllele template, Class chromosomeClass) { + boolean foundInvalidAlleles = false; - // use the other chromosome instead of the template if it's valid - if (primary != null && chromosomeClass.isInstance(primary)) { - template = primary; - } else if (secondary != null && chromosomeClass.isInstance(secondary)) { - template = secondary; - } + // use the other chromosome instead of the template if it's valid + if (primary != null && chromosomeClass.isInstance(primary)) { + template = primary; + } else if (secondary != null && chromosomeClass.isInstance(secondary)) { + template = secondary; + } - if (primary == null) { - Log.warning("Missing primary allele: {0}. Setting to: {1}", this, template); - primary = template; - foundInvalidAlleles = true; - } else if (!chromosomeClass.isInstance(primary)) { - Log.warning("Wrong primary allele: {0}. Setting to: {1}", this, template); - primary = template; - foundInvalidAlleles = true; - } - - if (secondary == null) { - Log.warning("Missing secondary allele: {0}. Setting to: {1}", this, template); - secondary = template; - foundInvalidAlleles = true; - } else if (!chromosomeClass.isInstance(secondary)) { - Log.warning("Wrong secondary allele: {0}. Setting to: {1}", this, template); - secondary = template; - foundInvalidAlleles = true; - } + if (primary == null) { + Log.warning("Missing primary allele: {0}. Setting to: {1}", this, template); + primary = template; + foundInvalidAlleles = true; + } else if (!chromosomeClass.isInstance(primary)) { + Log.warning("Wrong primary allele: {0}. Setting to: {1}", this, template); + primary = template; + foundInvalidAlleles = true; + } - return foundInvalidAlleles; - } - - public boolean hasInvalidAlleles(Class chromosomeClass) { - if (primary == null) { - Log.severe("Missing primary allele: {0}", this); - return true; - } + if (secondary == null) { + Log.warning("Missing secondary allele: {0}. Setting to: {1}", this, template); + secondary = template; + foundInvalidAlleles = true; + } else if (!chromosomeClass.isInstance(secondary)) { + Log.warning("Wrong secondary allele: {0}. Setting to: {1}", this, template); + secondary = template; + foundInvalidAlleles = true; + } - if (!chromosomeClass.isInstance(primary)) { - Log.severe("Wrong primary allele for: {0}. Should be: {1}", this, chromosomeClass.getSimpleName()); - return true; - } - - if (secondary == null) { - Log.severe("Missing secondary allele: {0}", this); - return true; - } + return foundInvalidAlleles; + } - if (!chromosomeClass.isInstance(secondary)) { - Log.severe("Wrong secondary allele for: {0}. Should be: {1}", this, chromosomeClass.getSimpleName()); - return true; - } - - return false; - } + public boolean hasInvalidAlleles(Class chromosomeClass) { + if (primary == null) { + Log.severe("Missing primary allele: {0}", this); + return true; + } - /* HELPER FUNCTIONS */ - public static Chromosome loadChromosomeFromNBT(NBTTagCompound compound) { - Chromosome chromosome = new Chromosome(); - chromosome.readFromNBT(compound); - return chromosome; - } + if (!chromosomeClass.isInstance(primary)) { + Log.severe("Wrong primary allele for: {0}. Should be: {1}", this, chromosomeClass.getSimpleName()); + return true; + } - public static IChromosome inheritChromosome(Random rand, IChromosome parent1, IChromosome parent2) { + if (secondary == null) { + Log.severe("Missing secondary allele: {0}", this); + return true; + } - IAllele choice1; - if (rand.nextBoolean()) { - choice1 = parent1.getPrimaryAllele(); - } else { - choice1 = parent1.getSecondaryAllele(); - } + if (!chromosomeClass.isInstance(secondary)) { + Log.severe("Wrong secondary allele for: {0}. Should be: {1}", this, chromosomeClass.getSimpleName()); + return true; + } - IAllele choice2; - if (rand.nextBoolean()) { - choice2 = parent2.getPrimaryAllele(); - } else { - choice2 = parent2.getSecondaryAllele(); - } + return false; + } - if (rand.nextBoolean()) { - return new Chromosome(choice1, choice2); - } else { - return new Chromosome(choice2, choice1); - } - } + /* HELPER FUNCTIONS */ + public static Chromosome loadChromosomeFromNBT(NBTTagCompound compound) { + Chromosome chromosome = new Chromosome(); + chromosome.readFromNBT(compound); + return chromosome; + } - @Override - public String toString() { - return "{" + primary + ", " + secondary + "}"; - } + public static IChromosome inheritChromosome(Random rand, IChromosome parent1, IChromosome parent2) { + IAllele choice1; + if (rand.nextBoolean()) { + choice1 = parent1.getPrimaryAllele(); + } else { + choice1 = parent1.getSecondaryAllele(); + } + + IAllele choice2; + if (rand.nextBoolean()) { + choice2 = parent2.getPrimaryAllele(); + } else { + choice2 = parent2.getSecondaryAllele(); + } + + if (rand.nextBoolean()) { + return new Chromosome(choice1, choice2); + } else { + return new Chromosome(choice2, choice1); + } + } + + @Override + public String toString() { + return "{" + primary + ", " + secondary + "}"; + } } diff --git a/src/main/java/forestry/core/genetics/Classification.java b/src/main/java/forestry/core/genetics/Classification.java index 8a5420cb4..14a5d0538 100755 --- a/src/main/java/forestry/core/genetics/Classification.java +++ b/src/main/java/forestry/core/genetics/Classification.java @@ -10,86 +10,84 @@ ******************************************************************************/ package forestry.core.genetics; -import java.util.ArrayList; -import java.util.Locale; - import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IClassification; import forestry.core.utils.StringUtil; +import java.util.ArrayList; +import java.util.Locale; public class Classification implements IClassification { - private final EnumClassLevel level; - private final String uid; - private final String scientific; + private final EnumClassLevel level; + private final String uid; + private final String scientific; - private IClassification parent; + private IClassification parent; - private final ArrayList members = new ArrayList<>(); - private final ArrayList groups = new ArrayList<>(); + private final ArrayList members = new ArrayList<>(); + private final ArrayList groups = new ArrayList<>(); - public Classification(EnumClassLevel level, String uid, String scientific) { - this.level = level; - this.uid = level.name().toLowerCase(Locale.ENGLISH) + "." + uid; - this.scientific = scientific; - AlleleManager.alleleRegistry.registerClassification(this); - } + public Classification(EnumClassLevel level, String uid, String scientific) { + this.level = level; + this.uid = level.name().toLowerCase(Locale.ENGLISH) + "." + uid; + this.scientific = scientific; + AlleleManager.alleleRegistry.registerClassification(this); + } - @Override - public EnumClassLevel getLevel() { - return level; - } + @Override + public EnumClassLevel getLevel() { + return level; + } - @Override - public String getUID() { - return uid; - } + @Override + public String getUID() { + return uid; + } - @Override - public IClassification getParent() { - return parent; - } + @Override + public IClassification getParent() { + return parent; + } - @Override - public void setParent(IClassification parent) { - this.parent = parent; - } + @Override + public void setParent(IClassification parent) { + this.parent = parent; + } - @Override - public String getScientific() { - return this.scientific; - } + @Override + public String getScientific() { + return this.scientific; + } - @Override - public String getName() { - return StringUtil.localize(uid); - } + @Override + public String getName() { + return StringUtil.localize(uid); + } - @Override - public String getDescription() { - return StringUtil.localize(uid + ".description"); - } + @Override + public String getDescription() { + return StringUtil.localize(uid + ".description"); + } - @Override - public IClassification[] getMemberGroups() { - return groups.toArray(new IClassification[groups.size()]); - } + @Override + public IClassification[] getMemberGroups() { + return groups.toArray(new IClassification[groups.size()]); + } - @Override - public void addMemberGroup(IClassification group) { - groups.add(group); - group.setParent(this); - } + @Override + public void addMemberGroup(IClassification group) { + groups.add(group); + group.setParent(this); + } - @Override - public IAlleleSpecies[] getMemberSpecies() { - return members.toArray(new IAlleleSpecies[members.size()]); - } - - @Override - public void addMemberSpecies(IAlleleSpecies species) { - members.add(species); - } + @Override + public IAlleleSpecies[] getMemberSpecies() { + return members.toArray(new IAlleleSpecies[members.size()]); + } + @Override + public void addMemberSpecies(IAlleleSpecies species) { + members.add(species); + } } diff --git a/src/main/java/forestry/core/genetics/EffectData.java b/src/main/java/forestry/core/genetics/EffectData.java index bd28f14a9..a30084588 100755 --- a/src/main/java/forestry/core/genetics/EffectData.java +++ b/src/main/java/forestry/core/genetics/EffectData.java @@ -10,60 +10,57 @@ ******************************************************************************/ package forestry.core.genetics; -import net.minecraft.nbt.NBTTagCompound; - import forestry.api.genetics.IEffectData; +import net.minecraft.nbt.NBTTagCompound; public class EffectData implements IEffectData { - private final int[] intData; - private float[] floatData; - private final boolean[] boolData; + private final int[] intData; + private float[] floatData; + private final boolean[] boolData; - public EffectData(int intSize, int boolSize) { - this.intData = new int[intSize]; - this.boolData = new boolean[boolSize]; - } + public EffectData(int intSize, int boolSize) { + this.intData = new int[intSize]; + this.boolData = new boolean[boolSize]; + } - @Override - public void setInteger(int index, int val) { - intData[index] = val; - } + @Override + public void setInteger(int index, int val) { + intData[index] = val; + } - @Override - public void setBoolean(int index, boolean val) { - boolData[index] = val; - } + @Override + public void setBoolean(int index, boolean val) { + boolData[index] = val; + } - @Override - public int getInteger(int index) { - return intData[index]; - } + @Override + public int getInteger(int index) { + return intData[index]; + } - @Override - public boolean getBoolean(int index) { - return boolData[index]; - } + @Override + public boolean getBoolean(int index) { + return boolData[index]; + } - public int getIntSize() { - return intData.length; - } + public int getIntSize() { + return intData.length; + } - @Override - public void setFloat(int index, float val) { - floatData[index] = val; - } + @Override + public void setFloat(int index, float val) { + floatData[index] = val; + } - @Override - public float getFloat(int index) { - return floatData[index]; - } + @Override + public float getFloat(int index) { + return floatData[index]; + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - } + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) {} - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) {} } diff --git a/src/main/java/forestry/core/genetics/GenericRatings.java b/src/main/java/forestry/core/genetics/GenericRatings.java index 7aa5b3477..1e9d7bd0e 100755 --- a/src/main/java/forestry/core/genetics/GenericRatings.java +++ b/src/main/java/forestry/core/genetics/GenericRatings.java @@ -10,36 +10,38 @@ ******************************************************************************/ package forestry.core.genetics; -import net.minecraft.util.StatCollector; - import forestry.core.utils.StringUtil; +import net.minecraft.util.StatCollector; public class GenericRatings { - public static String rateMetabolism(int metabolism) { - if (metabolism >= 19) { - return StatCollector.translateToLocal("forestry.allele.highest"); - } else if (metabolism >= 16) { - return StatCollector.translateToLocal("forestry.allele.higher"); - } else if (metabolism >= 13) { - return StatCollector.translateToLocal("forestry.allele.high"); - } else if (metabolism >= 10) { - return StatCollector.translateToLocal("forestry.allele.average"); - } else if (metabolism >= 7) { - return StatCollector.translateToLocal("forestry.allele.slow"); - } else if (metabolism >= 4) { - return StatCollector.translateToLocal("forestry.allele.slower"); - } else { - return StatCollector.translateToLocal("forestry.allele.slowest"); - } - } + public static String rateMetabolism(int metabolism) { + if (metabolism >= 19) { + return StatCollector.translateToLocal("forestry.allele.highest"); + } else if (metabolism >= 16) { + return StatCollector.translateToLocal("forestry.allele.higher"); + } else if (metabolism >= 13) { + return StatCollector.translateToLocal("forestry.allele.high"); + } else if (metabolism >= 10) { + return StatCollector.translateToLocal("forestry.allele.average"); + } else if (metabolism >= 7) { + return StatCollector.translateToLocal("forestry.allele.slow"); + } else if (metabolism >= 4) { + return StatCollector.translateToLocal("forestry.allele.slower"); + } else { + return StatCollector.translateToLocal("forestry.allele.slowest"); + } + } - public static String rateActivityTime(boolean nocturnalTrait, boolean naturalNocturnal) { - String active = naturalNocturnal ? StringUtil.localize("gui.nocturnal") : StringUtil.localize("gui.diurnal"); - if (nocturnalTrait) { - active = StringUtil.append(", ", active, naturalNocturnal ? StringUtil.localize("gui.diurnal") : StringUtil.localize("gui.nocturnal")); - } - - return active; - } + public static String rateActivityTime(boolean nocturnalTrait, boolean naturalNocturnal) { + String active = naturalNocturnal ? StringUtil.localize("gui.nocturnal") : StringUtil.localize("gui.diurnal"); + if (nocturnalTrait) { + active = StringUtil.append( + ", ", + active, + naturalNocturnal ? StringUtil.localize("gui.diurnal") : StringUtil.localize("gui.nocturnal")); + } + + return active; + } } diff --git a/src/main/java/forestry/core/genetics/Genome.java b/src/main/java/forestry/core/genetics/Genome.java index 2b8a30960..0db34997a 100755 --- a/src/main/java/forestry/core/genetics/Genome.java +++ b/src/main/java/forestry/core/genetics/Genome.java @@ -11,15 +11,6 @@ package forestry.core.genetics; import com.google.common.base.Objects; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; - import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleSpecies; @@ -29,277 +20,311 @@ import forestry.api.genetics.IGenome; import forestry.api.genetics.ISpeciesRoot; import forestry.api.lepidopterology.EnumButterflyChromosome; import forestry.core.config.Config; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; public abstract class Genome implements IGenome { - private static final String SLOT_TAG = "Slot"; - private static final Set unusedChromsomes = new HashSet<>(); + private static final String SLOT_TAG = "Slot"; + private static final Set unusedChromsomes = new HashSet<>(); - static { - unusedChromsomes.add(EnumBeeChromosome.HUMIDITY); - unusedChromsomes.add(EnumButterflyChromosome.TERRITORY); - } + static { + unusedChromsomes.add(EnumBeeChromosome.HUMIDITY); + unusedChromsomes.add(EnumButterflyChromosome.TERRITORY); + } - private IChromosome[] chromosomes; + private IChromosome[] chromosomes; - // / CONSTRUCTOR - protected Genome(NBTTagCompound nbttagcompound) { - this.chromosomes = new Chromosome[getDefaultTemplate().length]; - readFromNBT(nbttagcompound); - } + // / CONSTRUCTOR + protected Genome(NBTTagCompound nbttagcompound) { + this.chromosomes = new Chromosome[getDefaultTemplate().length]; + readFromNBT(nbttagcompound); + } - protected Genome(IChromosome[] chromosomes) { - checkChromosomes(chromosomes); - this.chromosomes = chromosomes; - } + protected Genome(IChromosome[] chromosomes) { + checkChromosomes(chromosomes); + this.chromosomes = chromosomes; + } - private void checkChromosomes(IChromosome[] chromosomes) { - if (chromosomes == null || chromosomes.length != getDefaultTemplate().length) { - String message = String.format("Tried to create a genome for '%s' from an invalid chromosome template.\n%s", getSpeciesRoot().getUID(), chromosomesToString(chromosomes)); - throw new IllegalArgumentException(message); - } + private void checkChromosomes(IChromosome[] chromosomes) { + if (chromosomes == null || chromosomes.length != getDefaultTemplate().length) { + String message = String.format( + "Tried to create a genome for '%s' from an invalid chromosome template.\n%s", + getSpeciesRoot().getUID(), chromosomesToString(chromosomes)); + throw new IllegalArgumentException(message); + } - IChromosomeType[] karyotype = getSpeciesRoot().getKaryotype(); - for (int i = 0; i < karyotype.length; i++) { - IChromosomeType chromosomeType = karyotype[i]; - if (unusedChromsomes.contains(chromosomeType)) { - continue; - } + IChromosomeType[] karyotype = getSpeciesRoot().getKaryotype(); + for (int i = 0; i < karyotype.length; i++) { + IChromosomeType chromosomeType = karyotype[i]; + if (unusedChromsomes.contains(chromosomeType)) { + continue; + } - IChromosome chromosome = chromosomes[i]; - if (chromosome == null) { - String message = String.format("Tried to create a genome for '%s' from an invalid chromosome template. " + - "Missing chromosome '%s'.\n%s", getSpeciesRoot().getUID(), chromosomeType.getName(), chromosomesToString(chromosomes)); - throw new IllegalArgumentException(message); - } + IChromosome chromosome = chromosomes[i]; + if (chromosome == null) { + String message = String.format( + "Tried to create a genome for '%s' from an invalid chromosome template. " + + "Missing chromosome '%s'.\n%s", + getSpeciesRoot().getUID(), chromosomeType.getName(), chromosomesToString(chromosomes)); + throw new IllegalArgumentException(message); + } - IAllele primary = chromosome.getPrimaryAllele(); - if (primary == null) { - String message = String.format("Tried to create a genome for '%s' from an invalid chromosome template. " + - "Missing primary allele for '%s'.\n%s", getSpeciesRoot().getUID(), chromosomeType.getName(), chromosomesToString(chromosomes)); - throw new IllegalArgumentException(message); - } + IAllele primary = chromosome.getPrimaryAllele(); + if (primary == null) { + String message = String.format( + "Tried to create a genome for '%s' from an invalid chromosome template. " + + "Missing primary allele for '%s'.\n%s", + getSpeciesRoot().getUID(), chromosomeType.getName(), chromosomesToString(chromosomes)); + throw new IllegalArgumentException(message); + } - IAllele secondary = chromosome.getSecondaryAllele(); - if (secondary == null) { - String message = String.format("Tried to create a genome for '%s' from an invalid chromosome template. " + - "Missing secondary allele for '%s'.\n%s", getSpeciesRoot().getUID(), chromosomeType.getName(), chromosomesToString(chromosomes)); - throw new IllegalArgumentException(message); - } + IAllele secondary = chromosome.getSecondaryAllele(); + if (secondary == null) { + String message = String.format( + "Tried to create a genome for '%s' from an invalid chromosome template. " + + "Missing secondary allele for '%s'.\n%s", + getSpeciesRoot().getUID(), chromosomeType.getName(), chromosomesToString(chromosomes)); + throw new IllegalArgumentException(message); + } - Class chromosomeAlleleClass = chromosomeType.getAlleleClass(); - if (!chromosomeAlleleClass.isAssignableFrom(primary.getClass())) { - String message = String.format("Tried to create a genome for '%s' from an invalid chromosome template. " + - "Incorrect type for primary allele '%s'.\n%s.", getSpeciesRoot().getUID(), chromosomeType.getName(), chromosomesToString(chromosomes)); - throw new IllegalArgumentException(message); - } + Class chromosomeAlleleClass = chromosomeType.getAlleleClass(); + if (!chromosomeAlleleClass.isAssignableFrom(primary.getClass())) { + String message = String.format( + "Tried to create a genome for '%s' from an invalid chromosome template. " + + "Incorrect type for primary allele '%s'.\n%s.", + getSpeciesRoot().getUID(), chromosomeType.getName(), chromosomesToString(chromosomes)); + throw new IllegalArgumentException(message); + } - if (!chromosomeAlleleClass.isAssignableFrom(secondary.getClass())) { - String message = String.format("Tried to create a genome for '%s' from an invalid chromosome template. " + - "Incorrect type for secondary allele '%s'.\n%s.", getSpeciesRoot().getUID(), chromosomeType.getName(), chromosomesToString(chromosomes)); - throw new IllegalArgumentException(message); - } - } - } + if (!chromosomeAlleleClass.isAssignableFrom(secondary.getClass())) { + String message = String.format( + "Tried to create a genome for '%s' from an invalid chromosome template. " + + "Incorrect type for secondary allele '%s'.\n%s.", + getSpeciesRoot().getUID(), chromosomeType.getName(), chromosomesToString(chromosomes)); + throw new IllegalArgumentException(message); + } + } + } - private String chromosomesToString(IChromosome[] chromosomes) { - if (chromosomes == null) { - return "null"; - } + private String chromosomesToString(IChromosome[] chromosomes) { + if (chromosomes == null) { + return "null"; + } - StringBuilder stringBuilder = new StringBuilder(); - IChromosomeType[] karyotype = getSpeciesRoot().getKaryotype(); - for (int i = 0; i < chromosomes.length; i++) { - IChromosomeType chromosomeType = karyotype[i]; - if (unusedChromsomes.contains(chromosomeType)) { - continue; - } - IChromosome chromosome = chromosomes[i]; - stringBuilder.append(chromosomeType.getName()).append(": ").append(chromosome).append("\n"); - } + StringBuilder stringBuilder = new StringBuilder(); + IChromosomeType[] karyotype = getSpeciesRoot().getKaryotype(); + for (int i = 0; i < chromosomes.length; i++) { + IChromosomeType chromosomeType = karyotype[i]; + if (unusedChromsomes.contains(chromosomeType)) { + continue; + } + IChromosome chromosome = chromosomes[i]; + stringBuilder + .append(chromosomeType.getName()) + .append(": ") + .append(chromosome) + .append("\n"); + } - return stringBuilder.toString(); - } + return stringBuilder.toString(); + } - private IAllele[] getDefaultTemplate() { - return getSpeciesRoot().getDefaultTemplate(); - } + private IAllele[] getDefaultTemplate() { + return getSpeciesRoot().getDefaultTemplate(); + } - // NBT RETRIEVAL + // NBT RETRIEVAL - /** - * Quickly gets the species without loading the whole genome. - * We need this because the client uses the species for rendering. - */ - protected static IAlleleSpecies getSpeciesDirectly(ItemStack itemStack) { - NBTTagCompound nbtTagCompound = itemStack.getTagCompound(); - if (nbtTagCompound == null) { - return null; - } + /** + * Quickly gets the species without loading the whole genome. + * We need this because the client uses the species for rendering. + */ + protected static IAlleleSpecies getSpeciesDirectly(ItemStack itemStack) { + NBTTagCompound nbtTagCompound = itemStack.getTagCompound(); + if (nbtTagCompound == null) { + return null; + } - NBTTagCompound genomeNBT = nbtTagCompound.getCompoundTag("Genome"); - if (genomeNBT == null) { - return null; - } + NBTTagCompound genomeNBT = nbtTagCompound.getCompoundTag("Genome"); + if (genomeNBT == null) { + return null; + } - NBTTagList chromosomesNBT = genomeNBT.getTagList("Chromosomes", 10); - if (chromosomesNBT == null) { - return null; - } + NBTTagList chromosomesNBT = genomeNBT.getTagList("Chromosomes", 10); + if (chromosomesNBT == null) { + return null; + } - NBTTagCompound chromosomeNBT = chromosomesNBT.getCompoundTagAt(0); - Chromosome chromosome = Chromosome.loadChromosomeFromNBT(chromosomeNBT); + NBTTagCompound chromosomeNBT = chromosomesNBT.getCompoundTagAt(0); + Chromosome chromosome = Chromosome.loadChromosomeFromNBT(chromosomeNBT); - IAllele activeAllele = chromosome.getActiveAllele(); - if (!(activeAllele instanceof IAlleleSpecies)) { - return null; - } + IAllele activeAllele = chromosome.getActiveAllele(); + if (!(activeAllele instanceof IAlleleSpecies)) { + return null; + } - return (IAlleleSpecies) activeAllele; - } + return (IAlleleSpecies) activeAllele; + } - private static IChromosome getChromosome(ItemStack itemStack, IChromosomeType chromosomeType, ISpeciesRoot speciesRoot) { - NBTTagCompound nbtTagCompound = itemStack.getTagCompound(); - if (nbtTagCompound == null) { - return null; - } + private static IChromosome getChromosome( + ItemStack itemStack, IChromosomeType chromosomeType, ISpeciesRoot speciesRoot) { + NBTTagCompound nbtTagCompound = itemStack.getTagCompound(); + if (nbtTagCompound == null) { + return null; + } - NBTTagCompound genome = nbtTagCompound.getCompoundTag("Genome"); - if (genome == null) { - return null; - } + NBTTagCompound genome = nbtTagCompound.getCompoundTag("Genome"); + if (genome == null) { + return null; + } - IChromosome[] chromosomes = getChromosomes(genome, speciesRoot); - if (chromosomes == null) { - return null; - } + IChromosome[] chromosomes = getChromosomes(genome, speciesRoot); + if (chromosomes == null) { + return null; + } - return chromosomes[chromosomeType.ordinal()]; - } + return chromosomes[chromosomeType.ordinal()]; + } - private static IChromosome[] getChromosomes(NBTTagCompound genomeNBT, ISpeciesRoot speciesRoot) { + private static IChromosome[] getChromosomes(NBTTagCompound genomeNBT, ISpeciesRoot speciesRoot) { - NBTTagList chromosomesNBT = genomeNBT.getTagList("Chromosomes", 10); - IChromosome[] chromosomes = new IChromosome[speciesRoot.getDefaultTemplate().length]; + NBTTagList chromosomesNBT = genomeNBT.getTagList("Chromosomes", 10); + IChromosome[] chromosomes = new IChromosome[speciesRoot.getDefaultTemplate().length]; - for (int i = 0; i < chromosomesNBT.tagCount(); i++) { - NBTTagCompound chromosomeNBT = chromosomesNBT.getCompoundTagAt(i); - byte chromosomeOrdinal = chromosomeNBT.getByte(SLOT_TAG); + for (int i = 0; i < chromosomesNBT.tagCount(); i++) { + NBTTagCompound chromosomeNBT = chromosomesNBT.getCompoundTagAt(i); + byte chromosomeOrdinal = chromosomeNBT.getByte(SLOT_TAG); - if (chromosomeOrdinal >= 0 && chromosomeOrdinal < chromosomes.length) { - Chromosome chromosome = Chromosome.loadChromosomeFromNBT(chromosomeNBT); - chromosomes[chromosomeOrdinal] = chromosome; + if (chromosomeOrdinal >= 0 && chromosomeOrdinal < chromosomes.length) { + Chromosome chromosome = Chromosome.loadChromosomeFromNBT(chromosomeNBT); + chromosomes[chromosomeOrdinal] = chromosome; - if (Config.clearInvalidChromosomes) { - IAllele template = speciesRoot.getDefaultTemplate()[chromosomeOrdinal]; - Class chromosomeClass = speciesRoot.getKaryotype()[chromosomeOrdinal].getAlleleClass(); - if (chromosome.overrideInvalidAlleles(template, chromosomeClass)) { - chromosome.writeToNBT(chromosomeNBT); - } - } + if (Config.clearInvalidChromosomes) { + IAllele template = speciesRoot.getDefaultTemplate()[chromosomeOrdinal]; + Class chromosomeClass = + speciesRoot.getKaryotype()[chromosomeOrdinal].getAlleleClass(); + if (chromosome.overrideInvalidAlleles(template, chromosomeClass)) { + chromosome.writeToNBT(chromosomeNBT); + } + } - if (chromosome.hasInvalidAlleles(speciesRoot.getKaryotype()[chromosomeOrdinal].getAlleleClass())) { - throw new RuntimeException("Found Chromosome with invalid Alleles.\nNBTTagCompound: " + chromosomesNBT + "\nSee config option \"genetics.clear.invalid.chromosomes\".\nMissing: " + chromosomeNBT); - } - } - } + if (chromosome.hasInvalidAlleles(speciesRoot.getKaryotype()[chromosomeOrdinal].getAlleleClass())) { + throw new RuntimeException("Found Chromosome with invalid Alleles.\nNBTTagCompound: " + + chromosomesNBT + "\nSee config option \"genetics.clear.invalid.chromosomes\".\nMissing: " + + chromosomeNBT); + } + } + } - // handle old saves that have missing chromosomes - IChromosome speciesChromosome = chromosomes[speciesRoot.getKaryotypeKey().ordinal()]; - if (speciesChromosome != null) { - IAlleleSpecies species = (IAlleleSpecies) speciesChromosome.getActiveAllele(); - IAllele[] template = speciesRoot.getTemplate(species.getUID()); - for (int i = 0; i < chromosomes.length; i++) { - IAllele allele = template[i]; - if ((chromosomes[i] == null) && (allele != null)) { - chromosomes[i] = new Chromosome(allele); - } - } - } + // handle old saves that have missing chromosomes + IChromosome speciesChromosome = + chromosomes[speciesRoot.getKaryotypeKey().ordinal()]; + if (speciesChromosome != null) { + IAlleleSpecies species = (IAlleleSpecies) speciesChromosome.getActiveAllele(); + IAllele[] template = speciesRoot.getTemplate(species.getUID()); + for (int i = 0; i < chromosomes.length; i++) { + IAllele allele = template[i]; + if ((chromosomes[i] == null) && (allele != null)) { + chromosomes[i] = new Chromosome(allele); + } + } + } - return chromosomes; - } + return chromosomes; + } - protected static IAllele getActiveAllele(ItemStack itemStack, IChromosomeType chromosomeType, ISpeciesRoot speciesRoot) { - IChromosome chromosome = getChromosome(itemStack, chromosomeType, speciesRoot); - if (chromosome == null) { - return null; - } - return chromosome.getActiveAllele(); - } + protected static IAllele getActiveAllele( + ItemStack itemStack, IChromosomeType chromosomeType, ISpeciesRoot speciesRoot) { + IChromosome chromosome = getChromosome(itemStack, chromosomeType, speciesRoot); + if (chromosome == null) { + return null; + } + return chromosome.getActiveAllele(); + } - // / SAVING & LOADING - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - chromosomes = getChromosomes(nbttagcompound, getSpeciesRoot()); - } + // / SAVING & LOADING + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + chromosomes = getChromosomes(nbttagcompound, getSpeciesRoot()); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { - NBTTagList nbttaglist = new NBTTagList(); - for (int i = 0; i < chromosomes.length; i++) { - if (chromosomes[i] != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte(SLOT_TAG, (byte) i); - chromosomes[i].writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); - } - } - nbttagcompound.setTag("Chromosomes", nbttaglist); - } + NBTTagList nbttaglist = new NBTTagList(); + for (int i = 0; i < chromosomes.length; i++) { + if (chromosomes[i] != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setByte(SLOT_TAG, (byte) i); + chromosomes[i].writeToNBT(nbttagcompound1); + nbttaglist.appendTag(nbttagcompound1); + } + } + nbttagcompound.setTag("Chromosomes", nbttaglist); + } - // / INFORMATION RETRIEVAL - @Override - public IChromosome[] getChromosomes() { - return Arrays.copyOf(chromosomes, chromosomes.length); - } + // / INFORMATION RETRIEVAL + @Override + public IChromosome[] getChromosomes() { + return Arrays.copyOf(chromosomes, chromosomes.length); + } - @Override - public IAllele getActiveAllele(IChromosomeType chromosomeType) { - return chromosomes[chromosomeType.ordinal()].getActiveAllele(); - } + @Override + public IAllele getActiveAllele(IChromosomeType chromosomeType) { + return chromosomes[chromosomeType.ordinal()].getActiveAllele(); + } - @Override - public IAllele getInactiveAllele(IChromosomeType chromosomeType) { - return chromosomes[chromosomeType.ordinal()].getInactiveAllele(); - } + @Override + public IAllele getInactiveAllele(IChromosomeType chromosomeType) { + return chromosomes[chromosomeType.ordinal()].getInactiveAllele(); + } - @Override - public boolean isGeneticEqual(IGenome other) { - IChromosome[] genetics = other.getChromosomes(); - if (chromosomes.length != genetics.length) { - return false; - } + @Override + public boolean isGeneticEqual(IGenome other) { + IChromosome[] genetics = other.getChromosomes(); + if (chromosomes.length != genetics.length) { + return false; + } - for (int i = 0; i < chromosomes.length; i++) { - IChromosome chromosome = chromosomes[i]; - IChromosome otherChromosome = genetics[i]; - if (chromosome == null && otherChromosome == null) { - continue; - } - if (chromosome == null || otherChromosome == null) { - return false; - } + for (int i = 0; i < chromosomes.length; i++) { + IChromosome chromosome = chromosomes[i]; + IChromosome otherChromosome = genetics[i]; + if (chromosome == null && otherChromosome == null) { + continue; + } + if (chromosome == null || otherChromosome == null) { + return false; + } - if (!chromosome.getPrimaryAllele().getUID().equals(otherChromosome.getPrimaryAllele().getUID())) { - return false; - } - if (!chromosome.getSecondaryAllele().getUID().equals(otherChromosome.getSecondaryAllele().getUID())) { - return false; - } - } + if (!chromosome + .getPrimaryAllele() + .getUID() + .equals(otherChromosome.getPrimaryAllele().getUID())) { + return false; + } + if (!chromosome + .getSecondaryAllele() + .getUID() + .equals(otherChromosome.getSecondaryAllele().getUID())) { + return false; + } + } - return true; - } + return true; + } - @Override - public String toString() { - Objects.ToStringHelper toStringHelper = Objects.toStringHelper(this); - int i = 0; - for (IChromosome chromosome : chromosomes) { - toStringHelper.add(String.valueOf(i++), chromosome); - } - return toStringHelper.toString(); - } + @Override + public String toString() { + Objects.ToStringHelper toStringHelper = Objects.toStringHelper(this); + int i = 0; + for (IChromosome chromosome : chromosomes) { + toStringHelper.add(String.valueOf(i++), chromosome); + } + return toStringHelper.toString(); + } } diff --git a/src/main/java/forestry/core/genetics/IBranchDefinition.java b/src/main/java/forestry/core/genetics/IBranchDefinition.java index ed327ae83..9c8fcdd80 100644 --- a/src/main/java/forestry/core/genetics/IBranchDefinition.java +++ b/src/main/java/forestry/core/genetics/IBranchDefinition.java @@ -1,10 +1,10 @@ -package forestry.core.genetics; - -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IClassification; - -public interface IBranchDefinition { - IAllele[] getTemplate(); - - IClassification getBranch(); -} +package forestry.core.genetics; + +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IClassification; + +public interface IBranchDefinition { + IAllele[] getTemplate(); + + IClassification getBranch(); +} diff --git a/src/main/java/forestry/core/genetics/IGeneticDefinition.java b/src/main/java/forestry/core/genetics/IGeneticDefinition.java index 73b9ff29f..8793f763c 100644 --- a/src/main/java/forestry/core/genetics/IGeneticDefinition.java +++ b/src/main/java/forestry/core/genetics/IGeneticDefinition.java @@ -1,15 +1,14 @@ -package forestry.core.genetics; - -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IGenome; -import forestry.api.genetics.IIndividual; - -public interface IGeneticDefinition { - - IAllele[] getTemplate(); - - IGenome getGenome(); - - IIndividual getIndividual(); - -} +package forestry.core.genetics; + +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IGenome; +import forestry.api.genetics.IIndividual; + +public interface IGeneticDefinition { + + IAllele[] getTemplate(); + + IGenome getGenome(); + + IIndividual getIndividual(); +} diff --git a/src/main/java/forestry/core/genetics/Individual.java b/src/main/java/forestry/core/genetics/Individual.java index 863f80703..6012eee3b 100755 --- a/src/main/java/forestry/core/genetics/Individual.java +++ b/src/main/java/forestry/core/genetics/Individual.java @@ -10,74 +10,76 @@ ******************************************************************************/ package forestry.core.genetics; -import net.minecraft.nbt.NBTTagCompound; - import forestry.api.genetics.IChromosomeType; import forestry.api.genetics.IIndividual; +import net.minecraft.nbt.NBTTagCompound; public abstract class Individual implements IIndividual { - protected boolean isAnalyzed = false; + protected boolean isAnalyzed = false; - @Override - public boolean isAnalyzed() { - return isAnalyzed; - } + @Override + public boolean isAnalyzed() { + return isAnalyzed; + } - @Override - public boolean analyze() { - if (isAnalyzed) { - return false; - } + @Override + public boolean analyze() { + if (isAnalyzed) { + return false; + } - isAnalyzed = true; - return true; - } + isAnalyzed = true; + return true; + } - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - if (nbttagcompound == null) { - return; - } + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + if (nbttagcompound == null) { + return; + } - isAnalyzed = nbttagcompound.getBoolean("IsAnalyzed"); - } + isAnalyzed = nbttagcompound.getBoolean("IsAnalyzed"); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setBoolean("IsAnalyzed", isAnalyzed); - } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setBoolean("IsAnalyzed", isAnalyzed); + } - /* IDENTIFICATION */ - @Override - public String getIdent() { - return getGenome().getPrimary().getUID(); - } + /* IDENTIFICATION */ + @Override + public String getIdent() { + return getGenome().getPrimary().getUID(); + } - @Override - public String getDisplayName() { - return getGenome().getPrimary().getName(); - } + @Override + public String getDisplayName() { + return getGenome().getPrimary().getName(); + } - /* INFORMATION */ - @Override - public boolean hasEffect() { - return getGenome().getPrimary().hasEffect(); - } + /* INFORMATION */ + @Override + public boolean hasEffect() { + return getGenome().getPrimary().hasEffect(); + } - @Override - public boolean isSecret() { - return getGenome().getPrimary().isSecret(); - } + @Override + public boolean isSecret() { + return getGenome().getPrimary().isSecret(); + } - @Override - public boolean isGeneticEqual(IIndividual other) { - return getGenome().isGeneticEqual(other.getGenome()); - } + @Override + public boolean isGeneticEqual(IIndividual other) { + return getGenome().isGeneticEqual(other.getGenome()); + } - @Override - public boolean isPureBred(IChromosomeType chromosomeType) { - return getGenome().getActiveAllele(chromosomeType).getUID().equals(getGenome().getInactiveAllele(chromosomeType).getUID()); - } + @Override + public boolean isPureBred(IChromosomeType chromosomeType) { + return getGenome() + .getActiveAllele(chromosomeType) + .getUID() + .equals(getGenome().getInactiveAllele(chromosomeType).getUID()); + } } diff --git a/src/main/java/forestry/core/genetics/IndividualLiving.java b/src/main/java/forestry/core/genetics/IndividualLiving.java index 9c5a647a7..5b580c290 100755 --- a/src/main/java/forestry/core/genetics/IndividualLiving.java +++ b/src/main/java/forestry/core/genetics/IndividualLiving.java @@ -10,97 +10,92 @@ ******************************************************************************/ package forestry.core.genetics; +import forestry.api.genetics.IGenome; +import forestry.api.genetics.IIndividualLiving; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import forestry.api.genetics.IGenome; -import forestry.api.genetics.IIndividualLiving; - public abstract class IndividualLiving extends Individual implements IIndividualLiving { - private int health; - private int maxHealth; + private int health; + private int maxHealth; - protected IndividualLiving() { - } - - protected IndividualLiving(int newHealth) { - health = maxHealth = newHealth; - } - - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { + protected IndividualLiving() {} - super.readFromNBT(nbttagcompound); + protected IndividualLiving(int newHealth) { + health = maxHealth = newHealth; + } - health = nbttagcompound.getInteger("Health"); - maxHealth = nbttagcompound.getInteger("MaxH"); + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { - } + super.readFromNBT(nbttagcompound); - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { + health = nbttagcompound.getInteger("Health"); + maxHealth = nbttagcompound.getInteger("MaxH"); + } - super.writeToNBT(nbttagcompound); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setInteger("Health", health); - nbttagcompound.setInteger("MaxH", maxHealth); + super.writeToNBT(nbttagcompound); - if (getGenome() != null) { - NBTTagCompound nbtGenome = new NBTTagCompound(); - getGenome().writeToNBT(nbtGenome); - nbttagcompound.setTag("Genome", nbtGenome); - } - if (getMate() != null) { - NBTTagCompound nbtMate = new NBTTagCompound(); - getMate().writeToNBT(nbtMate); - nbttagcompound.setTag("Mate", nbtMate); - } + nbttagcompound.setInteger("Health", health); + nbttagcompound.setInteger("MaxH", maxHealth); - } + if (getGenome() != null) { + NBTTagCompound nbtGenome = new NBTTagCompound(); + getGenome().writeToNBT(nbtGenome); + nbttagcompound.setTag("Genome", nbtGenome); + } + if (getMate() != null) { + NBTTagCompound nbtMate = new NBTTagCompound(); + getMate().writeToNBT(nbtMate); + nbttagcompound.setTag("Mate", nbtMate); + } + } - /* GENERATION */ - public abstract IGenome getMate(); + /* GENERATION */ + public abstract IGenome getMate(); - @Override - public boolean isAlive() { - return health > 0; - } + @Override + public boolean isAlive() { + return health > 0; + } - @Override - public int getHealth() { - return health; - } + @Override + public int getHealth() { + return health; + } - @Override - public int getMaxHealth() { - return this.maxHealth; - } + @Override + public int getMaxHealth() { + return this.maxHealth; + } - @Override - public void age(World world, float lifespanModifier) { + @Override + public void age(World world, float lifespanModifier) { - if (lifespanModifier < 0.001f) { - this.health = 0; - return; - } + if (lifespanModifier < 0.001f) { + this.health = 0; + return; + } - float ageModifier = 1.0f / lifespanModifier; + float ageModifier = 1.0f / lifespanModifier; - while (ageModifier > 1.0f) { - decreaseHealth(); - ageModifier--; - } - if (world.rand.nextFloat() < ageModifier) { - decreaseHealth(); - } - } - - private void decreaseHealth() { - if (health > 0) { - health--; - } - } + while (ageModifier > 1.0f) { + decreaseHealth(); + ageModifier--; + } + if (world.rand.nextFloat() < ageModifier) { + decreaseHealth(); + } + } + private void decreaseHealth() { + if (health > 0) { + health--; + } + } } diff --git a/src/main/java/forestry/core/genetics/ItemGE.java b/src/main/java/forestry/core/genetics/ItemGE.java index c8408158d..9de985d61 100755 --- a/src/main/java/forestry/core/genetics/ItemGE.java +++ b/src/main/java/forestry/core/genetics/ItemGE.java @@ -10,97 +10,94 @@ ******************************************************************************/ package forestry.core.genetics; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.genetics.IAlleleSpecies; +import forestry.api.genetics.IIndividual; +import forestry.core.items.ItemForestry; +import forestry.core.proxy.Proxies; +import forestry.core.utils.StringUtil; import java.util.List; - import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.genetics.IAlleleSpecies; -import forestry.api.genetics.IIndividual; -import forestry.core.items.ItemForestry; -import forestry.core.proxy.Proxies; -import forestry.core.utils.StringUtil; - public abstract class ItemGE extends ItemForestry { - protected ItemGE(CreativeTabs creativeTab) { - super(creativeTab); - hasSubtypes = true; - } + protected ItemGE(CreativeTabs creativeTab) { + super(creativeTab); + hasSubtypes = true; + } - protected abstract int getDefaultPrimaryColour(); + protected abstract int getDefaultPrimaryColour(); - protected abstract int getDefaultSecondaryColour(); + protected abstract int getDefaultSecondaryColour(); - public abstract IIndividual getIndividual(ItemStack itemstack); + public abstract IIndividual getIndividual(ItemStack itemstack); - protected abstract IAlleleSpecies getSpecies(ItemStack itemStack); + protected abstract IAlleleSpecies getSpecies(ItemStack itemStack); - @Override - public boolean isDamageable() { - return false; - } + @Override + public boolean isDamageable() { + return false; + } - @Override - public boolean isRepairable() { - return false; - } + @Override + public boolean isRepairable() { + return false; + } - @Override - public boolean getShareTag() { - return true; - } + @Override + public boolean getShareTag() { + return true; + } - @Override - public boolean hasEffect(ItemStack itemstack, int pass) { - IAlleleSpecies species = getSpecies(itemstack); - return species != null && species.hasEffect(); - } + @Override + public boolean hasEffect(ItemStack itemstack, int pass) { + IAlleleSpecies species = getSpecies(itemstack); + return species != null && species.hasEffect(); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { - if (!itemstack.hasTagCompound()) { - return; - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { + if (!itemstack.hasTagCompound()) { + return; + } - IIndividual individual = getIndividual(itemstack); + IIndividual individual = getIndividual(itemstack); - if (individual.isAnalyzed()) { - if (Proxies.common.isShiftDown()) { - individual.addTooltip(list); - } else { - list.add(EnumChatFormatting.ITALIC + "<" + StringUtil.localize("gui.tooltip.tmi") + ">"); - } - } else { - list.add("<" + StringUtil.localize("gui.unknown") + ">"); - } - } + if (individual.isAnalyzed()) { + if (Proxies.common.isShiftDown()) { + individual.addTooltip(list); + } else { + list.add(EnumChatFormatting.ITALIC + "<" + StringUtil.localize("gui.tooltip.tmi") + ">"); + } + } else { + list.add("<" + StringUtil.localize("gui.unknown") + ">"); + } + } - /* ICONS */ - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister par1IconRegister) { - // Need to disable normal registration. - } + /* ICONS */ + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister par1IconRegister) { + // Need to disable normal registration. + } - @Override - public int getColorFromItemStack(ItemStack itemstack, int renderPass) { - if (renderPass == 0) { - return getDefaultPrimaryColour(); - } else if (renderPass == 1) { - return getDefaultSecondaryColour(); - } else { - return 0xffffff; - } - } + @Override + public int getColorFromItemStack(ItemStack itemstack, int renderPass) { + if (renderPass == 0) { + return getDefaultPrimaryColour(); + } else if (renderPass == 1) { + return getDefaultSecondaryColour(); + } else { + return 0xffffff; + } + } - public int getColourFromSpecies(IAlleleSpecies species, int renderPass) { - return 0xffffff; - } + public int getColourFromSpecies(IAlleleSpecies species, int renderPass) { + return 0xffffff; + } } diff --git a/src/main/java/forestry/core/genetics/ItemResearchNote.java b/src/main/java/forestry/core/genetics/ItemResearchNote.java index f1068a2a1..7cbac7b77 100755 --- a/src/main/java/forestry/core/genetics/ItemResearchNote.java +++ b/src/main/java/forestry/core/genetics/ItemResearchNote.java @@ -10,10 +10,22 @@ ******************************************************************************/ package forestry.core.genetics; +import com.mojang.authlib.GameProfile; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IAlleleSpecies; +import forestry.api.genetics.IBreedingTracker; +import forestry.api.genetics.IMutation; +import forestry.api.genetics.ISpeciesRoot; +import forestry.core.genetics.mutations.EnumMutateChance; +import forestry.core.items.ItemForestry; +import forestry.core.proxy.Proxies; +import forestry.core.utils.StringUtil; import java.util.ArrayList; import java.util.List; import java.util.Locale; - import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; @@ -26,295 +38,289 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IIcon; import net.minecraft.world.World; -import com.mojang.authlib.GameProfile; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IAlleleSpecies; -import forestry.api.genetics.IBreedingTracker; -import forestry.api.genetics.IMutation; -import forestry.api.genetics.ISpeciesRoot; -import forestry.core.genetics.mutations.EnumMutateChance; -import forestry.core.items.ItemForestry; -import forestry.core.proxy.Proxies; -import forestry.core.utils.StringUtil; - public class ItemResearchNote extends ItemForestry { - public enum EnumNoteType { - NONE, MUTATION, SPECIES; + public enum EnumNoteType { + NONE, + MUTATION, + SPECIES; - public static final EnumNoteType[] VALUES = values(); + public static final EnumNoteType[] VALUES = values(); - private static IMutation getEncodedMutation(ISpeciesRoot root, NBTTagCompound compound) { - IAllele allele0 = AlleleManager.alleleRegistry.getAllele(compound.getString("AL0")); - IAllele allele1 = AlleleManager.alleleRegistry.getAllele(compound.getString("AL1")); - if (allele0 == null || allele1 == null) { - return null; - } + private static IMutation getEncodedMutation(ISpeciesRoot root, NBTTagCompound compound) { + IAllele allele0 = AlleleManager.alleleRegistry.getAllele(compound.getString("AL0")); + IAllele allele1 = AlleleManager.alleleRegistry.getAllele(compound.getString("AL1")); + if (allele0 == null || allele1 == null) { + return null; + } - IAllele result = null; - if (compound.hasKey("RST")) { - result = AlleleManager.alleleRegistry.getAllele(compound.getString("RST")); - } + IAllele result = null; + if (compound.hasKey("RST")) { + result = AlleleManager.alleleRegistry.getAllele(compound.getString("RST")); + } - IMutation encoded = null; - for (IMutation mutation : root.getCombinations(allele0)) { - if (mutation.isPartner(allele1)) { - if (result == null - || mutation.getTemplate()[0].getUID().equals(result.getUID())) { - encoded = mutation; - break; - } - } - } + IMutation encoded = null; + for (IMutation mutation : root.getCombinations(allele0)) { + if (mutation.isPartner(allele1)) { + if (result == null || mutation.getTemplate()[0].getUID().equals(result.getUID())) { + encoded = mutation; + break; + } + } + } - return encoded; - } + return encoded; + } - public ArrayList getTooltip(NBTTagCompound compound) { - ArrayList tooltips = new ArrayList<>(); + public ArrayList getTooltip(NBTTagCompound compound) { + ArrayList tooltips = new ArrayList<>(); - if (compound == null || this == NONE) { - return tooltips; - } + if (compound == null || this == NONE) { + return tooltips; + } - if (this == MUTATION) { - ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(compound.getString("ROT")); - if (root == null) { - return tooltips; - } + if (this == MUTATION) { + ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(compound.getString("ROT")); + if (root == null) { + return tooltips; + } - IMutation encoded = getEncodedMutation(root, compound); - if (encoded == null) { - return tooltips; - } + IMutation encoded = getEncodedMutation(root, compound); + if (encoded == null) { + return tooltips; + } - String species1 = encoded.getAllele0().getName(); - String species2 = encoded.getAllele1().getName(); - String mutationChanceKey = EnumMutateChance.rateChance(encoded.getBaseChance()).toString().toLowerCase(Locale.ENGLISH); - String mutationChance = StringUtil.localize("researchNote.chance." + mutationChanceKey); - String speciesResult = encoded.getTemplate()[root.getKaryotypeKey().ordinal()].getName(); + String species1 = encoded.getAllele0().getName(); + String species2 = encoded.getAllele1().getName(); + String mutationChanceKey = EnumMutateChance.rateChance(encoded.getBaseChance()) + .toString() + .toLowerCase(Locale.ENGLISH); + String mutationChance = StringUtil.localize("researchNote.chance." + mutationChanceKey); + String speciesResult = + encoded.getTemplate()[root.getKaryotypeKey().ordinal()].getName(); - tooltips.add(StringUtil.localize("researchNote.discovery.0")); - tooltips.add(StringUtil.localize("researchNote.discovery.1").replace("%SPEC1", species1).replace("%SPEC2", species2)); - tooltips.add(StringUtil.localizeAndFormat("researchNote.discovery.2", mutationChance)); - tooltips.add(StringUtil.localizeAndFormat("researchNote.discovery.3", speciesResult)); + tooltips.add(StringUtil.localize("researchNote.discovery.0")); + tooltips.add(StringUtil.localize("researchNote.discovery.1") + .replace("%SPEC1", species1) + .replace("%SPEC2", species2)); + tooltips.add(StringUtil.localizeAndFormat("researchNote.discovery.2", mutationChance)); + tooltips.add(StringUtil.localizeAndFormat("researchNote.discovery.3", speciesResult)); - if (encoded.getSpecialConditions() != null && encoded.getSpecialConditions().size() > 0) { - for (String line : encoded.getSpecialConditions()) { - tooltips.add(EnumChatFormatting.GOLD + line); - } - } - } else if (this == SPECIES) { - IAlleleSpecies allele0 = (IAlleleSpecies) AlleleManager.alleleRegistry.getAllele(compound.getString("AL0")); - if (allele0 == null) { - return tooltips; - } - ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(compound.getString("ROT")); - if (root == null) { - return tooltips; - } + if (encoded.getSpecialConditions() != null + && encoded.getSpecialConditions().size() > 0) { + for (String line : encoded.getSpecialConditions()) { + tooltips.add(EnumChatFormatting.GOLD + line); + } + } + } else if (this == SPECIES) { + IAlleleSpecies allele0 = + (IAlleleSpecies) AlleleManager.alleleRegistry.getAllele(compound.getString("AL0")); + if (allele0 == null) { + return tooltips; + } + ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(compound.getString("ROT")); + if (root == null) { + return tooltips; + } - tooltips.add("researchNote.discovered.0"); - tooltips.add(StringUtil.localizeAndFormat("researchNote.discovered.1", allele0.getName(), allele0.getBinomial())); - } + tooltips.add("researchNote.discovered.0"); + tooltips.add(StringUtil.localizeAndFormat( + "researchNote.discovered.1", allele0.getName(), allele0.getBinomial())); + } - return tooltips; - } + return tooltips; + } - public boolean registerResults(World world, EntityPlayer player, NBTTagCompound compound) { - if (compound == null || this == NONE) { - return false; - } + public boolean registerResults(World world, EntityPlayer player, NBTTagCompound compound) { + if (compound == null || this == NONE) { + return false; + } - if (this == MUTATION) { - ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(compound.getString("ROT")); - if (root == null) { - return false; - } + if (this == MUTATION) { + ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(compound.getString("ROT")); + if (root == null) { + return false; + } - IMutation encoded = getEncodedMutation(root, compound); - if (encoded == null) { - return false; - } + IMutation encoded = getEncodedMutation(root, compound); + if (encoded == null) { + return false; + } - IBreedingTracker tracker = encoded.getRoot().getBreedingTracker(world, player.getGameProfile()); - if (tracker.isResearched(encoded)) { - player.addChatMessage(new ChatComponentTranslation("for.chat.cannotmemorizeagain")); - return false; - } + IBreedingTracker tracker = encoded.getRoot().getBreedingTracker(world, player.getGameProfile()); + if (tracker.isResearched(encoded)) { + player.addChatMessage(new ChatComponentTranslation("for.chat.cannotmemorizeagain")); + return false; + } - IAlleleSpecies species0 = encoded.getAllele0(); - IAlleleSpecies species1 = encoded.getAllele1(); - IAlleleSpecies speciesResult = (IAlleleSpecies) encoded.getTemplate()[root.getKaryotypeKey().ordinal()]; + IAlleleSpecies species0 = encoded.getAllele0(); + IAlleleSpecies species1 = encoded.getAllele1(); + IAlleleSpecies speciesResult = (IAlleleSpecies) + encoded.getTemplate()[root.getKaryotypeKey().ordinal()]; - tracker.registerSpecies(species0); - tracker.registerSpecies(species1); - tracker.registerSpecies(speciesResult); + tracker.registerSpecies(species0); + tracker.registerSpecies(species1); + tracker.registerSpecies(speciesResult); - tracker.researchMutation(encoded); - player.addChatMessage(new ChatComponentTranslation("for.chat.memorizednote")); + tracker.researchMutation(encoded); + player.addChatMessage(new ChatComponentTranslation("for.chat.memorizednote")); - player.addChatMessage(new ChatComponentTranslation("for.chat.memorizednote2", - EnumChatFormatting.GRAY + species0.getName(), - EnumChatFormatting.GRAY + species1.getName(), - EnumChatFormatting.GREEN + speciesResult.getName())); + player.addChatMessage(new ChatComponentTranslation( + "for.chat.memorizednote2", + EnumChatFormatting.GRAY + species0.getName(), + EnumChatFormatting.GRAY + species1.getName(), + EnumChatFormatting.GREEN + speciesResult.getName())); - return true; - } + return true; + } - return false; + return false; + } - } + public static ResearchNote createMutationNote(GameProfile researcher, IMutation mutation) { + NBTTagCompound compound = new NBTTagCompound(); + compound.setString("ROT", mutation.getRoot().getUID()); + compound.setString("AL0", mutation.getAllele0().getUID()); + compound.setString("AL1", mutation.getAllele1().getUID()); + compound.setString("RST", mutation.getTemplate()[0].getUID()); + return new ResearchNote(researcher, MUTATION, compound); + } - public static ResearchNote createMutationNote(GameProfile researcher, IMutation mutation) { - NBTTagCompound compound = new NBTTagCompound(); - compound.setString("ROT", mutation.getRoot().getUID()); - compound.setString("AL0", mutation.getAllele0().getUID()); - compound.setString("AL1", mutation.getAllele1().getUID()); - compound.setString("RST", mutation.getTemplate()[0].getUID()); - return new ResearchNote(researcher, MUTATION, compound); - } + public static ItemStack createMutationNoteStack(Item item, GameProfile researcher, IMutation mutation) { + ResearchNote note = createMutationNote(researcher, mutation); + NBTTagCompound compound = new NBTTagCompound(); + note.writeToNBT(compound); + ItemStack created = new ItemStack(item); + created.setTagCompound(compound); + return created; + } - public static ItemStack createMutationNoteStack(Item item, GameProfile researcher, IMutation mutation) { - ResearchNote note = createMutationNote(researcher, mutation); - NBTTagCompound compound = new NBTTagCompound(); - note.writeToNBT(compound); - ItemStack created = new ItemStack(item); - created.setTagCompound(compound); - return created; - } + public static ResearchNote createSpeciesNote(GameProfile researcher, IAlleleSpecies species) { + NBTTagCompound compound = new NBTTagCompound(); + compound.setString("ROT", species.getRoot().getUID()); + compound.setString("AL0", species.getUID()); + return new ResearchNote(researcher, SPECIES, compound); + } - public static ResearchNote createSpeciesNote(GameProfile researcher, IAlleleSpecies species) { - NBTTagCompound compound = new NBTTagCompound(); - compound.setString("ROT", species.getRoot().getUID()); - compound.setString("AL0", species.getUID()); - return new ResearchNote(researcher, SPECIES, compound); - } + public static ItemStack createSpeciesNoteStack(Item item, GameProfile researcher, IAlleleSpecies species) { + ResearchNote note = createSpeciesNote(researcher, species); + NBTTagCompound compound = new NBTTagCompound(); + note.writeToNBT(compound); + ItemStack created = new ItemStack(item); + created.setTagCompound(compound); + return created; + } + } - public static ItemStack createSpeciesNoteStack(Item item, GameProfile researcher, IAlleleSpecies species) { - ResearchNote note = createSpeciesNote(researcher, species); - NBTTagCompound compound = new NBTTagCompound(); - note.writeToNBT(compound); - ItemStack created = new ItemStack(item); - created.setTagCompound(compound); - return created; - } + public static class ResearchNote { - } + private final GameProfile researcher; + private final EnumNoteType type; + private final NBTTagCompound inner; - public static class ResearchNote { + public ResearchNote(GameProfile researcher, EnumNoteType type, NBTTagCompound inner) { + this.researcher = researcher; + this.type = type; + this.inner = inner; + } - private final GameProfile researcher; - private final EnumNoteType type; - private final NBTTagCompound inner; + public ResearchNote(NBTTagCompound compound) { + if (compound != null) { + if (compound.hasKey("res")) { + this.researcher = NBTUtil.func_152459_a(compound.getCompoundTag("res")); + } else { + this.researcher = null; + } + this.type = EnumNoteType.VALUES[compound.getByte("TYP")]; + this.inner = compound.getCompoundTag("INN"); + } else { + this.type = EnumNoteType.NONE; + this.researcher = null; + this.inner = new NBTTagCompound(); + } + } - public ResearchNote(GameProfile researcher, EnumNoteType type, NBTTagCompound inner) { - this.researcher = researcher; - this.type = type; - this.inner = inner; - } + public void writeToNBT(NBTTagCompound compound) { + if (this.researcher != null) { + NBTTagCompound nbt = new NBTTagCompound(); + NBTUtil.func_152460_a(nbt, researcher); + compound.setTag("res", nbt); + } + compound.setByte("TYP", (byte) type.ordinal()); + compound.setTag("INN", inner); + } - public ResearchNote(NBTTagCompound compound) { - if (compound != null) { - if (compound.hasKey("res")) { - this.researcher = NBTUtil.func_152459_a(compound.getCompoundTag("res")); - } else { - this.researcher = null; - } - this.type = EnumNoteType.VALUES[compound.getByte("TYP")]; - this.inner = compound.getCompoundTag("INN"); - } else { - this.type = EnumNoteType.NONE; - this.researcher = null; - this.inner = new NBTTagCompound(); - } - } + public void addTooltip(List list) { + ArrayList tooltips = type.getTooltip(inner); + if (tooltips.size() <= 0) { + list.add(EnumChatFormatting.ITALIC + + EnumChatFormatting.RED.toString() + + StringUtil.localize("researchNote.error.0")); + list.add(StringUtil.localize("researchNote.error.1")); + return; + } - public void writeToNBT(NBTTagCompound compound) { - if (this.researcher != null) { - NBTTagCompound nbt = new NBTTagCompound(); - NBTUtil.func_152460_a(nbt, researcher); - compound.setTag("res", nbt); - } - compound.setByte("TYP", (byte) type.ordinal()); - compound.setTag("INN", inner); - } + list.addAll(tooltips); + } - public void addTooltip(List list) { - ArrayList tooltips = type.getTooltip(inner); - if (tooltips.size() <= 0) { - list.add(EnumChatFormatting.ITALIC + EnumChatFormatting.RED.toString() + StringUtil.localize("researchNote.error.0")); - list.add(StringUtil.localize("researchNote.error.1")); - return; - } + public boolean registerResults(World world, EntityPlayer player) { + return type.registerResults(world, player, inner); + } + } - list.addAll(tooltips); - } + public ItemResearchNote() { + super(); + setCreativeTab(null); + } - public boolean registerResults(World world, EntityPlayer player) { - return type.registerResults(world, player, inner); - } - } + @Override + public String getItemStackDisplayName(ItemStack itemstack) { + ResearchNote note = new ResearchNote(itemstack.getTagCompound()); + String researcherName; + if (note.researcher == null) { + researcherName = "Sengir"; + } else { + researcherName = note.researcher.getName(); + } + return StringUtil.localizeAndFormatRaw(getUnlocalizedName(itemstack) + ".name", researcherName); + } - public ItemResearchNote() { - super(); - setCreativeTab(null); - } + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { + ResearchNote note = new ResearchNote(itemstack.getTagCompound()); + note.addTooltip(list); + } - @Override - public String getItemStackDisplayName(ItemStack itemstack) { - ResearchNote note = new ResearchNote(itemstack.getTagCompound()); - String researcherName; - if (note.researcher == null) { - researcherName = "Sengir"; - } else { - researcherName = note.researcher.getName(); - } - return StringUtil.localizeAndFormatRaw(getUnlocalizedName(itemstack) + ".name", researcherName); - } + @Override + public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { - ResearchNote note = new ResearchNote(itemstack.getTagCompound()); - note.addTooltip(list); - } + if (world.isRemote) { + return itemstack; + } - @Override - public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { + ResearchNote note = new ResearchNote(itemstack.getTagCompound()); + if (note.registerResults(world, entityplayer)) { + entityplayer.inventory.decrStackSize(entityplayer.inventory.currentItem, 1); + // Notify player that his inventory has changed. + Proxies.net.inventoryChangeNotify(entityplayer); + } - if (world.isRemote) { - return itemstack; - } + return itemstack; + } - ResearchNote note = new ResearchNote(itemstack.getTagCompound()); - if (note.registerResults(world, entityplayer)) { - entityplayer.inventory.decrStackSize(entityplayer.inventory.currentItem, 1); - // Notify player that his inventory has changed. - Proxies.net.inventoryChangeNotify(entityplayer); - } + @Override + public int getColorFromItemStack(ItemStack itemstack, int j) { + return 0xffe8a5; + } - return itemstack; - } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) {} - @Override - public int getColorFromItemStack(ItemStack itemstack, int j) { - return 0xffe8a5; - } - - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - } - - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamage(int meta) { - return Items.paper.getIconFromDamage(0); - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamage(int meta) { + return Items.paper.getIconFromDamage(0); + } } diff --git a/src/main/java/forestry/core/genetics/SpeciesRoot.java b/src/main/java/forestry/core/genetics/SpeciesRoot.java index fdc6832e9..ea0a0d395 100644 --- a/src/main/java/forestry/core/genetics/SpeciesRoot.java +++ b/src/main/java/forestry/core/genetics/SpeciesRoot.java @@ -10,6 +10,12 @@ ******************************************************************************/ package forestry.core.genetics; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IAlleleSpecies; +import forestry.api.genetics.IChromosome; +import forestry.api.genetics.IChromosomeType; +import forestry.api.genetics.IMutation; +import forestry.api.genetics.ISpeciesRoot; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -19,137 +25,130 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IAlleleSpecies; -import forestry.api.genetics.IChromosome; -import forestry.api.genetics.IChromosomeType; -import forestry.api.genetics.IMutation; -import forestry.api.genetics.ISpeciesRoot; - public abstract class SpeciesRoot implements ISpeciesRoot { - - /* RESEARCH */ - private final LinkedHashMap researchCatalysts = new LinkedHashMap<>(); - - @Override - public Map getResearchCatalysts() { - return Collections.unmodifiableMap(researchCatalysts); - } - @Override - public void setResearchSuitability(ItemStack itemstack, float suitability) { - researchCatalysts.put(itemstack, suitability); - } + /* RESEARCH */ + private final LinkedHashMap researchCatalysts = new LinkedHashMap<>(); - /* TEMPLATES */ - protected final HashMap speciesTemplates = new HashMap<>(); + @Override + public Map getResearchCatalysts() { + return Collections.unmodifiableMap(researchCatalysts); + } - @Override - public Map getGenomeTemplates() { - return speciesTemplates; - } - - @Override - public void registerTemplate(IAllele[] template) { - if (template == null) { - throw new IllegalArgumentException("Tried to register null template"); - } - if (template.length == 0) { - throw new IllegalArgumentException("Tried to register empty template"); - } - registerTemplate(template[0].getUID(), template); - } + @Override + public void setResearchSuitability(ItemStack itemstack, float suitability) { + researchCatalysts.put(itemstack, suitability); + } - @Override - public IAllele[] getRandomTemplate(Random rand) { - Collection templates = speciesTemplates.values(); - int size = templates.size(); - IAllele[][] templatesArray = templates.toArray(new IAllele[size][]); - return templatesArray[rand.nextInt(size)]; - } + /* TEMPLATES */ + protected final HashMap speciesTemplates = new HashMap<>(); - @Override - public IAllele[] getTemplate(String identifier) { - IAllele[] template = speciesTemplates.get(identifier); - if (template == null) { - return null; - } - return Arrays.copyOf(template, template.length); - } + @Override + public Map getGenomeTemplates() { + return speciesTemplates; + } - /* MUTATIONS */ - @Override - public Collection getCombinations(IAllele other) { - ArrayList combinations = new ArrayList<>(); - for (IMutation mutation : getMutations(false)) { - if (mutation.isPartner(other)) { - combinations.add(mutation); - } - } + @Override + public void registerTemplate(IAllele[] template) { + if (template == null) { + throw new IllegalArgumentException("Tried to register null template"); + } + if (template.length == 0) { + throw new IllegalArgumentException("Tried to register empty template"); + } + registerTemplate(template[0].getUID(), template); + } - return combinations; - } + @Override + public IAllele[] getRandomTemplate(Random rand) { + Collection templates = speciesTemplates.values(); + int size = templates.size(); + IAllele[][] templatesArray = templates.toArray(new IAllele[size][]); + return templatesArray[rand.nextInt(size)]; + } - @Override - public List getCombinations(IAlleleSpecies parentSpecies0, IAlleleSpecies parentSpecies1, boolean shuffle) { - List combinations = new ArrayList<>(); + @Override + public IAllele[] getTemplate(String identifier) { + IAllele[] template = speciesTemplates.get(identifier); + if (template == null) { + return null; + } + return Arrays.copyOf(template, template.length); + } - String parentSpecies1UID = parentSpecies1.getUID(); - for (IMutation mutation : getMutations(shuffle)) { - if (mutation.isPartner(parentSpecies0)) { - IAllele partner = mutation.getPartner(parentSpecies0); - if (partner != null && partner.getUID().equals(parentSpecies1UID)) { - combinations.add(mutation); - } - } - } + /* MUTATIONS */ + @Override + public Collection getCombinations(IAllele other) { + ArrayList combinations = new ArrayList<>(); + for (IMutation mutation : getMutations(false)) { + if (mutation.isPartner(other)) { + combinations.add(mutation); + } + } - return combinations; - } + return combinations; + } - @Override - public Collection getPaths(IAllele result, IChromosomeType chromosomeType) { - ArrayList paths = new ArrayList<>(); - for (IMutation mutation : getMutations(false)) { - if (mutation.getTemplate()[chromosomeType.ordinal()] == result) { - paths.add(mutation); - } - } + @Override + public List getCombinations( + IAlleleSpecies parentSpecies0, IAlleleSpecies parentSpecies1, boolean shuffle) { + List combinations = new ArrayList<>(); - return paths; - } + String parentSpecies1UID = parentSpecies1.getUID(); + for (IMutation mutation : getMutations(shuffle)) { + if (mutation.isPartner(parentSpecies0)) { + IAllele partner = mutation.getPartner(parentSpecies0); + if (partner != null && partner.getUID().equals(parentSpecies1UID)) { + combinations.add(mutation); + } + } + } - /* GENOME CONVERSIONS */ - @Override - public IChromosome[] templateAsChromosomes(IAllele[] template) { - Chromosome[] chromosomes = new Chromosome[template.length]; - for (int i = 0; i < template.length; i++) { - if (template[i] != null) { - chromosomes[i] = new Chromosome(template[i]); - } - } + return combinations; + } - return chromosomes; - } + @Override + public Collection getPaths(IAllele result, IChromosomeType chromosomeType) { + ArrayList paths = new ArrayList<>(); + for (IMutation mutation : getMutations(false)) { + if (mutation.getTemplate()[chromosomeType.ordinal()] == result) { + paths.add(mutation); + } + } - @Override - public IChromosome[] templateAsChromosomes(IAllele[] templateActive, IAllele[] templateInactive) { - Chromosome[] chromosomes = new Chromosome[templateActive.length]; - for (int i = 0; i < templateActive.length; i++) { - if (templateActive[i] != null) { - chromosomes[i] = new Chromosome(templateActive[i], templateInactive[i]); - } - } + return paths; + } - return chromosomes; - } + /* GENOME CONVERSIONS */ + @Override + public IChromosome[] templateAsChromosomes(IAllele[] template) { + Chromosome[] chromosomes = new Chromosome[template.length]; + for (int i = 0; i < template.length; i++) { + if (template[i] != null) { + chromosomes[i] = new Chromosome(template[i]); + } + } - @Override - public void syncBreedingTrackerToPlayer(EntityPlayer player) { - getBreedingTracker(player.worldObj, player.getGameProfile()).synchToPlayer(player); - } + return chromosomes; + } + + @Override + public IChromosome[] templateAsChromosomes(IAllele[] templateActive, IAllele[] templateInactive) { + Chromosome[] chromosomes = new Chromosome[templateActive.length]; + for (int i = 0; i < templateActive.length; i++) { + if (templateActive[i] != null) { + chromosomes[i] = new Chromosome(templateActive[i], templateInactive[i]); + } + } + + return chromosomes; + } + + @Override + public void syncBreedingTrackerToPlayer(EntityPlayer player) { + getBreedingTracker(player.worldObj, player.getGameProfile()).synchToPlayer(player); + } } diff --git a/src/main/java/forestry/core/genetics/alleles/Allele.java b/src/main/java/forestry/core/genetics/alleles/Allele.java index 6c4833080..6f8da66c3 100644 --- a/src/main/java/forestry/core/genetics/alleles/Allele.java +++ b/src/main/java/forestry/core/genetics/alleles/Allele.java @@ -10,44 +10,43 @@ ******************************************************************************/ package forestry.core.genetics.alleles; -import net.minecraft.util.StatCollector; - import forestry.api.genetics.IAllele; +import net.minecraft.util.StatCollector; public abstract class Allele implements IAllele { - private final String uid; - private final boolean isDominant; - private final String unlocalizedName; + private final String uid; + private final boolean isDominant; + private final String unlocalizedName; - protected Allele(String uid, String unlocalizedName, boolean isDominant) { - this.uid = uid; - this.isDominant = isDominant; - this.unlocalizedName = unlocalizedName; - } + protected Allele(String uid, String unlocalizedName, boolean isDominant) { + this.uid = uid; + this.isDominant = isDominant; + this.unlocalizedName = unlocalizedName; + } - @Override - public String getUID() { - return uid; - } + @Override + public String getUID() { + return uid; + } - @Override - public boolean isDominant() { - return isDominant; - } + @Override + public boolean isDominant() { + return isDominant; + } - @Override - public String getName() { - return StatCollector.translateToLocal(getUnlocalizedName()); - } + @Override + public String getName() { + return StatCollector.translateToLocal(getUnlocalizedName()); + } - @Override - public String getUnlocalizedName() { - return unlocalizedName; - } + @Override + public String getUnlocalizedName() { + return unlocalizedName; + } - @Override - public String toString() { - return uid; - } + @Override + public String toString() { + return uid; + } } diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleArea.java b/src/main/java/forestry/core/genetics/alleles/AlleleArea.java index d93d4114f..a7a95baff 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleArea.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleArea.java @@ -15,18 +15,18 @@ import forestry.core.utils.vect.Vect; public class AlleleArea extends AlleleCategorized implements IAlleleArea { - private final int[] area; + private final int[] area; - public AlleleArea(String modId, String category, String name, int[] value, boolean isDominant) { - super(modId, category, name, isDominant); - this.area = value; - } - - public int[] getValue() { - return area; - } + public AlleleArea(String modId, String category, String name, int[] value, boolean isDominant) { + super(modId, category, name, isDominant); + this.area = value; + } - public Vect getArea() { - return new Vect(area); - } + public int[] getValue() { + return area; + } + + public Vect getArea() { + return new Vect(area); + } } diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleBoolean.java b/src/main/java/forestry/core/genetics/alleles/AlleleBoolean.java index a981a76c2..13d5dcaf9 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleBoolean.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleBoolean.java @@ -14,15 +14,14 @@ import forestry.api.genetics.IAlleleBoolean; public class AlleleBoolean extends AlleleCategorized implements IAlleleBoolean { - private final boolean value; + private final boolean value; - public AlleleBoolean(String modId, String category, boolean value, boolean isDominant) { - super(modId, category, Boolean.toString(value), isDominant); - this.value = value; - } - - public boolean getValue() { - return value; - } + public AlleleBoolean(String modId, String category, boolean value, boolean isDominant) { + super(modId, category, Boolean.toString(value), isDominant); + this.value = value; + } + public boolean getValue() { + return value; + } } diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleCategorized.java b/src/main/java/forestry/core/genetics/alleles/AlleleCategorized.java index b0f712796..7a91079b9 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleCategorized.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleCategorized.java @@ -1,33 +1,32 @@ -package forestry.core.genetics.alleles; - -import org.apache.commons.lang3.text.WordUtils; - -import net.minecraft.util.StatCollector; - -/** - * Alleles that have a category with several values inherit from this class. - * For example, temperature tolerances or speeds are categories with several values. - * - * This class helps localization by allowing specific names like - * forestry.allele.speed.fast - * and can fall back on generic names like - * forestry.allele.fast - */ -public abstract class AlleleCategorized extends Allele { - protected AlleleCategorized(String modId, String category, String valueName, boolean isDominant) { - super(getUid(modId, category, valueName), getUnlocalizedName(modId, category, valueName), isDominant); - } - - private static String getUid(String modId, String category, String valueName) { - return modId + '.' + category + WordUtils.capitalize(valueName); - } - - private static String getUnlocalizedName(String modId, String category, String valueName) { - String customName = modId + '.' + "allele." + category + '.' + valueName; - if (StatCollector.canTranslate(customName)) { - return customName; - } else { - return modId + '.' + "allele." + valueName; - } - } -} +package forestry.core.genetics.alleles; + +import net.minecraft.util.StatCollector; +import org.apache.commons.lang3.text.WordUtils; + +/** + * Alleles that have a category with several values inherit from this class. + * For example, temperature tolerances or speeds are categories with several values. + * + * This class helps localization by allowing specific names like + * forestry.allele.speed.fast + * and can fall back on generic names like + * forestry.allele.fast + */ +public abstract class AlleleCategorized extends Allele { + protected AlleleCategorized(String modId, String category, String valueName, boolean isDominant) { + super(getUid(modId, category, valueName), getUnlocalizedName(modId, category, valueName), isDominant); + } + + private static String getUid(String modId, String category, String valueName) { + return modId + '.' + category + WordUtils.capitalize(valueName); + } + + private static String getUnlocalizedName(String modId, String category, String valueName) { + String customName = modId + '.' + "allele." + category + '.' + valueName; + if (StatCollector.canTranslate(customName)) { + return customName; + } else { + return modId + '.' + "allele." + valueName; + } + } +} diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleFactory.java b/src/main/java/forestry/core/genetics/alleles/AlleleFactory.java index 4b99be470..1717f8cad 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleFactory.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleFactory.java @@ -1,95 +1,121 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.genetics.alleles; - -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAlleleArea; -import forestry.api.genetics.IAlleleBoolean; -import forestry.api.genetics.IAlleleFactory; -import forestry.api.genetics.IAlleleFloat; -import forestry.api.genetics.IAlleleFlowers; -import forestry.api.genetics.IAlleleInteger; -import forestry.api.genetics.IChromosomeType; -import forestry.api.genetics.IFlowerProvider; -import forestry.apiculture.genetics.alleles.AlleleFlowers; - -public class AlleleFactory implements IAlleleFactory { - - @Override - public IAlleleFloat createFloat(String modId, String category, String valueName, float value, boolean isDominant, IChromosomeType... types) { - IAlleleFloat alleleFloat = new AlleleFloat(modId, category, valueName, value, isDominant); - AlleleManager.alleleRegistry.registerAllele(alleleFloat, types); - return alleleFloat; - } - - @Override - public IAlleleArea createArea(String modId, String category, String valueName, int xDimValue, int yDimValue, int zDimValue, boolean isDominant, IChromosomeType... types) { - IAlleleArea alleleArea = new AlleleArea(modId, category, valueName, new int[]{xDimValue, yDimValue, zDimValue}, isDominant); - AlleleManager.alleleRegistry.registerAllele(alleleArea, types); - return alleleArea; - } - - @Override - public IAlleleInteger createInteger(String modId, String category, String valueName, int value, boolean isDominant, IChromosomeType... types) { - IAlleleInteger alleleInteger = new AlleleInteger(modId, category, valueName, value, isDominant); - AlleleManager.alleleRegistry.registerAllele(alleleInteger, types); - return alleleInteger; - } - - @Override - public IAlleleBoolean createBoolean(String modId, String category, boolean value, boolean isDominant, IChromosomeType... types) { - IAlleleBoolean alleleBoolean = new AlleleBoolean(modId, category, value, isDominant); - AlleleManager.alleleRegistry.registerAllele(alleleBoolean, types); - return alleleBoolean; - } - - @Override - public IAlleleFlowers createFlowers(String modId, String category, String valueName, IFlowerProvider value, boolean isDominant, IChromosomeType... types) { - IAlleleFlowers alleleFlowers = new AlleleFlowers(modId, category, valueName, value, isDominant); - AlleleManager.alleleRegistry.registerAllele(alleleFlowers, types); - return alleleFlowers; - } - - @Override - public IAlleleFloat createFloat(String modId, String category, String name, float value, boolean isDominant) { - IAlleleFloat alleleFloat = new AlleleFloat(modId, category, name, value, isDominant); - AlleleManager.alleleRegistry.registerAllele(alleleFloat); - return alleleFloat; - } - - @Override - public IAlleleArea createArea(String modId, String category, String name, int xDim, int yDim, int zDim, boolean isDominant) { - IAlleleArea alleleArea = new AlleleArea(modId, category, name, new int[]{xDim, yDim, zDim}, isDominant); - AlleleManager.alleleRegistry.registerAllele(alleleArea); - return alleleArea; - } - - @Override - public IAlleleInteger createInteger(String modId, String category, String valueName, int value, boolean isDominant) { - IAlleleInteger alleleInteger = new AlleleInteger(modId, category, valueName, value, isDominant); - AlleleManager.alleleRegistry.registerAllele(alleleInteger); - return alleleInteger; - } - - @Override - public IAlleleBoolean createBoolean(String modId, String category, boolean value, boolean isDominant) { - IAlleleBoolean alleleBoolean = new AlleleBoolean(modId, category, value, isDominant); - AlleleManager.alleleRegistry.registerAllele(alleleBoolean); - return alleleBoolean; - } - - @Override - public IAlleleFlowers createFlowers(String modId, String category, String name, IFlowerProvider flowerProvider, boolean isDominant) { - IAlleleFlowers alleleFlowers = new AlleleFlowers(modId, category, name, flowerProvider, isDominant); - AlleleManager.alleleRegistry.registerAllele(alleleFlowers); - return alleleFlowers; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.genetics.alleles; + +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAlleleArea; +import forestry.api.genetics.IAlleleBoolean; +import forestry.api.genetics.IAlleleFactory; +import forestry.api.genetics.IAlleleFloat; +import forestry.api.genetics.IAlleleFlowers; +import forestry.api.genetics.IAlleleInteger; +import forestry.api.genetics.IChromosomeType; +import forestry.api.genetics.IFlowerProvider; +import forestry.apiculture.genetics.alleles.AlleleFlowers; + +public class AlleleFactory implements IAlleleFactory { + + @Override + public IAlleleFloat createFloat( + String modId, + String category, + String valueName, + float value, + boolean isDominant, + IChromosomeType... types) { + IAlleleFloat alleleFloat = new AlleleFloat(modId, category, valueName, value, isDominant); + AlleleManager.alleleRegistry.registerAllele(alleleFloat, types); + return alleleFloat; + } + + @Override + public IAlleleArea createArea( + String modId, + String category, + String valueName, + int xDimValue, + int yDimValue, + int zDimValue, + boolean isDominant, + IChromosomeType... types) { + IAlleleArea alleleArea = + new AlleleArea(modId, category, valueName, new int[] {xDimValue, yDimValue, zDimValue}, isDominant); + AlleleManager.alleleRegistry.registerAllele(alleleArea, types); + return alleleArea; + } + + @Override + public IAlleleInteger createInteger( + String modId, String category, String valueName, int value, boolean isDominant, IChromosomeType... types) { + IAlleleInteger alleleInteger = new AlleleInteger(modId, category, valueName, value, isDominant); + AlleleManager.alleleRegistry.registerAllele(alleleInteger, types); + return alleleInteger; + } + + @Override + public IAlleleBoolean createBoolean( + String modId, String category, boolean value, boolean isDominant, IChromosomeType... types) { + IAlleleBoolean alleleBoolean = new AlleleBoolean(modId, category, value, isDominant); + AlleleManager.alleleRegistry.registerAllele(alleleBoolean, types); + return alleleBoolean; + } + + @Override + public IAlleleFlowers createFlowers( + String modId, + String category, + String valueName, + IFlowerProvider value, + boolean isDominant, + IChromosomeType... types) { + IAlleleFlowers alleleFlowers = new AlleleFlowers(modId, category, valueName, value, isDominant); + AlleleManager.alleleRegistry.registerAllele(alleleFlowers, types); + return alleleFlowers; + } + + @Override + public IAlleleFloat createFloat(String modId, String category, String name, float value, boolean isDominant) { + IAlleleFloat alleleFloat = new AlleleFloat(modId, category, name, value, isDominant); + AlleleManager.alleleRegistry.registerAllele(alleleFloat); + return alleleFloat; + } + + @Override + public IAlleleArea createArea( + String modId, String category, String name, int xDim, int yDim, int zDim, boolean isDominant) { + IAlleleArea alleleArea = new AlleleArea(modId, category, name, new int[] {xDim, yDim, zDim}, isDominant); + AlleleManager.alleleRegistry.registerAllele(alleleArea); + return alleleArea; + } + + @Override + public IAlleleInteger createInteger( + String modId, String category, String valueName, int value, boolean isDominant) { + IAlleleInteger alleleInteger = new AlleleInteger(modId, category, valueName, value, isDominant); + AlleleManager.alleleRegistry.registerAllele(alleleInteger); + return alleleInteger; + } + + @Override + public IAlleleBoolean createBoolean(String modId, String category, boolean value, boolean isDominant) { + IAlleleBoolean alleleBoolean = new AlleleBoolean(modId, category, value, isDominant); + AlleleManager.alleleRegistry.registerAllele(alleleBoolean); + return alleleBoolean; + } + + @Override + public IAlleleFlowers createFlowers( + String modId, String category, String name, IFlowerProvider flowerProvider, boolean isDominant) { + IAlleleFlowers alleleFlowers = new AlleleFlowers(modId, category, name, flowerProvider, isDominant); + AlleleManager.alleleRegistry.registerAllele(alleleFlowers); + return alleleFlowers; + } +} diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleFloat.java b/src/main/java/forestry/core/genetics/alleles/AlleleFloat.java index c30294d19..26bad5777 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleFloat.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleFloat.java @@ -14,15 +14,15 @@ import forestry.api.genetics.IAlleleFloat; public class AlleleFloat extends AlleleCategorized implements IAlleleFloat { - private final float value; + private final float value; - public AlleleFloat(String modId, String category, String valueName, float value, boolean isDominant) { - super(modId, category, valueName, isDominant); - this.value = value; - } + public AlleleFloat(String modId, String category, String valueName, float value, boolean isDominant) { + super(modId, category, valueName, isDominant); + this.value = value; + } - @Override - public float getValue() { - return value; - } + @Override + public float getValue() { + return value; + } } diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleHelper.java b/src/main/java/forestry/core/genetics/alleles/AlleleHelper.java index 2f735fb61..63e18ce1e 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleHelper.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleHelper.java @@ -1,213 +1,223 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.genetics.alleles; - -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import forestry.api.apiculture.EnumBeeChromosome; -import forestry.api.arboriculture.EnumTreeChromosome; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.EnumTolerance; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IAlleleBoolean; -import forestry.api.genetics.IAlleleInteger; -import forestry.api.genetics.IAlleleTolerance; -import forestry.api.genetics.IChromosomeType; -import forestry.api.lepidopterology.EnumButterflyChromosome; -import forestry.apiculture.flowers.FlowerProvider; -import forestry.core.config.Constants; -import forestry.core.utils.vect.IVect; -import forestry.plugins.PluginManager; - -public class AlleleHelper implements IAlleleHelper { - - private static final String modId = Constants.ID; - public static AlleleHelper instance; - - private final Map> alleleMaps = new HashMap<>(); - - public void init() { - if (PluginManager.Module.APICULTURE.isEnabled()) { - createAlleles(EnumAllele.Fertility.class, EnumBeeChromosome.FERTILITY); - createAlleles(EnumAllele.Flowering.class, EnumBeeChromosome.FLOWERING); - } - - if (PluginManager.Module.APICULTURE.isEnabled() || PluginManager.Module.ARBORICULTURE.isEnabled()) { - createAlleles(EnumAllele.Territory.class, - EnumBeeChromosome.TERRITORY, - EnumTreeChromosome.TERRITORY - ); - - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.territoryDefault", get(EnumAllele.Territory.AVERAGE)); - } - - if (PluginManager.Module.APICULTURE.isEnabled() || PluginManager.Module.LEPIDOPTEROLOGY.isEnabled()) { - createAlleles(EnumAllele.Speed.class, - EnumBeeChromosome.SPEED, - EnumButterflyChromosome.SPEED - ); - createAlleles(EnumAllele.Lifespan.class, - EnumBeeChromosome.LIFESPAN, - EnumButterflyChromosome.LIFESPAN - ); - createAlleles(EnumAllele.Tolerance.class, - EnumBeeChromosome.TEMPERATURE_TOLERANCE, - EnumBeeChromosome.HUMIDITY_TOLERANCE, - EnumButterflyChromosome.TEMPERATURE_TOLERANCE, - EnumButterflyChromosome.HUMIDITY_TOLERANCE - ); - createAlleles(EnumAllele.Flowers.class, - EnumBeeChromosome.FLOWER_PROVIDER, - EnumButterflyChromosome.FLOWER_PROVIDER - ); - - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.speedNorm", get(EnumAllele.Speed.NORMAL)); - } - - if (PluginManager.Module.ARBORICULTURE.isEnabled()) { - createAlleles(EnumAllele.Height.class, EnumTreeChromosome.HEIGHT); - createAlleles(EnumAllele.Saplings.class, EnumTreeChromosome.FERTILITY); - createAlleles(EnumAllele.Yield.class, EnumTreeChromosome.YIELD); - createAlleles(EnumAllele.Fireproof.class, EnumTreeChromosome.FIREPROOF); - createAlleles(EnumAllele.Maturation.class, EnumTreeChromosome.MATURATION); - createAlleles(EnumAllele.Sappiness.class, EnumTreeChromosome.SAPPINESS); - - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.heightMax10", get(EnumAllele.Height.AVERAGE)); - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.saplingsDefault", get(EnumAllele.Saplings.AVERAGE)); - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.saplingsDouble", get(EnumAllele.Saplings.HIGH)); - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.saplingsTriple", get(EnumAllele.Saplings.HIGHER)); - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.yieldDefault", get(EnumAllele.Yield.AVERAGE)); - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.maturitySlowest", get(EnumAllele.Maturation.SLOWEST)); - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.maturitySlower", get(EnumAllele.Maturation.SLOWER)); - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.maturitySlow", get(EnumAllele.Maturation.SLOW)); - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.maturityAverage", get(EnumAllele.Maturation.AVERAGE)); - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.maturityFast", get(EnumAllele.Maturation.FAST)); - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.maturityFaster", get(EnumAllele.Maturation.FASTER)); - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.maturityFastest", get(EnumAllele.Maturation.FASTEST)); - } - - if (PluginManager.Module.LEPIDOPTEROLOGY.isEnabled()) { - createAlleles(EnumAllele.Size.class, EnumButterflyChromosome.SIZE); - } - - Map integers = new HashMap<>(); - for (int i = 1; i <= 10; i++) { - IAlleleInteger alleleInteger = new AlleleInteger(modId, "i", i + "d", i, true); - AlleleManager.alleleRegistry.registerAllele(alleleInteger, - EnumTreeChromosome.GIRTH, - EnumButterflyChromosome.METABOLISM, - EnumButterflyChromosome.FERTILITY - ); - integers.put(i, alleleInteger); - } - alleleMaps.put(Integer.class, integers); - - Map booleans = new HashMap<>(); - booleans.put(true, new AlleleBoolean(modId, "bool", true, false)); - booleans.put(false, new AlleleBoolean(modId, "bool", false, false)); - for (IAlleleBoolean alleleBoolean : booleans.values()) { - AlleleManager.alleleRegistry.registerAllele(alleleBoolean, - EnumBeeChromosome.NOCTURNAL, - EnumBeeChromosome.TOLERANT_FLYER, - EnumBeeChromosome.CAVE_DWELLING, - EnumButterflyChromosome.NOCTURNAL, - EnumButterflyChromosome.TOLERANT_FLYER, - EnumButterflyChromosome.FIRE_RESIST - ); - } - alleleMaps.put(Boolean.class, booleans); - } - - private IAllele get(Object value) { - Class valueClass = value.getClass(); - Map map = alleleMaps.get(valueClass); - if (map == null) { - throw new IllegalArgumentException("There is no IAllele type for: " + valueClass + ' ' + value); - } - IAllele allele = map.get(value); - if (allele == null) { - throw new IllegalArgumentException("There is no IAllele for: " + valueClass + ' ' + value); - } - - return allele; - } - - @Override - public & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, IAllele allele) { - if (allele == null) { - throw new NullPointerException("Allele must not be null"); - } - if (!chromosomeType.getAlleleClass().isInstance(allele)) { - throw new IllegalArgumentException("Allele is the wrong type. Expected: " + chromosomeType + " Got: " + allele); - } - - // uncomment this once all addon mods are using the allele registration with IChromosomeType - // Collection validTypes = AlleleManager.alleleRegistry.getChromosomeTypes(allele); - // if (validTypes.size() > 0 && !validTypes.contains(chromosomeType)) { - // throw new IllegalArgumentException("Allele can't applied to this Chromosome type. Expected: " + validTypes + " Got: " + chromosomeType); - // } - - alleles[chromosomeType.ordinal()] = allele; - } - - @Override - public & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, IAlleleValue value) { - set(alleles, chromosomeType, get(value)); - } - - @Override - public & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, boolean value) { - set(alleles, chromosomeType, get(value)); - } - - @Override - public & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, int value) { - set(alleles, chromosomeType, get(value)); - } - - private & IAlleleValue, V> void createAlleles(Class enumClass, IChromosomeType... types) { - String category = enumClass.getSimpleName().toLowerCase(Locale.ENGLISH); - EnumMap map = new EnumMap<>(enumClass); - for (K enumValue : enumClass.getEnumConstants()) { - IAllele allele = createAllele(category, enumValue, types); - map.put(enumValue, allele); - } - alleleMaps.put(enumClass, map); - } - - private static , V> IAllele createAllele(String category, K enumValue, IChromosomeType... types) { - V value = enumValue.getValue(); - boolean isDominant = enumValue.isDominant(); - String name = enumValue.toString().toLowerCase(Locale.ENGLISH); - - Class valueClass = value.getClass(); - if (Float.class.isAssignableFrom(valueClass)) { - return AlleleManager.alleleFactory.createFloat(modId, category, name, (Float) value, isDominant, types); - } else if (Integer.class.isAssignableFrom(valueClass)) { - return AlleleManager.alleleFactory.createInteger(modId, category, name, (Integer) value, isDominant, types); - } else if (IVect.class.isAssignableFrom(valueClass)) { - IVect area = (IVect) value; - return AlleleManager.alleleFactory.createArea(modId, category, name, area.getX(), area.getY(), area.getZ(), isDominant, types); - } else if (Boolean.class.isAssignableFrom(valueClass)) { - return AlleleManager.alleleFactory.createBoolean(modId, category, (Boolean) value, isDominant, types); - } else if (EnumTolerance.class.isAssignableFrom(valueClass)) { - IAlleleTolerance alleleTolerance = new AlleleTolerance(modId, category, name, (EnumTolerance) value, isDominant); - AlleleManager.alleleRegistry.registerAllele(alleleTolerance, types); - return alleleTolerance; - } else if (FlowerProvider.class.isAssignableFrom(valueClass)) { - return AlleleManager.alleleFactory.createFlowers(modId, category, name, (FlowerProvider) value, isDominant, types); - } - throw new RuntimeException("could not create allele for category: " + category + " and value " + valueClass); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.genetics.alleles; + +import forestry.api.apiculture.EnumBeeChromosome; +import forestry.api.arboriculture.EnumTreeChromosome; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.EnumTolerance; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IAlleleBoolean; +import forestry.api.genetics.IAlleleInteger; +import forestry.api.genetics.IAlleleTolerance; +import forestry.api.genetics.IChromosomeType; +import forestry.api.lepidopterology.EnumButterflyChromosome; +import forestry.apiculture.flowers.FlowerProvider; +import forestry.core.config.Constants; +import forestry.core.utils.vect.IVect; +import forestry.plugins.PluginManager; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +public class AlleleHelper implements IAlleleHelper { + + private static final String modId = Constants.ID; + public static AlleleHelper instance; + + private final Map> alleleMaps = new HashMap<>(); + + public void init() { + if (PluginManager.Module.APICULTURE.isEnabled()) { + createAlleles(EnumAllele.Fertility.class, EnumBeeChromosome.FERTILITY); + createAlleles(EnumAllele.Flowering.class, EnumBeeChromosome.FLOWERING); + } + + if (PluginManager.Module.APICULTURE.isEnabled() || PluginManager.Module.ARBORICULTURE.isEnabled()) { + createAlleles(EnumAllele.Territory.class, EnumBeeChromosome.TERRITORY, EnumTreeChromosome.TERRITORY); + + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.territoryDefault", get(EnumAllele.Territory.AVERAGE)); + } + + if (PluginManager.Module.APICULTURE.isEnabled() || PluginManager.Module.LEPIDOPTEROLOGY.isEnabled()) { + createAlleles(EnumAllele.Speed.class, EnumBeeChromosome.SPEED, EnumButterflyChromosome.SPEED); + createAlleles(EnumAllele.Lifespan.class, EnumBeeChromosome.LIFESPAN, EnumButterflyChromosome.LIFESPAN); + createAlleles( + EnumAllele.Tolerance.class, + EnumBeeChromosome.TEMPERATURE_TOLERANCE, + EnumBeeChromosome.HUMIDITY_TOLERANCE, + EnumButterflyChromosome.TEMPERATURE_TOLERANCE, + EnumButterflyChromosome.HUMIDITY_TOLERANCE); + createAlleles( + EnumAllele.Flowers.class, + EnumBeeChromosome.FLOWER_PROVIDER, + EnumButterflyChromosome.FLOWER_PROVIDER); + + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.speedNorm", get(EnumAllele.Speed.NORMAL)); + } + + if (PluginManager.Module.ARBORICULTURE.isEnabled()) { + createAlleles(EnumAllele.Height.class, EnumTreeChromosome.HEIGHT); + createAlleles(EnumAllele.Saplings.class, EnumTreeChromosome.FERTILITY); + createAlleles(EnumAllele.Yield.class, EnumTreeChromosome.YIELD); + createAlleles(EnumAllele.Fireproof.class, EnumTreeChromosome.FIREPROOF); + createAlleles(EnumAllele.Maturation.class, EnumTreeChromosome.MATURATION); + createAlleles(EnumAllele.Sappiness.class, EnumTreeChromosome.SAPPINESS); + + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.heightMax10", get(EnumAllele.Height.AVERAGE)); + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.saplingsDefault", get(EnumAllele.Saplings.AVERAGE)); + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.saplingsDouble", get(EnumAllele.Saplings.HIGH)); + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.saplingsTriple", get(EnumAllele.Saplings.HIGHER)); + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.yieldDefault", get(EnumAllele.Yield.AVERAGE)); + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.maturitySlowest", get(EnumAllele.Maturation.SLOWEST)); + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.maturitySlower", get(EnumAllele.Maturation.SLOWER)); + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.maturitySlow", get(EnumAllele.Maturation.SLOW)); + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.maturityAverage", get(EnumAllele.Maturation.AVERAGE)); + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.maturityFast", get(EnumAllele.Maturation.FAST)); + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.maturityFaster", get(EnumAllele.Maturation.FASTER)); + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.maturityFastest", get(EnumAllele.Maturation.FASTEST)); + } + + if (PluginManager.Module.LEPIDOPTEROLOGY.isEnabled()) { + createAlleles(EnumAllele.Size.class, EnumButterflyChromosome.SIZE); + } + + Map integers = new HashMap<>(); + for (int i = 1; i <= 10; i++) { + IAlleleInteger alleleInteger = new AlleleInteger(modId, "i", i + "d", i, true); + AlleleManager.alleleRegistry.registerAllele( + alleleInteger, + EnumTreeChromosome.GIRTH, + EnumButterflyChromosome.METABOLISM, + EnumButterflyChromosome.FERTILITY); + integers.put(i, alleleInteger); + } + alleleMaps.put(Integer.class, integers); + + Map booleans = new HashMap<>(); + booleans.put(true, new AlleleBoolean(modId, "bool", true, false)); + booleans.put(false, new AlleleBoolean(modId, "bool", false, false)); + for (IAlleleBoolean alleleBoolean : booleans.values()) { + AlleleManager.alleleRegistry.registerAllele( + alleleBoolean, + EnumBeeChromosome.NOCTURNAL, + EnumBeeChromosome.TOLERANT_FLYER, + EnumBeeChromosome.CAVE_DWELLING, + EnumButterflyChromosome.NOCTURNAL, + EnumButterflyChromosome.TOLERANT_FLYER, + EnumButterflyChromosome.FIRE_RESIST); + } + alleleMaps.put(Boolean.class, booleans); + } + + private IAllele get(Object value) { + Class valueClass = value.getClass(); + Map map = alleleMaps.get(valueClass); + if (map == null) { + throw new IllegalArgumentException("There is no IAllele type for: " + valueClass + ' ' + value); + } + IAllele allele = map.get(value); + if (allele == null) { + throw new IllegalArgumentException("There is no IAllele for: " + valueClass + ' ' + value); + } + + return allele; + } + + @Override + public & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, IAllele allele) { + if (allele == null) { + throw new NullPointerException("Allele must not be null"); + } + if (!chromosomeType.getAlleleClass().isInstance(allele)) { + throw new IllegalArgumentException( + "Allele is the wrong type. Expected: " + chromosomeType + " Got: " + allele); + } + + // uncomment this once all addon mods are using the allele registration with IChromosomeType + // Collection validTypes = AlleleManager.alleleRegistry.getChromosomeTypes(allele); + // if (validTypes.size() > 0 && !validTypes.contains(chromosomeType)) { + // throw new IllegalArgumentException("Allele can't applied to this Chromosome type. Expected: " + validTypes + // + " Got: " + chromosomeType); + // } + + alleles[chromosomeType.ordinal()] = allele; + } + + @Override + public & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, IAlleleValue value) { + set(alleles, chromosomeType, get(value)); + } + + @Override + public & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, boolean value) { + set(alleles, chromosomeType, get(value)); + } + + @Override + public & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, int value) { + set(alleles, chromosomeType, get(value)); + } + + private & IAlleleValue, V> void createAlleles(Class enumClass, IChromosomeType... types) { + String category = enumClass.getSimpleName().toLowerCase(Locale.ENGLISH); + EnumMap map = new EnumMap<>(enumClass); + for (K enumValue : enumClass.getEnumConstants()) { + IAllele allele = createAllele(category, enumValue, types); + map.put(enumValue, allele); + } + alleleMaps.put(enumClass, map); + } + + private static , V> IAllele createAllele( + String category, K enumValue, IChromosomeType... types) { + V value = enumValue.getValue(); + boolean isDominant = enumValue.isDominant(); + String name = enumValue.toString().toLowerCase(Locale.ENGLISH); + + Class valueClass = value.getClass(); + if (Float.class.isAssignableFrom(valueClass)) { + return AlleleManager.alleleFactory.createFloat(modId, category, name, (Float) value, isDominant, types); + } else if (Integer.class.isAssignableFrom(valueClass)) { + return AlleleManager.alleleFactory.createInteger(modId, category, name, (Integer) value, isDominant, types); + } else if (IVect.class.isAssignableFrom(valueClass)) { + IVect area = (IVect) value; + return AlleleManager.alleleFactory.createArea( + modId, category, name, area.getX(), area.getY(), area.getZ(), isDominant, types); + } else if (Boolean.class.isAssignableFrom(valueClass)) { + return AlleleManager.alleleFactory.createBoolean(modId, category, (Boolean) value, isDominant, types); + } else if (EnumTolerance.class.isAssignableFrom(valueClass)) { + IAlleleTolerance alleleTolerance = + new AlleleTolerance(modId, category, name, (EnumTolerance) value, isDominant); + AlleleManager.alleleRegistry.registerAllele(alleleTolerance, types); + return alleleTolerance; + } else if (FlowerProvider.class.isAssignableFrom(valueClass)) { + return AlleleManager.alleleFactory.createFlowers( + modId, category, name, (FlowerProvider) value, isDominant, types); + } + throw new RuntimeException("could not create allele for category: " + category + " and value " + valueClass); + } +} diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleInteger.java b/src/main/java/forestry/core/genetics/alleles/AlleleInteger.java index eb3fbaf9c..ca9989cdd 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleInteger.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleInteger.java @@ -14,15 +14,15 @@ import forestry.api.genetics.IAlleleInteger; public class AlleleInteger extends AlleleCategorized implements IAlleleInteger { - private final int value; + private final int value; - public AlleleInteger(String modId, String category, String name, int value, boolean isDominant) { - super(modId, category, name, isDominant); - this.value = value; - } + public AlleleInteger(String modId, String category, String name, int value, boolean isDominant) { + super(modId, category, name, isDominant); + this.value = value; + } - @Override - public int getValue() { - return value; - } + @Override + public int getValue() { + return value; + } } diff --git a/src/main/java/forestry/core/genetics/alleles/AllelePlantType.java b/src/main/java/forestry/core/genetics/alleles/AllelePlantType.java index 3d669e446..a41f0acc3 100644 --- a/src/main/java/forestry/core/genetics/alleles/AllelePlantType.java +++ b/src/main/java/forestry/core/genetics/alleles/AllelePlantType.java @@ -10,57 +10,54 @@ ******************************************************************************/ package forestry.core.genetics.alleles; +import forestry.api.arboriculture.EnumTreeChromosome; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllelePlantType; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Locale; - import net.minecraftforge.common.EnumPlantType; -import forestry.api.arboriculture.EnumTreeChromosome; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAllelePlantType; - public class AllelePlantType extends AlleleCategorized implements IAllelePlantType { - public static IAllelePlantType plantTypeNone; - public static IAllelePlantType plantTypePlains; - public static IAllelePlantType plantTypeDesert; - public static IAllelePlantType plantTypeBeach; - public static IAllelePlantType plantTypeCave; - public static IAllelePlantType plantTypeWater; - public static IAllelePlantType plantTypeNether; - public static IAllelePlantType plantTypeCrop; + public static IAllelePlantType plantTypeNone; + public static IAllelePlantType plantTypePlains; + public static IAllelePlantType plantTypeDesert; + public static IAllelePlantType plantTypeBeach; + public static IAllelePlantType plantTypeCave; + public static IAllelePlantType plantTypeWater; + public static IAllelePlantType plantTypeNether; + public static IAllelePlantType plantTypeCrop; - public static void createAlleles() { - List alleles = Arrays.asList( - plantTypeNone = new AllelePlantType("none", EnumSet.noneOf(EnumPlantType.class), true), - plantTypePlains = new AllelePlantType(EnumPlantType.Plains), - plantTypeDesert = new AllelePlantType(EnumPlantType.Desert), - plantTypeBeach = new AllelePlantType(EnumPlantType.Beach), - plantTypeCave = new AllelePlantType(EnumPlantType.Cave), - plantTypeWater = new AllelePlantType(EnumPlantType.Water), - plantTypeNether = new AllelePlantType(EnumPlantType.Nether), - plantTypeCrop = new AllelePlantType(EnumPlantType.Crop) - ); + public static void createAlleles() { + List alleles = Arrays.asList( + plantTypeNone = new AllelePlantType("none", EnumSet.noneOf(EnumPlantType.class), true), + plantTypePlains = new AllelePlantType(EnumPlantType.Plains), + plantTypeDesert = new AllelePlantType(EnumPlantType.Desert), + plantTypeBeach = new AllelePlantType(EnumPlantType.Beach), + plantTypeCave = new AllelePlantType(EnumPlantType.Cave), + plantTypeWater = new AllelePlantType(EnumPlantType.Water), + plantTypeNether = new AllelePlantType(EnumPlantType.Nether), + plantTypeCrop = new AllelePlantType(EnumPlantType.Crop)); - for (IAllelePlantType allele : alleles) { - AlleleManager.alleleRegistry.registerAllele(allele, EnumTreeChromosome.PLANT); - } - } + for (IAllelePlantType allele : alleles) { + AlleleManager.alleleRegistry.registerAllele(allele, EnumTreeChromosome.PLANT); + } + } - private final EnumSet types; + private final EnumSet types; - protected AllelePlantType(EnumPlantType type) { - this(type.toString().toLowerCase(Locale.ENGLISH), EnumSet.of(type), false); - } + protected AllelePlantType(EnumPlantType type) { + this(type.toString().toLowerCase(Locale.ENGLISH), EnumSet.of(type), false); + } - protected AllelePlantType(String name, EnumSet types, boolean isDominant) { - super("forestry", "plantType", name, isDominant); - this.types = types; - } + protected AllelePlantType(String name, EnumSet types, boolean isDominant) { + super("forestry", "plantType", name, isDominant); + this.types = types; + } - public EnumSet getPlantTypes() { - return types; - } + public EnumSet getPlantTypes() { + return types; + } } diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleRegistry.java b/src/main/java/forestry/core/genetics/alleles/AlleleRegistry.java index 832910d23..3c99c7a3b 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleRegistry.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleRegistry.java @@ -11,18 +11,7 @@ package forestry.core.genetics.alleles; import com.google.common.collect.HashMultimap; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; - -import net.minecraft.item.ItemStack; - import com.mojang.authlib.GameProfile; - import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleHandler; import forestry.api.genetics.IAlleleRegistry; @@ -37,262 +26,273 @@ import forestry.api.genetics.ISpeciesRoot; import forestry.core.genetics.Classification; import forestry.core.genetics.ItemResearchNote.EnumNoteType; import forestry.plugins.PluginCore; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import net.minecraft.item.ItemStack; public class AlleleRegistry implements IAlleleRegistry { - private static final int ALLELE_ARRAY_SIZE = 2048; + private static final int ALLELE_ARRAY_SIZE = 2048; - /* SPECIES ROOT */ - private final LinkedHashMap rootMap = new LinkedHashMap<>(16); + /* SPECIES ROOT */ + private final LinkedHashMap rootMap = new LinkedHashMap<>(16); - @Override - public void registerSpeciesRoot(ISpeciesRoot root) { - rootMap.put(root.getUID(), root); - } + @Override + public void registerSpeciesRoot(ISpeciesRoot root) { + rootMap.put(root.getUID(), root); + } - @Override - public Map getSpeciesRoot() { - return Collections.unmodifiableMap(rootMap); - } + @Override + public Map getSpeciesRoot() { + return Collections.unmodifiableMap(rootMap); + } - @Override - public ISpeciesRoot getSpeciesRoot(String uid) { - if (rootMap.containsKey(uid)) { - return rootMap.get(uid); - } - return null; - } + @Override + public ISpeciesRoot getSpeciesRoot(String uid) { + if (rootMap.containsKey(uid)) { + return rootMap.get(uid); + } + return null; + } - @Override - public ISpeciesRoot getSpeciesRoot(ItemStack stack) { - if (stack == null) { - return null; - } + @Override + public ISpeciesRoot getSpeciesRoot(ItemStack stack) { + if (stack == null) { + return null; + } - for (ISpeciesRoot root : rootMap.values()) { - if (root.isMember(stack)) { - return root; - } - } - return null; - } + for (ISpeciesRoot root : rootMap.values()) { + if (root.isMember(stack)) { + return root; + } + } + return null; + } - @Override - public ISpeciesRoot getSpeciesRoot(Class clz) { - for (ISpeciesRoot root : rootMap.values()) { - if (root.getMemberClass().isAssignableFrom(clz)) { - return root; - } - } - return null; - } + @Override + public ISpeciesRoot getSpeciesRoot(Class clz) { + for (ISpeciesRoot root : rootMap.values()) { + if (root.getMemberClass().isAssignableFrom(clz)) { + return root; + } + } + return null; + } - /* INDIVIDUALS */ - @Override - public boolean isIndividual(ItemStack stack) { - if (stack == null) { - return false; - } - return getSpeciesRoot(stack) != null; - } + /* INDIVIDUALS */ + @Override + public boolean isIndividual(ItemStack stack) { + if (stack == null) { + return false; + } + return getSpeciesRoot(stack) != null; + } - @Override - public IIndividual getIndividual(ItemStack stack) { - ISpeciesRoot root = getSpeciesRoot(stack); - if (root == null) { - return null; - } + @Override + public IIndividual getIndividual(ItemStack stack) { + ISpeciesRoot root = getSpeciesRoot(stack); + if (root == null) { + return null; + } - return root.getMember(stack); - } + return root.getMember(stack); + } - /* ALLELES */ - private final LinkedHashMap alleleMap = new LinkedHashMap<>(ALLELE_ARRAY_SIZE); - private final HashMultimap allelesByType = HashMultimap.create(); - private final HashMultimap typesByAllele = HashMultimap.create(); - private final LinkedHashMap deprecatedAlleleMap = new LinkedHashMap<>(32); - private final LinkedHashMap classificationMap = new LinkedHashMap<>(128); - private final LinkedHashMap fruitMap = new LinkedHashMap<>(64); + /* ALLELES */ + private final LinkedHashMap alleleMap = new LinkedHashMap<>(ALLELE_ARRAY_SIZE); + private final HashMultimap allelesByType = HashMultimap.create(); + private final HashMultimap typesByAllele = HashMultimap.create(); + private final LinkedHashMap deprecatedAlleleMap = new LinkedHashMap<>(32); + private final LinkedHashMap classificationMap = new LinkedHashMap<>(128); + private final LinkedHashMap fruitMap = new LinkedHashMap<>(64); - /* - * Internal HashSet of all alleleHandlers, which trigger when an allele or branch is registered - */ - private final HashSet alleleHandlers = new HashSet<>(); + /* + * Internal HashSet of all alleleHandlers, which trigger when an allele or branch is registered + */ + private final HashSet alleleHandlers = new HashSet<>(); - public void initialize() { + public void initialize() { - createAndRegisterClassification(EnumClassLevel.DOMAIN, "archaea", "Archaea"); - createAndRegisterClassification(EnumClassLevel.DOMAIN, "bacteria", "Bacteria"); - IClassification eukarya = createAndRegisterClassification(EnumClassLevel.DOMAIN, "eukarya", "Eukarya"); + createAndRegisterClassification(EnumClassLevel.DOMAIN, "archaea", "Archaea"); + createAndRegisterClassification(EnumClassLevel.DOMAIN, "bacteria", "Bacteria"); + IClassification eukarya = createAndRegisterClassification(EnumClassLevel.DOMAIN, "eukarya", "Eukarya"); - eukarya.addMemberGroup(createAndRegisterClassification(EnumClassLevel.KINGDOM, "animalia", "Animalia")); - eukarya.addMemberGroup(createAndRegisterClassification(EnumClassLevel.KINGDOM, "plantae", "Plantae")); - eukarya.addMemberGroup(createAndRegisterClassification(EnumClassLevel.KINGDOM, "fungi", "Fungi")); - eukarya.addMemberGroup(createAndRegisterClassification(EnumClassLevel.KINGDOM, "protista", "Protista")); + eukarya.addMemberGroup(createAndRegisterClassification(EnumClassLevel.KINGDOM, "animalia", "Animalia")); + eukarya.addMemberGroup(createAndRegisterClassification(EnumClassLevel.KINGDOM, "plantae", "Plantae")); + eukarya.addMemberGroup(createAndRegisterClassification(EnumClassLevel.KINGDOM, "fungi", "Fungi")); + eukarya.addMemberGroup(createAndRegisterClassification(EnumClassLevel.KINGDOM, "protista", "Protista")); - getClassification("kingdom.animalia").addMemberGroup(createAndRegisterClassification(EnumClassLevel.PHYLUM, "arthropoda", "Arthropoda")); + getClassification("kingdom.animalia") + .addMemberGroup(createAndRegisterClassification(EnumClassLevel.PHYLUM, "arthropoda", "Arthropoda")); - // Animalia - getClassification("phylum.arthropoda").addMemberGroup(createAndRegisterClassification(EnumClassLevel.CLASS, "insecta", "Insecta")); + // Animalia + getClassification("phylum.arthropoda") + .addMemberGroup(createAndRegisterClassification(EnumClassLevel.CLASS, "insecta", "Insecta")); + } - } + @Override + public Map getRegisteredAlleles() { + return Collections.unmodifiableMap(alleleMap); + } - @Override - public Map getRegisteredAlleles() { - return Collections.unmodifiableMap(alleleMap); - } + @Override + public Map getDeprecatedAlleleReplacements() { + return Collections.unmodifiableMap(deprecatedAlleleMap); + } - @Override - public Map getDeprecatedAlleleReplacements() { - return Collections.unmodifiableMap(deprecatedAlleleMap); - } + @Override + public void registerAllele(IAllele allele) { + alleleMap.put(allele.getUID(), allele); + if (allele instanceof IAlleleSpecies) { + IClassification branch = ((IAlleleSpecies) allele).getBranch(); + if (branch != null) { + branch.addMemberSpecies((IAlleleSpecies) allele); + } + } + for (IAlleleHandler handler : this.alleleHandlers) { + handler.onRegisterAllele(allele); + } + } - @Override - public void registerAllele(IAllele allele) { - alleleMap.put(allele.getUID(), allele); - if (allele instanceof IAlleleSpecies) { - IClassification branch = ((IAlleleSpecies) allele).getBranch(); - if (branch != null) { - branch.addMemberSpecies((IAlleleSpecies) allele); - } - } - for (IAlleleHandler handler : this.alleleHandlers) { - handler.onRegisterAllele(allele); - } - } + @Override + public void registerAllele(IAllele allele, IChromosomeType... chromosomeTypes) { + for (IChromosomeType chromosomeType : chromosomeTypes) { + if (!chromosomeType.getAlleleClass().isAssignableFrom(allele.getClass())) { + throw new IllegalArgumentException("Allele class (" + allele.getClass() + + ") does not match chromosome type (" + chromosomeType.getAlleleClass() + ")."); + } + allelesByType.put(chromosomeType, allele); + typesByAllele.put(allele, chromosomeType); + } + registerAllele(allele); + } - @Override - public void registerAllele(IAllele allele, IChromosomeType... chromosomeTypes) { - for (IChromosomeType chromosomeType : chromosomeTypes) { - if (!chromosomeType.getAlleleClass().isAssignableFrom(allele.getClass())) { - throw new IllegalArgumentException("Allele class (" + allele.getClass() + ") does not match chromosome type (" + chromosomeType.getAlleleClass() + ")."); - } - allelesByType.put(chromosomeType, allele); - typesByAllele.put(allele, chromosomeType); - } - registerAllele(allele); - } + @Override + public void registerDeprecatedAlleleReplacement(String deprecatedUID, IAllele replacementAllele) { + if (deprecatedAlleleMap.containsKey(deprecatedUID)) { + return; + } - @Override - public void registerDeprecatedAlleleReplacement(String deprecatedUID, IAllele replacementAllele) { - if (deprecatedAlleleMap.containsKey(deprecatedUID)) { - return; - } + deprecatedAlleleMap.put(deprecatedUID, replacementAllele); + } - deprecatedAlleleMap.put(deprecatedUID, replacementAllele); - } + @Override + public IAllele getAllele(String uid) { + IAllele allele = alleleMap.get(uid); - @Override - public IAllele getAllele(String uid) { - IAllele allele = alleleMap.get(uid); + if (allele == null) { + allele = deprecatedAlleleMap.get(uid); + } - if (allele == null) { - allele = deprecatedAlleleMap.get(uid); - } + return allele; + } - return allele; - } + @Override + public Collection getRegisteredAlleles(IChromosomeType type) { + return Collections.unmodifiableSet(allelesByType.get(type)); + } - @Override - public Collection getRegisteredAlleles(IChromosomeType type) { - return Collections.unmodifiableSet(allelesByType.get(type)); - } + // This method is not useful until all mod addon alleles are registered with their valid IChromosomeTypes + public Collection getChromosomeTypes(IAllele allele) { + return Collections.unmodifiableSet(typesByAllele.get(allele)); + } - // This method is not useful until all mod addon alleles are registered with their valid IChromosomeTypes - public Collection getChromosomeTypes(IAllele allele) { - return Collections.unmodifiableSet(typesByAllele.get(allele)); - } + /* CLASSIFICATIONS */ + @Override + public void registerClassification(IClassification branch) { - /* CLASSIFICATIONS */ - @Override - public void registerClassification(IClassification branch) { + if (classificationMap.containsKey(branch.getUID())) { + throw new RuntimeException(String.format( + "Could not add new classification '%s', because the key is already taken by %s.", + branch.getUID(), classificationMap.get(branch.getUID()))); + } - if (classificationMap.containsKey(branch.getUID())) { - throw new RuntimeException(String.format("Could not add new classification '%s', because the key is already taken by %s.", branch.getUID(), - classificationMap.get(branch.getUID()))); - } + classificationMap.put(branch.getUID(), branch); + for (IAlleleHandler handler : this.alleleHandlers) { + handler.onRegisterClassification(branch); + } + } - classificationMap.put(branch.getUID(), branch); - for (IAlleleHandler handler : this.alleleHandlers) { - handler.onRegisterClassification(branch); - } - } + @Override + public Map getRegisteredClassifications() { + return Collections.unmodifiableMap(classificationMap); + } - @Override - public Map getRegisteredClassifications() { - return Collections.unmodifiableMap(classificationMap); - } + @Override + public IClassification createAndRegisterClassification(EnumClassLevel level, String uid, String scientific) { + return new Classification(level, uid, scientific); + } - @Override - public IClassification createAndRegisterClassification(EnumClassLevel level, String uid, String scientific) { - return new Classification(level, uid, scientific); - } + @Override + public IClassification createAndRegisterClassification( + EnumClassLevel level, String uid, String scientific, IClassification... members) { + IClassification classification = new Classification(level, uid, scientific); + for (IClassification member : members) { + classification.addMemberGroup(member); + } + return classification; + } - @Override - public IClassification createAndRegisterClassification(EnumClassLevel level, String uid, String scientific, IClassification... members) { - IClassification classification = new Classification(level, uid, scientific); - for (IClassification member : members) { - classification.addMemberGroup(member); - } - return classification; - } + @Override + public IClassification getClassification(String uid) { + return classificationMap.get(uid); + } - @Override - public IClassification getClassification(String uid) { - return classificationMap.get(uid); - } + /* FRUIT FAMILIES */ + @Override + public void registerFruitFamily(IFruitFamily family) { + fruitMap.put(family.getUID(), family); + for (IAlleleHandler handler : this.alleleHandlers) { + handler.onRegisterFruitFamily(family); + } + } - /* FRUIT FAMILIES */ - @Override - public void registerFruitFamily(IFruitFamily family) { - fruitMap.put(family.getUID(), family); - for (IAlleleHandler handler : this.alleleHandlers) { - handler.onRegisterFruitFamily(family); - } - } + @Override + public Map getRegisteredFruitFamilies() { + return Collections.unmodifiableMap(fruitMap); + } - @Override - public Map getRegisteredFruitFamilies() { - return Collections.unmodifiableMap(fruitMap); - } + @Override + public IFruitFamily getFruitFamily(String uid) { + return fruitMap.get(uid); + } - @Override - public IFruitFamily getFruitFamily(String uid) { - return fruitMap.get(uid); - } + /* ALLELE HANDLERS */ + @Override + public void registerAlleleHandler(IAlleleHandler handler) { + this.alleleHandlers.add(handler); + } - /* ALLELE HANDLERS */ - @Override - public void registerAlleleHandler(IAlleleHandler handler) { - this.alleleHandlers.add(handler); - } + /* BLACKLIST */ + private final ArrayList blacklist = new ArrayList<>(); - /* BLACKLIST */ - private final ArrayList blacklist = new ArrayList<>(); + @Override + public void blacklistAllele(String uid) { + blacklist.add(uid); + } - @Override - public void blacklistAllele(String uid) { - blacklist.add(uid); - } + @Override + public Collection getAlleleBlacklist() { + return Collections.unmodifiableCollection(blacklist); + } - @Override - public Collection getAlleleBlacklist() { - return Collections.unmodifiableCollection(blacklist); - } + @Override + public boolean isBlacklisted(String uid) { + return blacklist.contains(uid); + } - @Override - public boolean isBlacklisted(String uid) { - return blacklist.contains(uid); - } + /* RESEARCH */ + @Override + public ItemStack getSpeciesNoteStack(GameProfile researcher, IAlleleSpecies species) { + return EnumNoteType.createSpeciesNoteStack(PluginCore.items.researchNote, researcher, species); + } - /* RESEARCH */ - @Override - public ItemStack getSpeciesNoteStack(GameProfile researcher, IAlleleSpecies species) { - return EnumNoteType.createSpeciesNoteStack(PluginCore.items.researchNote, researcher, species); - } - - @Override - public ItemStack getMutationNoteStack(GameProfile researcher, IMutation mutation) { - return EnumNoteType.createMutationNoteStack(PluginCore.items.researchNote, researcher, mutation); - } + @Override + public ItemStack getMutationNoteStack(GameProfile researcher, IMutation mutation) { + return EnumNoteType.createMutationNoteStack(PluginCore.items.researchNote, researcher, mutation); + } } diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleSpecies.java b/src/main/java/forestry/core/genetics/alleles/AlleleSpecies.java index 551ba2781..73e01c50e 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleSpecies.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleSpecies.java @@ -10,19 +10,9 @@ ******************************************************************************/ package forestry.core.genetics.alleles; -import java.util.Collection; -import java.util.Map; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.StatCollector; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; import forestry.api.core.IIconProvider; @@ -35,158 +25,173 @@ import forestry.apiculture.items.ItemRegistryApiculture; import forestry.core.utils.GeneticsUtil; import forestry.core.utils.ItemStackUtil; import forestry.plugins.PluginApiculture; +import java.util.Collection; +import java.util.Map; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.StatCollector; +import net.minecraft.world.World; public abstract class AlleleSpecies extends Allele implements IAlleleSpeciesCustom { - private final String binomial; - private final String authority; - private final String description; - private final IClassification branch; + private final String binomial; + private final String authority; + private final String description; + private final IClassification branch; - private boolean hasEffect = false; - private boolean isSecret = false; - private boolean isCounted = true; - private EnumTemperature climate = EnumTemperature.NORMAL; - private EnumHumidity humidity = EnumHumidity.NORMAL; + private boolean hasEffect = false; + private boolean isSecret = false; + private boolean isCounted = true; + private EnumTemperature climate = EnumTemperature.NORMAL; + private EnumHumidity humidity = EnumHumidity.NORMAL; - protected AlleleSpecies(String uid, String unlocalizedName, String authority, String unlocalizedDescription, boolean isDominant, IClassification branch, String binomial) { - super(uid, unlocalizedName, isDominant); + protected AlleleSpecies( + String uid, + String unlocalizedName, + String authority, + String unlocalizedDescription, + boolean isDominant, + IClassification branch, + String binomial) { + super(uid, unlocalizedName, isDominant); - this.branch = branch; - this.binomial = binomial; - this.description = StatCollector.translateToLocal(unlocalizedDescription); - this.authority = authority; - } + this.branch = branch; + this.binomial = binomial; + this.description = StatCollector.translateToLocal(unlocalizedDescription); + this.authority = authority; + } - @Override - public String getDescription() { - return description; - } + @Override + public String getDescription() { + return description; + } - @Override - public float getResearchSuitability(ItemStack itemstack) { - if (itemstack == null) { - return 0f; - } + @Override + public float getResearchSuitability(ItemStack itemstack) { + if (itemstack == null) { + return 0f; + } - ItemRegistryApiculture beeItems = PluginApiculture.items; - if (beeItems != null) { - Item item = itemstack.getItem(); - if (beeItems.honeyDrop == item) { - return 0.5f; - } else if (beeItems.honeydew == item) { - return 0.7f; - } else if (beeItems.beeComb == item) { - return 0.4f; - } - } + ItemRegistryApiculture beeItems = PluginApiculture.items; + if (beeItems != null) { + Item item = itemstack.getItem(); + if (beeItems.honeyDrop == item) { + return 0.5f; + } else if (beeItems.honeydew == item) { + return 0.7f; + } else if (beeItems.beeComb == item) { + return 0.4f; + } + } - if (getRoot().isMember(itemstack)) { - return 1.0f; - } + if (getRoot().isMember(itemstack)) { + return 1.0f; + } - for (Map.Entry entry : getRoot().getResearchCatalysts().entrySet()) { - if (ItemStackUtil.isIdenticalItem(entry.getKey(), itemstack)) { - return entry.getValue(); - } - } + for (Map.Entry entry : + getRoot().getResearchCatalysts().entrySet()) { + if (ItemStackUtil.isIdenticalItem(entry.getKey(), itemstack)) { + return entry.getValue(); + } + } - return 0f; - } + return 0f; + } - @Override - public int getComplexity() { - return GeneticsUtil.getResearchComplexity(this, getRoot().getKaryotypeKey()); - } + @Override + public int getComplexity() { + return GeneticsUtil.getResearchComplexity(this, getRoot().getKaryotypeKey()); + } - @Override - public ItemStack[] getResearchBounty(World world, GameProfile researcher, IIndividual individual, int bountyLevel) { - ItemStack research = null; - if (world.rand.nextFloat() < ((float) 10 / bountyLevel)) { - Collection combinations = getRoot().getCombinations(this); - if (combinations.size() > 0) { - IMutation[] candidates = combinations.toArray(new IMutation[combinations.size()]); - research = AlleleManager.alleleRegistry.getMutationNoteStack(researcher, candidates[world.rand.nextInt(candidates.length)]); - } - } + @Override + public ItemStack[] getResearchBounty(World world, GameProfile researcher, IIndividual individual, int bountyLevel) { + ItemStack research = null; + if (world.rand.nextFloat() < ((float) 10 / bountyLevel)) { + Collection combinations = getRoot().getCombinations(this); + if (combinations.size() > 0) { + IMutation[] candidates = combinations.toArray(new IMutation[combinations.size()]); + research = AlleleManager.alleleRegistry.getMutationNoteStack( + researcher, candidates[world.rand.nextInt(candidates.length)]); + } + } - if (research != null) { - return new ItemStack[]{research}; - } else { - return ItemStackUtil.EMPTY_STACK_ARRAY; - } - } + if (research != null) { + return new ItemStack[] {research}; + } else { + return ItemStackUtil.EMPTY_STACK_ARRAY; + } + } - @Override - public EnumTemperature getTemperature() { - return climate; - } + @Override + public EnumTemperature getTemperature() { + return climate; + } - @Override - public EnumHumidity getHumidity() { - return humidity; - } + @Override + public EnumHumidity getHumidity() { + return humidity; + } - @Override - public boolean hasEffect() { - return hasEffect; - } + @Override + public boolean hasEffect() { + return hasEffect; + } - @Override - public boolean isSecret() { - return isSecret; - } + @Override + public boolean isSecret() { + return isSecret; + } - @Override - public boolean isCounted() { - return isCounted; - } + @Override + public boolean isCounted() { + return isCounted; + } - @Override - public String getBinomial() { - return binomial; - } + @Override + public String getBinomial() { + return binomial; + } - @Override - public String getAuthority() { - return authority; - } + @Override + public String getAuthority() { + return authority; + } - @Override - public IClassification getBranch() { - return this.branch; - } + @Override + public IClassification getBranch() { + return this.branch; + } - @Override - public IAlleleSpeciesCustom setTemperature(EnumTemperature temperature) { - climate = temperature; - return this; - } + @Override + public IAlleleSpeciesCustom setTemperature(EnumTemperature temperature) { + climate = temperature; + return this; + } - @Override - public IAlleleSpeciesCustom setHumidity(EnumHumidity humidity) { - this.humidity = humidity; - return this; - } + @Override + public IAlleleSpeciesCustom setHumidity(EnumHumidity humidity) { + this.humidity = humidity; + return this; + } - @Override - public IAlleleSpeciesCustom setHasEffect() { - hasEffect = true; - return this; - } + @Override + public IAlleleSpeciesCustom setHasEffect() { + hasEffect = true; + return this; + } - @Override - public IAlleleSpeciesCustom setIsSecret() { - isSecret = true; - return this; - } + @Override + public IAlleleSpeciesCustom setIsSecret() { + isSecret = true; + return this; + } - @Override - public IAlleleSpeciesCustom setIsNotCounted() { - isCounted = false; - return this; - } + @Override + public IAlleleSpeciesCustom setIsNotCounted() { + isCounted = false; + return this; + } - @Override - @SideOnly(Side.CLIENT) - public abstract IIconProvider getIconProvider(); + @Override + @SideOnly(Side.CLIENT) + public abstract IIconProvider getIconProvider(); } diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleTolerance.java b/src/main/java/forestry/core/genetics/alleles/AlleleTolerance.java index 0614a48de..089c4372b 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleTolerance.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleTolerance.java @@ -15,14 +15,14 @@ import forestry.api.genetics.IAlleleTolerance; public class AlleleTolerance extends AlleleCategorized implements IAlleleTolerance { - private final EnumTolerance value; + private final EnumTolerance value; - public AlleleTolerance(String modId, String category, String name, EnumTolerance value, boolean isDominant) { - super(modId, category, name, isDominant); - this.value = value; - } + public AlleleTolerance(String modId, String category, String name, EnumTolerance value, boolean isDominant) { + super(modId, category, name, isDominant); + this.value = value; + } - public EnumTolerance getValue() { - return value; - } + public EnumTolerance getValue() { + return value; + } } diff --git a/src/main/java/forestry/core/genetics/alleles/EnumAllele.java b/src/main/java/forestry/core/genetics/alleles/EnumAllele.java index 709f22483..8186bb19f 100644 --- a/src/main/java/forestry/core/genetics/alleles/EnumAllele.java +++ b/src/main/java/forestry/core/genetics/alleles/EnumAllele.java @@ -1,457 +1,468 @@ -package forestry.core.genetics.alleles; - -import java.util.Locale; - -import forestry.api.apiculture.FlowerManager; -import forestry.api.genetics.EnumTolerance; -import forestry.apiculture.flowers.FlowerProvider; -import forestry.core.utils.vect.IVect; -import forestry.core.utils.vect.Vect; - -public class EnumAllele { - public enum Fertility implements IAlleleValue { - LOW(1, true), - NORMAL(2, true), - HIGH(3), - MAXIMUM(4); - - private final Integer value; - private final boolean dominant; - - Fertility(Integer value) { - this(value, false); - } - - Fertility(Integer value, boolean dominant) { - this.value = value; - this.dominant = dominant; - } - - @Override - public Integer getValue() { - return value; - } - - @Override - public boolean isDominant() { - return dominant; - } - } - - public enum Fireproof implements IAlleleValue { - TRUE(true), - FALSE(false); - - private final boolean value; - private final boolean dominant; - - Fireproof(boolean value) { - this(value, false); - } - - Fireproof(boolean value, boolean dominant) { - this.value = value; - this.dominant = dominant; - } - - @Override - public boolean isDominant() { - return dominant; - } - - @Override - public Boolean getValue() { - return value; - } - } - - public enum Flowering implements IAlleleValue { - SLOWEST(5, true), - SLOWER(10), - SLOW(15), - AVERAGE(20), - FAST(25), - FASTER(30), - FASTEST(35), - MAXIMUM(99, true); - - private final Integer value; - private final boolean dominant; - - Flowering(Integer value) { - this(value, false); - } - - Flowering(Integer value, boolean dominant) { - this.value = value; - this.dominant = dominant; - } - - @Override - public Integer getValue() { - return value; - } - - @Override - public boolean isDominant() { - return dominant; - } - } - - public enum Flowers implements IAlleleValue { - VANILLA(FlowerManager.FlowerTypeVanilla, true), - NETHER(FlowerManager.FlowerTypeNether), - CACTI(FlowerManager.FlowerTypeCacti), - MUSHROOMS(FlowerManager.FlowerTypeMushrooms), - END(FlowerManager.FlowerTypeEnd), - JUNGLE(FlowerManager.FlowerTypeJungle), - SNOW(FlowerManager.FlowerTypeSnow, true), - WHEAT(FlowerManager.FlowerTypeWheat, true), - GOURD(FlowerManager.FlowerTypeGourd, true); - - private final FlowerProvider value; - private final boolean dominant; - - Flowers(String flowerType) { - this(flowerType, false); - } - - Flowers(String flowerType, boolean dominant) { - String lowercaseName = toString().toLowerCase(Locale.ENGLISH); - this.value = new FlowerProvider(flowerType, "flowers." + lowercaseName); - this.dominant = dominant; - } - - @Override - public FlowerProvider getValue() { - return value; - } - - @Override - public boolean isDominant() { - return dominant; - } - } - - public enum Height implements IAlleleValue { - SMALLEST(0.25f), - SMALLER(0.5f), - SMALL(0.75f), - AVERAGE(1.0f), - LARGE(1.25f), - LARGER(1.5f), - LARGEST(1.75f), - GIGANTIC(2.0f); - - private final float value; - private final boolean dominant; - - Height(float value) { - this(value, false); - } - - Height(float value, boolean dominant) { - this.value = value; - this.dominant = dominant; - } - - @Override - public Float getValue() { - return value; - } - - @Override - public boolean isDominant() { - return dominant; - } - } - - public enum Lifespan implements IAlleleValue { - SHORTEST(10), - SHORTER(20, true), - SHORT(30, true), - SHORTENED(35, true), - NORMAL(40), - ELONGATED(45, true), - LONG(50), - LONGER(60), - LONGEST(70); - - private final Integer value; - private final boolean dominant; - - Lifespan(Integer value) { - this(value, false); - } - - Lifespan(Integer value, boolean dominant) { - this.value = value; - this.dominant = dominant; - } - - @Override - public Integer getValue() { - return value; - } - - @Override - public boolean isDominant() { - return dominant; - } - } - - public enum Maturation implements IAlleleValue { - SLOWEST(10, true), - SLOWER(7), - SLOW(5, true), - AVERAGE(4), - FAST(3), - FASTER(2), - FASTEST(1); - - private final Integer value; - private final boolean dominant; - - Maturation(Integer value) { - this(value, false); - } - - Maturation(Integer value, boolean dominant) { - this.value = value; - this.dominant = dominant; - } - - @Override - public Integer getValue() { - return value; - } - - @Override - public boolean isDominant() { - return dominant; - } - } - - public enum Saplings implements IAlleleValue { - LOWEST(0.01f, true), - LOWER(0.025f, true), - LOW(0.035f, true), - AVERAGE(0.05f, true), - HIGH(0.1f, true), - HIGHER(0.2f, true), - HIGHEST(0.3f, true); - - private final float value; - private final boolean dominant; - - Saplings(float value) { - this(value, false); - } - - Saplings(float value, boolean dominant) { - this.value = value; - this.dominant = dominant; - } - - @Override - public Float getValue() { - return value; - } - - @Override - public boolean isDominant() { - return dominant; - } - } - - public enum Sappiness implements IAlleleValue { - LOWEST(0.1f, true), - LOWER(0.2f, true), - LOW(0.3f, true), - AVERAGE(0.4f, true), - HIGH(0.6f, true), - HIGHER(0.8f), - HIGHEST(1.0f); - - private final Float value; - private final boolean dominant; - - Sappiness(Float value) { - this(value, false); - } - - Sappiness(Float value, boolean dominant) { - this.value = value; - this.dominant = dominant; - } - - @Override - public Float getValue() { - return value; - } - - @Override - public boolean isDominant() { - return dominant; - } - } - - public enum Size implements IAlleleValue { - SMALLEST(0.3f), - SMALLER(0.4f), - SMALL(0.5f), - AVERAGE(0.6f), - LARGE(0.75f), - LARGER(0.9f), - LARGEST(1.0f); - - private final float value; - private final boolean dominant; - - Size(float value) { - this(value, false); - } - - Size(float value, boolean dominant) { - this.value = value; - this.dominant = dominant; - } - - @Override - public Float getValue() { - return value; - } - - @Override - public boolean isDominant() { - return dominant; - } - } - - public enum Speed implements IAlleleValue { - SLOWEST(0.3f, true), - SLOWER(0.6f, true), - SLOW(0.8f, true), - NORMAL(1.0f), - FAST(1.2f, true), - FASTER(1.4f), - FASTEST(1.7f); - - private final float value; - private final boolean dominant; - - Speed(float value) { - this(value, false); - } - - Speed(float value, boolean dominant) { - this.value = value; - this.dominant = dominant; - } - - @Override - public Float getValue() { - return value; - } - - @Override - public boolean isDominant() { - return dominant; - } - } - - public enum Territory implements IAlleleValue { - AVERAGE(9, 6, 9), - LARGE(11, 8, 11), - LARGER(13, 12, 13), - LARGEST(15, 13, 15); - - private final IVect area; - private final boolean dominant; - - Territory(int x, int y, int z) { - this(x, y, z, false); - } - - Territory(int x, int y, int z, boolean dominant) { - this.area = new Vect(x, y, z); - this.dominant = dominant; - } - - @Override - public IVect getValue() { - return area; - } - - @Override - public boolean isDominant() { - return dominant; - } - } - - public enum Tolerance implements IAlleleValue { - NONE, - BOTH_1(true), BOTH_2, BOTH_3, BOTH_4, BOTH_5, - UP_1(true), UP_2, UP_3, UP_4, UP_5, - DOWN_1(true), DOWN_2, DOWN_3, DOWN_4, DOWN_5; - - private final EnumTolerance value; - private final boolean dominant; - - Tolerance() { - this(false); - } - - Tolerance(boolean dominant) { - this.value = EnumTolerance.values()[ordinal()]; - this.dominant = dominant; - } - - @Override - public String toString() { - return super.toString().replace("_", ""); - } - - @Override - public EnumTolerance getValue() { - return value; - } - - @Override - public boolean isDominant() { - return dominant; - } - } - - public enum Yield implements IAlleleValue { - LOWEST(0.025f, true), - LOWER(0.05f, true), - LOW(0.1f, true), - AVERAGE(0.2f, true), - HIGH(0.3f), - HIGHER(0.35f), - HIGHEST(0.4f); - - private final float value; - private final boolean dominant; - - Yield(float value) { - this(value, false); - } - - Yield(float value, boolean dominant) { - this.value = value; - this.dominant = dominant; - } - - @Override - public Float getValue() { - return value; - } - - @Override - public boolean isDominant() { - return dominant; - } - } -} +package forestry.core.genetics.alleles; + +import forestry.api.apiculture.FlowerManager; +import forestry.api.genetics.EnumTolerance; +import forestry.apiculture.flowers.FlowerProvider; +import forestry.core.utils.vect.IVect; +import forestry.core.utils.vect.Vect; +import java.util.Locale; + +public class EnumAllele { + public enum Fertility implements IAlleleValue { + LOW(1, true), + NORMAL(2, true), + HIGH(3), + MAXIMUM(4); + + private final Integer value; + private final boolean dominant; + + Fertility(Integer value) { + this(value, false); + } + + Fertility(Integer value, boolean dominant) { + this.value = value; + this.dominant = dominant; + } + + @Override + public Integer getValue() { + return value; + } + + @Override + public boolean isDominant() { + return dominant; + } + } + + public enum Fireproof implements IAlleleValue { + TRUE(true), + FALSE(false); + + private final boolean value; + private final boolean dominant; + + Fireproof(boolean value) { + this(value, false); + } + + Fireproof(boolean value, boolean dominant) { + this.value = value; + this.dominant = dominant; + } + + @Override + public boolean isDominant() { + return dominant; + } + + @Override + public Boolean getValue() { + return value; + } + } + + public enum Flowering implements IAlleleValue { + SLOWEST(5, true), + SLOWER(10), + SLOW(15), + AVERAGE(20), + FAST(25), + FASTER(30), + FASTEST(35), + MAXIMUM(99, true); + + private final Integer value; + private final boolean dominant; + + Flowering(Integer value) { + this(value, false); + } + + Flowering(Integer value, boolean dominant) { + this.value = value; + this.dominant = dominant; + } + + @Override + public Integer getValue() { + return value; + } + + @Override + public boolean isDominant() { + return dominant; + } + } + + public enum Flowers implements IAlleleValue { + VANILLA(FlowerManager.FlowerTypeVanilla, true), + NETHER(FlowerManager.FlowerTypeNether), + CACTI(FlowerManager.FlowerTypeCacti), + MUSHROOMS(FlowerManager.FlowerTypeMushrooms), + END(FlowerManager.FlowerTypeEnd), + JUNGLE(FlowerManager.FlowerTypeJungle), + SNOW(FlowerManager.FlowerTypeSnow, true), + WHEAT(FlowerManager.FlowerTypeWheat, true), + GOURD(FlowerManager.FlowerTypeGourd, true); + + private final FlowerProvider value; + private final boolean dominant; + + Flowers(String flowerType) { + this(flowerType, false); + } + + Flowers(String flowerType, boolean dominant) { + String lowercaseName = toString().toLowerCase(Locale.ENGLISH); + this.value = new FlowerProvider(flowerType, "flowers." + lowercaseName); + this.dominant = dominant; + } + + @Override + public FlowerProvider getValue() { + return value; + } + + @Override + public boolean isDominant() { + return dominant; + } + } + + public enum Height implements IAlleleValue { + SMALLEST(0.25f), + SMALLER(0.5f), + SMALL(0.75f), + AVERAGE(1.0f), + LARGE(1.25f), + LARGER(1.5f), + LARGEST(1.75f), + GIGANTIC(2.0f); + + private final float value; + private final boolean dominant; + + Height(float value) { + this(value, false); + } + + Height(float value, boolean dominant) { + this.value = value; + this.dominant = dominant; + } + + @Override + public Float getValue() { + return value; + } + + @Override + public boolean isDominant() { + return dominant; + } + } + + public enum Lifespan implements IAlleleValue { + SHORTEST(10), + SHORTER(20, true), + SHORT(30, true), + SHORTENED(35, true), + NORMAL(40), + ELONGATED(45, true), + LONG(50), + LONGER(60), + LONGEST(70); + + private final Integer value; + private final boolean dominant; + + Lifespan(Integer value) { + this(value, false); + } + + Lifespan(Integer value, boolean dominant) { + this.value = value; + this.dominant = dominant; + } + + @Override + public Integer getValue() { + return value; + } + + @Override + public boolean isDominant() { + return dominant; + } + } + + public enum Maturation implements IAlleleValue { + SLOWEST(10, true), + SLOWER(7), + SLOW(5, true), + AVERAGE(4), + FAST(3), + FASTER(2), + FASTEST(1); + + private final Integer value; + private final boolean dominant; + + Maturation(Integer value) { + this(value, false); + } + + Maturation(Integer value, boolean dominant) { + this.value = value; + this.dominant = dominant; + } + + @Override + public Integer getValue() { + return value; + } + + @Override + public boolean isDominant() { + return dominant; + } + } + + public enum Saplings implements IAlleleValue { + LOWEST(0.01f, true), + LOWER(0.025f, true), + LOW(0.035f, true), + AVERAGE(0.05f, true), + HIGH(0.1f, true), + HIGHER(0.2f, true), + HIGHEST(0.3f, true); + + private final float value; + private final boolean dominant; + + Saplings(float value) { + this(value, false); + } + + Saplings(float value, boolean dominant) { + this.value = value; + this.dominant = dominant; + } + + @Override + public Float getValue() { + return value; + } + + @Override + public boolean isDominant() { + return dominant; + } + } + + public enum Sappiness implements IAlleleValue { + LOWEST(0.1f, true), + LOWER(0.2f, true), + LOW(0.3f, true), + AVERAGE(0.4f, true), + HIGH(0.6f, true), + HIGHER(0.8f), + HIGHEST(1.0f); + + private final Float value; + private final boolean dominant; + + Sappiness(Float value) { + this(value, false); + } + + Sappiness(Float value, boolean dominant) { + this.value = value; + this.dominant = dominant; + } + + @Override + public Float getValue() { + return value; + } + + @Override + public boolean isDominant() { + return dominant; + } + } + + public enum Size implements IAlleleValue { + SMALLEST(0.3f), + SMALLER(0.4f), + SMALL(0.5f), + AVERAGE(0.6f), + LARGE(0.75f), + LARGER(0.9f), + LARGEST(1.0f); + + private final float value; + private final boolean dominant; + + Size(float value) { + this(value, false); + } + + Size(float value, boolean dominant) { + this.value = value; + this.dominant = dominant; + } + + @Override + public Float getValue() { + return value; + } + + @Override + public boolean isDominant() { + return dominant; + } + } + + public enum Speed implements IAlleleValue { + SLOWEST(0.3f, true), + SLOWER(0.6f, true), + SLOW(0.8f, true), + NORMAL(1.0f), + FAST(1.2f, true), + FASTER(1.4f), + FASTEST(1.7f); + + private final float value; + private final boolean dominant; + + Speed(float value) { + this(value, false); + } + + Speed(float value, boolean dominant) { + this.value = value; + this.dominant = dominant; + } + + @Override + public Float getValue() { + return value; + } + + @Override + public boolean isDominant() { + return dominant; + } + } + + public enum Territory implements IAlleleValue { + AVERAGE(9, 6, 9), + LARGE(11, 8, 11), + LARGER(13, 12, 13), + LARGEST(15, 13, 15); + + private final IVect area; + private final boolean dominant; + + Territory(int x, int y, int z) { + this(x, y, z, false); + } + + Territory(int x, int y, int z, boolean dominant) { + this.area = new Vect(x, y, z); + this.dominant = dominant; + } + + @Override + public IVect getValue() { + return area; + } + + @Override + public boolean isDominant() { + return dominant; + } + } + + public enum Tolerance implements IAlleleValue { + NONE, + BOTH_1(true), + BOTH_2, + BOTH_3, + BOTH_4, + BOTH_5, + UP_1(true), + UP_2, + UP_3, + UP_4, + UP_5, + DOWN_1(true), + DOWN_2, + DOWN_3, + DOWN_4, + DOWN_5; + + private final EnumTolerance value; + private final boolean dominant; + + Tolerance() { + this(false); + } + + Tolerance(boolean dominant) { + this.value = EnumTolerance.values()[ordinal()]; + this.dominant = dominant; + } + + @Override + public String toString() { + return super.toString().replace("_", ""); + } + + @Override + public EnumTolerance getValue() { + return value; + } + + @Override + public boolean isDominant() { + return dominant; + } + } + + public enum Yield implements IAlleleValue { + LOWEST(0.025f, true), + LOWER(0.05f, true), + LOW(0.1f, true), + AVERAGE(0.2f, true), + HIGH(0.3f), + HIGHER(0.35f), + HIGHEST(0.4f); + + private final float value; + private final boolean dominant; + + Yield(float value) { + this(value, false); + } + + Yield(float value, boolean dominant) { + this.value = value; + this.dominant = dominant; + } + + @Override + public Float getValue() { + return value; + } + + @Override + public boolean isDominant() { + return dominant; + } + } +} diff --git a/src/main/java/forestry/core/genetics/alleles/IAlleleHelper.java b/src/main/java/forestry/core/genetics/alleles/IAlleleHelper.java index a1047e04b..4f149a2ff 100644 --- a/src/main/java/forestry/core/genetics/alleles/IAlleleHelper.java +++ b/src/main/java/forestry/core/genetics/alleles/IAlleleHelper.java @@ -1,26 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.genetics.alleles; - -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IChromosomeType; - -public interface IAlleleHelper { - - & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, IAllele allele); - - & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, IAlleleValue value); - - & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, boolean value); - - & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, int value); - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.genetics.alleles; + +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IChromosomeType; + +public interface IAlleleHelper { + + & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, IAllele allele); + + & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, IAlleleValue value); + + & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, boolean value); + + & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, int value); +} diff --git a/src/main/java/forestry/core/genetics/alleles/IAlleleValue.java b/src/main/java/forestry/core/genetics/alleles/IAlleleValue.java index 119b08be4..b7596f17f 100644 --- a/src/main/java/forestry/core/genetics/alleles/IAlleleValue.java +++ b/src/main/java/forestry/core/genetics/alleles/IAlleleValue.java @@ -1,7 +1,7 @@ -package forestry.core.genetics.alleles; - -public interface IAlleleValue { - boolean isDominant(); - - V getValue(); -} +package forestry.core.genetics.alleles; + +public interface IAlleleValue { + boolean isDominant(); + + V getValue(); +} diff --git a/src/main/java/forestry/core/genetics/mutations/EnumMutateChance.java b/src/main/java/forestry/core/genetics/mutations/EnumMutateChance.java index 4ab285610..c23df6a89 100644 --- a/src/main/java/forestry/core/genetics/mutations/EnumMutateChance.java +++ b/src/main/java/forestry/core/genetics/mutations/EnumMutateChance.java @@ -11,29 +11,34 @@ package forestry.core.genetics.mutations; public enum EnumMutateChance { - NONE(0xffffff), LOWEST(0xffba77), LOW(0xfffd77), NORMAL(0xfffd77), HIGH(0xfffd77), HIGHER(0xbeff77), HIGHEST(0x7bff77); + NONE(0xffffff), + LOWEST(0xffba77), + LOW(0xfffd77), + NORMAL(0xfffd77), + HIGH(0xfffd77), + HIGHER(0xbeff77), + HIGHEST(0x7bff77); - public final int colour; - - EnumMutateChance(int colour) { - this.colour = colour; - } - - public static EnumMutateChance rateChance(float percent) { + public final int colour; - if (percent >= 20) { - return HIGHEST; - } else if (percent >= 15) { - return HIGHER; - } else if (percent >= 12) { - return HIGH; - } else if (percent >= 10) { - return NORMAL; - } else if (percent >= 5) { - return LOW; - } else { - return LOWEST; - } + EnumMutateChance(int colour) { + this.colour = colour; + } - } + public static EnumMutateChance rateChance(float percent) { + + if (percent >= 20) { + return HIGHEST; + } else if (percent >= 15) { + return HIGHER; + } else if (percent >= 12) { + return HIGH; + } else if (percent >= 10) { + return NORMAL; + } else if (percent >= 5) { + return LOW; + } else { + return LOWEST; + } + } } diff --git a/src/main/java/forestry/core/genetics/mutations/Mutation.java b/src/main/java/forestry/core/genetics/mutations/Mutation.java index 9a39c938c..2a218a7d6 100644 --- a/src/main/java/forestry/core/genetics/mutations/Mutation.java +++ b/src/main/java/forestry/core/genetics/mutations/Mutation.java @@ -10,15 +10,6 @@ ******************************************************************************/ package forestry.core.genetics.mutations; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.world.World; - -import net.minecraftforge.common.BiomeDictionary; - import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; import forestry.api.core.IClimateProvider; @@ -27,152 +18,166 @@ import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IGenome; import forestry.api.genetics.IMutationCondition; import forestry.api.genetics.IMutationCustom; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.world.World; +import net.minecraftforge.common.BiomeDictionary; public abstract class Mutation implements IMutationCustom { - private final int chance; + private final int chance; - private final IAlleleSpecies species0; - private final IAlleleSpecies species1; + private final IAlleleSpecies species0; + private final IAlleleSpecies species1; - private final IAllele[] template; + private final IAllele[] template; - private final List mutationConditions = new ArrayList<>(); - private final List specialConditions = new ArrayList<>(); + private final List mutationConditions = new ArrayList<>(); + private final List specialConditions = new ArrayList<>(); - private boolean isSecret = false; + private boolean isSecret = false; - protected Mutation(IAlleleSpecies species0, IAlleleSpecies species1, IAllele[] template, int chance) { - this.species0 = species0; - this.species1 = species1; - this.template = template; - this.chance = chance; - } + protected Mutation(IAlleleSpecies species0, IAlleleSpecies species1, IAllele[] template, int chance) { + this.species0 = species0; + this.species1 = species1; + this.template = template; + this.chance = chance; + } - @Override - public Collection getSpecialConditions() { - return specialConditions; - } + @Override + public Collection getSpecialConditions() { + return specialConditions; + } - @Override - public Mutation setIsSecret() { - isSecret = true; - return this; - } + @Override + public Mutation setIsSecret() { + isSecret = true; + return this; + } - @Override - public Mutation restrictTemperature(EnumTemperature temperature) { - return restrictTemperature(temperature, temperature); - } + @Override + public Mutation restrictTemperature(EnumTemperature temperature) { + return restrictTemperature(temperature, temperature); + } - @Override - public Mutation restrictTemperature(EnumTemperature minTemperature, EnumTemperature maxTemperature) { - IMutationCondition mutationCondition = new MutationConditionTemperature(minTemperature, maxTemperature); - return addMutationCondition(mutationCondition); - } + @Override + public Mutation restrictTemperature(EnumTemperature minTemperature, EnumTemperature maxTemperature) { + IMutationCondition mutationCondition = new MutationConditionTemperature(minTemperature, maxTemperature); + return addMutationCondition(mutationCondition); + } - @Override - public Mutation restrictHumidity(EnumHumidity humidity) { - return restrictHumidity(humidity, humidity); - } + @Override + public Mutation restrictHumidity(EnumHumidity humidity) { + return restrictHumidity(humidity, humidity); + } - @Override - public Mutation restrictHumidity(EnumHumidity minHumidity, EnumHumidity maxHumidity) { - IMutationCondition mutationCondition = new MutationConditionHumidity(minHumidity, maxHumidity); - return addMutationCondition(mutationCondition); - } + @Override + public Mutation restrictHumidity(EnumHumidity minHumidity, EnumHumidity maxHumidity) { + IMutationCondition mutationCondition = new MutationConditionHumidity(minHumidity, maxHumidity); + return addMutationCondition(mutationCondition); + } - @Override - public Mutation restrictBiomeType(BiomeDictionary.Type... types) { - IMutationCondition mutationCondition = new MutationConditionBiome(types); - return addMutationCondition(mutationCondition); - } + @Override + public Mutation restrictBiomeType(BiomeDictionary.Type... types) { + IMutationCondition mutationCondition = new MutationConditionBiome(types); + return addMutationCondition(mutationCondition); + } - @Override - public Mutation requireDay() { - IMutationCondition mutationCondition = new MutationConditionDaytime(true); - return addMutationCondition(mutationCondition); - } + @Override + public Mutation requireDay() { + IMutationCondition mutationCondition = new MutationConditionDaytime(true); + return addMutationCondition(mutationCondition); + } - @Override - public Mutation requireNight() { - IMutationCondition mutationCondition = new MutationConditionDaytime(false); - return addMutationCondition(mutationCondition); - } + @Override + public Mutation requireNight() { + IMutationCondition mutationCondition = new MutationConditionDaytime(false); + return addMutationCondition(mutationCondition); + } - @Override - public Mutation restrictDateRange(int startMonth, int startDay, int endMonth, int endDay) { - IMutationCondition mutationCondition = new MutationConditionTimeLimited(startMonth, startDay, endMonth, endDay); - return addMutationCondition(mutationCondition); - } + @Override + public Mutation restrictDateRange(int startMonth, int startDay, int endMonth, int endDay) { + IMutationCondition mutationCondition = new MutationConditionTimeLimited(startMonth, startDay, endMonth, endDay); + return addMutationCondition(mutationCondition); + } - @Override - public Mutation requireResource(Block block, int meta) { - IMutationCondition mutationCondition = new MutationConditionRequiresResource(block, meta); - return addMutationCondition(mutationCondition); - } + @Override + public Mutation requireResource(Block block, int meta) { + IMutationCondition mutationCondition = new MutationConditionRequiresResource(block, meta); + return addMutationCondition(mutationCondition); + } - @Override - public Mutation requireResource(String oreName) { - IMutationCondition mutationCondition = new MutationConditionRequiresResourceOreDict(oreName); - return addMutationCondition(mutationCondition); - } + @Override + public Mutation requireResource(String oreName) { + IMutationCondition mutationCondition = new MutationConditionRequiresResourceOreDict(oreName); + return addMutationCondition(mutationCondition); + } - @Override - public Mutation addMutationCondition(IMutationCondition mutationCondition) { - mutationConditions.add(mutationCondition); - specialConditions.add(mutationCondition.getDescription()); - return this; - } + @Override + public Mutation addMutationCondition(IMutationCondition mutationCondition) { + mutationConditions.add(mutationCondition); + specialConditions.add(mutationCondition.getDescription()); + return this; + } - protected float getChance(World world, int x, int y, int z, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1, IClimateProvider climate) { - float mutationChance = chance; - for (IMutationCondition mutationCondition : mutationConditions) { - mutationChance *= mutationCondition.getChance(world, x, y, z, allele0, allele1, genome0, genome1, climate); - if (mutationChance == 0) { - return 0; - } - } - return mutationChance; - } + protected float getChance( + World world, + int x, + int y, + int z, + IAllele allele0, + IAllele allele1, + IGenome genome0, + IGenome genome1, + IClimateProvider climate) { + float mutationChance = chance; + for (IMutationCondition mutationCondition : mutationConditions) { + mutationChance *= mutationCondition.getChance(world, x, y, z, allele0, allele1, genome0, genome1, climate); + if (mutationChance == 0) { + return 0; + } + } + return mutationChance; + } - @Override - public IAlleleSpecies getAllele0() { - return species0; - } + @Override + public IAlleleSpecies getAllele0() { + return species0; + } - @Override - public IAlleleSpecies getAllele1() { - return species1; - } + @Override + public IAlleleSpecies getAllele1() { + return species1; + } - @Override - public float getBaseChance() { - return chance; - } + @Override + public float getBaseChance() { + return chance; + } - @Override - public IAllele[] getTemplate() { - return template; - } + @Override + public IAllele[] getTemplate() { + return template; + } - @Override - public boolean isPartner(IAllele allele) { - return species0.getUID().equals(allele.getUID()) || species1.getUID().equals(allele.getUID()); - } + @Override + public boolean isPartner(IAllele allele) { + return species0.getUID().equals(allele.getUID()) || species1.getUID().equals(allele.getUID()); + } - @Override - public IAllele getPartner(IAllele allele) { - if (species0.getUID().equals(allele.getUID())) { - return species1; - } else { - return species0; - } - } - - @Override - public boolean isSecret() { - return isSecret; - } + @Override + public IAllele getPartner(IAllele allele) { + if (species0.getUID().equals(allele.getUID())) { + return species1; + } else { + return species0; + } + } + @Override + public boolean isSecret() { + return isSecret; + } } diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionBiome.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionBiome.java index 0ebbd57e3..7a5599ba0 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionBiome.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionBiome.java @@ -1,58 +1,64 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.genetics.mutations; - -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - -import net.minecraftforge.common.BiomeDictionary; - -import forestry.api.core.IClimateProvider; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IGenome; -import forestry.api.genetics.IMutationCondition; -import forestry.core.utils.StringUtil; - -public class MutationConditionBiome implements IMutationCondition { - - private final List validBiomeTypes; - - public MutationConditionBiome(BiomeDictionary.Type... types) { - this.validBiomeTypes = Arrays.asList(types); - } - - @Override - public float getChance(World world, int x, int y, int z, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1, IClimateProvider climate) { - BiomeGenBase biome = climate.getBiome(); - for (BiomeDictionary.Type type : validBiomeTypes) { - if (BiomeDictionary.isBiomeOfType(biome, type)) { - return 1; - } - } - - return 0; - } - - @Override - public String getDescription() { - if (validBiomeTypes.size() > 1) { - String biomeTypes = Arrays.toString(validBiomeTypes.toArray()).toLowerCase(Locale.ENGLISH); - return StringUtil.localizeAndFormat("mutation.condition.biome.multiple", biomeTypes); - } else { - String biomeType = validBiomeTypes.get(0).toString().toLowerCase(Locale.ENGLISH); - return StringUtil.localizeAndFormat("mutation.condition.biome.single", biomeType); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.genetics.mutations; + +import forestry.api.core.IClimateProvider; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IGenome; +import forestry.api.genetics.IMutationCondition; +import forestry.core.utils.StringUtil; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; +import net.minecraftforge.common.BiomeDictionary; + +public class MutationConditionBiome implements IMutationCondition { + + private final List validBiomeTypes; + + public MutationConditionBiome(BiomeDictionary.Type... types) { + this.validBiomeTypes = Arrays.asList(types); + } + + @Override + public float getChance( + World world, + int x, + int y, + int z, + IAllele allele0, + IAllele allele1, + IGenome genome0, + IGenome genome1, + IClimateProvider climate) { + BiomeGenBase biome = climate.getBiome(); + for (BiomeDictionary.Type type : validBiomeTypes) { + if (BiomeDictionary.isBiomeOfType(biome, type)) { + return 1; + } + } + + return 0; + } + + @Override + public String getDescription() { + if (validBiomeTypes.size() > 1) { + String biomeTypes = Arrays.toString(validBiomeTypes.toArray()).toLowerCase(Locale.ENGLISH); + return StringUtil.localizeAndFormat("mutation.condition.biome.multiple", biomeTypes); + } else { + String biomeType = validBiomeTypes.get(0).toString().toLowerCase(Locale.ENGLISH); + return StringUtil.localizeAndFormat("mutation.condition.biome.single", biomeType); + } + } +} diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionDaytime.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionDaytime.java index b1bead23b..8f4e6362b 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionDaytime.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionDaytime.java @@ -1,45 +1,53 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.genetics.mutations; - -import net.minecraft.world.World; - -import forestry.api.core.IClimateProvider; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IGenome; -import forestry.api.genetics.IMutationCondition; -import forestry.core.utils.StringUtil; - -public class MutationConditionDaytime implements IMutationCondition { - - private final boolean daytime; - - public MutationConditionDaytime(boolean daytime) { - this.daytime = daytime; - } - - @Override - public float getChance(World world, int x, int y, int z, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1, IClimateProvider climate) { - if (world.isDaytime() == daytime) { - return 1; - } - return 0; - } - - @Override - public String getDescription() { - if (daytime) { - return StringUtil.localize("mutation.condition.daytime.day"); - } else { - return StringUtil.localize("mutation.condition.daytime.night"); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.genetics.mutations; + +import forestry.api.core.IClimateProvider; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IGenome; +import forestry.api.genetics.IMutationCondition; +import forestry.core.utils.StringUtil; +import net.minecraft.world.World; + +public class MutationConditionDaytime implements IMutationCondition { + + private final boolean daytime; + + public MutationConditionDaytime(boolean daytime) { + this.daytime = daytime; + } + + @Override + public float getChance( + World world, + int x, + int y, + int z, + IAllele allele0, + IAllele allele1, + IGenome genome0, + IGenome genome1, + IClimateProvider climate) { + if (world.isDaytime() == daytime) { + return 1; + } + return 0; + } + + @Override + public String getDescription() { + if (daytime) { + return StringUtil.localize("mutation.condition.daytime.day"); + } else { + return StringUtil.localize("mutation.condition.daytime.night"); + } + } +} diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionHumidity.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionHumidity.java index e321e78b4..c9bcf969e 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionHumidity.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionHumidity.java @@ -1,53 +1,63 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.genetics.mutations; - -import net.minecraft.world.World; - -import forestry.api.core.EnumHumidity; -import forestry.api.core.IClimateProvider; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IGenome; -import forestry.api.genetics.IMutationCondition; -import forestry.core.utils.StringUtil; - -public class MutationConditionHumidity implements IMutationCondition { - private final EnumHumidity minHumidity; - private final EnumHumidity maxHumidity; - - public MutationConditionHumidity(EnumHumidity minHumidity, EnumHumidity maxHumidity) { - this.minHumidity = minHumidity; - this.maxHumidity = maxHumidity; - } - - @Override - public float getChance(World world, int x, int y, int z, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1, IClimateProvider climate) { - EnumHumidity biomeHumidity = climate.getHumidity(); - - if (biomeHumidity.ordinal() < minHumidity.ordinal() || biomeHumidity.ordinal() > maxHumidity.ordinal()) { - return 0; - } - return 1; - } - - @Override - public String getDescription() { - String minHumidityString = AlleleManager.climateHelper.toDisplay(minHumidity); - - if (minHumidity != maxHumidity) { - String maxHumidityString = AlleleManager.climateHelper.toDisplay(maxHumidity); - return StringUtil.localize("mutation.condition.humidity.range").replace("%LOW", minHumidityString).replace("%HIGH", maxHumidityString); - } else { - return StringUtil.localizeAndFormat("mutation.condition.humidity.single", minHumidityString); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.genetics.mutations; + +import forestry.api.core.EnumHumidity; +import forestry.api.core.IClimateProvider; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IGenome; +import forestry.api.genetics.IMutationCondition; +import forestry.core.utils.StringUtil; +import net.minecraft.world.World; + +public class MutationConditionHumidity implements IMutationCondition { + private final EnumHumidity minHumidity; + private final EnumHumidity maxHumidity; + + public MutationConditionHumidity(EnumHumidity minHumidity, EnumHumidity maxHumidity) { + this.minHumidity = minHumidity; + this.maxHumidity = maxHumidity; + } + + @Override + public float getChance( + World world, + int x, + int y, + int z, + IAllele allele0, + IAllele allele1, + IGenome genome0, + IGenome genome1, + IClimateProvider climate) { + EnumHumidity biomeHumidity = climate.getHumidity(); + + if (biomeHumidity.ordinal() < minHumidity.ordinal() || biomeHumidity.ordinal() > maxHumidity.ordinal()) { + return 0; + } + return 1; + } + + @Override + public String getDescription() { + String minHumidityString = AlleleManager.climateHelper.toDisplay(minHumidity); + + if (minHumidity != maxHumidity) { + String maxHumidityString = AlleleManager.climateHelper.toDisplay(maxHumidity); + return StringUtil.localize("mutation.condition.humidity.range") + .replace("%LOW", minHumidityString) + .replace("%HIGH", maxHumidityString); + } else { + return StringUtil.localizeAndFormat("mutation.condition.humidity.single", minHumidityString); + } + } +} diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionRequiresResource.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionRequiresResource.java index a96ceb411..72cc73045 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionRequiresResource.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionRequiresResource.java @@ -1,65 +1,71 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.genetics.mutations; - -import forestry.api.apiculture.IBeeHousing; -import forestry.api.core.IClimateProvider; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IGenome; -import forestry.api.genetics.IMutationCondition; -import forestry.core.utils.BlockUtil; -import forestry.core.utils.InventoryUtil; -import forestry.core.utils.ItemStackUtil; -import forestry.core.utils.StringUtil; - -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; - -//import forestry.core.utils.ItemStackUtil; - -public class MutationConditionRequiresResource implements IMutationCondition { - - private final ItemStack blockRequired; - - public MutationConditionRequiresResource(Block block, int meta) { - blockRequired = new ItemStack(block, 1, meta); - } - - @Override - public float getChance(World world, int x, int y, int z, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1, IClimateProvider climate) { -/* - Block block; - TileEntity tile; - int meta; - int i = 1; - do { - block = world.getBlock(x, y - i, z); - meta = world.getBlockMetadata(x, y - i, z); - tile = world.getTileEntity(x, y - i, z); - i++; - } while (tile instanceof IBeeHousing); - - return ItemStackUtil.equals(block, meta, blockRequired) ? 1 : 0; -*/ - ItemStack stk = BlockUtil.getItemStackFromBlockBelow(world, x, y, z, - (TileEntity tile) -> (tile instanceof IBeeHousing) - ); - - return InventoryUtil.isItemEqual(blockRequired, stk, true, true) ? 1 : 0; - } - - @Override - public String getDescription() { - return StringUtil.localizeAndFormat("mutation.condition.resource", blockRequired.getDisplayName()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.genetics.mutations; + +import forestry.api.apiculture.IBeeHousing; +import forestry.api.core.IClimateProvider; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IGenome; +import forestry.api.genetics.IMutationCondition; +import forestry.core.utils.BlockUtil; +import forestry.core.utils.InventoryUtil; +import forestry.core.utils.StringUtil; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; + +// import forestry.core.utils.ItemStackUtil; + +public class MutationConditionRequiresResource implements IMutationCondition { + + private final ItemStack blockRequired; + + public MutationConditionRequiresResource(Block block, int meta) { + blockRequired = new ItemStack(block, 1, meta); + } + + @Override + public float getChance( + World world, + int x, + int y, + int z, + IAllele allele0, + IAllele allele1, + IGenome genome0, + IGenome genome1, + IClimateProvider climate) { + /* + Block block; + TileEntity tile; + int meta; + int i = 1; + do { + block = world.getBlock(x, y - i, z); + meta = world.getBlockMetadata(x, y - i, z); + tile = world.getTileEntity(x, y - i, z); + i++; + } while (tile instanceof IBeeHousing); + + return ItemStackUtil.equals(block, meta, blockRequired) ? 1 : 0; + */ + ItemStack stk = BlockUtil.getItemStackFromBlockBelow( + world, x, y, z, (TileEntity tile) -> (tile instanceof IBeeHousing)); + + return InventoryUtil.isItemEqual(blockRequired, stk, true, true) ? 1 : 0; + } + + @Override + public String getDescription() { + return StringUtil.localizeAndFormat("mutation.condition.resource", blockRequired.getDisplayName()); + } +} diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionRequiresResourceOreDict.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionRequiresResourceOreDict.java index 137dcc66c..57bb31fb2 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionRequiresResourceOreDict.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionRequiresResourceOreDict.java @@ -1,73 +1,76 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.genetics.mutations; - -import forestry.api.apiculture.IBeeHousing; -import forestry.api.core.IClimateProvider; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IGenome; -import forestry.api.genetics.IMutationCondition; -import forestry.core.utils.BlockUtil; -import forestry.core.utils.StringUtil; - -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraftforge.oredict.OreDictionary; - -import java.util.ArrayList; - -public class MutationConditionRequiresResourceOreDict implements IMutationCondition { - - private final int oreDictId; - private final String displayName; - - public MutationConditionRequiresResourceOreDict(String oreDictName) { - this.oreDictId = OreDictionary.getOreID(oreDictName); - - ArrayList ores = OreDictionary.getOres(oreDictName); - if (ores != null && 0 < ores.size()) { - this.displayName = ores.get(0).getDisplayName(); - } else { - this.displayName = oreDictName; - } - } - - @Override - public float getChance(World world, int x, int y, int z, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1, IClimateProvider climate) { -/* - Block block; - int meta; - TileEntity tile; - int i = 1; - do { - block = world.getBlock(x, y - i, z); - meta = world.getBlockMetadata(x, y - i, z); - tile = world.getTileEntity(x, y-i, z); - i++; - } while (tile instanceof IBeeHousing); -*/ - ItemStack stk = BlockUtil.getItemStackFromBlockBelow(world, x, y, z, - (TileEntity tile) -> (tile instanceof IBeeHousing) - ); - int[] oreIds = OreDictionary.getOreIDs(stk); - for (int oreId : oreIds) - if (oreId == this.oreDictId) - return 1f; - return 0f; - } - - @Override - public String getDescription() { - return StringUtil.localizeAndFormat("mutation.condition.resource", displayName); - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.genetics.mutations; + +import forestry.api.apiculture.IBeeHousing; +import forestry.api.core.IClimateProvider; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IGenome; +import forestry.api.genetics.IMutationCondition; +import forestry.core.utils.BlockUtil; +import forestry.core.utils.StringUtil; +import java.util.ArrayList; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.oredict.OreDictionary; + +public class MutationConditionRequiresResourceOreDict implements IMutationCondition { + + private final int oreDictId; + private final String displayName; + + public MutationConditionRequiresResourceOreDict(String oreDictName) { + this.oreDictId = OreDictionary.getOreID(oreDictName); + + ArrayList ores = OreDictionary.getOres(oreDictName); + if (ores != null && 0 < ores.size()) { + this.displayName = ores.get(0).getDisplayName(); + } else { + this.displayName = oreDictName; + } + } + + @Override + public float getChance( + World world, + int x, + int y, + int z, + IAllele allele0, + IAllele allele1, + IGenome genome0, + IGenome genome1, + IClimateProvider climate) { + /* + Block block; + int meta; + TileEntity tile; + int i = 1; + do { + block = world.getBlock(x, y - i, z); + meta = world.getBlockMetadata(x, y - i, z); + tile = world.getTileEntity(x, y-i, z); + i++; + } while (tile instanceof IBeeHousing); + */ + ItemStack stk = BlockUtil.getItemStackFromBlockBelow( + world, x, y, z, (TileEntity tile) -> (tile instanceof IBeeHousing)); + int[] oreIds = OreDictionary.getOreIDs(stk); + for (int oreId : oreIds) if (oreId == this.oreDictId) return 1f; + return 0f; + } + + @Override + public String getDescription() { + return StringUtil.localizeAndFormat("mutation.condition.resource", displayName); + } +} diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionTemperature.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionTemperature.java index f15307a99..581386efb 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionTemperature.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionTemperature.java @@ -1,54 +1,65 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.genetics.mutations; - -import net.minecraft.world.World; - -import forestry.api.core.EnumTemperature; -import forestry.api.core.IClimateProvider; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IGenome; -import forestry.api.genetics.IMutationCondition; -import forestry.core.utils.StringUtil; - -public class MutationConditionTemperature implements IMutationCondition { - - private final EnumTemperature minTemperature; - private final EnumTemperature maxTemperature; - - public MutationConditionTemperature(EnumTemperature minTemperature, EnumTemperature maxTemperature) { - this.minTemperature = minTemperature; - this.maxTemperature = maxTemperature; - } - - @Override - public float getChance(World world, int x, int y, int z, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1, IClimateProvider climate) { - EnumTemperature biomeTemperature = climate.getTemperature(); - - if (biomeTemperature.ordinal() < minTemperature.ordinal() || biomeTemperature.ordinal() > maxTemperature.ordinal()) { - return 0; - } - return 1; - } - - @Override - public String getDescription() { - String minString = AlleleManager.climateHelper.toDisplay(minTemperature); - - if (minTemperature != maxTemperature) { - String maxString = AlleleManager.climateHelper.toDisplay(maxTemperature); - return StringUtil.localize("mutation.condition.temperature.range").replace("%LOW", minString).replace("%HIGH", maxString); - } else { - return StringUtil.localizeAndFormat("mutation.condition.temperature.single", minString); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.genetics.mutations; + +import forestry.api.core.EnumTemperature; +import forestry.api.core.IClimateProvider; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IGenome; +import forestry.api.genetics.IMutationCondition; +import forestry.core.utils.StringUtil; +import net.minecraft.world.World; + +public class MutationConditionTemperature implements IMutationCondition { + + private final EnumTemperature minTemperature; + private final EnumTemperature maxTemperature; + + public MutationConditionTemperature(EnumTemperature minTemperature, EnumTemperature maxTemperature) { + this.minTemperature = minTemperature; + this.maxTemperature = maxTemperature; + } + + @Override + public float getChance( + World world, + int x, + int y, + int z, + IAllele allele0, + IAllele allele1, + IGenome genome0, + IGenome genome1, + IClimateProvider climate) { + EnumTemperature biomeTemperature = climate.getTemperature(); + + if (biomeTemperature.ordinal() < minTemperature.ordinal() + || biomeTemperature.ordinal() > maxTemperature.ordinal()) { + return 0; + } + return 1; + } + + @Override + public String getDescription() { + String minString = AlleleManager.climateHelper.toDisplay(minTemperature); + + if (minTemperature != maxTemperature) { + String maxString = AlleleManager.climateHelper.toDisplay(maxTemperature); + return StringUtil.localize("mutation.condition.temperature.range") + .replace("%LOW", minString) + .replace("%HIGH", maxString); + } else { + return StringUtil.localizeAndFormat("mutation.condition.temperature.single", minString); + } + } +} diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionTimeLimited.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionTimeLimited.java index 72ff8cc44..3658302d0 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionTimeLimited.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionTimeLimited.java @@ -10,52 +10,63 @@ ******************************************************************************/ package forestry.core.genetics.mutations; -import java.util.Calendar; - -import net.minecraft.world.World; - import forestry.api.core.IClimateProvider; import forestry.api.genetics.IAllele; import forestry.api.genetics.IGenome; import forestry.api.genetics.IMutationCondition; import forestry.core.utils.DayMonth; import forestry.core.utils.StringUtil; +import java.util.Calendar; +import net.minecraft.world.World; public class MutationConditionTimeLimited implements IMutationCondition { - private final DayMonth start; - private final DayMonth end; + private final DayMonth start; + private final DayMonth end; - public MutationConditionTimeLimited(int startMonth, int startDay, int endMonth, int endDay) { - this.start = new DayMonth(startDay, startMonth); - this.end = new DayMonth(endDay, endMonth); - } + public MutationConditionTimeLimited(int startMonth, int startDay, int endMonth, int endDay) { + this.start = new DayMonth(startDay, startMonth); + this.end = new DayMonth(endDay, endMonth); + } - @Override - public float getChance(World world, int x, int y, int z, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1, IClimateProvider climate) { - DayMonth now = new DayMonth(); + @Override + public float getChance( + World world, + int x, + int y, + int z, + IAllele allele0, + IAllele allele1, + IGenome genome0, + IGenome genome1, + IClimateProvider climate) { + DayMonth now = new DayMonth(); - // If we are equal to start day, return 1. - if (Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == start.day && Calendar.getInstance().get(Calendar.MONTH) + 1 == start.month) { - return 1; - } + // If we are equal to start day, return 1. + if (Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == start.day + && Calendar.getInstance().get(Calendar.MONTH) + 1 == start.month) { + return 1; + } - // Equal to end date, return 1 - if (Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == end.day && Calendar.getInstance().get(Calendar.MONTH) + 1 == end.month) { - return 1; - } + // Equal to end date, return 1 + if (Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == end.day + && Calendar.getInstance().get(Calendar.MONTH) + 1 == end.month) { + return 1; + } - // Still a chance we are in between - if (now.between(start, end)) { - return 1; - } + // Still a chance we are in between + if (now.between(start, end)) { + return 1; + } - // Now we finally failed. - return 0; - } + // Now we finally failed. + return 0; + } - @Override - public String getDescription() { - return StringUtil.localize("mutation.condition.date").replace("%START", start.toString()).replace("%END", end.toString()); - } + @Override + public String getDescription() { + return StringUtil.localize("mutation.condition.date") + .replace("%START", start.toString()) + .replace("%END", end.toString()); + } } diff --git a/src/main/java/forestry/core/gui/ContainerAlyzer.java b/src/main/java/forestry/core/gui/ContainerAlyzer.java index 5abd5dcfe..5c724e39b 100644 --- a/src/main/java/forestry/core/gui/ContainerAlyzer.java +++ b/src/main/java/forestry/core/gui/ContainerAlyzer.java @@ -1,25 +1,24 @@ package forestry.core.gui; -import net.minecraft.entity.player.EntityPlayer; - import forestry.core.gui.slots.SlotFiltered; import forestry.core.inventory.ItemInventoryAlyzer; +import net.minecraft.entity.player.EntityPlayer; public class ContainerAlyzer extends ContainerItemInventory { - public ContainerAlyzer(ItemInventoryAlyzer inventory, EntityPlayer player) { - super(inventory, player.inventory, 43, 156); + public ContainerAlyzer(ItemInventoryAlyzer inventory, EntityPlayer player) { + super(inventory, player.inventory, 43, 156); - final int xPosLeftSlots = 223; + final int xPosLeftSlots = 223; - addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ENERGY, xPosLeftSlots, 8)); + addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ENERGY, xPosLeftSlots, 8)); - addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_SPECIMEN, xPosLeftSlots, 26)); + addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_SPECIMEN, xPosLeftSlots, 26)); - addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_1, xPosLeftSlots, 57)); - addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_2, xPosLeftSlots, 75)); - addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_3, xPosLeftSlots, 93)); - addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_4, xPosLeftSlots, 111)); - addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_5, xPosLeftSlots, 129)); - } + addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_1, xPosLeftSlots, 57)); + addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_2, xPosLeftSlots, 75)); + addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_3, xPosLeftSlots, 93)); + addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_4, xPosLeftSlots, 111)); + addSlotToContainer(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_5, xPosLeftSlots, 129)); + } } diff --git a/src/main/java/forestry/core/gui/ContainerAnalyzer.java b/src/main/java/forestry/core/gui/ContainerAnalyzer.java index cc942d58c..b29d6599f 100755 --- a/src/main/java/forestry/core/gui/ContainerAnalyzer.java +++ b/src/main/java/forestry/core/gui/ContainerAnalyzer.java @@ -10,37 +10,38 @@ ******************************************************************************/ package forestry.core.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.core.gui.slots.SlotWorking; import forestry.core.inventory.InventoryAnalyzer; import forestry.core.tiles.TileAnalyzer; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerAnalyzer extends ContainerLiquidTanks { - public ContainerAnalyzer(InventoryPlayer player, TileAnalyzer tile) { - super(tile, player, 8, 94); + public ContainerAnalyzer(InventoryPlayer player, TileAnalyzer tile) { + super(tile, player, 8, 94); - // Input buffer - for (int i = 0; i < 3; i++) { - for (int k = 0; k < 2; k++) { - addSlotToContainer(new SlotFiltered(tile, InventoryAnalyzer.SLOT_INPUT_1 + i * 2 + k, 8 + k * 18, 28 + i * 18)); - } - } + // Input buffer + for (int i = 0; i < 3; i++) { + for (int k = 0; k < 2; k++) { + addSlotToContainer( + new SlotFiltered(tile, InventoryAnalyzer.SLOT_INPUT_1 + i * 2 + k, 8 + k * 18, 28 + i * 18)); + } + } - // Analyze slot - addSlotToContainer(new SlotWorking(tile, InventoryAnalyzer.SLOT_ANALYZE, 73, 59)); + // Analyze slot + addSlotToContainer(new SlotWorking(tile, InventoryAnalyzer.SLOT_ANALYZE, 73, 59)); - // Can slot - addSlotToContainer(new SlotFiltered(tile, InventoryAnalyzer.SLOT_CAN, 143, 24)); + // Can slot + addSlotToContainer(new SlotFiltered(tile, InventoryAnalyzer.SLOT_CAN, 143, 24)); - // Output buffer - for (int i = 0; i < 2; i++) { - for (int k = 0; k < 2; k++) { - addSlotToContainer(new SlotOutput(tile, InventoryAnalyzer.SLOT_OUTPUT_1 + i * 2 + k, 134 + k * 18, 48 + i * 18)); - } - } - } + // Output buffer + for (int i = 0; i < 2; i++) { + for (int k = 0; k < 2; k++) { + addSlotToContainer( + new SlotOutput(tile, InventoryAnalyzer.SLOT_OUTPUT_1 + i * 2 + k, 134 + k * 18, 48 + i * 18)); + } + } + } } diff --git a/src/main/java/forestry/core/gui/ContainerDummy.java b/src/main/java/forestry/core/gui/ContainerDummy.java index 30d0d191a..4460509bd 100755 --- a/src/main/java/forestry/core/gui/ContainerDummy.java +++ b/src/main/java/forestry/core/gui/ContainerDummy.java @@ -14,15 +14,12 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; public class ContainerDummy extends Container { - public static final ContainerDummy instance = new ContainerDummy(); + public static final ContainerDummy instance = new ContainerDummy(); - private ContainerDummy() { - - } - - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - return true; - } + private ContainerDummy() {} + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return true; + } } diff --git a/src/main/java/forestry/core/gui/ContainerEntity.java b/src/main/java/forestry/core/gui/ContainerEntity.java index 5b35582d5..94f562adb 100644 --- a/src/main/java/forestry/core/gui/ContainerEntity.java +++ b/src/main/java/forestry/core/gui/ContainerEntity.java @@ -1,90 +1,89 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -import com.google.common.collect.ImmutableSet; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IInventory; - -import forestry.api.core.IErrorLogicSource; -import forestry.api.core.IErrorState; -import forestry.core.access.EnumAccess; -import forestry.core.access.FakeAccessHandler; -import forestry.core.access.IAccessHandler; -import forestry.core.access.IRestrictedAccess; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.packets.PacketAccessUpdateEntity; -import forestry.core.network.packets.PacketErrorUpdateEntity; - -public class ContainerEntity extends ContainerForestry { - protected final T entity; - private final IAccessHandler accessHandler; - - protected ContainerEntity(T entity) { - this.entity = entity; - - if (entity instanceof IRestrictedAccess) { - accessHandler = ((IRestrictedAccess) entity).getAccessHandler(); - } else { - accessHandler = FakeAccessHandler.getInstance(); - } - } - - protected ContainerEntity(T entity, InventoryPlayer playerInventory, int xInv, int yInv) { - this(entity); - addPlayerInventory(playerInventory, xInv, yInv); - } - - @Override - protected final boolean canAccess(EntityPlayer player) { - return player != null && accessHandler.allowsAlteration(player); - } - - @Override - public final boolean canInteractWith(EntityPlayer entityplayer) { - return entity.isUseableByPlayer(entityplayer) && accessHandler.allowsViewing(entityplayer); - } - - private ImmutableSet previousErrorStates; - private EnumAccess previousAccess; - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - if (entity instanceof IErrorLogicSource) { - IErrorLogicSource errorLogicSource = (IErrorLogicSource) entity; - ImmutableSet errorStates = errorLogicSource.getErrorLogic().getErrorStates(); - - if ((previousErrorStates == null) || !errorStates.equals(previousErrorStates)) { - PacketErrorUpdateEntity packet = new PacketErrorUpdateEntity(entity, errorLogicSource); - sendPacketToCrafters(packet); - } - - previousErrorStates = errorStates; - } - - if (entity instanceof IRestrictedAccess) { - IRestrictedAccess restrictedAccess = (IRestrictedAccess) entity; - IAccessHandler accessHandler = restrictedAccess.getAccessHandler(); - EnumAccess access = accessHandler.getAccess(); - if (access != previousAccess) { - IForestryPacketClient packet = new PacketAccessUpdateEntity(restrictedAccess, entity); - sendPacketToCrafters(packet); - - previousAccess = access; - } - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +import com.google.common.collect.ImmutableSet; +import forestry.api.core.IErrorLogicSource; +import forestry.api.core.IErrorState; +import forestry.core.access.EnumAccess; +import forestry.core.access.FakeAccessHandler; +import forestry.core.access.IAccessHandler; +import forestry.core.access.IRestrictedAccess; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.packets.PacketAccessUpdateEntity; +import forestry.core.network.packets.PacketErrorUpdateEntity; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IInventory; + +public class ContainerEntity extends ContainerForestry { + protected final T entity; + private final IAccessHandler accessHandler; + + protected ContainerEntity(T entity) { + this.entity = entity; + + if (entity instanceof IRestrictedAccess) { + accessHandler = ((IRestrictedAccess) entity).getAccessHandler(); + } else { + accessHandler = FakeAccessHandler.getInstance(); + } + } + + protected ContainerEntity(T entity, InventoryPlayer playerInventory, int xInv, int yInv) { + this(entity); + addPlayerInventory(playerInventory, xInv, yInv); + } + + @Override + protected final boolean canAccess(EntityPlayer player) { + return player != null && accessHandler.allowsAlteration(player); + } + + @Override + public final boolean canInteractWith(EntityPlayer entityplayer) { + return entity.isUseableByPlayer(entityplayer) && accessHandler.allowsViewing(entityplayer); + } + + private ImmutableSet previousErrorStates; + private EnumAccess previousAccess; + + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + + if (entity instanceof IErrorLogicSource) { + IErrorLogicSource errorLogicSource = (IErrorLogicSource) entity; + ImmutableSet errorStates = + errorLogicSource.getErrorLogic().getErrorStates(); + + if ((previousErrorStates == null) || !errorStates.equals(previousErrorStates)) { + PacketErrorUpdateEntity packet = new PacketErrorUpdateEntity(entity, errorLogicSource); + sendPacketToCrafters(packet); + } + + previousErrorStates = errorStates; + } + + if (entity instanceof IRestrictedAccess) { + IRestrictedAccess restrictedAccess = (IRestrictedAccess) entity; + IAccessHandler accessHandler = restrictedAccess.getAccessHandler(); + EnumAccess access = accessHandler.getAccess(); + if (access != previousAccess) { + IForestryPacketClient packet = new PacketAccessUpdateEntity(restrictedAccess, entity); + sendPacketToCrafters(packet); + + previousAccess = access; + } + } + } +} diff --git a/src/main/java/forestry/core/gui/ContainerEscritoire.java b/src/main/java/forestry/core/gui/ContainerEscritoire.java index 6d8921021..8335c941c 100755 --- a/src/main/java/forestry/core/gui/ContainerEscritoire.java +++ b/src/main/java/forestry/core/gui/ContainerEscritoire.java @@ -10,9 +10,6 @@ ******************************************************************************/ package forestry.core.gui; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; - import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.core.inventory.InventoryEscritoire; @@ -21,55 +18,61 @@ import forestry.core.network.packets.PacketGuiUpdate; import forestry.core.proxy.Proxies; import forestry.core.tiles.EscritoireGame; import forestry.core.tiles.TileEscritoire; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; public class ContainerEscritoire extends ContainerTile implements IGuiSelectable { - private final EntityPlayer player; + private final EntityPlayer player; - private long lastUpdate; + private long lastUpdate; - public ContainerEscritoire(EntityPlayer player, TileEscritoire tile) { - super(tile, player.inventory, 34, 153); + public ContainerEscritoire(EntityPlayer player, TileEscritoire tile) { + super(tile, player.inventory, 34, 153); - this.player = player; + this.player = player; - // Analyze slot - addSlotToContainer(new SlotFiltered(this.tile, InventoryEscritoire.SLOT_ANALYZE, 97, 67).setPickupWatcher(this.tile).setStackLimit(1)); + // Analyze slot + addSlotToContainer(new SlotFiltered(this.tile, InventoryEscritoire.SLOT_ANALYZE, 97, 67) + .setPickupWatcher(this.tile) + .setStackLimit(1)); - for (int i = 0; i < InventoryEscritoire.SLOTS_INPUT_COUNT; i++) { - addSlotToContainer(new SlotFiltered(this.tile, InventoryEscritoire.SLOT_INPUT_1 + i, 17, 49 + i * 18).setBlockedTexture("slots/blocked_2")); - } + for (int i = 0; i < InventoryEscritoire.SLOTS_INPUT_COUNT; i++) { + addSlotToContainer(new SlotFiltered(this.tile, InventoryEscritoire.SLOT_INPUT_1 + i, 17, 49 + i * 18) + .setBlockedTexture("slots/blocked_2")); + } - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 2; j++) { - addSlotToContainer(new SlotOutput(this.tile, InventoryEscritoire.SLOT_RESULTS_1 + (i * 2) + j, 177 + j * 18, 85 + i * 18)); - } - } - } + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { + addSlotToContainer(new SlotOutput( + this.tile, InventoryEscritoire.SLOT_RESULTS_1 + (i * 2) + j, 177 + j * 18, 85 + i * 18)); + } + } + } - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); - long gameLastUpdate = tile.getGame().getLastUpdate(); - if (lastUpdate != gameLastUpdate) { - lastUpdate = gameLastUpdate; - Proxies.net.sendToPlayer(new PacketGuiUpdate(tile), player); - } - } + long gameLastUpdate = tile.getGame().getLastUpdate(); + if (lastUpdate != gameLastUpdate) { + lastUpdate = gameLastUpdate; + Proxies.net.sendToPlayer(new PacketGuiUpdate(tile), player); + } + } - @Override - public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { - EscritoireGame.Status status = tile.getGame().getStatus(); - if (status != EscritoireGame.Status.PLAYING) { - return; - } + @Override + public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { + EscritoireGame.Status status = tile.getGame().getStatus(); + if (status != EscritoireGame.Status.PLAYING) { + return; + } - int index = packet.getPrimaryIndex(); - if (index == -1) { - tile.probe(); - } else { - tile.choose(player.getGameProfile(), index); - } - } + int index = packet.getPrimaryIndex(); + if (index == -1) { + tile.probe(); + } else { + tile.choose(player.getGameProfile(), index); + } + } } diff --git a/src/main/java/forestry/core/gui/ContainerForestry.java b/src/main/java/forestry/core/gui/ContainerForestry.java index 6ae34f34f..94046aabc 100644 --- a/src/main/java/forestry/core/gui/ContainerForestry.java +++ b/src/main/java/forestry/core/gui/ContainerForestry.java @@ -12,122 +12,119 @@ package forestry.core.gui; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimaps; - -import java.util.List; -import java.util.Map; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; - import forestry.core.gui.slots.SlotFilteredInventory; import forestry.core.gui.slots.SlotForestry; import forestry.core.gui.slots.SlotLocked; import forestry.core.network.IForestryPacketClient; import forestry.core.proxy.Proxies; import forestry.core.utils.SlotUtil; - import invtweaks.api.container.ContainerSection; import invtweaks.api.container.ContainerSectionCallback; +import java.util.List; +import java.util.Map; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; @invtweaks.api.container.ChestContainer(showButtons = false) public abstract class ContainerForestry extends Container { - protected final void addPlayerInventory(InventoryPlayer playerInventory, int xInv, int yInv) { - // Player inventory - for (int row = 0; row < 3; row++) { - for (int column = 0; column < 9; column++) { - addSlotToContainer(new Slot(playerInventory, column + row * 9 + 9, xInv + column * 18, yInv + row * 18)); - } - } - // Player hotbar - for (int column = 0; column < 9; column++) { - addHotbarSlot(playerInventory, column, xInv + column * 18, yInv + 58); - } - } + protected final void addPlayerInventory(InventoryPlayer playerInventory, int xInv, int yInv) { + // Player inventory + for (int row = 0; row < 3; row++) { + for (int column = 0; column < 9; column++) { + addSlotToContainer( + new Slot(playerInventory, column + row * 9 + 9, xInv + column * 18, yInv + row * 18)); + } + } + // Player hotbar + for (int column = 0; column < 9; column++) { + addHotbarSlot(playerInventory, column, xInv + column * 18, yInv + 58); + } + } - protected void addHotbarSlot(InventoryPlayer playerInventory, int slot, int x, int y) { - addSlotToContainer(new Slot(playerInventory, slot, x, y)); - } + protected void addHotbarSlot(InventoryPlayer playerInventory, int slot, int x, int y) { + addSlotToContainer(new Slot(playerInventory, slot, x, y)); + } - @Override - public Slot addSlotToContainer(Slot p_75146_1_) { - return super.addSlotToContainer(p_75146_1_); - } + @Override + public Slot addSlotToContainer(Slot p_75146_1_) { + return super.addSlotToContainer(p_75146_1_); + } - @Override - public ItemStack slotClick(int slotIndex, int button, int modifier, EntityPlayer player) { - if (!canAccess(player)) { - return null; - } + @Override + public ItemStack slotClick(int slotIndex, int button, int modifier, EntityPlayer player) { + if (!canAccess(player)) { + return null; + } - if (modifier == 2 && button >= 0 && button < 9) { - // hotkey used to move item from slot to hotbar - int hotbarSlotIndex = 27 + button; - Slot hotbarSlot = getSlot(hotbarSlotIndex); - if (hotbarSlot instanceof SlotLocked) { - return null; - } - } + if (modifier == 2 && button >= 0 && button < 9) { + // hotkey used to move item from slot to hotbar + int hotbarSlotIndex = 27 + button; + Slot hotbarSlot = getSlot(hotbarSlotIndex); + if (hotbarSlot instanceof SlotLocked) { + return null; + } + } - Slot slot = (slotIndex < 0) ? null : getSlot(slotIndex); - if (slot instanceof SlotForestry) { - SlotForestry slotForestry = (SlotForestry) slot; - if (slotForestry.isPhantom()) { - return SlotUtil.slotClickPhantom(slotForestry, button, modifier, player); - } - } + Slot slot = (slotIndex < 0) ? null : getSlot(slotIndex); + if (slot instanceof SlotForestry) { + SlotForestry slotForestry = (SlotForestry) slot; + if (slotForestry.isPhantom()) { + return SlotUtil.slotClickPhantom(slotForestry, button, modifier, player); + } + } - return super.slotClick(slotIndex, button, modifier, player); - } + return super.slotClick(slotIndex, button, modifier, player); + } - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { - if (!canAccess(player)) { - return null; - } + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { + if (!canAccess(player)) { + return null; + } - return SlotUtil.transferStackInSlot(inventorySlots, player, slotIndex); - } + return SlotUtil.transferStackInSlot(inventorySlots, player, slotIndex); + } - protected abstract boolean canAccess(EntityPlayer player); + protected abstract boolean canAccess(EntityPlayer player); - protected final void sendPacketToCrafters(IForestryPacketClient packet) { - for (Object crafter : crafters) { - if (crafter instanceof EntityPlayer) { - Proxies.net.sendToPlayer(packet, (EntityPlayer) crafter); - } - } - } + protected final void sendPacketToCrafters(IForestryPacketClient packet) { + for (Object crafter : crafters) { + if (crafter instanceof EntityPlayer) { + Proxies.net.sendToPlayer(packet, (EntityPlayer) crafter); + } + } + } - @SuppressWarnings("unused") // inventory tweaks - @ContainerSectionCallback - public Map> getContainerSections() { - ArrayListMultimap map = ArrayListMultimap.create(); + @SuppressWarnings("unused") // inventory tweaks + @ContainerSectionCallback + public Map> getContainerSections() { + ArrayListMultimap map = ArrayListMultimap.create(); - for (Object object : inventorySlots) { - if (!(object instanceof Slot)) { - continue; - } - Slot slot = (Slot) object; + for (Object object : inventorySlots) { + if (!(object instanceof Slot)) { + continue; + } + Slot slot = (Slot) object; - if (slot.inventory instanceof InventoryPlayer) { - map.put(ContainerSection.INVENTORY, slot); - if (slot.slotNumber < 9) { - map.put(ContainerSection.INVENTORY_HOTBAR, slot); - } else if (slot.slotNumber < 36) { - map.put(ContainerSection.INVENTORY_NOT_HOTBAR, slot); - } else { - map.put(ContainerSection.ARMOR, slot); - } - } else { - if (!(slot instanceof SlotForestry) || slot instanceof SlotFilteredInventory) { - map.put(ContainerSection.CHEST, slot); - } - } - } - - return Multimaps.asMap(map); - } + if (slot.inventory instanceof InventoryPlayer) { + map.put(ContainerSection.INVENTORY, slot); + if (slot.slotNumber < 9) { + map.put(ContainerSection.INVENTORY_HOTBAR, slot); + } else if (slot.slotNumber < 36) { + map.put(ContainerSection.INVENTORY_NOT_HOTBAR, slot); + } else { + map.put(ContainerSection.ARMOR, slot); + } + } else { + if (!(slot instanceof SlotForestry) || slot instanceof SlotFilteredInventory) { + map.put(ContainerSection.CHEST, slot); + } + } + } + + return Multimaps.asMap(map); + } } diff --git a/src/main/java/forestry/core/gui/ContainerItemInventory.java b/src/main/java/forestry/core/gui/ContainerItemInventory.java index 4da8d8732..2909e5227 100755 --- a/src/main/java/forestry/core/gui/ContainerItemInventory.java +++ b/src/main/java/forestry/core/gui/ContainerItemInventory.java @@ -10,50 +10,48 @@ ******************************************************************************/ package forestry.core.gui; +import forestry.core.gui.slots.SlotLocked; +import forestry.core.inventory.ItemInventory; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; -import forestry.core.gui.slots.SlotLocked; -import forestry.core.inventory.ItemInventory; - public abstract class ContainerItemInventory extends ContainerForestry { - protected final I inventory; + protected final I inventory; - protected ContainerItemInventory(I inventory, InventoryPlayer playerInventory, int xInv, int yInv) { - this.inventory = inventory; + protected ContainerItemInventory(I inventory, InventoryPlayer playerInventory, int xInv, int yInv) { + this.inventory = inventory; - addPlayerInventory(playerInventory, xInv, yInv); - } + addPlayerInventory(playerInventory, xInv, yInv); + } - @Override - protected void addHotbarSlot(InventoryPlayer playerInventory, int slot, int x, int y) { - ItemStack stackInSlot = playerInventory.getStackInSlot(slot); + @Override + protected void addHotbarSlot(InventoryPlayer playerInventory, int slot, int x, int y) { + ItemStack stackInSlot = playerInventory.getStackInSlot(slot); - if (inventory.isParentItemInventory(stackInSlot)) { - addSlotToContainer(new SlotLocked(playerInventory, slot, x, y)); - } else { - addSlotToContainer(new Slot(playerInventory, slot, x, y)); - } - } + if (inventory.isParentItemInventory(stackInSlot)) { + addSlotToContainer(new SlotLocked(playerInventory, slot, x, y)); + } else { + addSlotToContainer(new Slot(playerInventory, slot, x, y)); + } + } - @Override - protected final boolean canAccess(EntityPlayer player) { - return canInteractWith(player); - } + @Override + protected final boolean canAccess(EntityPlayer player) { + return canInteractWith(player); + } - @Override - public final boolean canInteractWith(EntityPlayer entityplayer) { - return inventory.isUseableByPlayer(entityplayer); - } - - @Override - public final ItemStack slotClick(int slotIndex, int button, int modifier, EntityPlayer player) { - ItemStack result = super.slotClick(slotIndex, button, modifier, player); - inventory.onSlotClick(player); - return result; - } + @Override + public final boolean canInteractWith(EntityPlayer entityplayer) { + return inventory.isUseableByPlayer(entityplayer); + } + @Override + public final ItemStack slotClick(int slotIndex, int button, int modifier, EntityPlayer player) { + ItemStack result = super.slotClick(slotIndex, button, modifier, player); + inventory.onSlotClick(player); + return result; + } } diff --git a/src/main/java/forestry/core/gui/ContainerLiquidTanks.java b/src/main/java/forestry/core/gui/ContainerLiquidTanks.java index bea550ff7..24e130fdf 100755 --- a/src/main/java/forestry/core/gui/ContainerLiquidTanks.java +++ b/src/main/java/forestry/core/gui/ContainerLiquidTanks.java @@ -10,55 +10,54 @@ ******************************************************************************/ package forestry.core.gui; +import forestry.core.tiles.ILiquidTankTile; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ICrafting; import net.minecraft.tileentity.TileEntity; - import net.minecraftforge.fluids.IFluidTank; -import forestry.core.tiles.ILiquidTankTile; +public abstract class ContainerLiquidTanks extends ContainerTile + implements IContainerLiquidTanks { -public abstract class ContainerLiquidTanks extends ContainerTile implements IContainerLiquidTanks { + private final ContainerLiquidTanksHelper helper; - private final ContainerLiquidTanksHelper helper; + protected ContainerLiquidTanks(T tile, InventoryPlayer playerInventory, int xInv, int yInv) { + super(tile, playerInventory, xInv, yInv); + this.helper = new ContainerLiquidTanksHelper<>(tile); + } - protected ContainerLiquidTanks(T tile, InventoryPlayer playerInventory, int xInv, int yInv) { - super(tile, playerInventory, xInv, yInv); - this.helper = new ContainerLiquidTanksHelper<>(tile); - } + @Override + public void handlePipetteClickClient(int slot, EntityPlayer player) { + helper.handlePipetteClickClient(slot, player); + } - @Override - public void handlePipetteClickClient(int slot, EntityPlayer player) { - helper.handlePipetteClickClient(slot, player); - } + @Override + public void handlePipetteClick(int slot, EntityPlayerMP player) { + helper.handlePipetteClick(slot, player); + } - @Override - public void handlePipetteClick(int slot, EntityPlayerMP player) { - helper.handlePipetteClick(slot, player); - } + @Override + @SuppressWarnings("unchecked") + public void detectAndSendChanges() { + super.detectAndSendChanges(); + tile.getTankManager().updateGuiData(this, crafters); + } - @Override - @SuppressWarnings("unchecked") - public void detectAndSendChanges() { - super.detectAndSendChanges(); - tile.getTankManager().updateGuiData(this, crafters); - } + @Override + public void addCraftingToCrafters(ICrafting icrafting) { + super.addCraftingToCrafters(icrafting); + tile.getTankManager().containerAdded(this, icrafting); + } - @Override - public void addCraftingToCrafters(ICrafting icrafting) { - super.addCraftingToCrafters(icrafting); - tile.getTankManager().containerAdded(this, icrafting); - } + @Override + public void onContainerClosed(EntityPlayer entityPlayer) { + super.onContainerClosed(entityPlayer); + tile.getTankManager().containerRemoved(this); + } - @Override - public void onContainerClosed(EntityPlayer entityPlayer) { - super.onContainerClosed(entityPlayer); - tile.getTankManager().containerRemoved(this); - } - - public IFluidTank getTank(int slot) { - return tile.getTankManager().getTank(slot); - } + public IFluidTank getTank(int slot) { + return tile.getTankManager().getTank(slot); + } } diff --git a/src/main/java/forestry/core/gui/ContainerLiquidTanksHelper.java b/src/main/java/forestry/core/gui/ContainerLiquidTanksHelper.java index 8aafd16dd..92e305d6b 100644 --- a/src/main/java/forestry/core/gui/ContainerLiquidTanksHelper.java +++ b/src/main/java/forestry/core/gui/ContainerLiquidTanksHelper.java @@ -1,81 +1,79 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; - -import forestry.api.core.IToolPipette; -import forestry.core.network.packets.PacketPipetteClick; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.ILiquidTankTile; - -public class ContainerLiquidTanksHelper implements IContainerLiquidTanks { - - private final T tile; - - public ContainerLiquidTanksHelper(T tile) { - this.tile = tile; - } - - @Override - public void handlePipetteClickClient(int slot, EntityPlayer player) { - ItemStack itemstack = player.inventory.getItemStack(); - if (itemstack == null || !(itemstack.getItem() instanceof IToolPipette)) { - return; - } - - Proxies.net.sendToServer(new PacketPipetteClick(tile, slot)); - } - - @Override - public void handlePipetteClick(int slot, EntityPlayerMP player) { - ItemStack itemstack = player.inventory.getItemStack(); - if (itemstack == null) { - return; - } - - Item held = itemstack.getItem(); - if (!(held instanceof IToolPipette)) { - return; - } - - IToolPipette pipette = (IToolPipette) held; - IFluidTank tank = tile.getTankManager().getTank(slot); - int liquidAmount = tank.getFluidAmount(); - - if (pipette.canPipette(itemstack) && liquidAmount > 0) { - if (liquidAmount > 0) { - FluidStack fillAmount = tank.drain(1000, false); - int filled = pipette.fill(itemstack, fillAmount, true); - tank.drain(filled, true); - player.updateHeldItem(); - } - } else { - FluidStack potential = pipette.drain(itemstack, pipette.getCapacity(itemstack), false); - if (potential != null) { - pipette.drain(itemstack, tank.fill(potential, true), true); - player.updateHeldItem(); - } - } - } - - @Override - public IFluidTank getTank(int slot) { - return tile.getTankManager().getTank(slot); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +import forestry.api.core.IToolPipette; +import forestry.core.network.packets.PacketPipetteClick; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.ILiquidTankTile; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.IFluidTank; + +public class ContainerLiquidTanksHelper implements IContainerLiquidTanks { + + private final T tile; + + public ContainerLiquidTanksHelper(T tile) { + this.tile = tile; + } + + @Override + public void handlePipetteClickClient(int slot, EntityPlayer player) { + ItemStack itemstack = player.inventory.getItemStack(); + if (itemstack == null || !(itemstack.getItem() instanceof IToolPipette)) { + return; + } + + Proxies.net.sendToServer(new PacketPipetteClick(tile, slot)); + } + + @Override + public void handlePipetteClick(int slot, EntityPlayerMP player) { + ItemStack itemstack = player.inventory.getItemStack(); + if (itemstack == null) { + return; + } + + Item held = itemstack.getItem(); + if (!(held instanceof IToolPipette)) { + return; + } + + IToolPipette pipette = (IToolPipette) held; + IFluidTank tank = tile.getTankManager().getTank(slot); + int liquidAmount = tank.getFluidAmount(); + + if (pipette.canPipette(itemstack) && liquidAmount > 0) { + if (liquidAmount > 0) { + FluidStack fillAmount = tank.drain(1000, false); + int filled = pipette.fill(itemstack, fillAmount, true); + tank.drain(filled, true); + player.updateHeldItem(); + } + } else { + FluidStack potential = pipette.drain(itemstack, pipette.getCapacity(itemstack), false); + if (potential != null) { + pipette.drain(itemstack, tank.fill(potential, true), true); + player.updateHeldItem(); + } + } + } + + @Override + public IFluidTank getTank(int slot) { + return tile.getTankManager().getTank(slot); + } +} diff --git a/src/main/java/forestry/core/gui/ContainerLiquidTanksSocketed.java b/src/main/java/forestry/core/gui/ContainerLiquidTanksSocketed.java index 7e5385ee0..92ed6c9f1 100644 --- a/src/main/java/forestry/core/gui/ContainerLiquidTanksSocketed.java +++ b/src/main/java/forestry/core/gui/ContainerLiquidTanksSocketed.java @@ -10,82 +10,80 @@ ******************************************************************************/ package forestry.core.gui; +import forestry.core.circuits.ISocketable; +import forestry.core.tiles.ILiquidTankTile; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ICrafting; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; - import net.minecraftforge.fluids.IFluidTank; -import forestry.core.circuits.ISocketable; -import forestry.core.tiles.ILiquidTankTile; +public abstract class ContainerLiquidTanksSocketed + extends ContainerTile implements IContainerSocketed, IContainerLiquidTanks { -public abstract class ContainerLiquidTanksSocketed extends ContainerTile implements IContainerSocketed, IContainerLiquidTanks { + private final ContainerSocketedHelper socketedHelper; + private final ContainerLiquidTanksHelper tanksHelper; - private final ContainerSocketedHelper socketedHelper; - private final ContainerLiquidTanksHelper tanksHelper; + protected ContainerLiquidTanksSocketed(T tile, InventoryPlayer playerInventory, int xInv, int yInv) { + super(tile, playerInventory, xInv, yInv); + this.socketedHelper = new ContainerSocketedHelper<>(tile); + this.tanksHelper = new ContainerLiquidTanksHelper<>(tile); + } - protected ContainerLiquidTanksSocketed(T tile, InventoryPlayer playerInventory, int xInv, int yInv) { - super(tile, playerInventory, xInv, yInv); - this.socketedHelper = new ContainerSocketedHelper<>(tile); - this.tanksHelper = new ContainerLiquidTanksHelper<>(tile); - } + /* IContainerLiquidTanks */ + @Override + public void handlePipetteClickClient(int slot, EntityPlayer player) { + tanksHelper.handlePipetteClickClient(slot, player); + } - /* IContainerLiquidTanks */ - @Override - public void handlePipetteClickClient(int slot, EntityPlayer player) { - tanksHelper.handlePipetteClickClient(slot, player); - } + @Override + public void handlePipetteClick(int slot, EntityPlayerMP player) { + tanksHelper.handlePipetteClick(slot, player); + } - @Override - public void handlePipetteClick(int slot, EntityPlayerMP player) { - tanksHelper.handlePipetteClick(slot, player); - } + @Override + @SuppressWarnings("unchecked") + public void detectAndSendChanges() { + super.detectAndSendChanges(); + tile.getTankManager().updateGuiData(this, crafters); + } - @Override - @SuppressWarnings("unchecked") - public void detectAndSendChanges() { - super.detectAndSendChanges(); - tile.getTankManager().updateGuiData(this, crafters); - } + @Override + public void addCraftingToCrafters(ICrafting icrafting) { + super.addCraftingToCrafters(icrafting); + tile.getTankManager().containerAdded(this, icrafting); + } - @Override - public void addCraftingToCrafters(ICrafting icrafting) { - super.addCraftingToCrafters(icrafting); - tile.getTankManager().containerAdded(this, icrafting); - } + @Override + public void onContainerClosed(EntityPlayer entityPlayer) { + super.onContainerClosed(entityPlayer); + tile.getTankManager().containerRemoved(this); + } - @Override - public void onContainerClosed(EntityPlayer entityPlayer) { - super.onContainerClosed(entityPlayer); - tile.getTankManager().containerRemoved(this); - } + public IFluidTank getTank(int slot) { + return tile.getTankManager().getTank(slot); + } - public IFluidTank getTank(int slot) { - return tile.getTankManager().getTank(slot); - } + /* IContainerSocketed */ + @Override + public void handleChipsetClick(int slot) { + socketedHelper.handleChipsetClick(slot); + } - /* IContainerSocketed */ - @Override - public void handleChipsetClick(int slot) { - socketedHelper.handleChipsetClick(slot); - } + @Override + public void handleChipsetClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { + socketedHelper.handleChipsetClickServer(slot, player, itemstack); + } - @Override - public void handleChipsetClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { - socketedHelper.handleChipsetClickServer(slot, player, itemstack); - } - - @Override - public void handleSolderingIronClick(int slot) { - socketedHelper.handleSolderingIronClick(slot); - } - - @Override - public void handleSolderingIronClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { - socketedHelper.handleSolderingIronClickServer(slot, player, itemstack); - } + @Override + public void handleSolderingIronClick(int slot) { + socketedHelper.handleSolderingIronClick(slot); + } + @Override + public void handleSolderingIronClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { + socketedHelper.handleSolderingIronClickServer(slot, player, itemstack); + } } diff --git a/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java b/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java index dd484b3a6..9d0d26e7e 100755 --- a/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java +++ b/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java @@ -10,54 +10,55 @@ ******************************************************************************/ package forestry.core.gui; +import forestry.core.gui.slots.SlotFilteredInventory; +import forestry.core.network.packets.PacketGuiSelectRequest; +import forestry.core.tiles.IFilterSlotDelegate; +import forestry.core.tiles.TileNaturalistChest; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.IInventory; -import forestry.core.gui.slots.SlotFilteredInventory; -import forestry.core.network.packets.PacketGuiSelectRequest; -import forestry.core.tiles.IFilterSlotDelegate; -import forestry.core.tiles.TileNaturalistChest; - public class ContainerNaturalistInventory extends ContainerTile implements IGuiSelectable { - public ContainerNaturalistInventory(InventoryPlayer player, TileNaturalistChest tile, int page) { - super(tile, player, 18, 120); + public ContainerNaturalistInventory(InventoryPlayer player, TileNaturalistChest tile, int page) { + super(tile, player, 18, 120); - addInventory(this, tile, page); - } + addInventory(this, tile, page); + } - public static void addInventory(ContainerForestry container, T inventory, int selectedPage) { - for (int page = 0; page < 5; page++) { - for (int x = 0; x < 5; x++) { - for (int y = 0; y < 5; y++) { - int slot = y + page * 25 + x * 5; - if (page == selectedPage) { - container.addSlotToContainer(new SlotFilteredInventory(inventory, slot, 100 + y * 18, 21 + x * 18)); - } else { - container.addSlotToContainer(new SlotFilteredInventory(inventory, slot, -10000, -10000)); - } - } - } - } - } + public static void addInventory( + ContainerForestry container, T inventory, int selectedPage) { + for (int page = 0; page < 5; page++) { + for (int x = 0; x < 5; x++) { + for (int y = 0; y < 5; y++) { + int slot = y + page * 25 + x * 5; + if (page == selectedPage) { + container.addSlotToContainer( + new SlotFilteredInventory(inventory, slot, 100 + y * 18, 21 + x * 18)); + } else { + container.addSlotToContainer(new SlotFilteredInventory(inventory, slot, -10000, -10000)); + } + } + } + } + } - @Override - public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { - tile.flipPage(player, (short) packet.getPrimaryIndex()); - } + @Override + public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { + tile.flipPage(player, (short) packet.getPrimaryIndex()); + } - @Override - public void addCraftingToCrafters(ICrafting p_75132_1_) { - super.addCraftingToCrafters(p_75132_1_); - tile.increaseNumPlayersUsing(); - } + @Override + public void addCraftingToCrafters(ICrafting p_75132_1_) { + super.addCraftingToCrafters(p_75132_1_); + tile.increaseNumPlayersUsing(); + } - @Override - public void onContainerClosed(EntityPlayer player) { - super.onContainerClosed(player); - tile.decreaseNumPlayersUsing(); - } + @Override + public void onContainerClosed(EntityPlayer player) { + super.onContainerClosed(player); + tile.decreaseNumPlayersUsing(); + } } diff --git a/src/main/java/forestry/core/gui/ContainerSocketed.java b/src/main/java/forestry/core/gui/ContainerSocketed.java index 496bb5c75..9d270d580 100755 --- a/src/main/java/forestry/core/gui/ContainerSocketed.java +++ b/src/main/java/forestry/core/gui/ContainerSocketed.java @@ -10,39 +10,39 @@ ******************************************************************************/ package forestry.core.gui; +import forestry.core.circuits.ISocketable; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import forestry.core.circuits.ISocketable; +public abstract class ContainerSocketed extends ContainerTile + implements IContainerSocketed { -public abstract class ContainerSocketed extends ContainerTile implements IContainerSocketed { + private final ContainerSocketedHelper helper; - private final ContainerSocketedHelper helper; + protected ContainerSocketed(T tile, InventoryPlayer playerInventory, int xInv, int yInv) { + super(tile, playerInventory, xInv, yInv); + this.helper = new ContainerSocketedHelper<>(tile); + } - protected ContainerSocketed(T tile, InventoryPlayer playerInventory, int xInv, int yInv) { - super(tile, playerInventory, xInv, yInv); - this.helper = new ContainerSocketedHelper<>(tile); - } + @Override + public void handleChipsetClick(int slot) { + helper.handleChipsetClick(slot); + } - @Override - public void handleChipsetClick(int slot) { - helper.handleChipsetClick(slot); - } + @Override + public void handleChipsetClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { + helper.handleChipsetClickServer(slot, player, itemstack); + } - @Override - public void handleChipsetClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { - helper.handleChipsetClickServer(slot, player, itemstack); - } + @Override + public void handleSolderingIronClick(int slot) { + helper.handleSolderingIronClick(slot); + } - @Override - public void handleSolderingIronClick(int slot) { - helper.handleSolderingIronClick(slot); - } - - @Override - public void handleSolderingIronClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { - helper.handleSolderingIronClickServer(slot, player, itemstack); - } + @Override + public void handleSolderingIronClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { + helper.handleSolderingIronClickServer(slot, player, itemstack); + } } diff --git a/src/main/java/forestry/core/gui/ContainerSocketedHelper.java b/src/main/java/forestry/core/gui/ContainerSocketedHelper.java index bff547c9f..90b80b9a0 100644 --- a/src/main/java/forestry/core/gui/ContainerSocketedHelper.java +++ b/src/main/java/forestry/core/gui/ContainerSocketedHelper.java @@ -1,106 +1,104 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - -import forestry.api.circuits.ChipsetManager; -import forestry.api.circuits.ICircuitBoard; -import forestry.core.circuits.ISocketable; -import forestry.core.network.packets.PacketChipsetClick; -import forestry.core.network.packets.PacketSocketUpdate; -import forestry.core.network.packets.PacketSolderingIronClick; -import forestry.core.proxy.Proxies; -import forestry.core.utils.InventoryUtil; - -public class ContainerSocketedHelper implements IContainerSocketed { - - private final T tile; - - public ContainerSocketedHelper(T tile) { - this.tile = tile; - } - - @Override - public void handleChipsetClick(int slot) { - Proxies.net.sendToServer(new PacketChipsetClick(tile, slot)); - } - - @Override - public void handleChipsetClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { - if (tile.getSocket(slot) != null) { - return; - } - - if (!ChipsetManager.circuitRegistry.isChipset(itemstack)) { - return; - } - - ICircuitBoard circuitBoard = ChipsetManager.circuitRegistry.getCircuitboard(itemstack); - if (circuitBoard == null) { - return; - } - - try { - if (!tile.getSocketType().equals(circuitBoard.getSocketType())) { - return; - } - } catch (Throwable ignored) { - // older circuitBoards don't have getSocketType() - } - - ItemStack toSocket = itemstack.copy(); - toSocket.stackSize = 1; - tile.setSocket(slot, toSocket); - - ItemStack stack = player.inventory.getItemStack(); - stack.stackSize--; - if (stack.stackSize <= 0) { - player.inventory.setItemStack(null); - } - player.updateHeldItem(); - - PacketSocketUpdate packet = new PacketSocketUpdate(tile); - Proxies.net.sendToPlayer(packet, player); - } - - @Override - public void handleSolderingIronClick(int slot) { - Proxies.net.sendToServer(new PacketSolderingIronClick(tile, slot)); - } - - @Override - public void handleSolderingIronClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { - ItemStack socket = tile.getSocket(slot); - if (socket == null) { - return; - } - - InventoryUtil.stowInInventory(socket, player.inventory, true); - // Not sufficient space in player's inventory. failed to stow. - if (socket.stackSize > 0) { - return; - } - - tile.setSocket(slot, null); - itemstack.damageItem(1, player); - if (itemstack.stackSize <= 0) { - player.inventory.setItemStack(null); - } - player.updateHeldItem(); - - - PacketSocketUpdate packet = new PacketSocketUpdate(tile); - Proxies.net.sendToPlayer(packet, player); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +import forestry.api.circuits.ChipsetManager; +import forestry.api.circuits.ICircuitBoard; +import forestry.core.circuits.ISocketable; +import forestry.core.network.packets.PacketChipsetClick; +import forestry.core.network.packets.PacketSocketUpdate; +import forestry.core.network.packets.PacketSolderingIronClick; +import forestry.core.proxy.Proxies; +import forestry.core.utils.InventoryUtil; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; + +public class ContainerSocketedHelper implements IContainerSocketed { + + private final T tile; + + public ContainerSocketedHelper(T tile) { + this.tile = tile; + } + + @Override + public void handleChipsetClick(int slot) { + Proxies.net.sendToServer(new PacketChipsetClick(tile, slot)); + } + + @Override + public void handleChipsetClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { + if (tile.getSocket(slot) != null) { + return; + } + + if (!ChipsetManager.circuitRegistry.isChipset(itemstack)) { + return; + } + + ICircuitBoard circuitBoard = ChipsetManager.circuitRegistry.getCircuitboard(itemstack); + if (circuitBoard == null) { + return; + } + + try { + if (!tile.getSocketType().equals(circuitBoard.getSocketType())) { + return; + } + } catch (Throwable ignored) { + // older circuitBoards don't have getSocketType() + } + + ItemStack toSocket = itemstack.copy(); + toSocket.stackSize = 1; + tile.setSocket(slot, toSocket); + + ItemStack stack = player.inventory.getItemStack(); + stack.stackSize--; + if (stack.stackSize <= 0) { + player.inventory.setItemStack(null); + } + player.updateHeldItem(); + + PacketSocketUpdate packet = new PacketSocketUpdate(tile); + Proxies.net.sendToPlayer(packet, player); + } + + @Override + public void handleSolderingIronClick(int slot) { + Proxies.net.sendToServer(new PacketSolderingIronClick(tile, slot)); + } + + @Override + public void handleSolderingIronClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { + ItemStack socket = tile.getSocket(slot); + if (socket == null) { + return; + } + + InventoryUtil.stowInInventory(socket, player.inventory, true); + // Not sufficient space in player's inventory. failed to stow. + if (socket.stackSize > 0) { + return; + } + + tile.setSocket(slot, null); + itemstack.damageItem(1, player); + if (itemstack.stackSize <= 0) { + player.inventory.setItemStack(null); + } + player.updateHeldItem(); + + PacketSocketUpdate packet = new PacketSocketUpdate(tile); + Proxies.net.sendToPlayer(packet, player); + } +} diff --git a/src/main/java/forestry/core/gui/ContainerTile.java b/src/main/java/forestry/core/gui/ContainerTile.java index d5c699309..692c2a346 100644 --- a/src/main/java/forestry/core/gui/ContainerTile.java +++ b/src/main/java/forestry/core/gui/ContainerTile.java @@ -11,11 +11,6 @@ package forestry.core.gui; import com.google.common.collect.ImmutableSet; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.tileentity.TileEntity; - import forestry.api.core.IErrorLogicSource; import forestry.api.core.IErrorState; import forestry.core.access.EnumAccess; @@ -31,111 +26,115 @@ import forestry.core.tiles.IPowerHandler; import forestry.core.tiles.TilePowered; import forestry.core.tiles.TileUtil; import forestry.energy.EnergyManager; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.tileentity.TileEntity; public abstract class ContainerTile extends ContainerForestry { - protected final T tile; - private final IAccessHandler accessHandler; + protected final T tile; + private final IAccessHandler accessHandler; - protected ContainerTile(T tile) { - this.tile = tile; + protected ContainerTile(T tile) { + this.tile = tile; - if (tile instanceof IRestrictedAccess) { - accessHandler = ((IRestrictedAccess) tile).getAccessHandler(); - } else { - accessHandler = FakeAccessHandler.getInstance(); - } - } + if (tile instanceof IRestrictedAccess) { + accessHandler = ((IRestrictedAccess) tile).getAccessHandler(); + } else { + accessHandler = FakeAccessHandler.getInstance(); + } + } - protected ContainerTile(T tileForestry, InventoryPlayer playerInventory, int xInv, int yInv) { - this(tileForestry); + protected ContainerTile(T tileForestry, InventoryPlayer playerInventory, int xInv, int yInv) { + this(tileForestry); - addPlayerInventory(playerInventory, xInv, yInv); - } + addPlayerInventory(playerInventory, xInv, yInv); + } - @Override - protected final boolean canAccess(EntityPlayer player) { - return player != null && accessHandler.allowsAlteration(player); - } + @Override + protected final boolean canAccess(EntityPlayer player) { + return player != null && accessHandler.allowsAlteration(player); + } - @Override - public final boolean canInteractWith(EntityPlayer entityplayer) { - return TileUtil.isUsableByPlayer(entityplayer, tile) && accessHandler.allowsViewing(entityplayer); - } + @Override + public final boolean canInteractWith(EntityPlayer entityplayer) { + return TileUtil.isUsableByPlayer(entityplayer, tile) && accessHandler.allowsViewing(entityplayer); + } - private ImmutableSet previousErrorStates; - private int previousEnergyManagerData = 0; - private EnumAccess previousAccess; - private int previousWorkCounter = 0; - private int previousTicksPerWorkCycle = 0; + private ImmutableSet previousErrorStates; + private int previousEnergyManagerData = 0; + private EnumAccess previousAccess; + private int previousWorkCounter = 0; + private int previousTicksPerWorkCycle = 0; - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); - if (tile instanceof IErrorLogicSource) { - IErrorLogicSource errorLogicSource = (IErrorLogicSource) tile; - ImmutableSet errorStates = errorLogicSource.getErrorLogic().getErrorStates(); + if (tile instanceof IErrorLogicSource) { + IErrorLogicSource errorLogicSource = (IErrorLogicSource) tile; + ImmutableSet errorStates = + errorLogicSource.getErrorLogic().getErrorStates(); - if ((previousErrorStates == null) || !errorStates.equals(previousErrorStates)) { - PacketErrorUpdate packet = new PacketErrorUpdate(tile, errorLogicSource); - sendPacketToCrafters(packet); - } + if ((previousErrorStates == null) || !errorStates.equals(previousErrorStates)) { + PacketErrorUpdate packet = new PacketErrorUpdate(tile, errorLogicSource); + sendPacketToCrafters(packet); + } - previousErrorStates = errorStates; - } + previousErrorStates = errorStates; + } - if (tile instanceof IPowerHandler) { - EnergyManager energyManager = ((IPowerHandler) tile).getEnergyManager(); - int energyManagerData = energyManager.toGuiInt(); - if (energyManagerData != previousEnergyManagerData) { - PacketGuiEnergy packet = new PacketGuiEnergy(windowId, energyManagerData); - sendPacketToCrafters(packet); + if (tile instanceof IPowerHandler) { + EnergyManager energyManager = ((IPowerHandler) tile).getEnergyManager(); + int energyManagerData = energyManager.toGuiInt(); + if (energyManagerData != previousEnergyManagerData) { + PacketGuiEnergy packet = new PacketGuiEnergy(windowId, energyManagerData); + sendPacketToCrafters(packet); - previousEnergyManagerData = energyManagerData; - } - } + previousEnergyManagerData = energyManagerData; + } + } - if (tile instanceof IRestrictedAccess) { - IRestrictedAccess restrictedAccess = (IRestrictedAccess) tile; - IAccessHandler accessHandler = restrictedAccess.getAccessHandler(); - EnumAccess access = accessHandler.getAccess(); - if (access != previousAccess) { - IForestryPacketClient packet = new PacketAccessUpdate(restrictedAccess, tile); - sendPacketToCrafters(packet); + if (tile instanceof IRestrictedAccess) { + IRestrictedAccess restrictedAccess = (IRestrictedAccess) tile; + IAccessHandler accessHandler = restrictedAccess.getAccessHandler(); + EnumAccess access = accessHandler.getAccess(); + if (access != previousAccess) { + IForestryPacketClient packet = new PacketAccessUpdate(restrictedAccess, tile); + sendPacketToCrafters(packet); - previousAccess = access; - } - } + previousAccess = access; + } + } - if (tile instanceof TilePowered) { - boolean guiNeedsUpdate = false; + if (tile instanceof TilePowered) { + boolean guiNeedsUpdate = false; - TilePowered tilePowered = (TilePowered) tile; + TilePowered tilePowered = (TilePowered) tile; - int workCounter = tilePowered.getWorkCounter(); - if (workCounter != previousWorkCounter) { - guiNeedsUpdate = true; - previousWorkCounter = workCounter; - } + int workCounter = tilePowered.getWorkCounter(); + if (workCounter != previousWorkCounter) { + guiNeedsUpdate = true; + previousWorkCounter = workCounter; + } - int ticksPerWorkCycle = tilePowered.getTicksPerWorkCycle(); - if (ticksPerWorkCycle != previousTicksPerWorkCycle) { - guiNeedsUpdate = true; - previousTicksPerWorkCycle = ticksPerWorkCycle; - } + int ticksPerWorkCycle = tilePowered.getTicksPerWorkCycle(); + if (ticksPerWorkCycle != previousTicksPerWorkCycle) { + guiNeedsUpdate = true; + previousTicksPerWorkCycle = ticksPerWorkCycle; + } - if (guiNeedsUpdate) { - PacketGuiUpdate packet = new PacketGuiUpdate(tilePowered); - sendPacketToCrafters(packet); - } - } - } + if (guiNeedsUpdate) { + PacketGuiUpdate packet = new PacketGuiUpdate(tilePowered); + sendPacketToCrafters(packet); + } + } + } - public void onGuiEnergy(int energyStored) { - if (tile instanceof IPowerHandler) { - EnergyManager energyManager = ((IPowerHandler) tile).getEnergyManager(); - energyManager.fromGuiInt(energyStored); - } - } + public void onGuiEnergy(int energyStored) { + if (tile instanceof IPowerHandler) { + EnergyManager energyManager = ((IPowerHandler) tile).getEnergyManager(); + energyManager.fromGuiInt(energyStored); + } + } } diff --git a/src/main/java/forestry/core/gui/GuiAlyzer.java b/src/main/java/forestry/core/gui/GuiAlyzer.java index ab26799e1..a1b24f954 100755 --- a/src/main/java/forestry/core/gui/GuiAlyzer.java +++ b/src/main/java/forestry/core/gui/GuiAlyzer.java @@ -10,20 +10,6 @@ ******************************************************************************/ package forestry.core.gui; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Stack; - -import org.apache.commons.lang3.StringUtils; - -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - -import org.lwjgl.opengl.GL11; - import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.EnumTolerance; @@ -42,375 +28,450 @@ import forestry.core.genetics.mutations.EnumMutateChance; import forestry.core.gui.widgets.ItemStackWidget; import forestry.core.proxy.Proxies; import forestry.core.utils.StringUtil; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Stack; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import org.apache.commons.lang3.StringUtils; +import org.lwjgl.opengl.GL11; public abstract class GuiAlyzer extends GuiForestry { - protected static final int COLUMN_0 = 12; - protected static final int COLUMN_1 = 90; - protected static final int COLUMN_2 = 155; - - private final ISpeciesRoot speciesRoot; - private final IBreedingTracker breedingTracker; - - private final String guiName; - - protected final Map iconStacks = new HashMap<>(); - - protected GuiAlyzer(ISpeciesRoot speciesRoot, EntityPlayer player, ContainerAlyzer container, IInventory inventory, String guiName) { - super(Constants.TEXTURE_PATH_GUI + "/beealyzer2.png", container, inventory); - - this.xSize = 246; - this.ySize = 238; - - this.guiName = guiName; - - this.speciesRoot = speciesRoot; - this.breedingTracker = this.speciesRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); - } - - protected final int getColorCoding(boolean dominant) { - if (dominant) { - return fontColor.get("gui.beealyzer.dominant"); - } else { - return fontColor.get("gui.beealyzer.recessive"); - } - } - - protected final void drawLine(String text, int x, IIndividual individual, IChromosomeType chromosome, boolean inactive) { - if (!inactive) { - textLayout.drawLine(text, x, getColorCoding(individual.getGenome().getActiveAllele(chromosome).isDominant())); - } else { - textLayout.drawLine(text, x, getColorCoding(individual.getGenome().getInactiveAllele(chromosome).isDominant())); - } - } - - protected final void drawSplitLine(String text, int x, int maxWidth, IIndividual individual, IChromosomeType chromosome, boolean inactive) { - if (!inactive) { - textLayout.drawSplitLine(text, x, maxWidth, getColorCoding(individual.getGenome().getActiveAllele(chromosome).isDominant())); - } else { - textLayout.drawSplitLine(text, x, maxWidth, getColorCoding(individual.getGenome().getInactiveAllele(chromosome).isDominant())); - } - } - - protected final void drawRow(String text0, String text1, String text2, IIndividual individual, IChromosomeType chromosome) { - textLayout.drawRow(text0, text1, text2, fontColor.get("gui.screen"), getColorCoding(individual.getGenome().getActiveAllele(chromosome).isDominant()), - getColorCoding(individual.getGenome().getInactiveAllele(chromosome).isDominant())); - } - - protected final void drawChromosomeRow(String chromosomeName, IIndividual individual, IChromosomeType chromosome) { - IAllele active = individual.getGenome().getActiveAllele(chromosome); - IAllele inactive = individual.getGenome().getInactiveAllele(chromosome); - textLayout.drawRow(chromosomeName, active.getName(), inactive.getName(), - fontColor.get("gui.screen"), getColorCoding(active.isDominant()), - getColorCoding(inactive.isDominant())); - } - - protected final void drawSpeciesRow(String text0, IIndividual individual, IChromosomeType chromosome, String customPrimaryName, String customSecondaryName) { - IAlleleSpecies primary = individual.getGenome().getPrimary(); - IAlleleSpecies secondary = individual.getGenome().getSecondary(); - - textLayout.drawLine(text0, textLayout.column0); - int columnwidth = textLayout.column2 - textLayout.column1 - 2; - - GuiUtil.drawItemStack(this, iconStacks.get(primary.getUID()), guiLeft + textLayout.column1 + (columnwidth - 20), guiTop + 10); - GuiUtil.drawItemStack(this, iconStacks.get(secondary.getUID()), guiLeft + textLayout.column2 + (columnwidth - 20), guiTop + 10); - - String primaryName = customPrimaryName == null ? primary.getName() : customPrimaryName; - String secondaryName = customSecondaryName == null ? secondary.getName() : customSecondaryName; - - drawSplitLine(primaryName, textLayout.column1, columnwidth, individual, chromosome, false); - drawSplitLine(secondaryName, textLayout.column2, columnwidth, individual, chromosome, true); - - textLayout.newLine(); - } - - protected static String checkCustomName(String key) { - if (StringUtil.canTranslate(key)) { - return StringUtil.localize(key); - } else { - return null; - } - } - - @Override - protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY); - widgetManager.clear(); - } - - protected void drawAnalyticsOverview() { - - textLayout.startPage(); - - textLayout.newLine(); - String title = StringUtil.localize(guiName).toUpperCase(); - textLayout.drawCenteredLine(title, 8, 208, fontColor.get("gui.screen")); - textLayout.newLine(); - - fontRendererObj.drawSplitString(StringUtil.localize(guiName + ".help"), guiLeft + COLUMN_0 + 4, guiTop + 42, 200, fontColor.get("gui.screen")); - textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); - - textLayout.drawLine(StringUtil.localize("gui.alyzer.overview") + ":", COLUMN_0 + 4); - textLayout.newLine(); - textLayout.drawLine("I : " + StringUtil.localize("gui.general"), COLUMN_0 + 4); - textLayout.newLine(); - textLayout.drawLine("II : " + StringUtil.localize("gui.environment"), COLUMN_0 + 4); - textLayout.newLine(); - textLayout.drawLine("III: " + StringUtil.localize("gui.produce"), COLUMN_0 + 4); - textLayout.newLine(); - textLayout.drawLine("IV : " + StringUtil.localize("gui.evolution"), COLUMN_0 + 4); - - textLayout.endPage(); - } - - protected final void drawAnalyticsPageClassification(IIndividual individual) { - - textLayout.startPage(); - - textLayout.drawLine(StringUtil.localize("gui.alyzer.classification") + ":", 12); - textLayout.newLine(); - - Stack hierarchy = new Stack<>(); - IClassification classification = individual.getGenome().getPrimary().getBranch(); - while (classification != null) { - - if (classification.getScientific() != null && !classification.getScientific().isEmpty()) { - hierarchy.push(classification); - } - classification = classification.getParent(); - } - - boolean overcrowded = hierarchy.size() > 5; - int x = 12; - IClassification group = null; - - while (!hierarchy.isEmpty()) { - - group = hierarchy.pop(); - if (overcrowded && group.getLevel().isDroppable()) { - continue; - } - - textLayout.drawLine(group.getScientific(), x, group.getLevel().getColour()); - textLayout.drawLine(group.getLevel().name(), 170, group.getLevel().getColour()); - textLayout.newLineCompressed(); - x += 12; - } - - // Add the species name - String binomial = individual.getGenome().getPrimary().getBinomial(); - if (group != null && group.getLevel() == EnumClassLevel.GENUS) { - binomial = group.getScientific().substring(0, 1) + ". " + binomial.toLowerCase(Locale.ENGLISH); - } - - textLayout.drawLine(binomial, x, 0xebae85); - textLayout.drawLine("SPECIES", 170, 0xebae85); - - textLayout.newLine(); - textLayout.drawLine(StringUtil.localize("gui.alyzer.authority") + ": " + individual.getGenome().getPrimary().getAuthority(), 12); - if (AlleleManager.alleleRegistry.isBlacklisted(individual.getIdent())) { - String extinct = ">> " + StringUtil.localize("gui.alyzer.extinct").toUpperCase() + " <<"; - fontRendererObj.drawStringWithShadow(extinct, guiLeft + 200 - fontRendererObj.getStringWidth(extinct), - guiTop + textLayout.getLineY(), fontColor.get("gui.beealyzer.dominant")); - } - - textLayout.newLine(); - String description = individual.getGenome().getPrimary().getDescription(); - if (StringUtils.isBlank(description) || description.startsWith("for.description.")) { - textLayout.drawSplitLine(StringUtil.localize("gui.alyzer.nodescription"), 12, 200, 0x666666); - } else { - String tokens[] = description.split("\\|"); - textLayout.drawSplitLine(tokens[0], 12, 200, 0x666666); - if (tokens.length > 1) { - String signature = "- " + tokens[1]; - fontRendererObj.drawStringWithShadow(signature, (guiLeft + 210) - fontRendererObj.getStringWidth(signature), guiTop + 145 - 14, 0x99cc32); - } - } - - textLayout.endPage(); - } - - protected void drawAnalyticsPageMutations(IIndividual individual) { - - textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); - textLayout.drawLine(StringUtil.localize("gui.beealyzer.mutations") + ":", COLUMN_0); - textLayout.newLine(); - - RenderHelper.enableGUIStandardItemLighting(); - - HashMap combinations = new HashMap<>(); - - for (IMutation mutation : speciesRoot.getCombinations(individual.getGenome().getPrimary())) { - combinations.put(mutation, individual.getGenome().getPrimary()); - } - - for (IMutation mutation : speciesRoot.getCombinations(individual.getGenome().getSecondary())) { - combinations.put(mutation, individual.getGenome().getSecondary()); - } - - int columnWidth = 50; - int x = 0; - - for (Map.Entry mutation : combinations.entrySet()) { - - if (breedingTracker.isDiscovered(mutation.getKey())) { - drawMutationInfo(mutation.getKey(), mutation.getValue(), COLUMN_0 + x); - } else { - // Do not display secret undiscovered mutations. - if (mutation.getKey().isSecret()) { - continue; - } - - drawUnknownMutation(mutation.getKey(), COLUMN_0 + x); - } - - x += columnWidth; - if (x >= columnWidth * 4) { - x = 0; - textLayout.newLine(16); - } - } - - textLayout.endPage(); - } - - protected void drawMutationInfo(IMutation combination, IAllele species, int x) { - - ItemStack partnerBee = iconStacks.get(combination.getPartner(species).getUID()); - widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), partnerBee)); - - drawProbabilityArrow(combination, guiLeft + x + 18, guiTop + textLayout.getLineY() + 4); - - IAllele result = combination.getTemplate()[EnumBeeChromosome.SPECIES.ordinal()]; - ItemStack resultBee = iconStacks.get(result.getUID()); - widgetManager.add(new ItemStackWidget(widgetManager, x + 33, textLayout.getLineY(), resultBee)); - } - - private void drawUnknownMutation(IMutation combination, int x) { - - drawQuestionMark(guiLeft + x, guiTop + textLayout.getLineY()); - - drawProbabilityArrow(combination, guiLeft + x + 18, guiTop + textLayout.getLineY() + 4); - - drawQuestionMark(guiLeft + x + 32, guiTop + textLayout.getLineY()); - } - - private void drawQuestionMark(int x, int y) { - Proxies.render.bindTexture(textureFile); - drawTexturedModalRect(x, y, 78, 240, 16, 16); - } - - private void drawProbabilityArrow(IMutation combination, int x, int y) { - float chance = combination.getBaseChance(); - int line = 247; - int column = 100; - switch (EnumMutateChance.rateChance(chance)) { - case HIGHEST: - column = 100; - break; - case HIGHER: - column = 100 + 15; - break; - case HIGH: - column = 100 + 15 * 2; - break; - case NORMAL: - column = 100 + 15 * 3; - break; - case LOW: - column = 100 + 15 * 4; - break; - case LOWEST: - column = 100 + 15 * 5; - default: - break; - } - - // Probability arrow - Proxies.render.bindTexture(textureFile); - drawTexturedModalRect(x, y, column, line, 15, 9); - - boolean researched = breedingTracker.isResearched(combination); - if (researched) { - fontRendererObj.drawString("+", x + 9, y + 1, 0); - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - } - } - - protected void drawToleranceInfo(IAlleleTolerance toleranceAllele, int x) { - int textColor = getColorCoding(toleranceAllele.isDominant()); - EnumTolerance tolerance = toleranceAllele.getValue(); - String text = "(" + toleranceAllele.getName() + ")"; - - // Enable correct lighting. - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - - switch (tolerance) { - case BOTH_1: - case BOTH_2: - case BOTH_3: - case BOTH_4: - case BOTH_5: - drawBothSymbol(x - 2, textLayout.getLineY() - 1); - textLayout.drawLine(text, x + 14, textColor); - break; - case DOWN_1: - case DOWN_2: - case DOWN_3: - case DOWN_4: - case DOWN_5: - drawDownSymbol(x - 2, textLayout.getLineY() - 1); - textLayout.drawLine(text, x + 14, textColor); - break; - case UP_1: - case UP_2: - case UP_3: - case UP_4: - case UP_5: - drawUpSymbol(x - 2, textLayout.getLineY() - 1); - textLayout.drawLine(text, x + 14, textColor); - break; - default: - drawNoneSymbol(x - 2, textLayout.getLineY() - 1); - textLayout.drawLine("(0)", x + 14, textColor); - break; - } - } - - private void drawDownSymbol(int x, int y) { - Proxies.render.bindTexture(textureFile); - drawTexturedModalRect(guiLeft + x, guiTop + y, 0, 247, 15, 9); - } - - private void drawUpSymbol(int x, int y) { - Proxies.render.bindTexture(textureFile); - drawTexturedModalRect(guiLeft + x, guiTop + y, 15, 247, 15, 9); - } - - private void drawBothSymbol(int x, int y) { - Proxies.render.bindTexture(textureFile); - drawTexturedModalRect(guiLeft + x, guiTop + y, 30, 247, 15, 9); - } - - private void drawNoneSymbol(int x, int y) { - Proxies.render.bindTexture(textureFile); - drawTexturedModalRect(guiLeft + x, guiTop + y, 45, 247, 15, 9); - } - - protected void drawFertilityInfo(int fertility, int x, int textColor, int texOffset) { - // Enable correct lighting. - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - - String fertilityString = Integer.toString(fertility) + " x"; - - int stringWidth = fontRendererObj.getStringWidth(fertilityString); - - Proxies.render.bindTexture(textureFile); - drawTexturedModalRect(guiLeft + x + stringWidth + 2, guiTop + textLayout.getLineY() - 1, 60, 240 + texOffset, 12, 8); - - textLayout.drawLine(fertilityString, x, textColor); - } - + protected static final int COLUMN_0 = 12; + protected static final int COLUMN_1 = 90; + protected static final int COLUMN_2 = 155; + + private final ISpeciesRoot speciesRoot; + private final IBreedingTracker breedingTracker; + + private final String guiName; + + protected final Map iconStacks = new HashMap<>(); + + protected GuiAlyzer( + ISpeciesRoot speciesRoot, + EntityPlayer player, + ContainerAlyzer container, + IInventory inventory, + String guiName) { + super(Constants.TEXTURE_PATH_GUI + "/beealyzer2.png", container, inventory); + + this.xSize = 246; + this.ySize = 238; + + this.guiName = guiName; + + this.speciesRoot = speciesRoot; + this.breedingTracker = this.speciesRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); + } + + protected final int getColorCoding(boolean dominant) { + if (dominant) { + return fontColor.get("gui.beealyzer.dominant"); + } else { + return fontColor.get("gui.beealyzer.recessive"); + } + } + + protected final void drawLine( + String text, int x, IIndividual individual, IChromosomeType chromosome, boolean inactive) { + if (!inactive) { + textLayout.drawLine( + text, + x, + getColorCoding( + individual.getGenome().getActiveAllele(chromosome).isDominant())); + } else { + textLayout.drawLine( + text, + x, + getColorCoding( + individual.getGenome().getInactiveAllele(chromosome).isDominant())); + } + } + + protected final void drawSplitLine( + String text, int x, int maxWidth, IIndividual individual, IChromosomeType chromosome, boolean inactive) { + if (!inactive) { + textLayout.drawSplitLine( + text, + x, + maxWidth, + getColorCoding( + individual.getGenome().getActiveAllele(chromosome).isDominant())); + } else { + textLayout.drawSplitLine( + text, + x, + maxWidth, + getColorCoding( + individual.getGenome().getInactiveAllele(chromosome).isDominant())); + } + } + + protected final void drawRow( + String text0, String text1, String text2, IIndividual individual, IChromosomeType chromosome) { + textLayout.drawRow( + text0, + text1, + text2, + fontColor.get("gui.screen"), + getColorCoding( + individual.getGenome().getActiveAllele(chromosome).isDominant()), + getColorCoding( + individual.getGenome().getInactiveAllele(chromosome).isDominant())); + } + + protected final void drawChromosomeRow(String chromosomeName, IIndividual individual, IChromosomeType chromosome) { + IAllele active = individual.getGenome().getActiveAllele(chromosome); + IAllele inactive = individual.getGenome().getInactiveAllele(chromosome); + textLayout.drawRow( + chromosomeName, + active.getName(), + inactive.getName(), + fontColor.get("gui.screen"), + getColorCoding(active.isDominant()), + getColorCoding(inactive.isDominant())); + } + + protected final void drawSpeciesRow( + String text0, + IIndividual individual, + IChromosomeType chromosome, + String customPrimaryName, + String customSecondaryName) { + IAlleleSpecies primary = individual.getGenome().getPrimary(); + IAlleleSpecies secondary = individual.getGenome().getSecondary(); + + textLayout.drawLine(text0, textLayout.column0); + int columnwidth = textLayout.column2 - textLayout.column1 - 2; + + GuiUtil.drawItemStack( + this, iconStacks.get(primary.getUID()), guiLeft + textLayout.column1 + (columnwidth - 20), guiTop + 10); + GuiUtil.drawItemStack( + this, + iconStacks.get(secondary.getUID()), + guiLeft + textLayout.column2 + (columnwidth - 20), + guiTop + 10); + + String primaryName = customPrimaryName == null ? primary.getName() : customPrimaryName; + String secondaryName = customSecondaryName == null ? secondary.getName() : customSecondaryName; + + drawSplitLine(primaryName, textLayout.column1, columnwidth, individual, chromosome, false); + drawSplitLine(secondaryName, textLayout.column2, columnwidth, individual, chromosome, true); + + textLayout.newLine(); + } + + protected static String checkCustomName(String key) { + if (StringUtil.canTranslate(key)) { + return StringUtil.localize(key); + } else { + return null; + } + } + + @Override + protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY); + widgetManager.clear(); + } + + protected void drawAnalyticsOverview() { + + textLayout.startPage(); + + textLayout.newLine(); + String title = StringUtil.localize(guiName).toUpperCase(); + textLayout.drawCenteredLine(title, 8, 208, fontColor.get("gui.screen")); + textLayout.newLine(); + + fontRendererObj.drawSplitString( + StringUtil.localize(guiName + ".help"), + guiLeft + COLUMN_0 + 4, + guiTop + 42, + 200, + fontColor.get("gui.screen")); + textLayout.newLine(); + textLayout.newLine(); + textLayout.newLine(); + + textLayout.drawLine(StringUtil.localize("gui.alyzer.overview") + ":", COLUMN_0 + 4); + textLayout.newLine(); + textLayout.drawLine("I : " + StringUtil.localize("gui.general"), COLUMN_0 + 4); + textLayout.newLine(); + textLayout.drawLine("II : " + StringUtil.localize("gui.environment"), COLUMN_0 + 4); + textLayout.newLine(); + textLayout.drawLine("III: " + StringUtil.localize("gui.produce"), COLUMN_0 + 4); + textLayout.newLine(); + textLayout.drawLine("IV : " + StringUtil.localize("gui.evolution"), COLUMN_0 + 4); + + textLayout.endPage(); + } + + protected final void drawAnalyticsPageClassification(IIndividual individual) { + + textLayout.startPage(); + + textLayout.drawLine(StringUtil.localize("gui.alyzer.classification") + ":", 12); + textLayout.newLine(); + + Stack hierarchy = new Stack<>(); + IClassification classification = individual.getGenome().getPrimary().getBranch(); + while (classification != null) { + + if (classification.getScientific() != null + && !classification.getScientific().isEmpty()) { + hierarchy.push(classification); + } + classification = classification.getParent(); + } + + boolean overcrowded = hierarchy.size() > 5; + int x = 12; + IClassification group = null; + + while (!hierarchy.isEmpty()) { + + group = hierarchy.pop(); + if (overcrowded && group.getLevel().isDroppable()) { + continue; + } + + textLayout.drawLine(group.getScientific(), x, group.getLevel().getColour()); + textLayout.drawLine(group.getLevel().name(), 170, group.getLevel().getColour()); + textLayout.newLineCompressed(); + x += 12; + } + + // Add the species name + String binomial = individual.getGenome().getPrimary().getBinomial(); + if (group != null && group.getLevel() == EnumClassLevel.GENUS) { + binomial = group.getScientific().substring(0, 1) + ". " + binomial.toLowerCase(Locale.ENGLISH); + } + + textLayout.drawLine(binomial, x, 0xebae85); + textLayout.drawLine("SPECIES", 170, 0xebae85); + + textLayout.newLine(); + textLayout.drawLine( + StringUtil.localize("gui.alyzer.authority") + ": " + + individual.getGenome().getPrimary().getAuthority(), + 12); + if (AlleleManager.alleleRegistry.isBlacklisted(individual.getIdent())) { + String extinct = ">> " + StringUtil.localize("gui.alyzer.extinct").toUpperCase() + " <<"; + fontRendererObj.drawStringWithShadow( + extinct, + guiLeft + 200 - fontRendererObj.getStringWidth(extinct), + guiTop + textLayout.getLineY(), + fontColor.get("gui.beealyzer.dominant")); + } + + textLayout.newLine(); + String description = individual.getGenome().getPrimary().getDescription(); + if (StringUtils.isBlank(description) || description.startsWith("for.description.")) { + textLayout.drawSplitLine(StringUtil.localize("gui.alyzer.nodescription"), 12, 200, 0x666666); + } else { + String tokens[] = description.split("\\|"); + textLayout.drawSplitLine(tokens[0], 12, 200, 0x666666); + if (tokens.length > 1) { + String signature = "- " + tokens[1]; + fontRendererObj.drawStringWithShadow( + signature, + (guiLeft + 210) - fontRendererObj.getStringWidth(signature), + guiTop + 145 - 14, + 0x99cc32); + } + } + + textLayout.endPage(); + } + + protected void drawAnalyticsPageMutations(IIndividual individual) { + + textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); + textLayout.drawLine(StringUtil.localize("gui.beealyzer.mutations") + ":", COLUMN_0); + textLayout.newLine(); + + RenderHelper.enableGUIStandardItemLighting(); + + HashMap combinations = new HashMap<>(); + + for (IMutation mutation : + speciesRoot.getCombinations(individual.getGenome().getPrimary())) { + combinations.put(mutation, individual.getGenome().getPrimary()); + } + + for (IMutation mutation : + speciesRoot.getCombinations(individual.getGenome().getSecondary())) { + combinations.put(mutation, individual.getGenome().getSecondary()); + } + + int columnWidth = 50; + int x = 0; + + for (Map.Entry mutation : combinations.entrySet()) { + + if (breedingTracker.isDiscovered(mutation.getKey())) { + drawMutationInfo(mutation.getKey(), mutation.getValue(), COLUMN_0 + x); + } else { + // Do not display secret undiscovered mutations. + if (mutation.getKey().isSecret()) { + continue; + } + + drawUnknownMutation(mutation.getKey(), COLUMN_0 + x); + } + + x += columnWidth; + if (x >= columnWidth * 4) { + x = 0; + textLayout.newLine(16); + } + } + + textLayout.endPage(); + } + + protected void drawMutationInfo(IMutation combination, IAllele species, int x) { + + ItemStack partnerBee = iconStacks.get(combination.getPartner(species).getUID()); + widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), partnerBee)); + + drawProbabilityArrow(combination, guiLeft + x + 18, guiTop + textLayout.getLineY() + 4); + + IAllele result = combination.getTemplate()[EnumBeeChromosome.SPECIES.ordinal()]; + ItemStack resultBee = iconStacks.get(result.getUID()); + widgetManager.add(new ItemStackWidget(widgetManager, x + 33, textLayout.getLineY(), resultBee)); + } + + private void drawUnknownMutation(IMutation combination, int x) { + + drawQuestionMark(guiLeft + x, guiTop + textLayout.getLineY()); + + drawProbabilityArrow(combination, guiLeft + x + 18, guiTop + textLayout.getLineY() + 4); + + drawQuestionMark(guiLeft + x + 32, guiTop + textLayout.getLineY()); + } + + private void drawQuestionMark(int x, int y) { + Proxies.render.bindTexture(textureFile); + drawTexturedModalRect(x, y, 78, 240, 16, 16); + } + + private void drawProbabilityArrow(IMutation combination, int x, int y) { + float chance = combination.getBaseChance(); + int line = 247; + int column = 100; + switch (EnumMutateChance.rateChance(chance)) { + case HIGHEST: + column = 100; + break; + case HIGHER: + column = 100 + 15; + break; + case HIGH: + column = 100 + 15 * 2; + break; + case NORMAL: + column = 100 + 15 * 3; + break; + case LOW: + column = 100 + 15 * 4; + break; + case LOWEST: + column = 100 + 15 * 5; + default: + break; + } + + // Probability arrow + Proxies.render.bindTexture(textureFile); + drawTexturedModalRect(x, y, column, line, 15, 9); + + boolean researched = breedingTracker.isResearched(combination); + if (researched) { + fontRendererObj.drawString("+", x + 9, y + 1, 0); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } + } + + protected void drawToleranceInfo(IAlleleTolerance toleranceAllele, int x) { + int textColor = getColorCoding(toleranceAllele.isDominant()); + EnumTolerance tolerance = toleranceAllele.getValue(); + String text = "(" + toleranceAllele.getName() + ")"; + + // Enable correct lighting. + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + switch (tolerance) { + case BOTH_1: + case BOTH_2: + case BOTH_3: + case BOTH_4: + case BOTH_5: + drawBothSymbol(x - 2, textLayout.getLineY() - 1); + textLayout.drawLine(text, x + 14, textColor); + break; + case DOWN_1: + case DOWN_2: + case DOWN_3: + case DOWN_4: + case DOWN_5: + drawDownSymbol(x - 2, textLayout.getLineY() - 1); + textLayout.drawLine(text, x + 14, textColor); + break; + case UP_1: + case UP_2: + case UP_3: + case UP_4: + case UP_5: + drawUpSymbol(x - 2, textLayout.getLineY() - 1); + textLayout.drawLine(text, x + 14, textColor); + break; + default: + drawNoneSymbol(x - 2, textLayout.getLineY() - 1); + textLayout.drawLine("(0)", x + 14, textColor); + break; + } + } + + private void drawDownSymbol(int x, int y) { + Proxies.render.bindTexture(textureFile); + drawTexturedModalRect(guiLeft + x, guiTop + y, 0, 247, 15, 9); + } + + private void drawUpSymbol(int x, int y) { + Proxies.render.bindTexture(textureFile); + drawTexturedModalRect(guiLeft + x, guiTop + y, 15, 247, 15, 9); + } + + private void drawBothSymbol(int x, int y) { + Proxies.render.bindTexture(textureFile); + drawTexturedModalRect(guiLeft + x, guiTop + y, 30, 247, 15, 9); + } + + private void drawNoneSymbol(int x, int y) { + Proxies.render.bindTexture(textureFile); + drawTexturedModalRect(guiLeft + x, guiTop + y, 45, 247, 15, 9); + } + + protected void drawFertilityInfo(int fertility, int x, int textColor, int texOffset) { + // Enable correct lighting. + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + String fertilityString = Integer.toString(fertility) + " x"; + + int stringWidth = fontRendererObj.getStringWidth(fertilityString); + + Proxies.render.bindTexture(textureFile); + drawTexturedModalRect( + guiLeft + x + stringWidth + 2, guiTop + textLayout.getLineY() - 1, 60, 240 + texOffset, 12, 8); + + textLayout.drawLine(fertilityString, x, textColor); + } } diff --git a/src/main/java/forestry/core/gui/GuiAnalyzer.java b/src/main/java/forestry/core/gui/GuiAnalyzer.java index 675c22b46..4d74ad22f 100755 --- a/src/main/java/forestry/core/gui/GuiAnalyzer.java +++ b/src/main/java/forestry/core/gui/GuiAnalyzer.java @@ -10,31 +10,34 @@ ******************************************************************************/ package forestry.core.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.widgets.TankWidget; import forestry.core.render.EnumTankLevel; import forestry.core.tiles.TileAnalyzer; +import net.minecraft.entity.player.InventoryPlayer; public class GuiAnalyzer extends GuiForestryTitled { - public GuiAnalyzer(InventoryPlayer inventory, TileAnalyzer tile) { - super(Constants.TEXTURE_PATH_GUI + "/alyzer.png", new ContainerAnalyzer(inventory, tile), tile); - ySize = 176; - widgetManager.add(new TankWidget(this.widgetManager, 95, 24, 0)); - } + public GuiAnalyzer(InventoryPlayer inventory, TileAnalyzer tile) { + super(Constants.TEXTURE_PATH_GUI + "/alyzer.png", new ContainerAnalyzer(inventory, tile), tile); + ySize = 176; + widgetManager.add(new TankWidget(this.widgetManager, 95, 24, 0)); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - drawAnalyzeMeter(guiLeft + 64, guiTop + 30, inventory.getProgressScaled(46), EnumTankLevel.rateTankLevel(inventory.getProgressScaled(100))); - } + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + drawAnalyzeMeter( + guiLeft + 64, + guiTop + 30, + inventory.getProgressScaled(46), + EnumTankLevel.rateTankLevel(inventory.getProgressScaled(100))); + } - private void drawAnalyzeMeter(int x, int y, int height, EnumTankLevel rated) { - int i = 176 + rated.getLevelScaled(16); - int k = 60; + private void drawAnalyzeMeter(int x, int y, int height, EnumTankLevel rated) { + int i = 176 + rated.getLevelScaled(16); + int k = 60; - drawTexturedModalRect(x, y + 46 - height, i, k + 46 - height, 4, height); - } + drawTexturedModalRect(x, y + 46 - height, i, k + 46 - height, 4, height); + } } diff --git a/src/main/java/forestry/core/gui/GuiEscritoire.java b/src/main/java/forestry/core/gui/GuiEscritoire.java index b8eacebf4..a8e255b5c 100755 --- a/src/main/java/forestry/core/gui/GuiEscritoire.java +++ b/src/main/java/forestry/core/gui/GuiEscritoire.java @@ -10,13 +10,6 @@ ******************************************************************************/ package forestry.core.gui; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumChatFormatting; - -import org.lwjgl.opengl.GL11; - import forestry.core.config.Constants; import forestry.core.gui.widgets.GameTokenWidget; import forestry.core.gui.widgets.ProbeButton; @@ -25,81 +18,86 @@ import forestry.core.tiles.EscritoireGame; import forestry.core.tiles.EscritoireTextSource; import forestry.core.tiles.TileEscritoire; import forestry.core.utils.StringUtil; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; +import org.lwjgl.opengl.GL11; public class GuiEscritoire extends GuiForestry { - private final ItemStack LEVEL_ITEM = new ItemStack(Items.paper); - private final EscritoireTextSource textSource = new EscritoireTextSource(); + private final ItemStack LEVEL_ITEM = new ItemStack(Items.paper); + private final EscritoireTextSource textSource = new EscritoireTextSource(); - public GuiEscritoire(EntityPlayer player, TileEscritoire tile) { - super(Constants.TEXTURE_PATH_GUI + "/escritoire.png", new ContainerEscritoire(player, tile), tile); + public GuiEscritoire(EntityPlayer player, TileEscritoire tile) { + super(Constants.TEXTURE_PATH_GUI + "/escritoire.png", new ContainerEscritoire(player, tile), tile); - xSize = 228; - ySize = 235; + xSize = 228; + ySize = 235; - widgetManager.add(new ProbeButton(this, widgetManager, 14, 16)); + widgetManager.add(new ProbeButton(this, widgetManager, 14, 16)); - EscritoireGame game = tile.getGame(); + EscritoireGame game = tile.getGame(); - // Inner ring - addTokenWidget(game, 115, 51, 0); - addTokenWidget(game, 115, 77, 1); - addTokenWidget(game, 94, 90, 2); - addTokenWidget(game, 73, 77, 3); - addTokenWidget(game, 73, 51, 4); - addTokenWidget(game, 94, 38, 5); + // Inner ring + addTokenWidget(game, 115, 51, 0); + addTokenWidget(game, 115, 77, 1); + addTokenWidget(game, 94, 90, 2); + addTokenWidget(game, 73, 77, 3); + addTokenWidget(game, 73, 51, 4); + addTokenWidget(game, 94, 38, 5); - // Outer ring - addTokenWidget(game, 115, 25, 6); - addTokenWidget(game, 136, 38, 7); - addTokenWidget(game, 136, 64, 8); + // Outer ring + addTokenWidget(game, 115, 25, 6); + addTokenWidget(game, 136, 38, 7); + addTokenWidget(game, 136, 64, 8); - addTokenWidget(game, 136, 90, 9); - addTokenWidget(game, 115, 103, 10); - addTokenWidget(game, 94, 116, 11); + addTokenWidget(game, 136, 90, 9); + addTokenWidget(game, 115, 103, 10); + addTokenWidget(game, 94, 116, 11); - addTokenWidget(game, 73, 103, 12); - addTokenWidget(game, 52, 90, 13); - addTokenWidget(game, 52, 64, 14); + addTokenWidget(game, 73, 103, 12); + addTokenWidget(game, 52, 90, 13); + addTokenWidget(game, 52, 64, 14); - addTokenWidget(game, 52, 38, 15); - addTokenWidget(game, 73, 25, 16); - addTokenWidget(game, 94, 12, 17); + addTokenWidget(game, 52, 38, 15); + addTokenWidget(game, 73, 25, 16); + addTokenWidget(game, 94, 12, 17); - // Corners - addTokenWidget(game, 52, 12, 18); - addTokenWidget(game, 136, 12, 19); - addTokenWidget(game, 52, 116, 20); - addTokenWidget(game, 136, 116, 21); - } + // Corners + addTokenWidget(game, 52, 12, 18); + addTokenWidget(game, 136, 12, 19); + addTokenWidget(game, 52, 116, 20); + addTokenWidget(game, 136, 116, 21); + } - private void addTokenWidget(EscritoireGame game, int x, int y, int index) { - Widget gameTokenWidget = new GameTokenWidget(game, widgetManager, x, y, index); - widgetManager.add(gameTokenWidget); - } + private void addTokenWidget(EscritoireGame game, int x, int y, int index) { + Widget gameTokenWidget = new GameTokenWidget(game, widgetManager, x, y, index); + widgetManager.add(gameTokenWidget); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - for (int i = 0; i <= inventory.getGame().getBountyLevel() / 4; i++) { - GuiUtil.drawItemStack(this, LEVEL_ITEM, guiLeft + 170 + i * 8, guiTop + 7); - } + for (int i = 0; i <= inventory.getGame().getBountyLevel() / 4; i++) { + GuiUtil.drawItemStack(this, LEVEL_ITEM, guiLeft + 170 + i * 8, guiTop + 7); + } - textLayout.startPage(); - { - GL11.glScaled(0.5, 0.5, 0.5); - GL11.glTranslated(guiLeft + 170, guiTop + 10, 0.0); + textLayout.startPage(); + { + GL11.glScaled(0.5, 0.5, 0.5); + GL11.glTranslated(guiLeft + 170, guiTop + 10, 0.0); - textLayout.newLine(); - textLayout.newLine(); - String format = EnumChatFormatting.UNDERLINE + EnumChatFormatting.ITALIC.toString(); - int attemptNo = EscritoireGame.BOUNTY_MAX - inventory.getGame().getBountyLevel(); - String attemptNoString = StringUtil.localizeAndFormat("gui.escritoire.attempt.number", attemptNo); - textLayout.drawLine(format + attemptNoString, 170, fontColor.get("gui.mail.lettertext")); - textLayout.newLine(); - String escritoireText = textSource.getText(inventory.getGame()); - textLayout.drawSplitLine(escritoireText, 170, 90, fontColor.get("gui.mail.lettertext")); - } - textLayout.endPage(); - } + textLayout.newLine(); + textLayout.newLine(); + String format = EnumChatFormatting.UNDERLINE + EnumChatFormatting.ITALIC.toString(); + int attemptNo = EscritoireGame.BOUNTY_MAX - inventory.getGame().getBountyLevel(); + String attemptNoString = StringUtil.localizeAndFormat("gui.escritoire.attempt.number", attemptNo); + textLayout.drawLine(format + attemptNoString, 170, fontColor.get("gui.mail.lettertext")); + textLayout.newLine(); + String escritoireText = textSource.getText(inventory.getGame()); + textLayout.drawSplitLine(escritoireText, 170, 90, fontColor.get("gui.mail.lettertext")); + } + textLayout.endPage(); + } } diff --git a/src/main/java/forestry/core/gui/GuiForestry.java b/src/main/java/forestry/core/gui/GuiForestry.java index 43d8d304d..dd7745d04 100755 --- a/src/main/java/forestry/core/gui/GuiForestry.java +++ b/src/main/java/forestry/core/gui/GuiForestry.java @@ -10,27 +10,10 @@ ******************************************************************************/ package forestry.core.gui; -import java.util.Collections; -import java.util.List; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.client.renderer.OpenGlHelper; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.client.renderer.entity.RenderItem; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - +import codechicken.nei.VisiblityData; +import codechicken.nei.api.INEIGuiHandler; +import codechicken.nei.api.TaggedInventoryArea; import cpw.mods.fml.common.Optional; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; - import forestry.api.core.IErrorLogicSource; import forestry.api.core.IErrorSource; import forestry.core.access.IRestrictedAccess; @@ -45,267 +28,282 @@ import forestry.core.proxy.Proxies; import forestry.core.render.FontColour; import forestry.core.tiles.IClimatised; import forestry.core.tiles.IPowerHandler; - -import codechicken.nei.VisiblityData; -import codechicken.nei.api.INEIGuiHandler; -import codechicken.nei.api.TaggedInventoryArea; +import java.util.Collections; +import java.util.List; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.renderer.OpenGlHelper; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; @Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems") -public abstract class GuiForestry extends GuiContainer implements INEIGuiHandler { - protected final I inventory; - protected final C container; +public abstract class GuiForestry extends GuiContainer + implements INEIGuiHandler { + protected final I inventory; + protected final C container; - public final ResourceLocation textureFile; - protected final WidgetManager widgetManager; - protected LedgerManager ledgerManager; - protected TextLayoutHelper textLayout; - protected FontColour fontColor; + public final ResourceLocation textureFile; + protected final WidgetManager widgetManager; + protected LedgerManager ledgerManager; + protected TextLayoutHelper textLayout; + protected FontColour fontColor; - protected GuiForestry(String texture, C container, I inventory) { - this(new ResourceLocation("forestry", texture), container, inventory); - } + protected GuiForestry(String texture, C container, I inventory) { + this(new ResourceLocation("forestry", texture), container, inventory); + } - protected GuiForestry(ResourceLocation texture, C container, I inventory) { - super(container); + protected GuiForestry(ResourceLocation texture, C container, I inventory) { + super(container); - this.widgetManager = new WidgetManager(this); + this.widgetManager = new WidgetManager(this); - this.textureFile = texture; + this.textureFile = texture; - this.inventory = inventory; - this.container = container; + this.inventory = inventory; + this.container = container; - this.fontColor = new FontColour(Proxies.render.getSelectedTexturePack()); - this.textLayout = new TextLayoutHelper(this, this.fontColor); - } + this.fontColor = new FontColour(Proxies.render.getSelectedTexturePack()); + this.textLayout = new TextLayoutHelper(this, this.fontColor); + } - @Override - public void setWorldAndResolution(Minecraft minecraft, int width, int height) { - super.setWorldAndResolution(minecraft, width, height); - textLayout.setFontRendererObj(fontRendererObj); - } + @Override + public void setWorldAndResolution(Minecraft minecraft, int width, int height) { + super.setWorldAndResolution(minecraft, width, height); + textLayout.setFontRendererObj(fontRendererObj); + } - /* LEDGERS */ - @Override - public void initGui() { - super.initGui(); + /* LEDGERS */ + @Override + public void initGui() { + super.initGui(); - int maxLedgerWidth = (this.width - this.xSize) / 2; - this.ledgerManager = new LedgerManager(this, maxLedgerWidth); + int maxLedgerWidth = (this.width - this.xSize) / 2; + this.ledgerManager = new LedgerManager(this, maxLedgerWidth); - addLedgers(); - } + addLedgers(); + } - protected void addLedgers() { - if (inventory instanceof IErrorSource) { - ledgerManager.add((IErrorSource) inventory); - } + protected void addLedgers() { + if (inventory instanceof IErrorSource) { + ledgerManager.add((IErrorSource) inventory); + } - if (inventory instanceof IErrorLogicSource) { - IErrorLogicSource errorLogicSource = (IErrorLogicSource) inventory; - ledgerManager.add(errorLogicSource.getErrorLogic()); - } + if (inventory instanceof IErrorLogicSource) { + IErrorLogicSource errorLogicSource = (IErrorLogicSource) inventory; + ledgerManager.add(errorLogicSource.getErrorLogic()); + } - if (inventory instanceof IClimatised) { - ledgerManager.add(new ClimateLedger(ledgerManager, (IClimatised) inventory)); - } + if (inventory instanceof IClimatised) { + ledgerManager.add(new ClimateLedger(ledgerManager, (IClimatised) inventory)); + } - if (Config.enableEnergyStat && inventory instanceof IPowerHandler && ((IPowerHandler) inventory).getEnergyManager().getMaxEnergyStored() > 0) { - ledgerManager.add(new PowerLedger(ledgerManager, (IPowerHandler) inventory)); - } + if (Config.enableEnergyStat + && inventory instanceof IPowerHandler + && ((IPowerHandler) inventory).getEnergyManager().getMaxEnergyStored() > 0) { + ledgerManager.add(new PowerLedger(ledgerManager, (IPowerHandler) inventory)); + } - if (Config.enableHints && inventory instanceof IHintSource) { - IHintSource hintSource = (IHintSource) inventory; - List hints = hintSource.getHints(); - if (hints != null && hints.size() > 0) { - ledgerManager.add(new HintLedger(ledgerManager, hintSource)); - } - } + if (Config.enableHints && inventory instanceof IHintSource) { + IHintSource hintSource = (IHintSource) inventory; + List hints = hintSource.getHints(); + if (hints != null && hints.size() > 0) { + ledgerManager.add(new HintLedger(ledgerManager, hintSource)); + } + } - if (inventory instanceof IRestrictedAccess) { - ledgerManager.add(new OwnerLedger(ledgerManager, (IRestrictedAccess) inventory)); - } - } + if (inventory instanceof IRestrictedAccess) { + ledgerManager.add(new OwnerLedger(ledgerManager, (IRestrictedAccess) inventory)); + } + } - @Override - public void onGuiClosed() { - super.onGuiClosed(); - ledgerManager.onGuiClosed(); - } + @Override + public void onGuiClosed() { + super.onGuiClosed(); + ledgerManager.onGuiClosed(); + } - public FontColour getFontColor() { - return fontColor; - } + public FontColour getFontColor() { + return fontColor; + } - public FontRenderer getFontRenderer() { - return fontRendererObj; - } + public FontRenderer getFontRenderer() { + return fontRendererObj; + } - @Override - protected void mouseClicked(int xPos, int yPos, int mouseButton) { - super.mouseClicked(xPos, yPos, mouseButton); + @Override + protected void mouseClicked(int xPos, int yPos, int mouseButton) { + super.mouseClicked(xPos, yPos, mouseButton); - // / Handle ledger clicks - ledgerManager.handleMouseClicked(xPos, yPos, mouseButton); - widgetManager.handleMouseClicked(xPos, yPos, mouseButton); - } + // / Handle ledger clicks + ledgerManager.handleMouseClicked(xPos, yPos, mouseButton); + widgetManager.handleMouseClicked(xPos, yPos, mouseButton); + } - @Override - protected void mouseMovedOrUp(int mouseX, int mouseY, int eventType) { - super.mouseMovedOrUp(mouseX, mouseY, eventType); + @Override + protected void mouseMovedOrUp(int mouseX, int mouseY, int eventType) { + super.mouseMovedOrUp(mouseX, mouseY, eventType); - widgetManager.handleMouseRelease(mouseX, mouseY, eventType); - } + widgetManager.handleMouseRelease(mouseX, mouseY, eventType); + } - @Override - protected void mouseClickMove(int mouseX, int mouseY, int mouseButton, long time) { + @Override + protected void mouseClickMove(int mouseX, int mouseY, int mouseButton, long time) { - widgetManager.handleMouseMove(mouseX, mouseY, mouseButton, time); + widgetManager.handleMouseMove(mouseX, mouseY, mouseButton, time); - super.mouseClickMove(mouseX, mouseY, mouseButton, time); - } + super.mouseClickMove(mouseX, mouseY, mouseButton, time); + } - protected Slot getSlotAtPosition(int par1, int par2) { - for (int k = 0; k < this.inventorySlots.inventorySlots.size(); ++k) { - Slot slot = (Slot) this.inventorySlots.inventorySlots.get(k); + protected Slot getSlotAtPosition(int par1, int par2) { + for (int k = 0; k < this.inventorySlots.inventorySlots.size(); ++k) { + Slot slot = (Slot) this.inventorySlots.inventorySlots.get(k); - if (isMouseOverSlot(slot, par1, par2)) { - return slot; - } - } + if (isMouseOverSlot(slot, par1, par2)) { + return slot; + } + } - return null; - } + return null; + } - private boolean isMouseOverSlot(Slot par1Slot, int par2, int par3) { - return this.func_146978_c(par1Slot.xDisplayPosition, par1Slot.yDisplayPosition, 16, 16, par2, par3); - } + private boolean isMouseOverSlot(Slot par1Slot, int par2, int par3) { + return this.func_146978_c(par1Slot.xDisplayPosition, par1Slot.yDisplayPosition, 16, 16, par2, par3); + } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - { - RenderHelper.enableGUIStandardItemLighting(); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240 / 1.0F, 240 / 1.0F); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + { + RenderHelper.enableGUIStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240 / 1.0F, 240 / 1.0F); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - ledgerManager.drawTooltips(mouseX, mouseY); + ledgerManager.drawTooltips(mouseX, mouseY); - InventoryPlayer playerInv = mc.thePlayer.inventory; + InventoryPlayer playerInv = mc.thePlayer.inventory; - if (playerInv.getItemStack() == null) { - GuiUtil.drawToolTips(this, widgetManager.getWidgets(), mouseX, mouseY); - GuiUtil.drawToolTips(this, buttonList, mouseX, mouseY); - GuiUtil.drawToolTips(this, inventorySlots.inventorySlots, mouseX, mouseY); - } - } - GL11.glPopAttrib(); - } + if (playerInv.getItemStack() == null) { + GuiUtil.drawToolTips(this, widgetManager.getWidgets(), mouseX, mouseY); + GuiUtil.drawToolTips(this, buttonList, mouseX, mouseY); + GuiUtil.drawToolTips(this, inventorySlots.inventorySlots, mouseX, mouseY); + } + } + GL11.glPopAttrib(); + } - @Override - protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { - bindTexture(textureFile); + @Override + protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { + bindTexture(textureFile); - int x = (width - xSize) / 2; - int y = (height - ySize) / 2; - drawTexturedModalRect(x, y, 0, 0, xSize, ySize); + int x = (width - xSize) / 2; + int y = (height - ySize) / 2; + drawTexturedModalRect(x, y, 0, 0, xSize, ySize); - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - { - RenderHelper.enableGUIStandardItemLighting(); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glPushMatrix(); - { - GL11.glTranslatef(guiLeft, guiTop, 0.0F); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + { + RenderHelper.enableGUIStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glPushMatrix(); + { + GL11.glTranslatef(guiLeft, guiTop, 0.0F); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240 / 1.0F, 240 / 1.0F); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240 / 1.0F, 240 / 1.0F); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - drawWidgets(); - } - GL11.glPopMatrix(); - } - GL11.glPopAttrib(); + drawWidgets(); + } + GL11.glPopMatrix(); + } + GL11.glPopAttrib(); - bindTexture(textureFile); - } + bindTexture(textureFile); + } - protected void drawWidgets() { - ledgerManager.drawLedgers(); - widgetManager.drawWidgets(); - } + protected void drawWidgets() { + ledgerManager.drawLedgers(); + widgetManager.drawWidgets(); + } - protected void bindTexture(ResourceLocation texturePath) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Proxies.render.bindTexture(texturePath); - } + protected void bindTexture(ResourceLocation texturePath) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Proxies.render.bindTexture(texturePath); + } - public void setZLevel(float level) { - this.zLevel = level; - } + public void setZLevel(float level) { + this.zLevel = level; + } - public static RenderItem getItemRenderer() { - return itemRender; - } + public static RenderItem getItemRenderer() { + return itemRender; + } - public int getSizeX() { - return xSize; - } + public int getSizeX() { + return xSize; + } - public int getSizeY() { - return ySize; - } + public int getSizeY() { + return ySize; + } - public int getGuiLeft() { - return guiLeft; - } + public int getGuiLeft() { + return guiLeft; + } - public int getGuiTop() { - return guiTop; - } + public int getGuiTop() { + return guiTop; + } - @Override - public void drawGradientRect(int par1, int par2, int par3, int par4, int par5, int par6) { - super.drawGradientRect(par1, par2, par3, par4, par5, par6); - } + @Override + public void drawGradientRect(int par1, int par2, int par3, int par4, int par5, int par6) { + super.drawGradientRect(par1, par2, par3, par4, par5, par6); + } - /* NEI */ - @Override - @Optional.Method(modid = "NotEnoughItems") - public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility) { - return null; - } + /* NEI */ + @Override + @Optional.Method(modid = "NotEnoughItems") + public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility) { + return null; + } - @Override - @Optional.Method(modid = "NotEnoughItems") - public Iterable getItemSpawnSlots(GuiContainer gui, ItemStack item) { - return Collections.emptyList(); - } + @Override + @Optional.Method(modid = "NotEnoughItems") + public Iterable getItemSpawnSlots(GuiContainer gui, ItemStack item) { + return Collections.emptyList(); + } - @Override - @Optional.Method(modid = "NotEnoughItems") - public List getInventoryAreas(GuiContainer gui) { - return Collections.emptyList(); - } + @Override + @Optional.Method(modid = "NotEnoughItems") + public List getInventoryAreas(GuiContainer gui) { + return Collections.emptyList(); + } - @Override - @Optional.Method(modid = "NotEnoughItems") - public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button) { - return false; - } + @Override + @Optional.Method(modid = "NotEnoughItems") + public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button) { + return false; + } - @Override - @Optional.Method(modid = "NotEnoughItems") - public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) { - if (gui instanceof GuiForestry) { - return ((GuiForestry) gui).ledgerManager.ledgerOverlaps(x, y, w, h); - } else { - return false; - } - } + @Override + @Optional.Method(modid = "NotEnoughItems") + public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) { + if (gui instanceof GuiForestry) { + return ((GuiForestry) gui).ledgerManager.ledgerOverlaps(x, y, w, h); + } else { + return false; + } + } } diff --git a/src/main/java/forestry/core/gui/GuiForestryTitled.java b/src/main/java/forestry/core/gui/GuiForestryTitled.java index 06349473e..fb1462beb 100644 --- a/src/main/java/forestry/core/gui/GuiForestryTitled.java +++ b/src/main/java/forestry/core/gui/GuiForestryTitled.java @@ -10,25 +10,24 @@ ******************************************************************************/ package forestry.core.gui; +import forestry.core.tiles.ITitled; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.util.StatCollector; -import forestry.core.tiles.ITitled; - public abstract class GuiForestryTitled extends GuiForestry { - protected GuiForestryTitled(String texture, C container, I inventory) { - super(texture, container, inventory); - } + protected GuiForestryTitled(String texture, C container, I inventory) { + super(texture, container, inventory); + } - @Override - protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY); - String name = StatCollector.translateToLocal(inventory.getUnlocalizedTitle()); - textLayout.line = 6; - textLayout.drawCenteredLine(name, 0, fontColor.get("gui.title")); - bindTexture(textureFile); - } + String name = StatCollector.translateToLocal(inventory.getUnlocalizedTitle()); + textLayout.line = 6; + textLayout.drawCenteredLine(name, 0, fontColor.get("gui.title")); + bindTexture(textureFile); + } } diff --git a/src/main/java/forestry/core/gui/GuiHandler.java b/src/main/java/forestry/core/gui/GuiHandler.java index 1ef367d6e..4d421e0d3 100644 --- a/src/main/java/forestry/core/gui/GuiHandler.java +++ b/src/main/java/forestry/core/gui/GuiHandler.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.gui; +import cpw.mods.fml.common.network.IGuiHandler; +import forestry.api.core.ForestryAPI; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; @@ -18,124 +20,126 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; -import cpw.mods.fml.common.network.IGuiHandler; - -import forestry.api.core.ForestryAPI; - public class GuiHandler implements IGuiHandler { - public static void openGui(EntityPlayer entityplayer, IGuiHandlerEntity guiHandler) { - openGui(entityplayer, guiHandler, (short) 0); - } + public static void openGui(EntityPlayer entityplayer, IGuiHandlerEntity guiHandler) { + openGui(entityplayer, guiHandler, (short) 0); + } - public static void openGui(EntityPlayer entityplayer, IGuiHandlerEntity guiHandler, short data) { - int guiData = encodeGuiData(guiHandler, data); - entityplayer.openGui(ForestryAPI.instance, guiData, entityplayer.worldObj, guiHandler.getIdOfEntity(), 0, 0); - } + public static void openGui(EntityPlayer entityplayer, IGuiHandlerEntity guiHandler, short data) { + int guiData = encodeGuiData(guiHandler, data); + entityplayer.openGui(ForestryAPI.instance, guiData, entityplayer.worldObj, guiHandler.getIdOfEntity(), 0, 0); + } - public static void openGui(EntityPlayer entityplayer, IGuiHandlerItem guiHandler) { - openGui(entityplayer, guiHandler, (short) 0); - } + public static void openGui(EntityPlayer entityplayer, IGuiHandlerItem guiHandler) { + openGui(entityplayer, guiHandler, (short) 0); + } - public static void openGui(EntityPlayer entityplayer, IGuiHandlerItem guiHandler, short data) { - int guiData = encodeGuiData(guiHandler, data); - entityplayer.openGui(ForestryAPI.instance, guiData, entityplayer.worldObj, 0, 0, 0); - } + public static void openGui(EntityPlayer entityplayer, IGuiHandlerItem guiHandler, short data) { + int guiData = encodeGuiData(guiHandler, data); + entityplayer.openGui(ForestryAPI.instance, guiData, entityplayer.worldObj, 0, 0, 0); + } - public static void openGui(EntityPlayer entityplayer, IGuiHandlerTile guiHandler) { - openGui(entityplayer, guiHandler, (short) 0); - } + public static void openGui(EntityPlayer entityplayer, IGuiHandlerTile guiHandler) { + openGui(entityplayer, guiHandler, (short) 0); + } - public static void openGui(EntityPlayer entityplayer, IGuiHandlerTile guiHandler, short data) { - int guiData = encodeGuiData(guiHandler, data); - ChunkCoordinates coordinates = guiHandler.getCoordinates(); - entityplayer.openGui(ForestryAPI.instance, guiData, entityplayer.worldObj, coordinates.posX, coordinates.posY, coordinates.posZ); - } + public static void openGui(EntityPlayer entityplayer, IGuiHandlerTile guiHandler, short data) { + int guiData = encodeGuiData(guiHandler, data); + ChunkCoordinates coordinates = guiHandler.getCoordinates(); + entityplayer.openGui( + ForestryAPI.instance, + guiData, + entityplayer.worldObj, + coordinates.posX, + coordinates.posY, + coordinates.posZ); + } - private static int encodeGuiData(IGuiHandlerForestry guiHandler, short data) { - GuiId guiId = GuiIdRegistry.getGuiIdForGuiHandler(guiHandler); - return data << 16 | guiId.getId(); - } + private static int encodeGuiData(IGuiHandlerForestry guiHandler, short data) { + GuiId guiId = GuiIdRegistry.getGuiIdForGuiHandler(guiHandler); + return data << 16 | guiId.getId(); + } - private static GuiId decodeGuiID(int guiData) { - int guiId = guiData & 0xFF; - return GuiIdRegistry.getGuiId(guiId); - } + private static GuiId decodeGuiID(int guiData) { + int guiId = guiData & 0xFF; + return GuiIdRegistry.getGuiId(guiId); + } - private static short decodeGuiData(int guiId) { - return (short) (guiId >> 16); - } + private static short decodeGuiData(int guiId) { + return (short) (guiId >> 16); + } - @Override - public Object getClientGuiElement(int guiData, EntityPlayer player, World world, int x, int y, int z) { - GuiId guiId = decodeGuiID(guiData); - if (guiId == null) { - return null; - } - short data = decodeGuiData(guiData); + @Override + public Object getClientGuiElement(int guiData, EntityPlayer player, World world, int x, int y, int z) { + GuiId guiId = decodeGuiID(guiData); + if (guiId == null) { + return null; + } + short data = decodeGuiData(guiData); - switch (guiId.getGuiType()) { - case Item: { - ItemStack heldItem = player.getCurrentEquippedItem(); - if (heldItem != null) { - Item item = heldItem.getItem(); - if (guiId.getGuiHandlerClass().isInstance(item)) { - return ((IGuiHandlerItem) item).getGui(player, heldItem, data); - } - } - break; - } - case Tile: { - TileEntity tileEntity = world.getTileEntity(x, y, z); - if (guiId.getGuiHandlerClass().isInstance(tileEntity)) { - return ((IGuiHandlerTile) tileEntity).getGui(player, data); - } - break; - } - case Entity: { - Entity entity = world.getEntityByID(x); - if (guiId.getGuiHandlerClass().isInstance(entity)) { - return ((IGuiHandlerEntity) entity).getGui(player, data); - } - break; - } - } - return null; - } + switch (guiId.getGuiType()) { + case Item: { + ItemStack heldItem = player.getCurrentEquippedItem(); + if (heldItem != null) { + Item item = heldItem.getItem(); + if (guiId.getGuiHandlerClass().isInstance(item)) { + return ((IGuiHandlerItem) item).getGui(player, heldItem, data); + } + } + break; + } + case Tile: { + TileEntity tileEntity = world.getTileEntity(x, y, z); + if (guiId.getGuiHandlerClass().isInstance(tileEntity)) { + return ((IGuiHandlerTile) tileEntity).getGui(player, data); + } + break; + } + case Entity: { + Entity entity = world.getEntityByID(x); + if (guiId.getGuiHandlerClass().isInstance(entity)) { + return ((IGuiHandlerEntity) entity).getGui(player, data); + } + break; + } + } + return null; + } - @Override - public Object getServerGuiElement(int guiData, EntityPlayer player, World world, int x, int y, int z) { - GuiId guiId = decodeGuiID(guiData); - if (guiId == null) { - return null; - } - short data = decodeGuiData(guiData); + @Override + public Object getServerGuiElement(int guiData, EntityPlayer player, World world, int x, int y, int z) { + GuiId guiId = decodeGuiID(guiData); + if (guiId == null) { + return null; + } + short data = decodeGuiData(guiData); - switch (guiId.getGuiType()) { - case Item: { - ItemStack heldItem = player.getCurrentEquippedItem(); - if (heldItem != null) { - Item item = heldItem.getItem(); - if (guiId.getGuiHandlerClass().isInstance(item)) { - return ((IGuiHandlerItem) item).getContainer(player, heldItem, data); - } - } - break; - } - case Tile: { - TileEntity tileEntity = world.getTileEntity(x, y, z); - if (guiId.getGuiHandlerClass().isInstance(tileEntity)) { - return ((IGuiHandlerTile) tileEntity).getContainer(player, data); - } - break; - } - case Entity: { - Entity entity = world.getEntityByID(x); - if (guiId.getGuiHandlerClass().isInstance(entity)) { - return ((IGuiHandlerEntity) entity).getContainer(player, data); - } - break; - } - } - return null; - } + switch (guiId.getGuiType()) { + case Item: { + ItemStack heldItem = player.getCurrentEquippedItem(); + if (heldItem != null) { + Item item = heldItem.getItem(); + if (guiId.getGuiHandlerClass().isInstance(item)) { + return ((IGuiHandlerItem) item).getContainer(player, heldItem, data); + } + } + break; + } + case Tile: { + TileEntity tileEntity = world.getTileEntity(x, y, z); + if (guiId.getGuiHandlerClass().isInstance(tileEntity)) { + return ((IGuiHandlerTile) tileEntity).getContainer(player, data); + } + break; + } + case Entity: { + Entity entity = world.getEntityByID(x); + if (guiId.getGuiHandlerClass().isInstance(entity)) { + return ((IGuiHandlerEntity) entity).getContainer(player, data); + } + break; + } + } + return null; + } } diff --git a/src/main/java/forestry/core/gui/GuiId.java b/src/main/java/forestry/core/gui/GuiId.java index 7b5f2a429..3834594bc 100644 --- a/src/main/java/forestry/core/gui/GuiId.java +++ b/src/main/java/forestry/core/gui/GuiId.java @@ -1,35 +1,35 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -public class GuiId { - private final int id; - private final GuiType guiType; - private final Class guiHandlerClass; - - GuiId(int id, GuiType guiType, Class guiHandlerClass) { - this.id = id; - this.guiType = guiType; - this.guiHandlerClass = guiHandlerClass; - } - - public GuiType getGuiType() { - return guiType; - } - - public Class getGuiHandlerClass() { - return guiHandlerClass; - } - - public int getId() { - return id; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +public class GuiId { + private final int id; + private final GuiType guiType; + private final Class guiHandlerClass; + + GuiId(int id, GuiType guiType, Class guiHandlerClass) { + this.id = id; + this.guiType = guiType; + this.guiHandlerClass = guiHandlerClass; + } + + public GuiType getGuiType() { + return guiType; + } + + public Class getGuiHandlerClass() { + return guiHandlerClass; + } + + public int getId() { + return id; + } +} diff --git a/src/main/java/forestry/core/gui/GuiIdRegistry.java b/src/main/java/forestry/core/gui/GuiIdRegistry.java index 258cff8f0..511a360d8 100644 --- a/src/main/java/forestry/core/gui/GuiIdRegistry.java +++ b/src/main/java/forestry/core/gui/GuiIdRegistry.java @@ -1,146 +1,143 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import forestry.apiculture.entities.EntityMinecartApiary; -import forestry.apiculture.entities.EntityMinecartBeehouse; -import forestry.apiculture.items.ItemBeealyzer; -import forestry.apiculture.items.ItemHabitatLocator; -import forestry.apiculture.items.ItemImprinter; -import forestry.apiculture.multiblock.TileAlveary; -import forestry.apiculture.multiblock.TileAlvearyHygroregulator; -import forestry.apiculture.multiblock.TileAlvearySieve; -import forestry.apiculture.tiles.TileApiary; -import forestry.apiculture.tiles.TileBeehouse; -import forestry.arboriculture.items.ItemTreealyzer; -import forestry.core.items.ItemSolderingIron; -import forestry.core.tiles.TileAnalyzer; -import forestry.core.tiles.TileEscritoire; -import forestry.core.tiles.TileNaturalistChest; -import forestry.energy.tiles.TileEngineBiogas; -import forestry.energy.tiles.TileEngineElectric; -import forestry.energy.tiles.TileEnginePeat; -import forestry.energy.tiles.TileGenerator; -import forestry.factory.tiles.TileBottler; -import forestry.factory.tiles.TileCarpenter; -import forestry.factory.tiles.TileCentrifuge; -import forestry.factory.tiles.TileFabricator; -import forestry.factory.tiles.TileFermenter; -import forestry.factory.tiles.TileMoistener; -import forestry.factory.tiles.TileRaintank; -import forestry.factory.tiles.TileSqueezer; -import forestry.factory.tiles.TileStill; -import forestry.factory.tiles.TileWorktable; -import forestry.farming.tiles.TileFarm; -import forestry.food.items.ItemInfuser; -import forestry.lepidopterology.items.ItemFlutterlyzer; -import forestry.mail.items.ItemCatalogue; -import forestry.mail.items.ItemLetter; -import forestry.mail.tiles.TileMailbox; -import forestry.mail.tiles.TileStampCollector; -import forestry.mail.tiles.TileTrader; -import forestry.storage.items.ItemBackpack; -import forestry.storage.items.ItemBackpackNaturalist; - -public class GuiIdRegistry { - private static final Map, GuiId> classMap = new HashMap<>(); - private static final Map idMap = new HashMap<>(); - private static int nextId = 0; - - static { - registerGuiHandlers(GuiType.Tile, Arrays.>asList( - TileAlveary.class, - TileAlvearyHygroregulator.class, - TileAlvearySieve.class, - TileApiary.class, - TileBeehouse.class, - - TileAnalyzer.class, - TileEscritoire.class, - TileNaturalistChest.class, - TileRaintank.class, - TileWorktable.class, - - TileBottler.class, - TileCarpenter.class, - TileCentrifuge.class, - TileFabricator.class, - TileFermenter.class, - TileMoistener.class, - TileSqueezer.class, - TileStill.class, - - TileFarm.class, - - TileEngineBiogas.class, - TileEngineElectric.class, - TileEnginePeat.class, - TileGenerator.class, - - TileMailbox.class, - TileStampCollector.class, - TileTrader.class - )); - - registerGuiHandlers(GuiType.Item, Arrays.>asList( - ItemBackpack.class, - ItemBackpackNaturalist.class, - ItemBeealyzer.class, - ItemCatalogue.class, - ItemFlutterlyzer.class, - ItemHabitatLocator.class, - ItemImprinter.class, - ItemInfuser.class, - ItemLetter.class, - ItemSolderingIron.class, - ItemTreealyzer.class - )); - - registerGuiHandlers(GuiType.Entity, Arrays.>asList( - EntityMinecartApiary.class, - EntityMinecartBeehouse.class - )); - } - - private static void registerGuiHandlers(GuiType guiType, List> guiHandlerClasses) { - for (Class tileGuiHandlerClass : guiHandlerClasses) { - GuiId guiId = new GuiId(nextId++, guiType, tileGuiHandlerClass); - classMap.put(tileGuiHandlerClass, guiId); - idMap.put(guiId.getId(), guiId); - } - } - - public static GuiId getGuiIdForGuiHandler(IGuiHandlerForestry guiHandler) { - Class guiHandlerClass = guiHandler.getClass(); - GuiId guiId = classMap.get(guiHandlerClass); - if (guiId == null) { - for (Map.Entry, GuiId> classGuiIdEntry : classMap.entrySet()) { - if (classGuiIdEntry.getKey().isAssignableFrom(guiHandlerClass)) { - guiId = classGuiIdEntry.getValue(); - break; - } - } - } - if (guiId == null) { - throw new IllegalStateException("No gui ID for gui handler: " + guiHandler); - } - return guiId; - } - - public static GuiId getGuiId(int id) { - return idMap.get(id); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +import forestry.apiculture.entities.EntityMinecartApiary; +import forestry.apiculture.entities.EntityMinecartBeehouse; +import forestry.apiculture.items.ItemBeealyzer; +import forestry.apiculture.items.ItemHabitatLocator; +import forestry.apiculture.items.ItemImprinter; +import forestry.apiculture.multiblock.TileAlveary; +import forestry.apiculture.multiblock.TileAlvearyHygroregulator; +import forestry.apiculture.multiblock.TileAlvearySieve; +import forestry.apiculture.tiles.TileApiary; +import forestry.apiculture.tiles.TileBeehouse; +import forestry.arboriculture.items.ItemTreealyzer; +import forestry.core.items.ItemSolderingIron; +import forestry.core.tiles.TileAnalyzer; +import forestry.core.tiles.TileEscritoire; +import forestry.core.tiles.TileNaturalistChest; +import forestry.energy.tiles.TileEngineBiogas; +import forestry.energy.tiles.TileEngineElectric; +import forestry.energy.tiles.TileEnginePeat; +import forestry.energy.tiles.TileGenerator; +import forestry.factory.tiles.TileBottler; +import forestry.factory.tiles.TileCarpenter; +import forestry.factory.tiles.TileCentrifuge; +import forestry.factory.tiles.TileFabricator; +import forestry.factory.tiles.TileFermenter; +import forestry.factory.tiles.TileMoistener; +import forestry.factory.tiles.TileRaintank; +import forestry.factory.tiles.TileSqueezer; +import forestry.factory.tiles.TileStill; +import forestry.factory.tiles.TileWorktable; +import forestry.farming.tiles.TileFarm; +import forestry.food.items.ItemInfuser; +import forestry.lepidopterology.items.ItemFlutterlyzer; +import forestry.mail.items.ItemCatalogue; +import forestry.mail.items.ItemLetter; +import forestry.mail.tiles.TileMailbox; +import forestry.mail.tiles.TileStampCollector; +import forestry.mail.tiles.TileTrader; +import forestry.storage.items.ItemBackpack; +import forestry.storage.items.ItemBackpackNaturalist; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class GuiIdRegistry { + private static final Map, GuiId> classMap = new HashMap<>(); + private static final Map idMap = new HashMap<>(); + private static int nextId = 0; + + static { + registerGuiHandlers( + GuiType.Tile, + Arrays.>asList( + TileAlveary.class, + TileAlvearyHygroregulator.class, + TileAlvearySieve.class, + TileApiary.class, + TileBeehouse.class, + TileAnalyzer.class, + TileEscritoire.class, + TileNaturalistChest.class, + TileRaintank.class, + TileWorktable.class, + TileBottler.class, + TileCarpenter.class, + TileCentrifuge.class, + TileFabricator.class, + TileFermenter.class, + TileMoistener.class, + TileSqueezer.class, + TileStill.class, + TileFarm.class, + TileEngineBiogas.class, + TileEngineElectric.class, + TileEnginePeat.class, + TileGenerator.class, + TileMailbox.class, + TileStampCollector.class, + TileTrader.class)); + + registerGuiHandlers( + GuiType.Item, + Arrays.>asList( + ItemBackpack.class, + ItemBackpackNaturalist.class, + ItemBeealyzer.class, + ItemCatalogue.class, + ItemFlutterlyzer.class, + ItemHabitatLocator.class, + ItemImprinter.class, + ItemInfuser.class, + ItemLetter.class, + ItemSolderingIron.class, + ItemTreealyzer.class)); + + registerGuiHandlers( + GuiType.Entity, + Arrays.>asList( + EntityMinecartApiary.class, EntityMinecartBeehouse.class)); + } + + private static void registerGuiHandlers( + GuiType guiType, List> guiHandlerClasses) { + for (Class tileGuiHandlerClass : guiHandlerClasses) { + GuiId guiId = new GuiId(nextId++, guiType, tileGuiHandlerClass); + classMap.put(tileGuiHandlerClass, guiId); + idMap.put(guiId.getId(), guiId); + } + } + + public static GuiId getGuiIdForGuiHandler(IGuiHandlerForestry guiHandler) { + Class guiHandlerClass = guiHandler.getClass(); + GuiId guiId = classMap.get(guiHandlerClass); + if (guiId == null) { + for (Map.Entry, GuiId> classGuiIdEntry : classMap.entrySet()) { + if (classGuiIdEntry.getKey().isAssignableFrom(guiHandlerClass)) { + guiId = classGuiIdEntry.getValue(); + break; + } + } + } + if (guiId == null) { + throw new IllegalStateException("No gui ID for gui handler: " + guiHandler); + } + return guiId; + } + + public static GuiId getGuiId(int id) { + return idMap.get(id); + } +} diff --git a/src/main/java/forestry/core/gui/GuiNaturalistInventory.java b/src/main/java/forestry/core/gui/GuiNaturalistInventory.java index 15a9c7471..8c8c5a28d 100755 --- a/src/main/java/forestry/core/gui/GuiNaturalistInventory.java +++ b/src/main/java/forestry/core/gui/GuiNaturalistInventory.java @@ -10,15 +10,6 @@ ******************************************************************************/ package forestry.core.gui; -import java.util.HashMap; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; - import forestry.api.apiculture.IApiaristTracker; import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.genetics.IAlleleSpecies; @@ -33,219 +24,247 @@ import forestry.core.gui.buttons.StandardButtonTextureSets; import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.proxy.Proxies; import forestry.core.utils.StringUtil; +import java.util.HashMap; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; public class GuiNaturalistInventory extends GuiForestry { - private final ISpeciesRoot speciesRoot; - private final IBreedingTracker breedingTracker; - private final HashMap iconStacks = new HashMap<>(); - private final int pageCurrent, pageMax; + private final ISpeciesRoot speciesRoot; + private final IBreedingTracker breedingTracker; + private final HashMap iconStacks = new HashMap<>(); + private final int pageCurrent, pageMax; - public GuiNaturalistInventory(ISpeciesRoot speciesRoot, EntityPlayer player, Container container, IPagedInventory inventory, int page, int maxPages) { - super(Constants.TEXTURE_PATH_GUI + "/apiaristinventory.png", container, inventory); + public GuiNaturalistInventory( + ISpeciesRoot speciesRoot, + EntityPlayer player, + Container container, + IPagedInventory inventory, + int page, + int maxPages) { + super(Constants.TEXTURE_PATH_GUI + "/apiaristinventory.png", container, inventory); - this.speciesRoot = speciesRoot; + this.speciesRoot = speciesRoot; - this.pageCurrent = page; - this.pageMax = maxPages; + this.pageCurrent = page; + this.pageMax = maxPages; - xSize = 196; - ySize = 202; + xSize = 196; + ySize = 202; - for (IIndividual individual : speciesRoot.getIndividualTemplates()) { - iconStacks.put(individual.getIdent(), speciesRoot.getMemberStack(individual, 0)); - } + for (IIndividual individual : speciesRoot.getIndividualTemplates()) { + iconStacks.put(individual.getIdent(), speciesRoot.getMemberStack(individual, 0)); + } - breedingTracker = speciesRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); - } + breedingTracker = speciesRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); + } - @Override - protected void drawGuiContainerBackgroundLayer(float f, int i, int j) { - super.drawGuiContainerBackgroundLayer(f, i, j); - String header = StringUtil.localize("gui.page") + " " + (pageCurrent + 1) + "/" + pageMax; - fontRendererObj.drawString(header, guiLeft + 95 + textLayout.getCenteredOffset(header, 98), guiTop + 10, fontColor.get("gui.title")); + @Override + protected void drawGuiContainerBackgroundLayer(float f, int i, int j) { + super.drawGuiContainerBackgroundLayer(f, i, j); + String header = StringUtil.localize("gui.page") + " " + (pageCurrent + 1) + "/" + pageMax; + fontRendererObj.drawString( + header, + guiLeft + 95 + textLayout.getCenteredOffset(header, 98), + guiTop + 10, + fontColor.get("gui.title")); - IIndividual individual = getIndividualAtPosition(i, j); - if (individual == null) { - displayBreedingStatistics(10); - } + IIndividual individual = getIndividualAtPosition(i, j); + if (individual == null) { + displayBreedingStatistics(10); + } - if (individual != null) { - RenderHelper.enableGUIStandardItemLighting(); - textLayout.startPage(); + if (individual != null) { + RenderHelper.enableGUIStandardItemLighting(); + textLayout.startPage(); - displaySpeciesInformation(true, individual.getGenome().getPrimary(), iconStacks.get(individual.getIdent()), 10); - if (!individual.isPureBred(EnumTreeChromosome.SPECIES)) { - displaySpeciesInformation(individual.isAnalyzed(), individual.getGenome().getSecondary(), iconStacks.get(individual.getGenome().getSecondary().getUID()), 10); - } + displaySpeciesInformation( + true, individual.getGenome().getPrimary(), iconStacks.get(individual.getIdent()), 10); + if (!individual.isPureBred(EnumTreeChromosome.SPECIES)) { + displaySpeciesInformation( + individual.isAnalyzed(), + individual.getGenome().getSecondary(), + iconStacks.get(individual.getGenome().getSecondary().getUID()), + 10); + } - textLayout.endPage(); - } - } + textLayout.endPage(); + } + } - @SuppressWarnings("unchecked") - @Override - public void initGui() { - super.initGui(); + @SuppressWarnings("unchecked") + @Override + public void initGui() { + super.initGui(); - buttonList.add(new GuiBetterButton(1, guiLeft + 99, guiTop + 7, StandardButtonTextureSets.LEFT_BUTTON_SMALL)); - buttonList.add(new GuiBetterButton(2, guiLeft + 180, guiTop + 7, StandardButtonTextureSets.RIGHT_BUTTON_SMALL)); - } + buttonList.add(new GuiBetterButton(1, guiLeft + 99, guiTop + 7, StandardButtonTextureSets.LEFT_BUTTON_SMALL)); + buttonList.add(new GuiBetterButton(2, guiLeft + 180, guiTop + 7, StandardButtonTextureSets.RIGHT_BUTTON_SMALL)); + } - private static void flipPage(int page) { - Proxies.net.sendToServer(new PacketGuiSelectRequest(page, 0)); - } + private static void flipPage(int page) { + Proxies.net.sendToServer(new PacketGuiSelectRequest(page, 0)); + } - @Override - protected void actionPerformed(GuiButton guibutton) { - super.actionPerformed(guibutton); + @Override + protected void actionPerformed(GuiButton guibutton) { + super.actionPerformed(guibutton); - if (guibutton.id == 1 && pageCurrent > 0) { - flipPage(pageCurrent - 1); - } else if (guibutton.id == 2 && pageCurrent < pageMax - 1) { - flipPage(pageCurrent + 1); - } - } + if (guibutton.id == 1 && pageCurrent > 0) { + flipPage(pageCurrent - 1); + } else if (guibutton.id == 2 && pageCurrent < pageMax - 1) { + flipPage(pageCurrent + 1); + } + } - private IIndividual getIndividualAtPosition(int x, int y) { - Slot slot = getSlotAtPosition(x, y); - if (slot == null) { - return null; - } + private IIndividual getIndividualAtPosition(int x, int y) { + Slot slot = getSlotAtPosition(x, y); + if (slot == null) { + return null; + } - if (!slot.getHasStack()) { - return null; - } + if (!slot.getHasStack()) { + return null; + } - if (!slot.getStack().hasTagCompound()) { - return null; - } + if (!slot.getStack().hasTagCompound()) { + return null; + } - if (!speciesRoot.isMember(slot.getStack())) { - return null; - } + if (!speciesRoot.isMember(slot.getStack())) { + return null; + } - return speciesRoot.getMember(slot.getStack()); - } + return speciesRoot.getMember(slot.getStack()); + } - private void displayBreedingStatistics(int x) { + private void displayBreedingStatistics(int x) { - textLayout.startPage(); + textLayout.startPage(); - textLayout.drawLine(StringUtil.localize("gui.speciescount") + ": " + breedingTracker.getSpeciesBred() + "/" + speciesRoot.getSpeciesCount(), x); - textLayout.newLine(); - textLayout.newLine(); + textLayout.drawLine( + StringUtil.localize("gui.speciescount") + ": " + breedingTracker.getSpeciesBred() + "/" + + speciesRoot.getSpeciesCount(), + x); + textLayout.newLine(); + textLayout.newLine(); - if (breedingTracker instanceof IApiaristTracker) { - IApiaristTracker tracker = (IApiaristTracker) breedingTracker; - textLayout.drawLine(StringUtil.localize("gui.queens") + ": " + tracker.getQueenCount(), x); - textLayout.newLine(); + if (breedingTracker instanceof IApiaristTracker) { + IApiaristTracker tracker = (IApiaristTracker) breedingTracker; + textLayout.drawLine(StringUtil.localize("gui.queens") + ": " + tracker.getQueenCount(), x); + textLayout.newLine(); - textLayout.drawLine(StringUtil.localize("gui.princesses") + ": " + tracker.getPrincessCount(), x); - textLayout.newLine(); + textLayout.drawLine(StringUtil.localize("gui.princesses") + ": " + tracker.getPrincessCount(), x); + textLayout.newLine(); - textLayout.drawLine(StringUtil.localize("gui.drones") + ": " + tracker.getDroneCount(), x); - textLayout.newLine(); - } + textLayout.drawLine(StringUtil.localize("gui.drones") + ": " + tracker.getDroneCount(), x); + textLayout.newLine(); + } - textLayout.endPage(); - } + textLayout.endPage(); + } - private void displaySpeciesInformation(boolean analyzed, IAlleleSpecies species, ItemStack iconStack, int x) { + private void displaySpeciesInformation(boolean analyzed, IAlleleSpecies species, ItemStack iconStack, int x) { - if (!analyzed) { - textLayout.drawLine(StringUtil.localize("gui.unknown"), x); - return; - } + if (!analyzed) { + textLayout.drawLine(StringUtil.localize("gui.unknown"), x); + return; + } - textLayout.drawLine(species.getName(), x); - GuiUtil.drawItemStack(this, iconStack, guiLeft + x + 69, guiTop + textLayout.getLineY() - 2); + textLayout.drawLine(species.getName(), x); + GuiUtil.drawItemStack(this, iconStack, guiLeft + x + 69, guiTop + textLayout.getLineY() - 2); - textLayout.newLine(); + textLayout.newLine(); - // Viable Combinations - int columnWidth = 16; - int column = 10; + // Viable Combinations + int columnWidth = 16; + int column = 10; - for (IMutation combination : speciesRoot.getCombinations(species)) { - if (combination.isSecret()) { - continue; - } + for (IMutation combination : speciesRoot.getCombinations(species)) { + if (combination.isSecret()) { + continue; + } - if (breedingTracker.isDiscovered(combination)) { - drawMutationIcon(combination, species, column); - } else { - drawUnknownIcon(combination, column); - } + if (breedingTracker.isDiscovered(combination)) { + drawMutationIcon(combination, species, column); + } else { + drawUnknownIcon(combination, column); + } - column += columnWidth; - if (column > 75) { - column = 10; - textLayout.newLine(18); - } - } + column += columnWidth; + if (column > 75) { + column = 10; + textLayout.newLine(18); + } + } - textLayout.newLine(); - textLayout.newLine(); - } + textLayout.newLine(); + textLayout.newLine(); + } - private void drawMutationIcon(IMutation combination, IAlleleSpecies species, int x) { - GuiUtil.drawItemStack(this, iconStacks.get(combination.getPartner(species).getUID()), guiLeft + x, guiTop + textLayout.getLineY()); + private void drawMutationIcon(IMutation combination, IAlleleSpecies species, int x) { + GuiUtil.drawItemStack( + this, + iconStacks.get(combination.getPartner(species).getUID()), + guiLeft + x, + guiTop + textLayout.getLineY()); - int line = 48; - int column; - EnumMutateChance chance = EnumMutateChance.rateChance(combination.getBaseChance()); - if (chance == EnumMutateChance.HIGHEST) { - line += 16; - column = 228; - } else if (chance == EnumMutateChance.HIGHER) { - line += 16; - column = 212; - } else if (chance == EnumMutateChance.HIGH) { - line += 16; - column = 196; - } else if (chance == EnumMutateChance.NORMAL) { - line += 0; - column = 228; - } else if (chance == EnumMutateChance.LOW) { - line += 0; - column = 212; - } else { - line += 0; - column = 196; - } + int line = 48; + int column; + EnumMutateChance chance = EnumMutateChance.rateChance(combination.getBaseChance()); + if (chance == EnumMutateChance.HIGHEST) { + line += 16; + column = 228; + } else if (chance == EnumMutateChance.HIGHER) { + line += 16; + column = 212; + } else if (chance == EnumMutateChance.HIGH) { + line += 16; + column = 196; + } else if (chance == EnumMutateChance.NORMAL) { + line += 0; + column = 228; + } else if (chance == EnumMutateChance.LOW) { + line += 0; + column = 212; + } else { + line += 0; + column = 196; + } - Proxies.render.bindTexture(textureFile); - drawTexturedModalRect(guiLeft + x, guiTop + textLayout.getLineY(), column, line, 16, 16); + Proxies.render.bindTexture(textureFile); + drawTexturedModalRect(guiLeft + x, guiTop + textLayout.getLineY(), column, line, 16, 16); + } - } + private void drawUnknownIcon(IMutation mutation, int x) { - private void drawUnknownIcon(IMutation mutation, int x) { + float chance = mutation.getBaseChance(); - float chance = mutation.getBaseChance(); + int line; + int column; + if (chance >= 20) { + line = 16; + column = 228; + } else if (chance >= 15) { + line = 16; + column = 212; + } else if (chance >= 12) { + line = 16; + column = 196; + } else if (chance >= 10) { + line = 0; + column = 228; + } else if (chance >= 5) { + line = 0; + column = 212; + } else { + line = 0; + column = 196; + } - int line; - int column; - if (chance >= 20) { - line = 16; - column = 228; - } else if (chance >= 15) { - line = 16; - column = 212; - } else if (chance >= 12) { - line = 16; - column = 196; - } else if (chance >= 10) { - line = 0; - column = 228; - } else if (chance >= 5) { - line = 0; - column = 212; - } else { - line = 0; - column = 196; - } - - Proxies.render.bindTexture(textureFile); - drawTexturedModalRect(guiLeft + x, guiTop + textLayout.getLineY(), column, line, 16, 16); - } + Proxies.render.bindTexture(textureFile); + drawTexturedModalRect(guiLeft + x, guiTop + textLayout.getLineY(), column, line, 16, 16); + } } diff --git a/src/main/java/forestry/core/gui/GuiTextBox.java b/src/main/java/forestry/core/gui/GuiTextBox.java index 6ca4e5dcd..8a332c9c8 100755 --- a/src/main/java/forestry/core/gui/GuiTextBox.java +++ b/src/main/java/forestry/core/gui/GuiTextBox.java @@ -11,103 +11,104 @@ package forestry.core.gui; import java.util.List; - import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiTextField; public class GuiTextBox extends GuiTextField { - private static final int enabledColor = 14737632; - private static final int disabledColor = 7368816; + private static final int enabledColor = 14737632; + private static final int disabledColor = 7368816; - private final FontRenderer fontRendererObj; - private final int startX, startY, width, height; + private final FontRenderer fontRendererObj; + private final int startX, startY, width, height; - private int lineScroll = 0; - private int maxLines = 0; + private int lineScroll = 0; + private int maxLines = 0; - public GuiTextBox(FontRenderer fontRendererObj, int startX, int startY, int width, int height) { - super(fontRendererObj, startX, startY, width, height); - this.fontRendererObj = fontRendererObj; - this.startX = startX; - this.startY = startY; - this.width = width; - this.height = height; - } + public GuiTextBox(FontRenderer fontRendererObj, int startX, int startY, int width, int height) { + super(fontRendererObj, startX, startY, width, height); + this.fontRendererObj = fontRendererObj; + this.startX = startX; + this.startY = startY; + this.width = width; + this.height = height; + } - private int getLineScrollOffset() { - return 0; - } + private int getLineScrollOffset() { + return 0; + } - public void advanceLine() { - if (lineScroll < maxLines - 1) { - lineScroll++; - } - } + public void advanceLine() { + if (lineScroll < maxLines - 1) { + lineScroll++; + } + } - public void regressLine() { - if (lineScroll > 0) { - lineScroll--; - } - } + public void regressLine() { + if (lineScroll > 0) { + lineScroll--; + } + } - public boolean moreLinesAllowed() { - return fontRendererObj.listFormattedStringToWidth(getCursoredText(), width).size() * fontRendererObj.FONT_HEIGHT < height; - } + public boolean moreLinesAllowed() { + return fontRendererObj + .listFormattedStringToWidth(getCursoredText(), width) + .size() + * fontRendererObj.FONT_HEIGHT + < height; + } - private String getCursoredText() { - if (!isFocused()) { - return getText(); - } + private String getCursoredText() { + if (!isFocused()) { + return getText(); + } - int cursorPos = getCursorPosition() - getLineScrollOffset(); - String text = getText(); - if (cursorPos < 0) { - return text; - } - if (cursorPos >= text.length()) { - return text + "_"; - } - return text.substring(0, cursorPos) + "_" + text.substring(cursorPos); - } + int cursorPos = getCursorPosition() - getLineScrollOffset(); + String text = getText(); + if (cursorPos < 0) { + return text; + } + if (cursorPos >= text.length()) { + return text + "_"; + } + return text.substring(0, cursorPos) + "_" + text.substring(cursorPos); + } - @SuppressWarnings("unchecked") - private void drawScrolledSplitString(String text, int startX, int startY, int width, int textColour) { - List lines = fontRendererObj.listFormattedStringToWidth(text, width); - maxLines = lines.size(); + @SuppressWarnings("unchecked") + private void drawScrolledSplitString(String text, int startX, int startY, int width, int textColour) { + List lines = fontRendererObj.listFormattedStringToWidth(text, width); + maxLines = lines.size(); - int count = 0; - int lineY = startY; + int count = 0; + int lineY = startY; - for (String line : lines) { - if (count < lineScroll) { - count++; - continue; - } else if (lineY + fontRendererObj.FONT_HEIGHT - startY > height) { - break; - } + for (String line : lines) { + if (count < lineScroll) { + count++; + continue; + } else if (lineY + fontRendererObj.FONT_HEIGHT - startY > height) { + break; + } - fontRendererObj.drawString(line, startX, lineY, textColour); - lineY += fontRendererObj.FONT_HEIGHT; + fontRendererObj.drawString(line, startX, lineY, textColour); + lineY += fontRendererObj.FONT_HEIGHT; - count++; - } + count++; + } + } - } + @Override + public void drawTextBox() { + if (!getVisible()) { + return; + } - @Override - public void drawTextBox() { - if (!getVisible()) { - return; - } + if (getEnableBackgroundDrawing()) { + drawRect(startX - 1, startY - 1, startX + this.width + 1, startY + this.height + 1, -6250336); + drawRect(startX, startY, startX + this.width, startY + this.height, -16777216); + } - if (getEnableBackgroundDrawing()) { - drawRect(startX - 1, startY - 1, startX + this.width + 1, startY + this.height + 1, -6250336); - drawRect(startX, startY, startX + this.width, startY + this.height, -16777216); - } - - int textColour = isFocused() ? enabledColor : disabledColor; - - drawScrolledSplitString(getCursoredText(), startX + 2, startY + 2, width - 4, textColour); - } + int textColour = isFocused() ? enabledColor : disabledColor; + drawScrolledSplitString(getCursoredText(), startX + 2, startY + 2, width - 4, textColour); + } } diff --git a/src/main/java/forestry/core/gui/GuiType.java b/src/main/java/forestry/core/gui/GuiType.java index f413b701c..aa754aad1 100644 --- a/src/main/java/forestry/core/gui/GuiType.java +++ b/src/main/java/forestry/core/gui/GuiType.java @@ -11,7 +11,7 @@ package forestry.core.gui; public enum GuiType { - Item, - Tile, - Entity; + Item, + Tile, + Entity; } diff --git a/src/main/java/forestry/core/gui/GuiUtil.java b/src/main/java/forestry/core/gui/GuiUtil.java index 2c7970939..aaaf0f04f 100644 --- a/src/main/java/forestry/core/gui/GuiUtil.java +++ b/src/main/java/forestry/core/gui/GuiUtil.java @@ -1,145 +1,146 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -import java.awt.Color; -import java.util.Collection; - -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.client.renderer.entity.RenderItem; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumChatFormatting; - -import org.lwjgl.opengl.GL11; - -import forestry.core.gui.tooltips.IToolTipProvider; -import forestry.core.gui.tooltips.ToolTip; -import forestry.core.gui.tooltips.ToolTipLine; - -public class GuiUtil { - public static void drawItemStack(GuiForestry gui, ItemStack stack, int xPos, int yPos) { - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - RenderHelper.enableGUIStandardItemLighting(); - - RenderItem itemRender = GuiForestry.getItemRenderer(); - - GL11.glTranslatef(0.0F, 0.0F, 32.0F); - gui.setZLevel(100.0F); - itemRender.zLevel = 100.0F; - FontRenderer font = null; - if (stack != null) { - font = stack.getItem().getFontRenderer(stack); - } - if (font == null) { - font = gui.getFontRenderer(); - } - itemRender.renderItemAndEffectIntoGUI(font, gui.mc.getTextureManager(), stack, xPos, yPos); - itemRender.renderItemOverlayIntoGUI(font, gui.mc.getTextureManager(), stack, xPos, yPos); - gui.setZLevel(0.0F); - itemRender.zLevel = 0.0F; - - RenderHelper.disableStandardItemLighting(); - GL11.glPopAttrib(); - } - - public static void drawToolTips(GuiForestry gui, ToolTip toolTips, int mouseX, int mouseY) { - if (toolTips == null) { - return; - } - if (toolTips.isEmpty()) { - return; - } - - RenderItem itemRender = GuiForestry.getItemRenderer(); - FontRenderer fontRendererObj = gui.getFontRenderer(); - - int left = gui.getGuiLeft(); - int top = gui.getGuiTop(); - int length = 0; - int height = 0; - int x; - int y; - - for (ToolTipLine tip : toolTips) { - y = fontRendererObj.getStringWidth(tip.toString()); - - height += 10 + tip.getSpacing(); - if (y > length) { - length = y; - } - } - - x = mouseX - left + 12; - y = mouseY - top - 12; - - gui.setZLevel(300.0F); - itemRender.zLevel = 300.0F; - Color backgroundColor = new Color(16, 0, 16, 240); - int backgroundColorInt = backgroundColor.getRGB(); - gui.drawGradientRect(x - 3, y - 4, x + length + 2, y - 3, backgroundColorInt, backgroundColorInt); - gui.drawGradientRect(x - 3, y + height + 1, x + length + 2, y + height + 2, backgroundColorInt, backgroundColorInt); - gui.drawGradientRect(x - 3, y - 3, x + length + 2, y + height + 1, backgroundColorInt, backgroundColorInt); - gui.drawGradientRect(x - 4, y - 3, x - 3, y + height + 1, backgroundColorInt, backgroundColorInt); - gui.drawGradientRect(x + length + 2, y - 3, x + length + 3, y + height + 1, backgroundColorInt, backgroundColorInt); - - Color borderColorTop = new Color(80, 0, 255, 80); - int borderColorTopInt = borderColorTop.getRGB(); - Color borderColorBottom = new Color((borderColorTopInt & 0xfefefe) >> 1 | borderColorTopInt & -0x1000000, true); - int borderColorBottomInt = borderColorBottom.getRGB(); - gui.drawGradientRect(x - 3, y - 3 + 1, x - 3 + 1, y + height, borderColorTopInt, borderColorBottomInt); - gui.drawGradientRect(x + length + 1, y - 3 + 1, x + length + 2, y + height, borderColorTopInt, borderColorBottomInt); - gui.drawGradientRect(x - 3, y - 3, x + length + 2, y - 3 + 1, borderColorTopInt, borderColorTopInt); - gui.drawGradientRect(x - 3, y + height, x + length + 2, y + height + 1, borderColorBottomInt, borderColorBottomInt); - - boolean firstLine = true; - for (ToolTipLine tip : toolTips) { - String line; - - if (firstLine) { - line = tip.toString(); - } else { - line = EnumChatFormatting.GRAY + tip.toString(); - } - - fontRendererObj.drawStringWithShadow(line, x, y, -1); - - y += 10 + tip.getSpacing(); - - firstLine = false; - } - - gui.setZLevel(0.0F); - itemRender.zLevel = 0.0F; - } - - public static void drawToolTips(GuiForestry gui, Collection objects, int mouseX, int mouseY) { - for (Object obj : objects) { - if (!(obj instanceof IToolTipProvider)) { - continue; - } - IToolTipProvider provider = (IToolTipProvider) obj; - if (!provider.isToolTipVisible()) { - continue; - } - ToolTip tips = provider.getToolTip(mouseX - gui.getGuiLeft(), mouseY - gui.getGuiTop()); - if (tips == null) { - continue; - } - boolean mouseOver = provider.isMouseOver(mouseX - gui.getGuiLeft(), mouseY - gui.getGuiTop()); - tips.onTick(mouseOver); - if (mouseOver && tips.isReady()) { - tips.refresh(); - drawToolTips(gui, tips, mouseX, mouseY); - } - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +import forestry.core.gui.tooltips.IToolTipProvider; +import forestry.core.gui.tooltips.ToolTip; +import forestry.core.gui.tooltips.ToolTipLine; +import java.awt.Color; +import java.util.Collection; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; +import org.lwjgl.opengl.GL11; + +public class GuiUtil { + public static void drawItemStack(GuiForestry gui, ItemStack stack, int xPos, int yPos) { + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + RenderHelper.enableGUIStandardItemLighting(); + + RenderItem itemRender = GuiForestry.getItemRenderer(); + + GL11.glTranslatef(0.0F, 0.0F, 32.0F); + gui.setZLevel(100.0F); + itemRender.zLevel = 100.0F; + FontRenderer font = null; + if (stack != null) { + font = stack.getItem().getFontRenderer(stack); + } + if (font == null) { + font = gui.getFontRenderer(); + } + itemRender.renderItemAndEffectIntoGUI(font, gui.mc.getTextureManager(), stack, xPos, yPos); + itemRender.renderItemOverlayIntoGUI(font, gui.mc.getTextureManager(), stack, xPos, yPos); + gui.setZLevel(0.0F); + itemRender.zLevel = 0.0F; + + RenderHelper.disableStandardItemLighting(); + GL11.glPopAttrib(); + } + + public static void drawToolTips(GuiForestry gui, ToolTip toolTips, int mouseX, int mouseY) { + if (toolTips == null) { + return; + } + if (toolTips.isEmpty()) { + return; + } + + RenderItem itemRender = GuiForestry.getItemRenderer(); + FontRenderer fontRendererObj = gui.getFontRenderer(); + + int left = gui.getGuiLeft(); + int top = gui.getGuiTop(); + int length = 0; + int height = 0; + int x; + int y; + + for (ToolTipLine tip : toolTips) { + y = fontRendererObj.getStringWidth(tip.toString()); + + height += 10 + tip.getSpacing(); + if (y > length) { + length = y; + } + } + + x = mouseX - left + 12; + y = mouseY - top - 12; + + gui.setZLevel(300.0F); + itemRender.zLevel = 300.0F; + Color backgroundColor = new Color(16, 0, 16, 240); + int backgroundColorInt = backgroundColor.getRGB(); + gui.drawGradientRect(x - 3, y - 4, x + length + 2, y - 3, backgroundColorInt, backgroundColorInt); + gui.drawGradientRect( + x - 3, y + height + 1, x + length + 2, y + height + 2, backgroundColorInt, backgroundColorInt); + gui.drawGradientRect(x - 3, y - 3, x + length + 2, y + height + 1, backgroundColorInt, backgroundColorInt); + gui.drawGradientRect(x - 4, y - 3, x - 3, y + height + 1, backgroundColorInt, backgroundColorInt); + gui.drawGradientRect( + x + length + 2, y - 3, x + length + 3, y + height + 1, backgroundColorInt, backgroundColorInt); + + Color borderColorTop = new Color(80, 0, 255, 80); + int borderColorTopInt = borderColorTop.getRGB(); + Color borderColorBottom = new Color((borderColorTopInt & 0xfefefe) >> 1 | borderColorTopInt & -0x1000000, true); + int borderColorBottomInt = borderColorBottom.getRGB(); + gui.drawGradientRect(x - 3, y - 3 + 1, x - 3 + 1, y + height, borderColorTopInt, borderColorBottomInt); + gui.drawGradientRect( + x + length + 1, y - 3 + 1, x + length + 2, y + height, borderColorTopInt, borderColorBottomInt); + gui.drawGradientRect(x - 3, y - 3, x + length + 2, y - 3 + 1, borderColorTopInt, borderColorTopInt); + gui.drawGradientRect( + x - 3, y + height, x + length + 2, y + height + 1, borderColorBottomInt, borderColorBottomInt); + + boolean firstLine = true; + for (ToolTipLine tip : toolTips) { + String line; + + if (firstLine) { + line = tip.toString(); + } else { + line = EnumChatFormatting.GRAY + tip.toString(); + } + + fontRendererObj.drawStringWithShadow(line, x, y, -1); + + y += 10 + tip.getSpacing(); + + firstLine = false; + } + + gui.setZLevel(0.0F); + itemRender.zLevel = 0.0F; + } + + public static void drawToolTips(GuiForestry gui, Collection objects, int mouseX, int mouseY) { + for (Object obj : objects) { + if (!(obj instanceof IToolTipProvider)) { + continue; + } + IToolTipProvider provider = (IToolTipProvider) obj; + if (!provider.isToolTipVisible()) { + continue; + } + ToolTip tips = provider.getToolTip(mouseX - gui.getGuiLeft(), mouseY - gui.getGuiTop()); + if (tips == null) { + continue; + } + boolean mouseOver = provider.isMouseOver(mouseX - gui.getGuiLeft(), mouseY - gui.getGuiTop()); + tips.onTick(mouseOver); + if (mouseOver && tips.isReady()) { + tips.refresh(); + drawToolTips(gui, tips, mouseX, mouseY); + } + } + } +} diff --git a/src/main/java/forestry/core/gui/IContainerCrafting.java b/src/main/java/forestry/core/gui/IContainerCrafting.java index a9340bcae..eab493219 100644 --- a/src/main/java/forestry/core/gui/IContainerCrafting.java +++ b/src/main/java/forestry/core/gui/IContainerCrafting.java @@ -13,5 +13,5 @@ package forestry.core.gui; import net.minecraft.inventory.IInventory; public interface IContainerCrafting { - void onCraftMatrixChanged(IInventory iinventory, int slot); + void onCraftMatrixChanged(IInventory iinventory, int slot); } diff --git a/src/main/java/forestry/core/gui/IContainerLiquidTanks.java b/src/main/java/forestry/core/gui/IContainerLiquidTanks.java index 87e6749cc..ceadd42d4 100644 --- a/src/main/java/forestry/core/gui/IContainerLiquidTanks.java +++ b/src/main/java/forestry/core/gui/IContainerLiquidTanks.java @@ -1,24 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; - -import net.minecraftforge.fluids.IFluidTank; - -public interface IContainerLiquidTanks { - void handlePipetteClickClient(int slot, EntityPlayer player); - - void handlePipetteClick(int slot, EntityPlayerMP player); - - IFluidTank getTank(int slot); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraftforge.fluids.IFluidTank; + +public interface IContainerLiquidTanks { + void handlePipetteClickClient(int slot, EntityPlayer player); + + void handlePipetteClick(int slot, EntityPlayerMP player); + + IFluidTank getTank(int slot); +} diff --git a/src/main/java/forestry/core/gui/IContainerSocketed.java b/src/main/java/forestry/core/gui/IContainerSocketed.java index 46cb6ae5b..a19ad6e82 100644 --- a/src/main/java/forestry/core/gui/IContainerSocketed.java +++ b/src/main/java/forestry/core/gui/IContainerSocketed.java @@ -1,24 +1,24 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; - -public interface IContainerSocketed { - void handleChipsetClick(int slot); - - void handleChipsetClickServer(int slot, EntityPlayerMP player, ItemStack itemstack); - - void handleSolderingIronClick(int slot); - - void handleSolderingIronClickServer(int slot, EntityPlayerMP player, ItemStack itemstack); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; + +public interface IContainerSocketed { + void handleChipsetClick(int slot); + + void handleChipsetClickServer(int slot, EntityPlayerMP player, ItemStack itemstack); + + void handleSolderingIronClick(int slot); + + void handleSolderingIronClickServer(int slot, EntityPlayerMP player, ItemStack itemstack); +} diff --git a/src/main/java/forestry/core/gui/IGuiHandlerEntity.java b/src/main/java/forestry/core/gui/IGuiHandlerEntity.java index a44f4639d..13922624e 100644 --- a/src/main/java/forestry/core/gui/IGuiHandlerEntity.java +++ b/src/main/java/forestry/core/gui/IGuiHandlerEntity.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -import net.minecraft.entity.player.EntityPlayer; - -public interface IGuiHandlerEntity extends IGuiHandlerForestry { - Object getGui(EntityPlayer player, int data); - - Object getContainer(EntityPlayer player, int data); - - // can't be named getEntityId() for obfuscation reasons - int getIdOfEntity(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +import net.minecraft.entity.player.EntityPlayer; + +public interface IGuiHandlerEntity extends IGuiHandlerForestry { + Object getGui(EntityPlayer player, int data); + + Object getContainer(EntityPlayer player, int data); + + // can't be named getEntityId() for obfuscation reasons + int getIdOfEntity(); +} diff --git a/src/main/java/forestry/core/gui/IGuiHandlerForestry.java b/src/main/java/forestry/core/gui/IGuiHandlerForestry.java index 29b4731f6..71f0cdf2d 100644 --- a/src/main/java/forestry/core/gui/IGuiHandlerForestry.java +++ b/src/main/java/forestry/core/gui/IGuiHandlerForestry.java @@ -1,14 +1,13 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -public interface IGuiHandlerForestry { -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +public interface IGuiHandlerForestry {} diff --git a/src/main/java/forestry/core/gui/IGuiHandlerItem.java b/src/main/java/forestry/core/gui/IGuiHandlerItem.java index 05bf7bc89..565d6869e 100644 --- a/src/main/java/forestry/core/gui/IGuiHandlerItem.java +++ b/src/main/java/forestry/core/gui/IGuiHandlerItem.java @@ -1,20 +1,20 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -public interface IGuiHandlerItem extends IGuiHandlerForestry { - Object getGui(EntityPlayer player, ItemStack heldItem, int data); - - Object getContainer(EntityPlayer player, ItemStack heldItem, int data); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public interface IGuiHandlerItem extends IGuiHandlerForestry { + Object getGui(EntityPlayer player, ItemStack heldItem, int data); + + Object getContainer(EntityPlayer player, ItemStack heldItem, int data); +} diff --git a/src/main/java/forestry/core/gui/IGuiHandlerTile.java b/src/main/java/forestry/core/gui/IGuiHandlerTile.java index 21319613f..033a06f96 100644 --- a/src/main/java/forestry/core/gui/IGuiHandlerTile.java +++ b/src/main/java/forestry/core/gui/IGuiHandlerTile.java @@ -1,21 +1,20 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -import net.minecraft.entity.player.EntityPlayer; - -import forestry.core.tiles.ILocatable; - -public interface IGuiHandlerTile extends IGuiHandlerForestry, ILocatable { - Object getGui(EntityPlayer player, int data); - - Object getContainer(EntityPlayer player, int data); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +import forestry.core.tiles.ILocatable; +import net.minecraft.entity.player.EntityPlayer; + +public interface IGuiHandlerTile extends IGuiHandlerForestry, ILocatable { + Object getGui(EntityPlayer player, int data); + + Object getContainer(EntityPlayer player, int data); +} diff --git a/src/main/java/forestry/core/gui/IGuiSelectable.java b/src/main/java/forestry/core/gui/IGuiSelectable.java index 34cf95fe0..83086c23a 100755 --- a/src/main/java/forestry/core/gui/IGuiSelectable.java +++ b/src/main/java/forestry/core/gui/IGuiSelectable.java @@ -10,11 +10,10 @@ ******************************************************************************/ package forestry.core.gui; +import forestry.core.network.packets.PacketGuiSelectRequest; import net.minecraft.entity.player.EntityPlayerMP; -import forestry.core.network.packets.PacketGuiSelectRequest; - public interface IGuiSelectable { - // server - void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packetRequest); + // server + void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packetRequest); } diff --git a/src/main/java/forestry/core/gui/IHintSource.java b/src/main/java/forestry/core/gui/IHintSource.java index 9d9911eda..03d4b432d 100644 --- a/src/main/java/forestry/core/gui/IHintSource.java +++ b/src/main/java/forestry/core/gui/IHintSource.java @@ -13,5 +13,5 @@ package forestry.core.gui; import java.util.List; public interface IHintSource { - List getHints(); + List getHints(); } diff --git a/src/main/java/forestry/core/gui/IPagedInventory.java b/src/main/java/forestry/core/gui/IPagedInventory.java index b396f12b9..833fa5324 100755 --- a/src/main/java/forestry/core/gui/IPagedInventory.java +++ b/src/main/java/forestry/core/gui/IPagedInventory.java @@ -18,5 +18,5 @@ import net.minecraft.inventory.IInventory; */ public interface IPagedInventory extends IInventory { - void flipPage(EntityPlayer player, short page); + void flipPage(EntityPlayer player, short page); } diff --git a/src/main/java/forestry/core/gui/TextLayoutHelper.java b/src/main/java/forestry/core/gui/TextLayoutHelper.java index 56eceb944..9c2a25480 100644 --- a/src/main/java/forestry/core/gui/TextLayoutHelper.java +++ b/src/main/java/forestry/core/gui/TextLayoutHelper.java @@ -1,111 +1,114 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -import net.minecraft.client.gui.FontRenderer; - -import org.lwjgl.opengl.GL11; - -import forestry.core.render.FontColour; - -public class TextLayoutHelper { - private static final int LINE_HEIGHT = 12; - - private final GuiForestry guiForestry; - private final int defaultFontColor; - private FontRenderer fontRendererObj; - - public int column0; - public int column1; - public int column2; - public int line; - - public TextLayoutHelper(GuiForestry guiForestry, FontColour fontColour) { - this.guiForestry = guiForestry; - this.defaultFontColor = fontColour.get("gui.screen"); - } - - public void setFontRendererObj(FontRenderer fontRendererObj) { - this.fontRendererObj = fontRendererObj; - } - - public void startPage() { - line = LINE_HEIGHT; - GL11.glPushMatrix(); - } - - public void startPage(int column0, int column1, int column2) { - - this.column0 = column0; - this.column1 = column1; - this.column2 = column2; - - startPage(); - } - - public int getLineY() { - return line; - } - - public void newLine() { - line += LINE_HEIGHT; - } - - public void newLineCompressed() { - line += (LINE_HEIGHT - 2); - } - - public void newLine(int lineHeight) { - line += lineHeight; - } - - public void endPage() { - GL11.glPopMatrix(); - } - - public void drawRow(String text0, String text1, String text2, int colour0, int colour1, int colour2) { - drawLine(text0, column0, colour0); - drawLine(text1, column1, colour1); - drawLine(text2, column2, colour2); - } - - public void drawLine(String text, int x) { - drawLine(text, x, defaultFontColor); - } - - public void drawSplitLine(String text, int x, int maxWidth) { - drawSplitLine(text, x, maxWidth, defaultFontColor); - } - - public void drawCenteredLine(String text, int x, int color) { - drawCenteredLine(text, x, guiForestry.getSizeX(), color); - } - - public void drawCenteredLine(String text, int x, int width, int color) { - fontRendererObj.drawString(text, guiForestry.getGuiLeft() + x + getCenteredOffset(text, width), guiForestry.getGuiTop() + line, color); - } - - public void drawLine(String text, int x, int color) { - fontRendererObj.drawString(text, guiForestry.getGuiLeft() + x, guiForestry.getGuiTop() + line, color); - } - - public void drawSplitLine(String text, int x, int maxWidth, int color) { - fontRendererObj.drawSplitString(text, guiForestry.getGuiLeft() + x, guiForestry.getGuiTop() + line, maxWidth, color); - } - - public int getCenteredOffset(String string) { - return getCenteredOffset(string, guiForestry.getSizeX()); - } - - public int getCenteredOffset(String string, int xWidth) { - return (xWidth - fontRendererObj.getStringWidth(string)) / 2; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui; + +import forestry.core.render.FontColour; +import net.minecraft.client.gui.FontRenderer; +import org.lwjgl.opengl.GL11; + +public class TextLayoutHelper { + private static final int LINE_HEIGHT = 12; + + private final GuiForestry guiForestry; + private final int defaultFontColor; + private FontRenderer fontRendererObj; + + public int column0; + public int column1; + public int column2; + public int line; + + public TextLayoutHelper(GuiForestry guiForestry, FontColour fontColour) { + this.guiForestry = guiForestry; + this.defaultFontColor = fontColour.get("gui.screen"); + } + + public void setFontRendererObj(FontRenderer fontRendererObj) { + this.fontRendererObj = fontRendererObj; + } + + public void startPage() { + line = LINE_HEIGHT; + GL11.glPushMatrix(); + } + + public void startPage(int column0, int column1, int column2) { + + this.column0 = column0; + this.column1 = column1; + this.column2 = column2; + + startPage(); + } + + public int getLineY() { + return line; + } + + public void newLine() { + line += LINE_HEIGHT; + } + + public void newLineCompressed() { + line += (LINE_HEIGHT - 2); + } + + public void newLine(int lineHeight) { + line += lineHeight; + } + + public void endPage() { + GL11.glPopMatrix(); + } + + public void drawRow(String text0, String text1, String text2, int colour0, int colour1, int colour2) { + drawLine(text0, column0, colour0); + drawLine(text1, column1, colour1); + drawLine(text2, column2, colour2); + } + + public void drawLine(String text, int x) { + drawLine(text, x, defaultFontColor); + } + + public void drawSplitLine(String text, int x, int maxWidth) { + drawSplitLine(text, x, maxWidth, defaultFontColor); + } + + public void drawCenteredLine(String text, int x, int color) { + drawCenteredLine(text, x, guiForestry.getSizeX(), color); + } + + public void drawCenteredLine(String text, int x, int width, int color) { + fontRendererObj.drawString( + text, + guiForestry.getGuiLeft() + x + getCenteredOffset(text, width), + guiForestry.getGuiTop() + line, + color); + } + + public void drawLine(String text, int x, int color) { + fontRendererObj.drawString(text, guiForestry.getGuiLeft() + x, guiForestry.getGuiTop() + line, color); + } + + public void drawSplitLine(String text, int x, int maxWidth, int color) { + fontRendererObj.drawSplitString( + text, guiForestry.getGuiLeft() + x, guiForestry.getGuiTop() + line, maxWidth, color); + } + + public int getCenteredOffset(String string) { + return getCenteredOffset(string, guiForestry.getSizeX()); + } + + public int getCenteredOffset(String string, int xWidth) { + return (xWidth - fontRendererObj.getStringWidth(string)) / 2; + } +} diff --git a/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java b/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java index 10e401a1f..97b83deee 100755 --- a/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java +++ b/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java @@ -10,123 +10,130 @@ ******************************************************************************/ package forestry.core.gui.buttons; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.config.Constants; +import forestry.core.gui.tooltips.IToolTipProvider; +import forestry.core.gui.tooltips.ToolTip; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; import net.minecraft.util.ResourceLocation; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - import org.lwjgl.opengl.GL11; -import forestry.core.config.Constants; -import forestry.core.gui.tooltips.IToolTipProvider; -import forestry.core.gui.tooltips.ToolTip; - @SideOnly(Side.CLIENT) public class GuiBetterButton extends GuiButton implements IToolTipProvider { - private static final ResourceLocation TEXTURE = new ResourceLocation("forestry", Constants.TEXTURE_PATH_GUI + "/buttons.png"); - protected IButtonTextureSet texture; - private ToolTip toolTip; - private boolean useTexWidth = false; + private static final ResourceLocation TEXTURE = + new ResourceLocation("forestry", Constants.TEXTURE_PATH_GUI + "/buttons.png"); + protected IButtonTextureSet texture; + private ToolTip toolTip; + private boolean useTexWidth = false; - public GuiBetterButton(int id, int x, int y, IButtonTextureSet texture) { - super(id, x, y, texture.getWidth(), texture.getHeight(), ""); - this.texture = texture; - useTexWidth = true; - } + public GuiBetterButton(int id, int x, int y, IButtonTextureSet texture) { + super(id, x, y, texture.getWidth(), texture.getHeight(), ""); + this.texture = texture; + useTexWidth = true; + } - public GuiBetterButton setTexture(IButtonTextureSet texture) { - this.texture = texture; - width = texture.getWidth(); - height = texture.getHeight(); - return this; - } + public GuiBetterButton setTexture(IButtonTextureSet texture) { + this.texture = texture; + width = texture.getWidth(); + height = texture.getHeight(); + return this; + } - public GuiBetterButton setUseTextureWidth() { - useTexWidth = true; - return this; - } + public GuiBetterButton setUseTextureWidth() { + useTexWidth = true; + return this; + } - public GuiBetterButton setWidth(int width) { - this.width = width; - useTexWidth = false; - return this; - } + public GuiBetterButton setWidth(int width) { + this.width = width; + useTexWidth = false; + return this; + } - public GuiBetterButton setLabel(String label) { - this.displayString = label; - return this; - } + public GuiBetterButton setLabel(String label) { + this.displayString = label; + return this; + } - public int getWidth() { - return width; - } + public int getWidth() { + return width; + } - public int getHeight() { - return texture.getHeight(); - } + public int getHeight() { + return texture.getHeight(); + } - public int getTextColor(boolean mouseOver) { - if (!enabled) { - return 0xffa0a0a0; - } else if (mouseOver) { - return 0xffffa0; - } else { - return 0xe0e0e0; - } - } + public int getTextColor(boolean mouseOver) { + if (!enabled) { + return 0xffa0a0a0; + } else if (mouseOver) { + return 0xffffa0; + } else { + return 0xe0e0e0; + } + } - public boolean isMouseOverButton(int mouseX, int mouseY) { - return mouseX >= xPosition && mouseY >= yPosition && mouseX < xPosition + getWidth() && mouseY < yPosition + getHeight(); - } + public boolean isMouseOverButton(int mouseX, int mouseY) { + return mouseX >= xPosition + && mouseY >= yPosition + && mouseX < xPosition + getWidth() + && mouseY < yPosition + getHeight(); + } - protected static void bindButtonTextures(Minecraft minecraft) { - minecraft.renderEngine.bindTexture(TEXTURE); - } + protected static void bindButtonTextures(Minecraft minecraft) { + minecraft.renderEngine.bindTexture(TEXTURE); + } - @Override - public void drawButton(Minecraft minecraft, int mouseX, int mouseY) { - if (!visible) { - return; - } - FontRenderer fontrenderer = minecraft.fontRenderer; - bindButtonTextures(minecraft); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - int xOffset = texture.getX(); - int yOffset = texture.getY(); - int h = texture.getHeight(); - int w = texture.getWidth(); - boolean mouseOver = isMouseOverButton(mouseX, mouseY); - int hoverState = getHoverState(mouseOver); - if (useTexWidth) { - drawTexturedModalRect(xPosition, yPosition, xOffset, yOffset + hoverState * h, w, h); - } else { - drawTexturedModalRect(xPosition, yPosition, xOffset, yOffset + hoverState * h, width / 2, h); - drawTexturedModalRect(xPosition + width / 2, yPosition, xOffset + w - width / 2, yOffset + hoverState * h, width / 2, h); - } - mouseDragged(minecraft, mouseX, mouseY); - drawCenteredString(fontrenderer, displayString, xPosition + getWidth() / 2, yPosition + (h - 8) / 2, getTextColor(mouseOver)); - } + @Override + public void drawButton(Minecraft minecraft, int mouseX, int mouseY) { + if (!visible) { + return; + } + FontRenderer fontrenderer = minecraft.fontRenderer; + bindButtonTextures(minecraft); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + int xOffset = texture.getX(); + int yOffset = texture.getY(); + int h = texture.getHeight(); + int w = texture.getWidth(); + boolean mouseOver = isMouseOverButton(mouseX, mouseY); + int hoverState = getHoverState(mouseOver); + if (useTexWidth) { + drawTexturedModalRect(xPosition, yPosition, xOffset, yOffset + hoverState * h, w, h); + } else { + drawTexturedModalRect(xPosition, yPosition, xOffset, yOffset + hoverState * h, width / 2, h); + drawTexturedModalRect( + xPosition + width / 2, yPosition, xOffset + w - width / 2, yOffset + hoverState * h, width / 2, h); + } + mouseDragged(minecraft, mouseX, mouseY); + drawCenteredString( + fontrenderer, + displayString, + xPosition + getWidth() / 2, + yPosition + (h - 8) / 2, + getTextColor(mouseOver)); + } - @Override - public ToolTip getToolTip(int mouseX, int mouseY) { - return toolTip; - } + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + return toolTip; + } - public void setToolTip(ToolTip tips) { - this.toolTip = tips; - } + public void setToolTip(ToolTip tips) { + this.toolTip = tips; + } - @Override - public boolean isToolTipVisible() { - return visible; - } + @Override + public boolean isToolTipVisible() { + return visible; + } - @Override - public boolean isMouseOver(int mouseX, int mouseY) { - return isMouseOverButton(mouseX, mouseY); - } + @Override + public boolean isMouseOver(int mouseX, int mouseY) { + return isMouseOverButton(mouseX, mouseY); + } } diff --git a/src/main/java/forestry/core/gui/buttons/IButtonTextureSet.java b/src/main/java/forestry/core/gui/buttons/IButtonTextureSet.java index ddb88d9a0..83ee492fe 100755 --- a/src/main/java/forestry/core/gui/buttons/IButtonTextureSet.java +++ b/src/main/java/forestry/core/gui/buttons/IButtonTextureSet.java @@ -15,12 +15,11 @@ package forestry.core.gui.buttons; */ public interface IButtonTextureSet { - int getX(); + int getX(); - int getY(); + int getY(); - int getHeight(); - - int getWidth(); + int getHeight(); + int getWidth(); } diff --git a/src/main/java/forestry/core/gui/buttons/StandardButtonTextureSets.java b/src/main/java/forestry/core/gui/buttons/StandardButtonTextureSets.java index d4dbfa439..e3b4853a3 100755 --- a/src/main/java/forestry/core/gui/buttons/StandardButtonTextureSets.java +++ b/src/main/java/forestry/core/gui/buttons/StandardButtonTextureSets.java @@ -14,42 +14,40 @@ package forestry.core.gui.buttons; * @author CovertJaguar */ public enum StandardButtonTextureSets implements IButtonTextureSet { + LARGE_BUTTON(0, 0, 20, 200), + SMALL_BUTTON(0, 80, 15, 200), + LOCKED_BUTTON(224, 0, 16, 16), + UNLOCKED_BUTTON(240, 0, 16, 16), + LEFT_BUTTON(204, 0, 16, 10), + RIGHT_BUTTON(214, 0, 16, 10), + LEFT_BUTTON_SMALL(238, 220, 12, 9), + RIGHT_BUTTON_SMALL(247, 220, 12, 9); + private final int x, y, height, width; - LARGE_BUTTON(0, 0, 20, 200), - SMALL_BUTTON(0, 80, 15, 200), - LOCKED_BUTTON(224, 0, 16, 16), - UNLOCKED_BUTTON(240, 0, 16, 16), - LEFT_BUTTON(204, 0, 16, 10), - RIGHT_BUTTON(214, 0, 16, 10), - LEFT_BUTTON_SMALL(238, 220, 12, 9), - RIGHT_BUTTON_SMALL(247, 220, 12, 9); - private final int x, y, height, width; + StandardButtonTextureSets(int x, int y, int height, int width) { + this.x = x; + this.y = y; + this.height = height; + this.width = width; + } - StandardButtonTextureSets(int x, int y, int height, int width) { - this.x = x; - this.y = y; - this.height = height; - this.width = width; - } + @Override + public int getX() { + return x; + } - @Override - public int getX() { - return x; - } + @Override + public int getY() { + return y; + } - @Override - public int getY() { - return y; - } - - @Override - public int getHeight() { - return height; - } - - @Override - public int getWidth() { - return width; - } + @Override + public int getHeight() { + return height; + } + @Override + public int getWidth() { + return width; + } } diff --git a/src/main/java/forestry/core/gui/ledgers/ClimateLedger.java b/src/main/java/forestry/core/gui/ledgers/ClimateLedger.java index 3a034816f..ea4be6013 100644 --- a/src/main/java/forestry/core/gui/ledgers/ClimateLedger.java +++ b/src/main/java/forestry/core/gui/ledgers/ClimateLedger.java @@ -20,41 +20,51 @@ import forestry.core.utils.StringUtil; */ public class ClimateLedger extends Ledger { - private final IClimatised tile; + private final IClimatised tile; - public ClimateLedger(LedgerManager manager, IClimatised tile) { - super(manager, "climate"); - this.tile = tile; - maxHeight = 72; - } + public ClimateLedger(LedgerManager manager, IClimatised tile) { + super(manager, "climate"); + this.tile = tile; + maxHeight = 72; + } - @Override - public void draw(int x, int y) { + @Override + public void draw(int x, int y) { - EnumTemperature temperature = tile.getTemperature(); + EnumTemperature temperature = tile.getTemperature(); - // Draw background - drawBackground(x, y); + // Draw background + drawBackground(x, y); - // Draw icon - drawIcon(temperature.getIcon(), x + 3, y + 4); + // Draw icon + drawIcon(temperature.getIcon(), x + 3, y + 4); - if (!isFullyOpened()) { - return; - } + if (!isFullyOpened()) { + return; + } - drawHeader(StringUtil.localize("gui.climate"), x + 22, y + 8); + drawHeader(StringUtil.localize("gui.climate"), x + 22, y + 8); - drawSubheader(StringUtil.localize("gui.temperature") + ':', x + 22, y + 20); - drawText(AlleleManager.climateHelper.toDisplay(temperature) + ' ' + StringUtil.floatAsPercent(tile.getExactTemperature()), x + 22, y + 32); + drawSubheader(StringUtil.localize("gui.temperature") + ':', x + 22, y + 20); + drawText( + AlleleManager.climateHelper.toDisplay(temperature) + + ' ' + + StringUtil.floatAsPercent(tile.getExactTemperature()), + x + 22, + y + 32); - drawSubheader(StringUtil.localize("gui.humidity") + ':', x + 22, y + 44); - drawText(AlleleManager.climateHelper.toDisplay(tile.getHumidity()) + ' ' + StringUtil.floatAsPercent(tile.getExactHumidity()), x + 22, y + 56); - } - - @Override - public String getTooltip() { - return "T: " + AlleleManager.climateHelper.toDisplay(tile.getTemperature()) + " / H: " + AlleleManager.climateHelper.toDisplay(tile.getHumidity()); - } + drawSubheader(StringUtil.localize("gui.humidity") + ':', x + 22, y + 44); + drawText( + AlleleManager.climateHelper.toDisplay(tile.getHumidity()) + + ' ' + + StringUtil.floatAsPercent(tile.getExactHumidity()), + x + 22, + y + 56); + } + @Override + public String getTooltip() { + return "T: " + AlleleManager.climateHelper.toDisplay(tile.getTemperature()) + " / H: " + + AlleleManager.climateHelper.toDisplay(tile.getHumidity()); + } } diff --git a/src/main/java/forestry/core/gui/ledgers/ErrorLedger.java b/src/main/java/forestry/core/gui/ledgers/ErrorLedger.java index ef5b94b8d..f2f279b63 100644 --- a/src/main/java/forestry/core/gui/ledgers/ErrorLedger.java +++ b/src/main/java/forestry/core/gui/ledgers/ErrorLedger.java @@ -10,71 +10,69 @@ ******************************************************************************/ package forestry.core.gui.ledgers; -import javax.annotation.Nullable; - import forestry.api.core.IErrorState; import forestry.core.utils.StringUtil; +import javax.annotation.Nullable; /** * A ledger displaying error messages and help text. */ public class ErrorLedger extends Ledger { - @Nullable - private IErrorState state; + @Nullable + private IErrorState state; - public ErrorLedger(LedgerManager manager) { - super(manager, "error", false); - maxHeight = 72; - } + public ErrorLedger(LedgerManager manager) { + super(manager, "error", false); + maxHeight = 72; + } - public void setState(@Nullable IErrorState state) { - this.state = state; - if (state != null) { - int lineHeight = StringUtil.getLineHeight(maxTextWidth, getTooltip(), StringUtil.localize(state.getHelp())); - maxHeight = lineHeight + 20; - } - } + public void setState(@Nullable IErrorState state) { + this.state = state; + if (state != null) { + int lineHeight = StringUtil.getLineHeight(maxTextWidth, getTooltip(), StringUtil.localize(state.getHelp())); + maxHeight = lineHeight + 20; + } + } - @Override - public void draw(int x, int y) { - if (state == null) { - return; - } + @Override + public void draw(int x, int y) { + if (state == null) { + return; + } - // Draw background - drawBackground(x, y); - y += 4; + // Draw background + drawBackground(x, y); + y += 4; - int xIcon = x + 5; - int xBody = x + 14; - int xHeader = x + 24; + int xIcon = x + 5; + int xBody = x + 14; + int xHeader = x + 24; - // Draw icon - drawIcon(state.getIcon(), xIcon, y); - y += 4; + // Draw icon + drawIcon(state.getIcon(), xIcon, y); + y += 4; - // Write description if fully opened - if (isFullyOpened()) { - y += drawHeader(getTooltip(), xHeader, y); - y += 4; + // Write description if fully opened + if (isFullyOpened()) { + y += drawHeader(getTooltip(), xHeader, y); + y += 4; - String helpString = StringUtil.localize(state.getHelp()); - drawSplitText(helpString, xBody, y, maxTextWidth); - } - } + String helpString = StringUtil.localize(state.getHelp()); + drawSplitText(helpString, xBody, y, maxTextWidth); + } + } - @Override - public boolean isVisible() { - return state != null; - } - - @Override - public String getTooltip() { - if (!isVisible()) { - return ""; - } - return StringUtil.localize(state.getDescription()); - } + @Override + public boolean isVisible() { + return state != null; + } + @Override + public String getTooltip() { + if (!isVisible()) { + return ""; + } + return StringUtil.localize(state.getDescription()); + } } diff --git a/src/main/java/forestry/core/gui/ledgers/HintLedger.java b/src/main/java/forestry/core/gui/ledgers/HintLedger.java index d10978e8c..d8b75b40c 100644 --- a/src/main/java/forestry/core/gui/ledgers/HintLedger.java +++ b/src/main/java/forestry/core/gui/ledgers/HintLedger.java @@ -10,56 +10,56 @@ ******************************************************************************/ package forestry.core.gui.ledgers; -import java.util.List; -import java.util.Random; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; - import forestry.core.gui.IHintSource; import forestry.core.proxy.Proxies; import forestry.core.render.TextureManager; import forestry.core.utils.StringUtil; +import java.util.List; +import java.util.Random; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; public class HintLedger extends Ledger { - private final String hintString; - private final String hintTooltip; + private final String hintString; + private final String hintTooltip; - public HintLedger(LedgerManager manager, IHintSource tile) { - super(manager, "hint"); - List hints = tile.getHints(); - int position = new Random().nextInt(hints.size()); - String hint = hints.get(position); + public HintLedger(LedgerManager manager, IHintSource tile) { + super(manager, "hint"); + List hints = tile.getHints(); + int position = new Random().nextInt(hints.size()); + String hint = hints.get(position); - hintString = StringUtil.localize("hints." + hint + ".desc"); - hintTooltip = StringUtil.localize("hints." + hint + ".tag"); + hintString = StringUtil.localize("hints." + hint + ".desc"); + hintTooltip = StringUtil.localize("hints." + hint + ".tag"); - Minecraft minecraft = Proxies.common.getClientInstance(); - FontRenderer fontRenderer = minecraft.fontRenderer; - int lineCount = fontRenderer.listFormattedStringToWidth(hintString, maxTextWidth).size(); - maxHeight = (lineCount + 1) * fontRenderer.FONT_HEIGHT + 20; - } + Minecraft minecraft = Proxies.common.getClientInstance(); + FontRenderer fontRenderer = minecraft.fontRenderer; + int lineCount = fontRenderer + .listFormattedStringToWidth(hintString, maxTextWidth) + .size(); + maxHeight = (lineCount + 1) * fontRenderer.FONT_HEIGHT + 20; + } - @Override - public void draw(int x, int y) { + @Override + public void draw(int x, int y) { - // Draw background - drawBackground(x, y); + // Draw background + drawBackground(x, y); - // Draw icon - drawIcon(TextureManager.getInstance().getDefault("misc/hint"), x + 3, y + 4); + // Draw icon + drawIcon(TextureManager.getInstance().getDefault("misc/hint"), x + 3, y + 4); - if (!isFullyOpened()) { - return; - } + if (!isFullyOpened()) { + return; + } - drawHeader(StringUtil.localize("gui.didyouknow") + '?', x + 22, y + 8); - drawSplitText(hintString, x + 12, y + 20, maxTextWidth); - } + drawHeader(StringUtil.localize("gui.didyouknow") + '?', x + 22, y + 8); + drawSplitText(hintString, x + 12, y + 20, maxTextWidth); + } - @Override - public String getTooltip() { - return hintTooltip; - } + @Override + public String getTooltip() { + return hintTooltip; + } } diff --git a/src/main/java/forestry/core/gui/ledgers/Ledger.java b/src/main/java/forestry/core/gui/ledgers/Ledger.java index e645881db..228bfef2d 100644 --- a/src/main/java/forestry/core/gui/ledgers/Ledger.java +++ b/src/main/java/forestry/core/gui/ledgers/Ledger.java @@ -10,232 +10,233 @@ ******************************************************************************/ package forestry.core.gui.ledgers; -import java.util.List; - -import net.minecraft.client.Minecraft; -import net.minecraft.util.IIcon; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.opengl.GL11; - import forestry.core.config.Config; import forestry.core.config.Constants; import forestry.core.config.SessionVars; import forestry.core.proxy.Proxies; import forestry.core.render.ForestryResource; import forestry.core.render.SpriteSheet; +import java.util.List; +import net.minecraft.client.Minecraft; +import net.minecraft.util.IIcon; +import net.minecraft.util.ResourceLocation; +import org.lwjgl.opengl.GL11; /** * Side ledger for guis */ public abstract class Ledger { - protected static final int minWidth = 24; - public static final int minHeight = 24; - protected final int maxWidth; - protected final int maxTextWidth; - protected int maxHeight = 24; + protected static final int minWidth = 24; + public static final int minHeight = 24; + protected final int maxWidth; + protected final int maxTextWidth; + protected int maxHeight = 24; - private static final ResourceLocation ledgerTextureRight = new ForestryResource(Constants.TEXTURE_PATH_GUI + "/ledger.png"); - private static final ResourceLocation ledgerTextureLeft = new ForestryResource(Constants.TEXTURE_PATH_GUI + "/ledgerLeft.png"); - - private final LedgerManager manager; + private static final ResourceLocation ledgerTextureRight = + new ForestryResource(Constants.TEXTURE_PATH_GUI + "/ledger.png"); + private static final ResourceLocation ledgerTextureLeft = + new ForestryResource(Constants.TEXTURE_PATH_GUI + "/ledgerLeft.png"); - private final int fontColorHeader; - private final int fontColorText; - private final int fontColorSubheader; - private final int overlayColor; + private final LedgerManager manager; - private boolean open; + private final int fontColorHeader; + private final int fontColorText; + private final int fontColorSubheader; + private final int overlayColor; - public int currentShiftX = 0; - public int currentShiftY = 0; + private boolean open; - protected float currentWidth = minWidth; - protected float currentHeight = minHeight; + public int currentShiftX = 0; + public int currentShiftY = 0; - private final ResourceLocation texture; + protected float currentWidth = minWidth; + protected float currentHeight = minHeight; - protected Ledger(LedgerManager manager, String name) { - this(manager, name, true); - } + private final ResourceLocation texture; - protected Ledger(LedgerManager manager, String name, boolean rightSide) { - this.manager = manager; - if (rightSide) { - texture = ledgerTextureRight; - } else { - texture = ledgerTextureLeft; - } + protected Ledger(LedgerManager manager, String name) { + this(manager, name, true); + } - fontColorHeader = manager.gui.getFontColor().get("ledger." + name + ".header"); - fontColorSubheader = manager.gui.getFontColor().get("ledger." + name + ".subheader"); - fontColorText = manager.gui.getFontColor().get("ledger." + name + ".text"); - overlayColor = manager.gui.getFontColor().get("ledger." + name + ".background"); + protected Ledger(LedgerManager manager, String name, boolean rightSide) { + this.manager = manager; + if (rightSide) { + texture = ledgerTextureRight; + } else { + texture = ledgerTextureLeft; + } - maxWidth = Math.min(124, manager.getMaxWidth()); - maxTextWidth = maxWidth - 18; - } + fontColorHeader = manager.gui.getFontColor().get("ledger." + name + ".header"); + fontColorSubheader = manager.gui.getFontColor().get("ledger." + name + ".subheader"); + fontColorText = manager.gui.getFontColor().get("ledger." + name + ".text"); + overlayColor = manager.gui.getFontColor().get("ledger." + name + ".background"); - // adjust the update's move amount to match the look of 60 fps (16.67 ms per update) - private static final float msPerUpdate = 16.667f; - private long lastUpdateTime = 0; + maxWidth = Math.min(124, manager.getMaxWidth()); + maxTextWidth = maxWidth - 18; + } - public void update() { + // adjust the update's move amount to match the look of 60 fps (16.67 ms per update) + private static final float msPerUpdate = 16.667f; + private long lastUpdateTime = 0; - long updateTime; - if (lastUpdateTime == 0) { - lastUpdateTime = System.currentTimeMillis(); - updateTime = lastUpdateTime + Math.round(msPerUpdate); - } else { - updateTime = System.currentTimeMillis(); - } + public void update() { - float moveAmount = Config.guiTabSpeed * (updateTime - lastUpdateTime) / msPerUpdate; + long updateTime; + if (lastUpdateTime == 0) { + lastUpdateTime = System.currentTimeMillis(); + updateTime = lastUpdateTime + Math.round(msPerUpdate); + } else { + updateTime = System.currentTimeMillis(); + } - lastUpdateTime = updateTime; + float moveAmount = Config.guiTabSpeed * (updateTime - lastUpdateTime) / msPerUpdate; - // Width - if (open && currentWidth < maxWidth) { - currentWidth += moveAmount; - if (currentWidth > maxWidth) { - currentWidth = maxWidth; - } - } else if (!open && currentWidth > minWidth) { - currentWidth -= moveAmount; - if (currentWidth < minWidth) { - currentWidth = minWidth; - } - } + lastUpdateTime = updateTime; - // Height - if (open && currentHeight < maxHeight) { - currentHeight += moveAmount; - if (currentHeight > maxHeight) { - currentHeight = maxHeight; - } - } else if (!open && currentHeight > minHeight) { - currentHeight -= moveAmount; - if (currentHeight < minHeight) { - currentHeight = minHeight; - } - } - } + // Width + if (open && currentWidth < maxWidth) { + currentWidth += moveAmount; + if (currentWidth > maxWidth) { + currentWidth = maxWidth; + } + } else if (!open && currentWidth > minWidth) { + currentWidth -= moveAmount; + if (currentWidth < minWidth) { + currentWidth = minWidth; + } + } - public int getHeight() { - return Math.round(currentHeight); - } + // Height + if (open && currentHeight < maxHeight) { + currentHeight += moveAmount; + if (currentHeight > maxHeight) { + currentHeight = maxHeight; + } + } else if (!open && currentHeight > minHeight) { + currentHeight -= moveAmount; + if (currentHeight < minHeight) { + currentHeight = minHeight; + } + } + } - public int getWidth() { - return Math.round(currentWidth); - } + public int getHeight() { + return Math.round(currentHeight); + } - public abstract void draw(int x, int y); + public int getWidth() { + return Math.round(currentWidth); + } - public abstract String getTooltip(); + public abstract void draw(int x, int y); - public boolean handleMouseClicked(int x, int y, int mouseButton) { - return false; - } + public abstract String getTooltip(); - public boolean intersectsWith(int mouseX, int mouseY) { - return mouseX >= currentShiftX && mouseX <= currentShiftX + currentWidth && mouseY >= currentShiftY && mouseY <= currentShiftY + getHeight(); - } + public boolean handleMouseClicked(int x, int y, int mouseButton) { + return false; + } - public void setFullyOpen() { - open = true; - currentWidth = maxWidth; - currentHeight = maxHeight; - } + public boolean intersectsWith(int mouseX, int mouseY) { + return mouseX >= currentShiftX + && mouseX <= currentShiftX + currentWidth + && mouseY >= currentShiftY + && mouseY <= currentShiftY + getHeight(); + } - public void toggleOpen() { - if (open) { - open = false; - SessionVars.setOpenedLedger(null); - } else { - open = true; - SessionVars.setOpenedLedger(this.getClass()); - } - } + public void setFullyOpen() { + open = true; + currentWidth = maxWidth; + currentHeight = maxHeight; + } - public boolean isVisible() { - return true; - } + public void toggleOpen() { + if (open) { + open = false; + SessionVars.setOpenedLedger(null); + } else { + open = true; + SessionVars.setOpenedLedger(this.getClass()); + } + } - public boolean isOpen() { - return this.open; - } + public boolean isVisible() { + return true; + } - protected boolean isFullyOpened() { - return currentWidth >= maxWidth; - } + public boolean isOpen() { + return this.open; + } - public void onGuiClosed() { + protected boolean isFullyOpened() { + return currentWidth >= maxWidth; + } - } + public void onGuiClosed() {} - protected void drawBackground(int x, int y) { + protected void drawBackground(int x, int y) { - float colorR = (overlayColor >> 16 & 255) / 255.0F; - float colorG = (overlayColor >> 8 & 255) / 255.0F; - float colorB = (overlayColor & 255) / 255.0F; + float colorR = (overlayColor >> 16 & 255) / 255.0F; + float colorG = (overlayColor >> 8 & 255) / 255.0F; + float colorB = (overlayColor & 255) / 255.0F; - GL11.glColor4f(colorR, colorG, colorB, 1.0F); + GL11.glColor4f(colorR, colorG, colorB, 1.0F); - Proxies.render.bindTexture(texture); + Proxies.render.bindTexture(texture); - int height = getHeight(); - int width = getWidth(); + int height = getHeight(); + int width = getWidth(); - manager.gui.drawTexturedModalRect(x, y + 4, 0, 256 - height + 4, 4, height - 4); // left edge - manager.gui.drawTexturedModalRect(x + 4, y, 256 - width + 4, 0, width - 4, 4); // top edge - manager.gui.drawTexturedModalRect(x, y, 0, 0, 4, 4); // top left corner + manager.gui.drawTexturedModalRect(x, y + 4, 0, 256 - height + 4, 4, height - 4); // left edge + manager.gui.drawTexturedModalRect(x + 4, y, 256 - width + 4, 0, width - 4, 4); // top edge + manager.gui.drawTexturedModalRect(x, y, 0, 0, 4, 4); // top left corner - manager.gui.drawTexturedModalRect(x + 4, y + 4, 256 - width + 4, 256 - height + 4, width - 4, height - 4); // body + bottom + right + manager.gui.drawTexturedModalRect( + x + 4, y + 4, 256 - width + 4, 256 - height + 4, width - 4, height - 4); // body + bottom + right - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); - } + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); + } - protected void drawIcon(IIcon icon, int x, int y) { - if (icon != null) { - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); - Proxies.render.bindTexture(SpriteSheet.ITEMS); - manager.gui.drawTexturedModelRectFromIcon(x, y, icon, 16, 16); - } - } + protected void drawIcon(IIcon icon, int x, int y) { + if (icon != null) { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); + Proxies.render.bindTexture(SpriteSheet.ITEMS); + manager.gui.drawTexturedModelRectFromIcon(x, y, icon, 16, 16); + } + } - protected int drawHeader(String string, int x, int y) { - return drawShadowText(string, x, y, fontColorHeader); - } + protected int drawHeader(String string, int x, int y) { + return drawShadowText(string, x, y, fontColorHeader); + } - protected int drawSubheader(String string, int x, int y) { - return drawShadowText(string, x, y, fontColorSubheader); - } + protected int drawSubheader(String string, int x, int y) { + return drawShadowText(string, x, y, fontColorSubheader); + } - protected int drawShadowText(String string, int x, int y, int color) { - return drawSplitText(string, x, y, maxTextWidth, color, true); - } + protected int drawShadowText(String string, int x, int y, int color) { + return drawSplitText(string, x, y, maxTextWidth, color, true); + } - protected int drawSplitText(String string, int x, int y, int width) { - return drawSplitText(string, x, y, width, fontColorText, false); - } + protected int drawSplitText(String string, int x, int y, int width) { + return drawSplitText(string, x, y, width, fontColorText, false); + } - protected int drawSplitText(String string, int x, int y, int width, int color, boolean shadow) { - int originalY = y; - Minecraft minecraft = Proxies.common.getClientInstance(); - List strings = minecraft.fontRenderer.listFormattedStringToWidth(string, width); - for (Object obj : strings) { - if (obj instanceof String) { - minecraft.fontRenderer.drawString((String) obj, x, y, color, shadow); - y += minecraft.fontRenderer.FONT_HEIGHT; - } - } - return y - originalY; - } + protected int drawSplitText(String string, int x, int y, int width, int color, boolean shadow) { + int originalY = y; + Minecraft minecraft = Proxies.common.getClientInstance(); + List strings = minecraft.fontRenderer.listFormattedStringToWidth(string, width); + for (Object obj : strings) { + if (obj instanceof String) { + minecraft.fontRenderer.drawString((String) obj, x, y, color, shadow); + y += minecraft.fontRenderer.FONT_HEIGHT; + } + } + return y - originalY; + } - protected int drawText(String string, int x, int y) { - Minecraft minecraft = Proxies.common.getClientInstance(); - minecraft.fontRenderer.drawString(string, x, y, fontColorText); - return minecraft.fontRenderer.FONT_HEIGHT; - } + protected int drawText(String string, int x, int y) { + Minecraft minecraft = Proxies.common.getClientInstance(); + minecraft.fontRenderer.drawString(string, x, y, fontColorText); + return minecraft.fontRenderer.FONT_HEIGHT; + } } diff --git a/src/main/java/forestry/core/gui/ledgers/LedgerManager.java b/src/main/java/forestry/core/gui/ledgers/LedgerManager.java index e1f5079b1..dc1a7f60d 100644 --- a/src/main/java/forestry/core/gui/ledgers/LedgerManager.java +++ b/src/main/java/forestry/core/gui/ledgers/LedgerManager.java @@ -10,11 +10,6 @@ ******************************************************************************/ package forestry.core.gui.ledgers; -import java.util.ArrayList; -import java.util.List; - -import org.lwjgl.opengl.GL11; - import forestry.api.core.IErrorSource; import forestry.api.core.IErrorState; import forestry.core.config.SessionVars; @@ -22,173 +17,178 @@ import forestry.core.errors.FakeErrorSource; import forestry.core.gui.GuiForestry; import forestry.core.gui.GuiUtil; import forestry.core.gui.tooltips.ToolTip; +import java.util.ArrayList; +import java.util.List; +import org.lwjgl.opengl.GL11; public class LedgerManager { - private final List ledgers = new ArrayList<>(); - private final List errorLedgers = new ArrayList<>(); + private final List ledgers = new ArrayList<>(); + private final List errorLedgers = new ArrayList<>(); - private IErrorSource errorSource; - private final int maxWidth; + private IErrorSource errorSource; + private final int maxWidth; - public final GuiForestry gui; + public final GuiForestry gui; - public LedgerManager(GuiForestry gui, int maxWidth) { - this.gui = gui; - this.errorSource = FakeErrorSource.instance; - this.maxWidth = maxWidth; - } + public LedgerManager(GuiForestry gui, int maxWidth) { + this.gui = gui; + this.errorSource = FakeErrorSource.instance; + this.maxWidth = maxWidth; + } - public void add(IErrorSource errorSource) { - if (errorSource == null) { - return; - } + public void add(IErrorSource errorSource) { + if (errorSource == null) { + return; + } - this.errorSource = errorSource; - int maxErrorLedgerCount = (gui.getSizeY() - 10) / Ledger.minHeight; - for (int i = 0; i < maxErrorLedgerCount; i++) { - errorLedgers.add(new ErrorLedger(this)); - } - } + this.errorSource = errorSource; + int maxErrorLedgerCount = (gui.getSizeY() - 10) / Ledger.minHeight; + for (int i = 0; i < maxErrorLedgerCount; i++) { + errorLedgers.add(new ErrorLedger(this)); + } + } - public void add(Ledger ledger) { - this.ledgers.add(ledger); - if (SessionVars.getOpenedLedger() != null && ledger.getClass().equals(SessionVars.getOpenedLedger())) { - ledger.setFullyOpen(); - } - } + public void add(Ledger ledger) { + this.ledgers.add(ledger); + if (SessionVars.getOpenedLedger() != null && ledger.getClass().equals(SessionVars.getOpenedLedger())) { + ledger.setFullyOpen(); + } + } - public void onGuiClosed() { - for (Ledger ledger : ledgers) { - ledger.onGuiClosed(); - } - } + public void onGuiClosed() { + for (Ledger ledger : ledgers) { + ledger.onGuiClosed(); + } + } - /** - * Inserts a ledger into the next-to-last position. - */ - public void insert(Ledger ledger) { - this.ledgers.add(ledgers.size() - 1, ledger); - } + /** + * Inserts a ledger into the next-to-last position. + */ + public void insert(Ledger ledger) { + this.ledgers.add(ledgers.size() - 1, ledger); + } - private Ledger getAtPosition(int mX, int mY) { - if (ledgers.size() > 0) { - final int xShift = ((gui.width - gui.getSizeX()) / 2) + gui.getSizeX(); - int yShift = ((gui.height - gui.getSizeY()) / 2) + 8; + private Ledger getAtPosition(int mX, int mY) { + if (ledgers.size() > 0) { + final int xShift = ((gui.width - gui.getSizeX()) / 2) + gui.getSizeX(); + int yShift = ((gui.height - gui.getSizeY()) / 2) + 8; - for (Ledger ledger : ledgers) { - if (!ledger.isVisible()) { - continue; - } + for (Ledger ledger : ledgers) { + if (!ledger.isVisible()) { + continue; + } - ledger.currentShiftX = xShift; - ledger.currentShiftY = yShift; - if (ledger.intersectsWith(mX, mY)) { - return ledger; - } + ledger.currentShiftX = xShift; + ledger.currentShiftY = yShift; + if (ledger.intersectsWith(mX, mY)) { + return ledger; + } - yShift += ledger.getHeight(); - } - } + yShift += ledger.getHeight(); + } + } - final int xShiftError = ((gui.width - gui.getSizeX()) / 2); - int yShiftError = ((gui.height - gui.getSizeY()) / 2) + 8; + final int xShiftError = ((gui.width - gui.getSizeX()) / 2); + int yShiftError = ((gui.height - gui.getSizeY()) / 2) + 8; - for (ErrorLedger errorLedger : errorLedgers) { - if (!errorLedger.isVisible()) { - continue; - } + for (ErrorLedger errorLedger : errorLedgers) { + if (!errorLedger.isVisible()) { + continue; + } - errorLedger.currentShiftX = xShiftError - errorLedger.getWidth(); - errorLedger.currentShiftY = yShiftError; - if (errorLedger.intersectsWith(mX, mY)) { - return errorLedger; - } + errorLedger.currentShiftX = xShiftError - errorLedger.getWidth(); + errorLedger.currentShiftY = yShiftError; + if (errorLedger.intersectsWith(mX, mY)) { + return errorLedger; + } - yShiftError += errorLedger.getHeight(); - } + yShiftError += errorLedger.getHeight(); + } - return null; - } + return null; + } - public void drawLedgers() { - int yPos = 8; - for (Ledger ledger : ledgers) { + public void drawLedgers() { + int yPos = 8; + for (Ledger ledger : ledgers) { - ledger.update(); - if (!ledger.isVisible()) { - continue; - } + ledger.update(); + if (!ledger.isVisible()) { + continue; + } - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - ledger.draw(gui.getSizeX(), yPos); - yPos += ledger.getHeight(); - } + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + ledger.draw(gui.getSizeX(), yPos); + yPos += ledger.getHeight(); + } - List errorStates = new ArrayList<>(errorSource.getErrorStates()); + List errorStates = new ArrayList<>(errorSource.getErrorStates()); - yPos = 8; - int index = 0; - for (ErrorLedger errorLedger : errorLedgers) { - if (index >= errorStates.size()) { - errorLedger.setState(null); - continue; - } - IErrorState errorState = errorStates.get(index++); - errorLedger.setState(errorState); + yPos = 8; + int index = 0; + for (ErrorLedger errorLedger : errorLedgers) { + if (index >= errorStates.size()) { + errorLedger.setState(null); + continue; + } + IErrorState errorState = errorStates.get(index++); + errorLedger.setState(errorState); - errorLedger.update(); - if (!errorLedger.isVisible()) { - continue; - } + errorLedger.update(); + if (!errorLedger.isVisible()) { + continue; + } - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - errorLedger.draw(-errorLedger.getWidth(), yPos); - yPos += errorLedger.getHeight(); - } - } + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + errorLedger.draw(-errorLedger.getWidth(), yPos); + yPos += errorLedger.getHeight(); + } + } - public void drawTooltips(int mouseX, int mouseY) { - Ledger ledger = getAtPosition(mouseX, mouseY); - if (ledger != null) { - ToolTip toolTip = new ToolTip(); - toolTip.add(ledger.getTooltip()); - GuiUtil.drawToolTips(gui, toolTip, mouseX, mouseY); - } - } + public void drawTooltips(int mouseX, int mouseY) { + Ledger ledger = getAtPosition(mouseX, mouseY); + if (ledger != null) { + ToolTip toolTip = new ToolTip(); + toolTip.add(ledger.getTooltip()); + GuiUtil.drawToolTips(gui, toolTip, mouseX, mouseY); + } + } - public void handleMouseClicked(int x, int y, int mouseButton) { + public void handleMouseClicked(int x, int y, int mouseButton) { - if (mouseButton == 0) { + if (mouseButton == 0) { - Ledger ledger = this.getAtPosition(x, y); + Ledger ledger = this.getAtPosition(x, y); - // Default action only if the mouse click was not handled by the - // ledger itself. - if (ledger != null && !ledger.handleMouseClicked(x, y, mouseButton)) { + // Default action only if the mouse click was not handled by the + // ledger itself. + if (ledger != null && !ledger.handleMouseClicked(x, y, mouseButton)) { - List toggleLedgers; - if (ledgers.contains(ledger)) { - toggleLedgers = ledgers; - } else { - toggleLedgers = errorLedgers; - } + List toggleLedgers; + if (ledgers.contains(ledger)) { + toggleLedgers = ledgers; + } else { + toggleLedgers = errorLedgers; + } - for (Ledger other : toggleLedgers) { - if (other != ledger && other.isOpen()) { - other.toggleOpen(); - } - } - ledger.toggleOpen(); - } - } + for (Ledger other : toggleLedgers) { + if (other != ledger && other.isOpen()) { + other.toggleOpen(); + } + } + ledger.toggleOpen(); + } + } + } - } + public boolean ledgerOverlaps(int x, int y, int width, int height) { + return getAtPosition(x + width, y + height) != null + || getAtPosition(x + width, y) != null + || getAtPosition(x, y + height) != null + || getAtPosition(x, y) != null; + } - public boolean ledgerOverlaps(int x, int y, int width, int height) { - return getAtPosition(x + width, y + height) != null || getAtPosition(x + width, y) != null || getAtPosition(x, y + height) != null || getAtPosition(x, y) != null; - } - - public int getMaxWidth() { - return maxWidth; - } + public int getMaxWidth() { + return maxWidth; + } } diff --git a/src/main/java/forestry/core/gui/ledgers/OwnerLedger.java b/src/main/java/forestry/core/gui/ledgers/OwnerLedger.java index b2b8ba0f9..cd858765b 100644 --- a/src/main/java/forestry/core/gui/ledgers/OwnerLedger.java +++ b/src/main/java/forestry/core/gui/ledgers/OwnerLedger.java @@ -10,14 +10,7 @@ ******************************************************************************/ package forestry.core.gui.ledgers; -import java.util.Locale; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.IIcon; - import com.mojang.authlib.GameProfile; - import forestry.core.access.EnumAccess; import forestry.core.access.IAccessHandler; import forestry.core.access.IAccessOwnerListener; @@ -26,96 +19,101 @@ import forestry.core.proxy.Proxies; import forestry.core.render.TextureManager; import forestry.core.utils.PlayerUtil; import forestry.core.utils.StringUtil; +import java.util.Locale; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.IIcon; /** * Ledger displaying ownership information */ public class OwnerLedger extends Ledger implements IAccessOwnerListener { - private final IAccessHandler accessHandler; + private final IAccessHandler accessHandler; - public OwnerLedger(LedgerManager manager, IRestrictedAccess tile) { - super(manager, "owner"); + public OwnerLedger(LedgerManager manager, IRestrictedAccess tile) { + super(manager, "owner"); - this.accessHandler = tile.getAccessHandler(); - accessHandler.addOwnerListener(this); - onOwnerSet(accessHandler.getOwner()); - } + this.accessHandler = tile.getAccessHandler(); + accessHandler.addOwnerListener(this); + onOwnerSet(accessHandler.getOwner()); + } - private boolean isAccessButton(int mouseX, int mouseY) { + private boolean isAccessButton(int mouseX, int mouseY) { - int shiftX = currentShiftX; - int shiftY = currentShiftY + 44; + int shiftX = currentShiftX; + int shiftY = currentShiftY + 44; - return mouseX >= shiftX && mouseX <= currentShiftX + currentWidth && mouseY >= shiftY && mouseY <= shiftY + 12; - } + return mouseX >= shiftX && mouseX <= currentShiftX + currentWidth && mouseY >= shiftY && mouseY <= shiftY + 12; + } - @Override - public boolean isVisible() { - return accessHandler.isOwned(); - } + @Override + public boolean isVisible() { + return accessHandler.isOwned(); + } - @Override - public void draw(int x, int y) { - // Draw background - drawBackground(x, y); + @Override + public void draw(int x, int y) { + // Draw background + drawBackground(x, y); - // Draw icon - EnumAccess accessType = accessHandler.getAccess(); - IIcon accessIcon = TextureManager.getInstance().getDefault("misc/access." + accessType.toString().toLowerCase(Locale.ENGLISH)); - drawIcon(accessIcon, x + 3, y + 4); + // Draw icon + EnumAccess accessType = accessHandler.getAccess(); + IIcon accessIcon = TextureManager.getInstance() + .getDefault("misc/access." + accessType.toString().toLowerCase(Locale.ENGLISH)); + drawIcon(accessIcon, x + 3, y + 4); - // Draw description - if (!isFullyOpened()) { - return; - } + // Draw description + if (!isFullyOpened()) { + return; + } - drawHeader(StringUtil.localize("gui.owner"), x + 22, y + 8); + drawHeader(StringUtil.localize("gui.owner"), x + 22, y + 8); - drawText(PlayerUtil.getOwnerName(accessHandler), x + 22, y + 20); + drawText(PlayerUtil.getOwnerName(accessHandler), x + 22, y + 20); - Minecraft minecraft = Proxies.common.getClientInstance(); - boolean playerIsOwner = accessHandler.isOwner(minecraft.thePlayer); - if (playerIsOwner) { - drawSubheader(StringUtil.localize("gui.access") + ':', x + 22, y + 32); - // Access rules - drawIcon(accessIcon, x + 20, y + 40); - drawText(StringUtil.localize(accessType.getName()), x + 38, y + 44); - } - } + Minecraft minecraft = Proxies.common.getClientInstance(); + boolean playerIsOwner = accessHandler.isOwner(minecraft.thePlayer); + if (playerIsOwner) { + drawSubheader(StringUtil.localize("gui.access") + ':', x + 22, y + 32); + // Access rules + drawIcon(accessIcon, x + 20, y + 40); + drawText(StringUtil.localize(accessType.getName()), x + 38, y + 44); + } + } - @Override - public String getTooltip() { - return StringUtil.localize("gui.owner") + ": " + PlayerUtil.getOwnerName(accessHandler); - } + @Override + public String getTooltip() { + return StringUtil.localize("gui.owner") + ": " + PlayerUtil.getOwnerName(accessHandler); + } - @Override - public boolean handleMouseClicked(int x, int y, int mouseButton) { + @Override + public boolean handleMouseClicked(int x, int y, int mouseButton) { - if (isAccessButton(x, y)) { - Minecraft minecraft = Proxies.common.getClientInstance(); - EntityPlayer player = minecraft.thePlayer; + if (isAccessButton(x, y)) { + Minecraft minecraft = Proxies.common.getClientInstance(); + EntityPlayer player = minecraft.thePlayer; - return accessHandler.switchAccess(player); - } + return accessHandler.switchAccess(player); + } - return false; - } + return false; + } - @Override - public void onOwnerSet(GameProfile gameProfile) { - Minecraft minecraft = Proxies.common.getClientInstance(); - boolean playerIsOwner = PlayerUtil.isSameGameProfile(minecraft.thePlayer.getGameProfile(), gameProfile); - if (playerIsOwner) { - maxHeight = 60; - } else { - maxHeight = 36; - } - } + @Override + public void onOwnerSet(GameProfile gameProfile) { + Minecraft minecraft = Proxies.common.getClientInstance(); + boolean playerIsOwner = PlayerUtil.isSameGameProfile(minecraft.thePlayer.getGameProfile(), gameProfile); + if (playerIsOwner) { + maxHeight = 60; + } else { + maxHeight = 36; + } + } - @Override - public void onGuiClosed() { - super.onGuiClosed(); - accessHandler.removeOwnerListener(this); - } + @Override + public void onGuiClosed() { + super.onGuiClosed(); + accessHandler.removeOwnerListener(this); + } } diff --git a/src/main/java/forestry/core/gui/ledgers/PowerLedger.java b/src/main/java/forestry/core/gui/ledgers/PowerLedger.java index b6f1a13ef..46d8997f1 100644 --- a/src/main/java/forestry/core/gui/ledgers/PowerLedger.java +++ b/src/main/java/forestry/core/gui/ledgers/PowerLedger.java @@ -17,46 +17,45 @@ import forestry.energy.EnergyManager; public class PowerLedger extends Ledger { - private final IPowerHandler tile; + private final IPowerHandler tile; - public PowerLedger(LedgerManager manager, IPowerHandler tile) { - super(manager, "power"); - this.tile = tile; - maxHeight = 94; - } + public PowerLedger(LedgerManager manager, IPowerHandler tile) { + super(manager, "power"); + this.tile = tile; + maxHeight = 94; + } - @Override - public void draw(int x, int y) { - // Draw background - drawBackground(x, y); + @Override + public void draw(int x, int y) { + // Draw background + drawBackground(x, y); - // Draw icon - drawIcon(TextureManager.getInstance().getDefault("misc/energy"), x + 3, y + 4); + // Draw icon + drawIcon(TextureManager.getInstance().getDefault("misc/energy"), x + 3, y + 4); - if (!isFullyOpened()) { - return; - } + if (!isFullyOpened()) { + return; + } - int xHeader = x + 22; - int xBody = x + 12; + int xHeader = x + 22; + int xBody = x + 12; - EnergyManager energyManager = tile.getEnergyManager(); + EnergyManager energyManager = tile.getEnergyManager(); - drawHeader(StringUtil.localize("gui.energy"), xHeader, y + 8); + drawHeader(StringUtil.localize("gui.energy"), xHeader, y + 8); - drawSubheader(StringUtil.localize("gui.stored") + ':', xBody, y + 20); - drawText(energyManager.getTotalEnergyStored() + " RF", xBody, y + 32); + drawSubheader(StringUtil.localize("gui.stored") + ':', xBody, y + 20); + drawText(energyManager.getTotalEnergyStored() + " RF", xBody, y + 32); - drawSubheader(StringUtil.localize("gui.maxenergy") + ':', xBody, y + 44); - drawText(energyManager.getMaxEnergyStored() + " RF", xBody, y + 56); + drawSubheader(StringUtil.localize("gui.maxenergy") + ':', xBody, y + 44); + drawText(energyManager.getMaxEnergyStored() + " RF", xBody, y + 56); - drawSubheader(StringUtil.localize("gui.maxenergyreceive") + ':', xBody, y + 68); - drawText(energyManager.getMaxEnergyReceived() + " RF", xBody, y + 80); - } - - @Override - public String getTooltip() { - return tile.getEnergyManager().getTotalEnergyStored() + " RF"; - } + drawSubheader(StringUtil.localize("gui.maxenergyreceive") + ':', xBody, y + 68); + drawText(energyManager.getMaxEnergyReceived() + " RF", xBody, y + 80); + } + @Override + public String getTooltip() { + return tile.getEnergyManager().getTotalEnergyStored() + " RF"; + } } diff --git a/src/main/java/forestry/core/gui/slots/SlotCraftMatrix.java b/src/main/java/forestry/core/gui/slots/SlotCraftMatrix.java index 372efca03..1f300eb1e 100644 --- a/src/main/java/forestry/core/gui/slots/SlotCraftMatrix.java +++ b/src/main/java/forestry/core/gui/slots/SlotCraftMatrix.java @@ -10,30 +10,28 @@ ******************************************************************************/ package forestry.core.gui.slots; -import net.minecraft.inventory.IInventory; - import forestry.core.gui.IContainerCrafting; +import net.minecraft.inventory.IInventory; /** * Informs the passed container of slot changes. Contains a dummy itemstack. */ public class SlotCraftMatrix extends SlotForestry { - private final IContainerCrafting eventHandler; - private final int slot; + private final IContainerCrafting eventHandler; + private final int slot; - public SlotCraftMatrix(IContainerCrafting container, IInventory iinventory, int i, int j, int k) { - super(iinventory, i, j, k); - setPhantom(); - this.eventHandler = container; - this.slot = i; - setStackLimit(1); - } - - @Override - public void onSlotChanged() { - super.onSlotChanged(); - eventHandler.onCraftMatrixChanged(inventory, slot); - } + public SlotCraftMatrix(IContainerCrafting container, IInventory iinventory, int i, int j, int k) { + super(iinventory, i, j, k); + setPhantom(); + this.eventHandler = container; + this.slot = i; + setStackLimit(1); + } + @Override + public void onSlotChanged() { + super.onSlotChanged(); + eventHandler.onCraftMatrixChanged(inventory, slot); + } } diff --git a/src/main/java/forestry/core/gui/slots/SlotCrafter.java b/src/main/java/forestry/core/gui/slots/SlotCrafter.java index 429d0f370..83cce4170 100755 --- a/src/main/java/forestry/core/gui/slots/SlotCrafter.java +++ b/src/main/java/forestry/core/gui/slots/SlotCrafter.java @@ -10,59 +10,58 @@ ******************************************************************************/ package forestry.core.gui.slots; +import cpw.mods.fml.common.FMLCommonHandler; +import forestry.factory.tiles.ICrafterWorktable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.SlotCrafting; import net.minecraft.item.ItemStack; -import cpw.mods.fml.common.FMLCommonHandler; - -import forestry.factory.tiles.ICrafterWorktable; - public class SlotCrafter extends SlotCrafting { - private final IInventory craftMatrix; - private final ICrafterWorktable crafter; + private final IInventory craftMatrix; + private final ICrafterWorktable crafter; - public SlotCrafter(EntityPlayer player, IInventory craftMatrix, ICrafterWorktable crafter, int slot, int xPos, int yPos) { - super(player, craftMatrix, craftMatrix, slot, xPos, yPos); - this.craftMatrix = craftMatrix; - this.crafter = crafter; - } + public SlotCrafter( + EntityPlayer player, IInventory craftMatrix, ICrafterWorktable crafter, int slot, int xPos, int yPos) { + super(player, craftMatrix, craftMatrix, slot, xPos, yPos); + this.craftMatrix = craftMatrix; + this.crafter = crafter; + } - @Override - public ItemStack decrStackSize(int amount) { - if (!this.getHasStack()) { - return null; - } + @Override + public ItemStack decrStackSize(int amount) { + if (!this.getHasStack()) { + return null; + } - return this.getStack(); - } + return this.getStack(); + } - @Override - public boolean canTakeStack(EntityPlayer player) { - return crafter.canTakeStack(getSlotIndex()); - } + @Override + public boolean canTakeStack(EntityPlayer player) { + return crafter.canTakeStack(getSlotIndex()); + } - @Override - public ItemStack getStack() { - return crafter.getResult(); - } + @Override + public ItemStack getStack() { + return crafter.getResult(); + } - @Override - public boolean getHasStack() { - return getStack() != null && crafter.canTakeStack(getSlotIndex()); - } + @Override + public boolean getHasStack() { + return getStack() != null && crafter.canTakeStack(getSlotIndex()); + } - @Override - public void onPickupFromSlot(EntityPlayer player, ItemStack itemStack) { - if (itemStack == null || !crafter.onCraftingStart(player)) { - return; - } + @Override + public void onPickupFromSlot(EntityPlayer player, ItemStack itemStack) { + if (itemStack == null || !crafter.onCraftingStart(player)) { + return; + } - FMLCommonHandler.instance().firePlayerCraftingEvent(player, itemStack, craftMatrix); - this.onCrafting(itemStack); // handles crafting achievements, maps, and statistics + FMLCommonHandler.instance().firePlayerCraftingEvent(player, itemStack, craftMatrix); + this.onCrafting(itemStack); // handles crafting achievements, maps, and statistics - crafter.onCraftingComplete(player); - } + crafter.onCraftingComplete(player); + } } diff --git a/src/main/java/forestry/core/gui/slots/SlotFiltered.java b/src/main/java/forestry/core/gui/slots/SlotFiltered.java index b400ddc16..e93abc0db 100644 --- a/src/main/java/forestry/core/gui/slots/SlotFiltered.java +++ b/src/main/java/forestry/core/gui/slots/SlotFiltered.java @@ -10,53 +10,51 @@ ******************************************************************************/ package forestry.core.gui.slots; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.render.TextureManager; +import forestry.core.tiles.IFilterSlotDelegate; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.render.TextureManager; -import forestry.core.tiles.IFilterSlotDelegate; - /** * Slot which only takes specific items, specified by the IFilterSlotDelegate. */ public class SlotFiltered extends SlotWatched { - private String blockedTexture = "slots/blocked"; - private final IFilterSlotDelegate filterSlotDelegate; + private String blockedTexture = "slots/blocked"; + private final IFilterSlotDelegate filterSlotDelegate; - public SlotFiltered(T inventory, int slotIndex, int xPos, int yPos) { - super(inventory, slotIndex, xPos, yPos); - this.filterSlotDelegate = inventory; - } + public SlotFiltered(T inventory, int slotIndex, int xPos, int yPos) { + super(inventory, slotIndex, xPos, yPos); + this.filterSlotDelegate = inventory; + } - @Override - public boolean isItemValid(ItemStack itemstack) { - int slotIndex = getSlotIndex(); - if (filterSlotDelegate.isLocked(slotIndex)) { - return false; - } - if (itemstack != null) { - return filterSlotDelegate.canSlotAccept(slotIndex, itemstack); - } - return true; - } + @Override + public boolean isItemValid(ItemStack itemstack) { + int slotIndex = getSlotIndex(); + if (filterSlotDelegate.isLocked(slotIndex)) { + return false; + } + if (itemstack != null) { + return filterSlotDelegate.canSlotAccept(slotIndex, itemstack); + } + return true; + } - public SlotFiltered setBlockedTexture(String ident) { - blockedTexture = ident; - return this; - } + public SlotFiltered setBlockedTexture(String ident) { + blockedTexture = ident; + return this; + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getBackgroundIconIndex() { - ItemStack stack = getStack(); - if (!isItemValid(stack)) { - return TextureManager.getInstance().getDefault(blockedTexture); - } else { - return null; - } - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getBackgroundIconIndex() { + ItemStack stack = getStack(); + if (!isItemValid(stack)) { + return TextureManager.getInstance().getDefault(blockedTexture); + } else { + return null; + } + } } diff --git a/src/main/java/forestry/core/gui/slots/SlotFilteredInventory.java b/src/main/java/forestry/core/gui/slots/SlotFilteredInventory.java index 6b01c45ed..409465c30 100644 --- a/src/main/java/forestry/core/gui/slots/SlotFilteredInventory.java +++ b/src/main/java/forestry/core/gui/slots/SlotFilteredInventory.java @@ -1,24 +1,24 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui.slots; - -import net.minecraft.inventory.IInventory; - -import forestry.core.tiles.IFilterSlotDelegate; - -/** - * Useful for InventoryTweaks. Works like SlotFiltered but allows InventoryTweaks to sort it. - */ -public class SlotFilteredInventory extends SlotFiltered { - public SlotFilteredInventory(T inventory, int slotIndex, int xPos, int yPos) { - super(inventory, slotIndex, xPos, yPos); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui.slots; + +import forestry.core.tiles.IFilterSlotDelegate; +import net.minecraft.inventory.IInventory; + +/** + * Useful for InventoryTweaks. Works like SlotFiltered but allows InventoryTweaks to sort it. + */ +public class SlotFilteredInventory extends SlotFiltered { + public SlotFilteredInventory( + T inventory, int slotIndex, int xPos, int yPos) { + super(inventory, slotIndex, xPos, yPos); + } +} diff --git a/src/main/java/forestry/core/gui/slots/SlotForestry.java b/src/main/java/forestry/core/gui/slots/SlotForestry.java index c2b21cf06..521a930bb 100755 --- a/src/main/java/forestry/core/gui/slots/SlotForestry.java +++ b/src/main/java/forestry/core/gui/slots/SlotForestry.java @@ -10,107 +10,109 @@ ******************************************************************************/ package forestry.core.gui.slots; +import forestry.core.gui.tooltips.IToolTipProvider; +import forestry.core.gui.tooltips.ToolTip; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; -import forestry.core.gui.tooltips.IToolTipProvider; -import forestry.core.gui.tooltips.ToolTip; - public class SlotForestry extends Slot implements IToolTipProvider { - private boolean isPhantom; - private boolean canAdjustPhantom = true; - private boolean canShift = true; - private int stackLimit; - private ToolTip toolTips; + private boolean isPhantom; + private boolean canAdjustPhantom = true; + private boolean canShift = true; + private int stackLimit; + private ToolTip toolTips; - public SlotForestry(IInventory inventory, int slotIndex, int xPos, int yPos) { - super(inventory, slotIndex, xPos, yPos); - if (inventory == null) { - throw new IllegalArgumentException("Inventory must not be null"); - } - this.stackLimit = -1; - } + public SlotForestry(IInventory inventory, int slotIndex, int xPos, int yPos) { + super(inventory, slotIndex, xPos, yPos); + if (inventory == null) { + throw new IllegalArgumentException("Inventory must not be null"); + } + this.stackLimit = -1; + } - public SlotForestry setPhantom() { - isPhantom = true; - return this; - } + public SlotForestry setPhantom() { + isPhantom = true; + return this; + } - public SlotForestry blockShift() { - canShift = false; - return this; - } + public SlotForestry blockShift() { + canShift = false; + return this; + } - @Override - public void putStack(ItemStack itemStack) { - if (!isPhantom() || canAdjustPhantom()) { - super.putStack(itemStack); - } - } + @Override + public void putStack(ItemStack itemStack) { + if (!isPhantom() || canAdjustPhantom()) { + super.putStack(itemStack); + } + } - public SlotForestry setCanAdjustPhantom(boolean canAdjust) { - this.canAdjustPhantom = canAdjust; - return this; - } + public SlotForestry setCanAdjustPhantom(boolean canAdjust) { + this.canAdjustPhantom = canAdjust; + return this; + } - public SlotForestry setStackLimit(int limit) { - this.stackLimit = limit; - return this; - } + public SlotForestry setStackLimit(int limit) { + this.stackLimit = limit; + return this; + } - public boolean isPhantom() { - return this.isPhantom; - } + public boolean isPhantom() { + return this.isPhantom; + } - public boolean canAdjustPhantom() { - return canAdjustPhantom; - } + public boolean canAdjustPhantom() { + return canAdjustPhantom; + } - @Override - public boolean canTakeStack(EntityPlayer stack) { - return !isPhantom(); - } + @Override + public boolean canTakeStack(EntityPlayer stack) { + return !isPhantom(); + } - public boolean canShift() { - return canShift; - } + public boolean canShift() { + return canShift; + } - @Override - public int getSlotStackLimit() { - if (stackLimit < 0) { - return super.getSlotStackLimit(); - } else { - return stackLimit; - } - } + @Override + public int getSlotStackLimit() { + if (stackLimit < 0) { + return super.getSlotStackLimit(); + } else { + return stackLimit; + } + } - /** - * @param toolTips the tooltips to set - */ - public void setToolTips(ToolTip toolTips) { - this.toolTips = toolTips; - } + /** + * @param toolTips the tooltips to set + */ + public void setToolTips(ToolTip toolTips) { + this.toolTips = toolTips; + } - /** - * @return the toolTips - * @param mouseX - * @param mouseY - */ - @Override - public ToolTip getToolTip(int mouseX, int mouseY) { - return toolTips; - } + /** + * @return the toolTips + * @param mouseX + * @param mouseY + */ + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + return toolTips; + } - @Override - public boolean isToolTipVisible() { - return getStack() == null; - } + @Override + public boolean isToolTipVisible() { + return getStack() == null; + } - @Override - public boolean isMouseOver(int mouseX, int mouseY) { - return mouseX >= xDisplayPosition && mouseX <= xDisplayPosition + 16 && mouseY >= yDisplayPosition && mouseY <= yDisplayPosition + 16; - } + @Override + public boolean isMouseOver(int mouseX, int mouseY) { + return mouseX >= xDisplayPosition + && mouseX <= xDisplayPosition + 16 + && mouseY >= yDisplayPosition + && mouseY <= yDisplayPosition + 16; + } } diff --git a/src/main/java/forestry/core/gui/slots/SlotLocked.java b/src/main/java/forestry/core/gui/slots/SlotLocked.java index 118c8466f..cec025ae7 100755 --- a/src/main/java/forestry/core/gui/slots/SlotLocked.java +++ b/src/main/java/forestry/core/gui/slots/SlotLocked.java @@ -16,29 +16,28 @@ import net.minecraft.item.ItemStack; public class SlotLocked extends SlotForestry { - public SlotLocked(IInventory inventory, int slotIndex, int xPos, int yPos) { - super(inventory, slotIndex, xPos, yPos); - setCanAdjustPhantom(false); - blockShift(); - setPhantom(); - } + public SlotLocked(IInventory inventory, int slotIndex, int xPos, int yPos) { + super(inventory, slotIndex, xPos, yPos); + setCanAdjustPhantom(false); + blockShift(); + setPhantom(); + } - @Override - public void onPickupFromSlot(EntityPlayer player, ItemStack itemStack) { - } + @Override + public void onPickupFromSlot(EntityPlayer player, ItemStack itemStack) {} - @Override - public boolean isItemValid(ItemStack par1ItemStack) { - return false; - } + @Override + public boolean isItemValid(ItemStack par1ItemStack) { + return false; + } - @Override - public boolean getHasStack() { - return false; - } + @Override + public boolean getHasStack() { + return false; + } - @Override - public ItemStack decrStackSize(int i) { - return null; - } + @Override + public ItemStack decrStackSize(int i) { + return null; + } } diff --git a/src/main/java/forestry/core/gui/slots/SlotOutput.java b/src/main/java/forestry/core/gui/slots/SlotOutput.java index d01078592..a72ab57d9 100755 --- a/src/main/java/forestry/core/gui/slots/SlotOutput.java +++ b/src/main/java/forestry/core/gui/slots/SlotOutput.java @@ -1,39 +1,38 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui.slots; - -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -/** - * @author CovertJaguar - */ -public class SlotOutput extends SlotWatched { - - public SlotOutput(IInventory iinventory, int slotIndex, int posX, int posY) { - super(iinventory, slotIndex, posX, posY); - } - - @Override - public boolean isItemValid(ItemStack itemstack) { - return false; - } - - @SideOnly(Side.CLIENT) - @Override - public IIcon getBackgroundIconIndex() { - return null; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui.slots; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; + +/** + * @author CovertJaguar + */ +public class SlotOutput extends SlotWatched { + + public SlotOutput(IInventory iinventory, int slotIndex, int posX, int posY) { + super(iinventory, slotIndex, posX, posY); + } + + @Override + public boolean isItemValid(ItemStack itemstack) { + return false; + } + + @SideOnly(Side.CLIENT) + @Override + public IIcon getBackgroundIconIndex() { + return null; + } +} diff --git a/src/main/java/forestry/core/gui/slots/SlotWatched.java b/src/main/java/forestry/core/gui/slots/SlotWatched.java index c98012e23..2ce5744f0 100644 --- a/src/main/java/forestry/core/gui/slots/SlotWatched.java +++ b/src/main/java/forestry/core/gui/slots/SlotWatched.java @@ -1,54 +1,53 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui.slots; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - -import forestry.core.inventory.watchers.FakeSlotChangeWatcher; -import forestry.core.inventory.watchers.FakeSlotPickupWatcher; -import forestry.core.inventory.watchers.ISlotChangeWatcher; -import forestry.core.inventory.watchers.ISlotPickupWatcher; - -/** - * Slot with a watcher callbacks. - */ -public class SlotWatched extends SlotForestry { - private ISlotPickupWatcher pickupWatcher = FakeSlotPickupWatcher.instance; - private ISlotChangeWatcher changeWatcher = FakeSlotChangeWatcher.instance; - - public SlotWatched(IInventory inventory, int slotIndex, int xPos, int yPos) { - super(inventory, slotIndex, xPos, yPos); - } - - public SlotWatched setPickupWatcher(ISlotPickupWatcher pickupWatcher) { - this.pickupWatcher = pickupWatcher; - return this; - } - - public SlotWatched setChangeWatcher(ISlotChangeWatcher changeWatcher) { - this.changeWatcher = changeWatcher; - return this; - } - - @Override - public void onPickupFromSlot(EntityPlayer player, ItemStack itemStack) { - super.onPickupFromSlot(player, itemStack); - pickupWatcher.onPickupFromSlot(getSlotIndex(), player); - } - - @Override - public void onSlotChanged() { - super.onSlotChanged(); - changeWatcher.onSlotChanged(inventory, getSlotIndex()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui.slots; + +import forestry.core.inventory.watchers.FakeSlotChangeWatcher; +import forestry.core.inventory.watchers.FakeSlotPickupWatcher; +import forestry.core.inventory.watchers.ISlotChangeWatcher; +import forestry.core.inventory.watchers.ISlotPickupWatcher; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + +/** + * Slot with a watcher callbacks. + */ +public class SlotWatched extends SlotForestry { + private ISlotPickupWatcher pickupWatcher = FakeSlotPickupWatcher.instance; + private ISlotChangeWatcher changeWatcher = FakeSlotChangeWatcher.instance; + + public SlotWatched(IInventory inventory, int slotIndex, int xPos, int yPos) { + super(inventory, slotIndex, xPos, yPos); + } + + public SlotWatched setPickupWatcher(ISlotPickupWatcher pickupWatcher) { + this.pickupWatcher = pickupWatcher; + return this; + } + + public SlotWatched setChangeWatcher(ISlotChangeWatcher changeWatcher) { + this.changeWatcher = changeWatcher; + return this; + } + + @Override + public void onPickupFromSlot(EntityPlayer player, ItemStack itemStack) { + super.onPickupFromSlot(player, itemStack); + pickupWatcher.onPickupFromSlot(getSlotIndex(), player); + } + + @Override + public void onSlotChanged() { + super.onSlotChanged(); + changeWatcher.onSlotChanged(inventory, getSlotIndex()); + } +} diff --git a/src/main/java/forestry/core/gui/slots/SlotWorking.java b/src/main/java/forestry/core/gui/slots/SlotWorking.java index 9855c5dd8..a6f6a2c77 100755 --- a/src/main/java/forestry/core/gui/slots/SlotWorking.java +++ b/src/main/java/forestry/core/gui/slots/SlotWorking.java @@ -16,27 +16,26 @@ import net.minecraft.item.ItemStack; public class SlotWorking extends SlotForestry { - public SlotWorking(IInventory iinventory, int i, int j, int k) { - super(iinventory, i, j, k); - blockShift(); - } + public SlotWorking(IInventory iinventory, int i, int j, int k) { + super(iinventory, i, j, k); + blockShift(); + } - @Override - public boolean isItemValid(ItemStack itemstack) { - return false; - } + @Override + public boolean isItemValid(ItemStack itemstack) { + return false; + } - @Override - public void onPickupFromSlot(EntityPlayer player, ItemStack itemStack) { - } + @Override + public void onPickupFromSlot(EntityPlayer player, ItemStack itemStack) {} - @Override - public boolean canTakeStack(EntityPlayer stack) { - return false; - } + @Override + public boolean canTakeStack(EntityPlayer stack) { + return false; + } - @Override - public ItemStack decrStackSize(int i) { - return null; - } + @Override + public ItemStack decrStackSize(int i) { + return null; + } } diff --git a/src/main/java/forestry/core/gui/tooltips/IToolTipProvider.java b/src/main/java/forestry/core/gui/tooltips/IToolTipProvider.java index 186632a46..86f8e2913 100755 --- a/src/main/java/forestry/core/gui/tooltips/IToolTipProvider.java +++ b/src/main/java/forestry/core/gui/tooltips/IToolTipProvider.java @@ -15,9 +15,9 @@ package forestry.core.gui.tooltips; */ public interface IToolTipProvider { - ToolTip getToolTip(int mouseX, int mouseY); + ToolTip getToolTip(int mouseX, int mouseY); - boolean isToolTipVisible(); + boolean isToolTipVisible(); - boolean isMouseOver(int mouseX, int mouseY); + boolean isMouseOver(int mouseX, int mouseY); } diff --git a/src/main/java/forestry/core/gui/tooltips/ToolTip.java b/src/main/java/forestry/core/gui/tooltips/ToolTip.java index a14816a52..9cbd513b4 100755 --- a/src/main/java/forestry/core/gui/tooltips/ToolTip.java +++ b/src/main/java/forestry/core/gui/tooltips/ToolTip.java @@ -11,7 +11,6 @@ package forestry.core.gui.tooltips; import com.google.common.collect.ForwardingList; - import java.util.ArrayList; import java.util.List; @@ -20,61 +19,59 @@ import java.util.List; */ public class ToolTip extends ForwardingList { - private final List delegate = new ArrayList<>(); - private final long delay; - private long mouseOverStart; + private final List delegate = new ArrayList<>(); + private final long delay; + private long mouseOverStart; - public ToolTip() { - this.delay = 0; - } + public ToolTip() { + this.delay = 0; + } - public ToolTip(int delay) { - this.delay = delay; - } + public ToolTip(int delay) { + this.delay = delay; + } - @Override - protected final List delegate() { - return delegate; - } + @Override + protected final List delegate() { + return delegate; + } - public boolean add(String line) { - return add(new ToolTipLine(line)); - } + public boolean add(String line) { + return add(new ToolTipLine(line)); + } - public boolean add(List lines) { - boolean changed = false; - for (Object line : lines) { - if (line instanceof String) { - changed |= add((String) line); - } - } - return changed; - } + public boolean add(List lines) { + boolean changed = false; + for (Object line : lines) { + if (line instanceof String) { + changed |= add((String) line); + } + } + return changed; + } - public void onTick(boolean mouseOver) { - if (delay == 0) { - return; - } - if (mouseOver) { - if (mouseOverStart == 0) { - mouseOverStart = System.currentTimeMillis(); - } - } else { - mouseOverStart = 0; - } - } + public void onTick(boolean mouseOver) { + if (delay == 0) { + return; + } + if (mouseOver) { + if (mouseOverStart == 0) { + mouseOverStart = System.currentTimeMillis(); + } + } else { + mouseOverStart = 0; + } + } - public boolean isReady() { - if (delay == 0) { - return true; - } - if (mouseOverStart == 0) { - return false; - } - return System.currentTimeMillis() - mouseOverStart >= delay; - } - - public void refresh() { - } + public boolean isReady() { + if (delay == 0) { + return true; + } + if (mouseOverStart == 0) { + return false; + } + return System.currentTimeMillis() - mouseOverStart >= delay; + } + public void refresh() {} } diff --git a/src/main/java/forestry/core/gui/tooltips/ToolTipLine.java b/src/main/java/forestry/core/gui/tooltips/ToolTipLine.java index 2ea687d09..8ff51896e 100755 --- a/src/main/java/forestry/core/gui/tooltips/ToolTipLine.java +++ b/src/main/java/forestry/core/gui/tooltips/ToolTipLine.java @@ -17,33 +17,32 @@ import net.minecraft.util.EnumChatFormatting; */ public class ToolTipLine { - private final String text; - private final EnumChatFormatting color; - private final int spacing; + private final String text; + private final EnumChatFormatting color; + private final int spacing; - public ToolTipLine(String text, EnumChatFormatting color, int spacing) { - this.text = text; - this.color = color; - this.spacing = spacing; - } + public ToolTipLine(String text, EnumChatFormatting color, int spacing) { + this.text = text; + this.color = color; + this.spacing = spacing; + } - public ToolTipLine(String text) { - this(text, null, 0); - } + public ToolTipLine(String text) { + this(text, null, 0); + } - public ToolTipLine() { - this("", null, 0); - } + public ToolTipLine() { + this("", null, 0); + } - public int getSpacing() { - return spacing; - } - - public String toString() { - if (color == null) { - return text; - } - return color + text; - } + public int getSpacing() { + return spacing; + } + public String toString() { + if (color == null) { + return text; + } + return color + text; + } } diff --git a/src/main/java/forestry/core/gui/widgets/GameTokenWidget.java b/src/main/java/forestry/core/gui/widgets/GameTokenWidget.java index c0c235301..6012a7d8c 100644 --- a/src/main/java/forestry/core/gui/widgets/GameTokenWidget.java +++ b/src/main/java/forestry/core/gui/widgets/GameTokenWidget.java @@ -1,97 +1,95 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui.widgets; - -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; - -import org.lwjgl.opengl.GL11; - -import forestry.core.gui.GuiUtil; -import forestry.core.network.packets.PacketGuiSelectRequest; -import forestry.core.proxy.Proxies; -import forestry.core.render.SpriteSheet; -import forestry.core.render.TextureManager; -import forestry.core.tiles.EscritoireGame; -import forestry.core.tiles.EscritoireGameToken; - -public class GameTokenWidget extends Widget { - private final ItemStack HIDDEN_TOKEN = new ItemStack(Items.book); - - private final EscritoireGame game; - private final int index; - - public GameTokenWidget(EscritoireGame game, WidgetManager manager, int xPos, int yPos, int index) { - super(manager, xPos, yPos); - this.game = game; - this.index = index; - } - - private EscritoireGameToken getToken() { - return game.getToken(index); - } - - @Override - public void draw(int startX, int startY) { - - EscritoireGameToken token = getToken(); - if (token == null) { - return; - } - - int tokenColour = token.getTokenColour(); - - float colorR = (tokenColour >> 16 & 255) / 255.0F; - float colorG = (tokenColour >> 8 & 255) / 255.0F; - float colorB = (tokenColour & 255) / 255.0F; - - Proxies.render.bindTexture(manager.gui.textureFile); - - GL11.glColor4f(colorR, colorG, colorB, 1.0F); - manager.gui.drawTexturedModalRect(startX + xPos, startY + yPos, 228, 0, 22, 22); - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); - - ItemStack tokenStack = HIDDEN_TOKEN; - if (token.isVisible()) { - tokenStack = token.getTokenStack(); - } - - GuiUtil.drawItemStack(manager.gui, tokenStack, startX + xPos + 3, startY + yPos + 3); - - manager.gui.setZLevel(150f); - for (String ident : getToken().getOverlayIcons()) { - RenderHelper.enableGUIStandardItemLighting(); - Proxies.render.bindTexture(SpriteSheet.ITEMS); - IIcon icon = TextureManager.getInstance().getDefault(ident); - manager.gui.drawTexturedModelRectFromIcon(startX + xPos + 3, startY + yPos + 3, icon, 16, 16); - RenderHelper.disableStandardItemLighting(); - } - manager.gui.setZLevel(0f); - } - - @Override - protected String getLegacyTooltip(EntityPlayer player) { - EscritoireGameToken token = getToken(); - if (token == null || !token.isVisible()) { - return null; - } - - return token.getTooltip(); - } - - @Override - public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - Proxies.net.sendToServer(new PacketGuiSelectRequest(index, 0)); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui.widgets; + +import forestry.core.gui.GuiUtil; +import forestry.core.network.packets.PacketGuiSelectRequest; +import forestry.core.proxy.Proxies; +import forestry.core.render.SpriteSheet; +import forestry.core.render.TextureManager; +import forestry.core.tiles.EscritoireGame; +import forestry.core.tiles.EscritoireGameToken; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import org.lwjgl.opengl.GL11; + +public class GameTokenWidget extends Widget { + private final ItemStack HIDDEN_TOKEN = new ItemStack(Items.book); + + private final EscritoireGame game; + private final int index; + + public GameTokenWidget(EscritoireGame game, WidgetManager manager, int xPos, int yPos, int index) { + super(manager, xPos, yPos); + this.game = game; + this.index = index; + } + + private EscritoireGameToken getToken() { + return game.getToken(index); + } + + @Override + public void draw(int startX, int startY) { + + EscritoireGameToken token = getToken(); + if (token == null) { + return; + } + + int tokenColour = token.getTokenColour(); + + float colorR = (tokenColour >> 16 & 255) / 255.0F; + float colorG = (tokenColour >> 8 & 255) / 255.0F; + float colorB = (tokenColour & 255) / 255.0F; + + Proxies.render.bindTexture(manager.gui.textureFile); + + GL11.glColor4f(colorR, colorG, colorB, 1.0F); + manager.gui.drawTexturedModalRect(startX + xPos, startY + yPos, 228, 0, 22, 22); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); + + ItemStack tokenStack = HIDDEN_TOKEN; + if (token.isVisible()) { + tokenStack = token.getTokenStack(); + } + + GuiUtil.drawItemStack(manager.gui, tokenStack, startX + xPos + 3, startY + yPos + 3); + + manager.gui.setZLevel(150f); + for (String ident : getToken().getOverlayIcons()) { + RenderHelper.enableGUIStandardItemLighting(); + Proxies.render.bindTexture(SpriteSheet.ITEMS); + IIcon icon = TextureManager.getInstance().getDefault(ident); + manager.gui.drawTexturedModelRectFromIcon(startX + xPos + 3, startY + yPos + 3, icon, 16, 16); + RenderHelper.disableStandardItemLighting(); + } + manager.gui.setZLevel(0f); + } + + @Override + protected String getLegacyTooltip(EntityPlayer player) { + EscritoireGameToken token = getToken(); + if (token == null || !token.isVisible()) { + return null; + } + + return token.getTooltip(); + } + + @Override + public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { + Proxies.net.sendToServer(new PacketGuiSelectRequest(index, 0)); + } +} diff --git a/src/main/java/forestry/core/gui/widgets/ItemStackWidget.java b/src/main/java/forestry/core/gui/widgets/ItemStackWidget.java index f52deaf11..7020b20c0 100644 --- a/src/main/java/forestry/core/gui/widgets/ItemStackWidget.java +++ b/src/main/java/forestry/core/gui/widgets/ItemStackWidget.java @@ -1,27 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui.widgets; - -import net.minecraft.item.ItemStack; - -public class ItemStackWidget extends ItemStackWidgetBase { - private final ItemStack itemStack; - - public ItemStackWidget(WidgetManager widgetManager, int xPos, int yPos, ItemStack itemStack) { - super(widgetManager, xPos, yPos); - this.itemStack = itemStack; - } - - @Override - public ItemStack getItemStack() { - return itemStack; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui.widgets; + +import net.minecraft.item.ItemStack; + +public class ItemStackWidget extends ItemStackWidgetBase { + private final ItemStack itemStack; + + public ItemStackWidget(WidgetManager widgetManager, int xPos, int yPos, ItemStack itemStack) { + super(widgetManager, xPos, yPos); + this.itemStack = itemStack; + } + + @Override + public ItemStack getItemStack() { + return itemStack; + } +} diff --git a/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java b/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java index 697702e55..69f62bdd7 100644 --- a/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java +++ b/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java @@ -1,45 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui.widgets; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.core.gui.GuiUtil; -import forestry.core.gui.tooltips.ToolTip; -import forestry.core.proxy.Proxies; - -public abstract class ItemStackWidgetBase extends Widget { - public ItemStackWidgetBase(WidgetManager widgetManager, int xPos, int yPos) { - super(widgetManager, xPos, yPos); - } - - protected abstract ItemStack getItemStack(); - - @Override - public void draw(int startX, int startY) { - ItemStack itemStack = getItemStack(); - if (itemStack != null) { - GuiUtil.drawItemStack(manager.gui, itemStack, xPos + startX, yPos + startY); - } - } - - @Override - public ToolTip getToolTip(int mouseX, int mouseY) { - EntityPlayer player = Proxies.common.getPlayer(); - ItemStack itemStack = getItemStack(); - ToolTip tip = new ToolTip(); - if (itemStack != null) { - tip.add(itemStack.getTooltip(player, false)); - } - return tip; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui.widgets; + +import forestry.core.gui.GuiUtil; +import forestry.core.gui.tooltips.ToolTip; +import forestry.core.proxy.Proxies; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public abstract class ItemStackWidgetBase extends Widget { + public ItemStackWidgetBase(WidgetManager widgetManager, int xPos, int yPos) { + super(widgetManager, xPos, yPos); + } + + protected abstract ItemStack getItemStack(); + + @Override + public void draw(int startX, int startY) { + ItemStack itemStack = getItemStack(); + if (itemStack != null) { + GuiUtil.drawItemStack(manager.gui, itemStack, xPos + startX, yPos + startY); + } + } + + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + EntityPlayer player = Proxies.common.getPlayer(); + ItemStack itemStack = getItemStack(); + ToolTip tip = new ToolTip(); + if (itemStack != null) { + tip.add(itemStack.getTooltip(player, false)); + } + return tip; + } +} diff --git a/src/main/java/forestry/core/gui/widgets/ProbeButton.java b/src/main/java/forestry/core/gui/widgets/ProbeButton.java index 8edeee5eb..c32ccf74f 100644 --- a/src/main/java/forestry/core/gui/widgets/ProbeButton.java +++ b/src/main/java/forestry/core/gui/widgets/ProbeButton.java @@ -1,65 +1,63 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui.widgets; - -import net.minecraft.entity.player.EntityPlayer; - -import org.lwjgl.opengl.GL11; - -import forestry.core.gui.GuiEscritoire; -import forestry.core.network.packets.PacketGuiSelectRequest; -import forestry.core.proxy.Proxies; -import forestry.core.utils.StringUtil; - -public class ProbeButton extends Widget { - - private final GuiEscritoire guiEscritoire; - private boolean pressed; - - public ProbeButton(GuiEscritoire guiEscritoire, WidgetManager manager, int xPos, int yPos) { - super(manager, xPos, yPos); - this.guiEscritoire = guiEscritoire; - width = 22; - height = 25; - } - - @Override - public void draw(int startX, int startY) { - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); - Proxies.render.bindTexture(manager.gui.textureFile); - manager.gui.drawTexturedModalRect(startX + xPos, startY + yPos, 228, pressed ? 47 : 22, width, height); - } - - @Override - protected String getLegacyTooltip(EntityPlayer player) { - return StringUtil.localize("gui.escritoire.probe"); - } - - @Override - public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - pressed = true; - Proxies.net.sendToServer(new PacketGuiSelectRequest(-1, 0)); - } - - @Override - public void handleMouseRelease(int mouseX, int mouseY, int eventType) { - if (pressed) { - pressed = false; - } - } - - @Override - public void handleMouseMove(int mouseX, int mouseY, int mouseButton, long time) { - if (manager.getAtPosition(mouseX - guiEscritoire.getGuiLeft(), mouseY - guiEscritoire.getGuiTop()) != this) { - pressed = false; - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.gui.widgets; + +import forestry.core.gui.GuiEscritoire; +import forestry.core.network.packets.PacketGuiSelectRequest; +import forestry.core.proxy.Proxies; +import forestry.core.utils.StringUtil; +import net.minecraft.entity.player.EntityPlayer; +import org.lwjgl.opengl.GL11; + +public class ProbeButton extends Widget { + + private final GuiEscritoire guiEscritoire; + private boolean pressed; + + public ProbeButton(GuiEscritoire guiEscritoire, WidgetManager manager, int xPos, int yPos) { + super(manager, xPos, yPos); + this.guiEscritoire = guiEscritoire; + width = 22; + height = 25; + } + + @Override + public void draw(int startX, int startY) { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); + Proxies.render.bindTexture(manager.gui.textureFile); + manager.gui.drawTexturedModalRect(startX + xPos, startY + yPos, 228, pressed ? 47 : 22, width, height); + } + + @Override + protected String getLegacyTooltip(EntityPlayer player) { + return StringUtil.localize("gui.escritoire.probe"); + } + + @Override + public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { + pressed = true; + Proxies.net.sendToServer(new PacketGuiSelectRequest(-1, 0)); + } + + @Override + public void handleMouseRelease(int mouseX, int mouseY, int eventType) { + if (pressed) { + pressed = false; + } + } + + @Override + public void handleMouseMove(int mouseX, int mouseY, int mouseButton, long time) { + if (manager.getAtPosition(mouseX - guiEscritoire.getGuiLeft(), mouseY - guiEscritoire.getGuiTop()) != this) { + pressed = false; + } + } +} diff --git a/src/main/java/forestry/core/gui/widgets/ReservoirWidget.java b/src/main/java/forestry/core/gui/widgets/ReservoirWidget.java index 21488e68d..17c2da5dc 100755 --- a/src/main/java/forestry/core/gui/widgets/ReservoirWidget.java +++ b/src/main/java/forestry/core/gui/widgets/ReservoirWidget.java @@ -11,9 +11,9 @@ package forestry.core.gui.widgets; public class ReservoirWidget extends TankWidget { - public ReservoirWidget(WidgetManager manager, int xPos, int yPos, int slot) { - super(manager, xPos, yPos, slot); - this.height = 16; - this.drawOverlay = false; - } + public ReservoirWidget(WidgetManager manager, int xPos, int yPos, int slot) { + super(manager, xPos, yPos, slot); + this.height = 16; + this.drawOverlay = false; + } } diff --git a/src/main/java/forestry/core/gui/widgets/SocketWidget.java b/src/main/java/forestry/core/gui/widgets/SocketWidget.java index dede50d54..cf61ffaaa 100755 --- a/src/main/java/forestry/core/gui/widgets/SocketWidget.java +++ b/src/main/java/forestry/core/gui/widgets/SocketWidget.java @@ -10,12 +10,6 @@ ******************************************************************************/ package forestry.core.gui.widgets; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumChatFormatting; - import forestry.core.circuits.ISocketable; import forestry.core.circuits.ISolderingIron; import forestry.core.circuits.ItemCircuitBoard; @@ -24,69 +18,80 @@ import forestry.core.gui.IContainerSocketed; import forestry.core.gui.tooltips.ToolTip; import forestry.core.proxy.Proxies; import forestry.core.utils.StringUtil; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; public class SocketWidget extends Widget { - private final ISocketable tile; - private final int slot; + private final ISocketable tile; + private final int slot; - public SocketWidget(WidgetManager manager, int xPos, int yPos, ISocketable tile, int slot) { - super(manager, xPos, yPos); - this.tile = tile; - this.slot = slot; - } + public SocketWidget(WidgetManager manager, int xPos, int yPos, ISocketable tile, int slot) { + super(manager, xPos, yPos); + this.tile = tile; + this.slot = slot; + } - @Override - public void draw(int startX, int startY) { - ItemStack socketStack = tile.getSocket(slot); - if (socketStack != null) { - GuiForestry.getItemRenderer().renderItemIntoGUI(manager.minecraft.fontRenderer, manager.minecraft.renderEngine, socketStack, startX + xPos, startY + yPos); - } - } + @Override + public void draw(int startX, int startY) { + ItemStack socketStack = tile.getSocket(slot); + if (socketStack != null) { + GuiForestry.getItemRenderer() + .renderItemIntoGUI( + manager.minecraft.fontRenderer, + manager.minecraft.renderEngine, + socketStack, + startX + xPos, + startY + yPos); + } + } - @Override - public ToolTip getToolTip(int mouseX, int mouseY) { - return toolTip; - } + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + return toolTip; + } - private final ToolTip toolTip = new ToolTip(250) { - @SuppressWarnings("unchecked") - @Override - public void refresh() { - toolTip.clear(); - ItemStack stack = tile.getSocket(slot); - if (stack != null) { - EntityPlayer player = Proxies.common.getClientInstance().thePlayer; - toolTip.add(stack.getTooltip(player, false)); - toolTip.add(EnumChatFormatting.ITALIC + StringUtil.localize("gui.socket.remove")); - } else { - toolTip.add(StringUtil.localize("gui.emptysocket")); - } - } - }; + private final ToolTip toolTip = new ToolTip(250) { + @SuppressWarnings("unchecked") + @Override + public void refresh() { + toolTip.clear(); + ItemStack stack = tile.getSocket(slot); + if (stack != null) { + EntityPlayer player = Proxies.common.getClientInstance().thePlayer; + toolTip.add(stack.getTooltip(player, false)); + toolTip.add(EnumChatFormatting.ITALIC + StringUtil.localize("gui.socket.remove")); + } else { + toolTip.add(StringUtil.localize("gui.emptysocket")); + } + } + }; - @Override - public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { + @Override + public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - ItemStack itemstack = manager.minecraft.thePlayer.inventory.getItemStack(); - if (itemstack == null) { - return; - } + ItemStack itemstack = manager.minecraft.thePlayer.inventory.getItemStack(); + if (itemstack == null) { + return; + } - Item held = itemstack.getItem(); + Item held = itemstack.getItem(); - Container container = manager.gui.inventorySlots; - if (!(container instanceof IContainerSocketed)) { - return; - } + Container container = manager.gui.inventorySlots; + if (!(container instanceof IContainerSocketed)) { + return; + } - IContainerSocketed containerSocketed = (IContainerSocketed) container; + IContainerSocketed containerSocketed = (IContainerSocketed) container; - // Insert chipsets - if (held instanceof ItemCircuitBoard) { - containerSocketed.handleChipsetClick(slot); - } else if (held instanceof ISolderingIron) { - containerSocketed.handleSolderingIronClick(slot); - } - } + // Insert chipsets + if (held instanceof ItemCircuitBoard) { + containerSocketed.handleChipsetClick(slot); + } else if (held instanceof ISolderingIron) { + containerSocketed.handleSolderingIronClick(slot); + } + } } diff --git a/src/main/java/forestry/core/gui/widgets/TankWidget.java b/src/main/java/forestry/core/gui/widgets/TankWidget.java index c45a39fad..c2058e935 100755 --- a/src/main/java/forestry/core/gui/widgets/TankWidget.java +++ b/src/main/java/forestry/core/gui/widgets/TankWidget.java @@ -10,17 +10,6 @@ ******************************************************************************/ package forestry.core.gui.widgets; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; - -import org.lwjgl.opengl.GL11; - import forestry.api.core.IToolPipette; import forestry.core.fluids.tanks.StandardTank; import forestry.core.gui.IContainerLiquidTanks; @@ -28,112 +17,121 @@ import forestry.core.gui.tooltips.ToolTip; import forestry.core.proxy.Proxies; import forestry.core.render.SpriteSheet; import forestry.farming.gui.ContainerFarm; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.IFluidTank; +import org.lwjgl.opengl.GL11; /** * Slot for liquid tanks */ public class TankWidget extends Widget { - private int overlayTexX = 176; - private int overlayTexY = 0; - private int slot = 0; - protected boolean drawOverlay = true; + private int overlayTexX = 176; + private int overlayTexY = 0; + private int slot = 0; + protected boolean drawOverlay = true; - public TankWidget(WidgetManager manager, int xPos, int yPos, int slot) { - super(manager, xPos, yPos); - this.slot = slot; - this.height = 58; - } + public TankWidget(WidgetManager manager, int xPos, int yPos, int slot) { + super(manager, xPos, yPos); + this.slot = slot; + this.height = 58; + } - public TankWidget setOverlayOrigin(int x, int y) { - overlayTexX = x; - overlayTexY = y; - return this; - } + public TankWidget setOverlayOrigin(int x, int y) { + overlayTexX = x; + overlayTexY = y; + return this; + } - public IFluidTank getTank() { - Container container = manager.gui.inventorySlots; - if (container instanceof IContainerLiquidTanks) { - return ((IContainerLiquidTanks) container).getTank(slot); - } else if (container instanceof ContainerFarm) { - return ((ContainerFarm) container).getTank(slot); - } - return null; - } + public IFluidTank getTank() { + Container container = manager.gui.inventorySlots; + if (container instanceof IContainerLiquidTanks) { + return ((IContainerLiquidTanks) container).getTank(slot); + } else if (container instanceof ContainerFarm) { + return ((ContainerFarm) container).getTank(slot); + } + return null; + } - @Override - public void draw(int startX, int startY) { - IFluidTank tank = getTank(); - if (tank == null || tank.getCapacity() <= 0) { - return; - } + @Override + public void draw(int startX, int startY) { + IFluidTank tank = getTank(); + if (tank == null || tank.getCapacity() <= 0) { + return; + } - FluidStack contents = tank.getFluid(); - if (contents == null || contents.amount <= 0 || contents.getFluid() == null) { - return; - } + FluidStack contents = tank.getFluid(); + if (contents == null || contents.amount <= 0 || contents.getFluid() == null) { + return; + } - IIcon liquidIcon = contents.getFluid().getIcon(contents); - if (liquidIcon == null) { - return; - } + IIcon liquidIcon = contents.getFluid().getIcon(contents); + if (liquidIcon == null) { + return; + } - int scaledLiquid = (contents.amount * height) / tank.getCapacity(); - if (scaledLiquid > height) { - scaledLiquid = height; - } + int scaledLiquid = (contents.amount * height) / tank.getCapacity(); + if (scaledLiquid > height) { + scaledLiquid = height; + } - Proxies.render.bindTexture(SpriteSheet.BLOCKS); - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - { - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); + Proxies.render.bindTexture(SpriteSheet.BLOCKS); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + { + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); - int start = 0; - while (scaledLiquid > 0) { - int x; + int start = 0; + while (scaledLiquid > 0) { + int x; - if (scaledLiquid > 16) { - x = 16; - scaledLiquid -= 16; - } else { - x = scaledLiquid; - scaledLiquid = 0; - } + if (scaledLiquid > 16) { + x = 16; + scaledLiquid -= 16; + } else { + x = scaledLiquid; + scaledLiquid = 0; + } - manager.gui.drawTexturedModelRectFromIcon(startX + xPos, startY + yPos + height - x - start, liquidIcon, 16, x); - start += 16; - } + manager.gui.drawTexturedModelRectFromIcon( + startX + xPos, startY + yPos + height - x - start, liquidIcon, 16, x); + start += 16; + } - if (drawOverlay) { - Proxies.render.bindTexture(manager.gui.textureFile); - manager.gui.drawTexturedModalRect(startX + xPos, startY + yPos, overlayTexX, overlayTexY, 16, 60); - } - } - GL11.glPopAttrib(); - } + if (drawOverlay) { + Proxies.render.bindTexture(manager.gui.textureFile); + manager.gui.drawTexturedModalRect(startX + xPos, startY + yPos, overlayTexX, overlayTexY, 16, 60); + } + } + GL11.glPopAttrib(); + } - @Override - public ToolTip getToolTip(int mouseX, int mouseY) { - IFluidTank tank = getTank(); - if (!(tank instanceof StandardTank)) { - return null; - } - return ((StandardTank) tank).getToolTip(); - } + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + IFluidTank tank = getTank(); + if (!(tank instanceof StandardTank)) { + return null; + } + return ((StandardTank) tank).getToolTip(); + } - @Override - public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - EntityPlayer player = manager.minecraft.thePlayer; - ItemStack itemstack = player.inventory.getItemStack(); - if (itemstack == null) { - return; - } + @Override + public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { + EntityPlayer player = manager.minecraft.thePlayer; + ItemStack itemstack = player.inventory.getItemStack(); + if (itemstack == null) { + return; + } - Item held = itemstack.getItem(); - Container container = manager.gui.inventorySlots; - if (held instanceof IToolPipette && container instanceof IContainerLiquidTanks) { - ((IContainerLiquidTanks) container).handlePipetteClickClient(slot, player); - } - } + Item held = itemstack.getItem(); + Container container = manager.gui.inventorySlots; + if (held instanceof IToolPipette && container instanceof IContainerLiquidTanks) { + ((IContainerLiquidTanks) container).handlePipetteClickClient(slot, player); + } + } } diff --git a/src/main/java/forestry/core/gui/widgets/Widget.java b/src/main/java/forestry/core/gui/widgets/Widget.java index 635ad2b39..72498f052 100755 --- a/src/main/java/forestry/core/gui/widgets/Widget.java +++ b/src/main/java/forestry/core/gui/widgets/Widget.java @@ -10,70 +10,66 @@ ******************************************************************************/ package forestry.core.gui.widgets; -import net.minecraft.entity.player.EntityPlayer; - import forestry.core.gui.tooltips.IToolTipProvider; import forestry.core.gui.tooltips.ToolTip; import forestry.core.proxy.Proxies; +import net.minecraft.entity.player.EntityPlayer; /** * Basic non-ItemStack slot */ public abstract class Widget implements IToolTipProvider { - protected final WidgetManager manager; - protected final int xPos; - protected final int yPos; - protected int width = 16; - protected int height = 16; + protected final WidgetManager manager; + protected final int xPos; + protected final int yPos; + protected int width = 16; + protected int height = 16; - public Widget(WidgetManager manager, int xPos, int yPos) { - this.manager = manager; - this.xPos = xPos; - this.yPos = yPos; - } + public Widget(WidgetManager manager, int xPos, int yPos) { + this.manager = manager; + this.xPos = xPos; + this.yPos = yPos; + } - public int getWidth() { - return width; - } + public int getWidth() { + return width; + } - public int getHeight() { - return height; - } + public int getHeight() { + return height; + } - public abstract void draw(int startX, int startY); + public abstract void draw(int startX, int startY); - @Override - public ToolTip getToolTip(int mouseX, int mouseY) { - String line = getLegacyTooltip(Proxies.common.getClientInstance().thePlayer); - if (line != null && !line.isEmpty()) { - ToolTip tip = new ToolTip(); - tip.add(line); - return tip; - } - return null; - } + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + String line = getLegacyTooltip(Proxies.common.getClientInstance().thePlayer); + if (line != null && !line.isEmpty()) { + ToolTip tip = new ToolTip(); + tip.add(line); + return tip; + } + return null; + } - protected String getLegacyTooltip(EntityPlayer player) { - return null; - } + protected String getLegacyTooltip(EntityPlayer player) { + return null; + } - // Not fully implemented - @Override - public boolean isToolTipVisible() { - return true; - } + // Not fully implemented + @Override + public boolean isToolTipVisible() { + return true; + } - @Override - public boolean isMouseOver(int mouseX, int mouseY) { - return mouseX >= xPos && mouseX <= xPos + this.width && mouseY >= yPos && mouseY <= yPos + this.height; - } + @Override + public boolean isMouseOver(int mouseX, int mouseY) { + return mouseX >= xPos && mouseX <= xPos + this.width && mouseY >= yPos && mouseY <= yPos + this.height; + } - public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - } + public void handleMouseClick(int mouseX, int mouseY, int mouseButton) {} - public void handleMouseRelease(int mouseX, int mouseY, int eventType) { - } + public void handleMouseRelease(int mouseX, int mouseY, int eventType) {} - public void handleMouseMove(int mouseX, int mouseY, int mouseButton, long time) { - } + public void handleMouseMove(int mouseX, int mouseY, int mouseButton, long time) {} } diff --git a/src/main/java/forestry/core/gui/widgets/WidgetManager.java b/src/main/java/forestry/core/gui/widgets/WidgetManager.java index 96c306cc2..1bd25dc74 100644 --- a/src/main/java/forestry/core/gui/widgets/WidgetManager.java +++ b/src/main/java/forestry/core/gui/widgets/WidgetManager.java @@ -10,81 +10,77 @@ ******************************************************************************/ package forestry.core.gui.widgets; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.Minecraft; - -import org.lwjgl.opengl.GL11; - import forestry.core.gui.GuiForestry; import forestry.core.proxy.Proxies; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.client.Minecraft; +import org.lwjgl.opengl.GL11; public class WidgetManager { - public final GuiForestry gui; - public final Minecraft minecraft; - protected final List widgets = new ArrayList<>(); + public final GuiForestry gui; + public final Minecraft minecraft; + protected final List widgets = new ArrayList<>(); - public WidgetManager(GuiForestry gui) { - this.gui = gui; - this.minecraft = Proxies.common.getClientInstance(); - } + public WidgetManager(GuiForestry gui) { + this.gui = gui; + this.minecraft = Proxies.common.getClientInstance(); + } - public void add(Widget slot) { - this.widgets.add(slot); - } + public void add(Widget slot) { + this.widgets.add(slot); + } - public void remove(Widget slot) { - this.widgets.remove(slot); - } + public void remove(Widget slot) { + this.widgets.remove(slot); + } - public void clear() { - this.widgets.clear(); - } + public void clear() { + this.widgets.clear(); + } - public List getWidgets() { - return widgets; - } + public List getWidgets() { + return widgets; + } - public Widget getAtPosition(int mX, int mY) { - for (Widget slot : widgets) { - if (slot.isMouseOver(mX, mY)) { - return slot; - } - } + public Widget getAtPosition(int mX, int mY) { + for (Widget slot : widgets) { + if (slot.isMouseOver(mX, mY)) { + return slot; + } + } - return null; - } + return null; + } - public void drawWidgets() { - gui.setZLevel(100.0F); - GuiForestry.getItemRenderer().zLevel = 100.0F; - for (Widget slot : widgets) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - slot.draw(0, 0); - } - gui.setZLevel(0.0F); - GuiForestry.getItemRenderer().zLevel = 0.0F; + public void drawWidgets() { + gui.setZLevel(100.0F); + GuiForestry.getItemRenderer().zLevel = 100.0F; + for (Widget slot : widgets) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + slot.draw(0, 0); + } + gui.setZLevel(0.0F); + GuiForestry.getItemRenderer().zLevel = 0.0F; + } - } + public void handleMouseClicked(int mouseX, int mouseY, int mouseButton) { + Widget slot = getAtPosition(mouseX - gui.getGuiLeft(), mouseY - gui.getGuiTop()); + if (slot != null) { + slot.handleMouseClick(mouseX, mouseY, mouseButton); + } + } - public void handleMouseClicked(int mouseX, int mouseY, int mouseButton) { - Widget slot = getAtPosition(mouseX - gui.getGuiLeft(), mouseY - gui.getGuiTop()); - if (slot != null) { - slot.handleMouseClick(mouseX, mouseY, mouseButton); - } - } + public void handleMouseRelease(int mouseX, int mouseY, int eventType) { + for (Widget slot : widgets) { + slot.handleMouseRelease(mouseX, mouseY, eventType); + } + } - public void handleMouseRelease(int mouseX, int mouseY, int eventType) { - for (Widget slot : widgets) { - slot.handleMouseRelease(mouseX, mouseY, eventType); - } - } - - public void handleMouseMove(int mouseX, int mouseY, int mouseButton, long time) { - for (Widget slot : widgets) { - slot.handleMouseMove(mouseX, mouseY, mouseButton, time); - } - } + public void handleMouseMove(int mouseX, int mouseY, int mouseButton, long time) { + for (Widget slot : widgets) { + slot.handleMouseMove(mouseX, mouseY, mouseButton, time); + } + } } diff --git a/src/main/java/forestry/core/inventory/AdjacentInventoryCache.java b/src/main/java/forestry/core/inventory/AdjacentInventoryCache.java index 98d49d716..a2737d465 100644 --- a/src/main/java/forestry/core/inventory/AdjacentInventoryCache.java +++ b/src/main/java/forestry/core/inventory/AdjacentInventoryCache.java @@ -10,92 +10,89 @@ ******************************************************************************/ package forestry.core.inventory; +import forestry.core.tiles.AdjacentTileCache; +import forestry.core.tiles.TileUtil; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; - import net.minecraft.inventory.IInventory; import net.minecraft.tileentity.TileEntity; - import net.minecraftforge.common.util.ForgeDirection; -import forestry.core.tiles.AdjacentTileCache; -import forestry.core.tiles.TileUtil; - /** * @author CovertJaguar */ public final class AdjacentInventoryCache implements AdjacentTileCache.ICacheListener { - public interface ITileFilter { - boolean matches(TileEntity tile); - } + public interface ITileFilter { + boolean matches(TileEntity tile); + } - private final AdjacentTileCache cache; - private boolean changed = true; - private final List invs = new LinkedList<>(); - private final IInventory[] sides = new IInventory[6]; - private final Comparator sorter; - private final ITileFilter filter; + private final AdjacentTileCache cache; + private boolean changed = true; + private final List invs = new LinkedList<>(); + private final IInventory[] sides = new IInventory[6]; + private final Comparator sorter; + private final ITileFilter filter; - public AdjacentInventoryCache(TileEntity tile, AdjacentTileCache cache) { - this(tile, cache, null, null); - } + public AdjacentInventoryCache(TileEntity tile, AdjacentTileCache cache) { + this(tile, cache, null, null); + } - public AdjacentInventoryCache(TileEntity tile, AdjacentTileCache cache, ITileFilter filter) { - this(tile, cache, filter, null); - } + public AdjacentInventoryCache(TileEntity tile, AdjacentTileCache cache, ITileFilter filter) { + this(tile, cache, filter, null); + } - public AdjacentInventoryCache(TileEntity tile, AdjacentTileCache cache, ITileFilter filter, Comparator sorter) { - this.cache = cache; - this.filter = filter; - this.sorter = sorter; - cache.addListener(this); - } + public AdjacentInventoryCache( + TileEntity tile, AdjacentTileCache cache, ITileFilter filter, Comparator sorter) { + this.cache = cache; + this.filter = filter; + this.sorter = sorter; + cache.addListener(this); + } - public IInventory getAdjacentInventory(ForgeDirection side) { - checkChanged(); - return sides[side.ordinal()]; - } + public IInventory getAdjacentInventory(ForgeDirection side) { + checkChanged(); + return sides[side.ordinal()]; + } - public Collection getAdjacentInventories() { - checkChanged(); - return invs; - } + public Collection getAdjacentInventories() { + checkChanged(); + return invs; + } - @Override - public void changed() { - changed = true; - } + @Override + public void changed() { + changed = true; + } - @Override - public void purge() { - invs.clear(); - Arrays.fill(sides, null); - } - - private void checkChanged() { - cache.refresh(); - if (changed) { - changed = false; - purge(); - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { - TileEntity tile = cache.getTileOnSide(side); - if (tile != null && (filter == null || filter.matches(tile))) { - IInventory inv = TileUtil.getInventoryFromTile(tile, side.getOpposite()); - if (inv != null) { - sides[side.ordinal()] = inv; - invs.add(inv); - } - } - } - if (sorter != null) { - Collections.sort(invs, sorter); - } - } - } + @Override + public void purge() { + invs.clear(); + Arrays.fill(sides, null); + } + private void checkChanged() { + cache.refresh(); + if (changed) { + changed = false; + purge(); + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + TileEntity tile = cache.getTileOnSide(side); + if (tile != null && (filter == null || filter.matches(tile))) { + IInventory inv = TileUtil.getInventoryFromTile(tile, side.getOpposite()); + if (inv != null) { + sides[side.ordinal()] = inv; + invs.add(inv); + } + } + } + if (sorter != null) { + Collections.sort(invs, sorter); + } + } + } } diff --git a/src/main/java/forestry/core/inventory/FakeInventoryAdapter.java b/src/main/java/forestry/core/inventory/FakeInventoryAdapter.java index 842fdef40..da1959e22 100644 --- a/src/main/java/forestry/core/inventory/FakeInventoryAdapter.java +++ b/src/main/java/forestry/core/inventory/FakeInventoryAdapter.java @@ -1,134 +1,118 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.inventory; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import forestry.core.config.Constants; - -public class FakeInventoryAdapter implements IInventoryAdapter { - - private static FakeInventoryAdapter instance; - - public static FakeInventoryAdapter instance() { - if (instance == null) { - instance = new FakeInventoryAdapter(); - } - return instance; - } - - private FakeInventoryAdapter() { - - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return false; - } - - @Override - public boolean isLocked(int slotIndex) { - return false; - } - - @Override - public int[] getAccessibleSlotsFromSide(int p_94128_1_) { - return Constants.SLOTS_NONE; - } - - @Override - public boolean canInsertItem(int p_102007_1_, ItemStack p_102007_2_, int p_102007_3_) { - return false; - } - - @Override - public boolean canExtractItem(int p_102008_1_, ItemStack p_102008_2_, int p_102008_3_) { - return false; - } - - @Override - public int getSizeInventory() { - return 0; - } - - @Override - public ItemStack getStackInSlot(int p_70301_1_) { - return null; - } - - @Override - public ItemStack decrStackSize(int p_70298_1_, int p_70298_2_) { - return null; - } - - @Override - public ItemStack getStackInSlotOnClosing(int p_70304_1_) { - return null; - } - - @Override - public void setInventorySlotContents(int p_70299_1_, ItemStack p_70299_2_) { - - } - - @Override - public String getInventoryName() { - return null; - } - - @Override - public boolean hasCustomInventoryName() { - return false; - } - - @Override - public int getInventoryStackLimit() { - return 0; - } - - @Override - public void markDirty() { - - } - - @Override - public boolean isUseableByPlayer(EntityPlayer p_70300_1_) { - return false; - } - - @Override - public void openInventory() { - - } - - @Override - public void closeInventory() { - - } - - @Override - public boolean isItemValidForSlot(int p_94041_1_, ItemStack p_94041_2_) { - return false; - } - - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.inventory; + +import forestry.core.config.Constants; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +public class FakeInventoryAdapter implements IInventoryAdapter { + + private static FakeInventoryAdapter instance; + + public static FakeInventoryAdapter instance() { + if (instance == null) { + instance = new FakeInventoryAdapter(); + } + return instance; + } + + private FakeInventoryAdapter() {} + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return false; + } + + @Override + public boolean isLocked(int slotIndex) { + return false; + } + + @Override + public int[] getAccessibleSlotsFromSide(int p_94128_1_) { + return Constants.SLOTS_NONE; + } + + @Override + public boolean canInsertItem(int p_102007_1_, ItemStack p_102007_2_, int p_102007_3_) { + return false; + } + + @Override + public boolean canExtractItem(int p_102008_1_, ItemStack p_102008_2_, int p_102008_3_) { + return false; + } + + @Override + public int getSizeInventory() { + return 0; + } + + @Override + public ItemStack getStackInSlot(int p_70301_1_) { + return null; + } + + @Override + public ItemStack decrStackSize(int p_70298_1_, int p_70298_2_) { + return null; + } + + @Override + public ItemStack getStackInSlotOnClosing(int p_70304_1_) { + return null; + } + + @Override + public void setInventorySlotContents(int p_70299_1_, ItemStack p_70299_2_) {} + + @Override + public String getInventoryName() { + return null; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + return 0; + } + + @Override + public void markDirty() {} + + @Override + public boolean isUseableByPlayer(EntityPlayer p_70300_1_) { + return false; + } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} + + @Override + public boolean isItemValidForSlot(int p_94041_1_, ItemStack p_94041_2_) { + return false; + } + + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) {} + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) {} +} diff --git a/src/main/java/forestry/core/inventory/IInventoryAdapter.java b/src/main/java/forestry/core/inventory/IInventoryAdapter.java index 33af8dcc2..594c5f91f 100644 --- a/src/main/java/forestry/core/inventory/IInventoryAdapter.java +++ b/src/main/java/forestry/core/inventory/IInventoryAdapter.java @@ -1,10 +1,7 @@ -package forestry.core.inventory; - -import net.minecraft.inventory.ISidedInventory; - -import forestry.api.core.INBTTagable; -import forestry.core.tiles.IFilterSlotDelegate; - -public interface IInventoryAdapter extends ISidedInventory, IFilterSlotDelegate, INBTTagable { - -} +package forestry.core.inventory; + +import forestry.api.core.INBTTagable; +import forestry.core.tiles.IFilterSlotDelegate; +import net.minecraft.inventory.ISidedInventory; + +public interface IInventoryAdapter extends ISidedInventory, IFilterSlotDelegate, INBTTagable {} diff --git a/src/main/java/forestry/core/inventory/InventoryAdapter.java b/src/main/java/forestry/core/inventory/InventoryAdapter.java index e40354391..8a43c677c 100755 --- a/src/main/java/forestry/core/inventory/InventoryAdapter.java +++ b/src/main/java/forestry/core/inventory/InventoryAdapter.java @@ -10,195 +10,191 @@ ******************************************************************************/ package forestry.core.inventory; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import forestry.core.config.Constants; import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; import forestry.core.utils.InventoryUtil; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; /** * With permission from Krapht. */ public class InventoryAdapter implements IInventoryAdapter, IStreamable { - private final IInventory inventory; - private boolean allowAutomation = true; + private final IInventory inventory; + private boolean allowAutomation = true; - //private boolean debug = false; + // private boolean debug = false; - public InventoryAdapter(int size, String name) { - this(size, name, 64); - } + public InventoryAdapter(int size, String name) { + this(size, name, 64); + } - public InventoryAdapter(int size, String name, int stackLimit) { - this(new InventoryPlain(size, name, stackLimit)); - } + public InventoryAdapter(int size, String name, int stackLimit) { + this(new InventoryPlain(size, name, stackLimit)); + } - public InventoryAdapter(IInventory inventory) { - this.inventory = inventory; - configureSided(); - } + public InventoryAdapter(IInventory inventory) { + this.inventory = inventory; + configureSided(); + } - public InventoryAdapter disableAutomation() { - this.allowAutomation = false; - return this; - } + public InventoryAdapter disableAutomation() { + this.allowAutomation = false; + return this; + } - // public InventoryAdapter enableDebug() { - // this.debug = true; - // return this; - // } + // public InventoryAdapter enableDebug() { + // this.debug = true; + // return this; + // } - /** - * @return Copy of this inventory. Stacks are copies. - */ - public InventoryAdapter copy() { - InventoryAdapter copy = new InventoryAdapter(inventory.getSizeInventory(), inventory.getInventoryName(), inventory.getInventoryStackLimit()); + /** + * @return Copy of this inventory. Stacks are copies. + */ + public InventoryAdapter copy() { + InventoryAdapter copy = new InventoryAdapter( + inventory.getSizeInventory(), inventory.getInventoryName(), inventory.getInventoryStackLimit()); - for (int i = 0; i < inventory.getSizeInventory(); i++) { - if (inventory.getStackInSlot(i) != null) { - copy.setInventorySlotContents(i, inventory.getStackInSlot(i).copy()); - } - } + for (int i = 0; i < inventory.getSizeInventory(); i++) { + if (inventory.getStackInSlot(i) != null) { + copy.setInventorySlotContents(i, inventory.getStackInSlot(i).copy()); + } + } - return copy; - } + return copy; + } + /* IINVENTORY */ + @Override + public int getSizeInventory() { + return inventory.getSizeInventory(); + } - /* IINVENTORY */ - @Override - public int getSizeInventory() { - return inventory.getSizeInventory(); - } + @Override + public ItemStack getStackInSlot(int slotId) { + return inventory.getStackInSlot(slotId); + } - @Override - public ItemStack getStackInSlot(int slotId) { - return inventory.getStackInSlot(slotId); - } + @Override + public ItemStack decrStackSize(int slotId, int count) { + return inventory.decrStackSize(slotId, count); + } - @Override - public ItemStack decrStackSize(int slotId, int count) { - return inventory.decrStackSize(slotId, count); - } + @Override + public void setInventorySlotContents(int slotId, ItemStack itemstack) { + inventory.setInventorySlotContents(slotId, itemstack); + } - @Override - public void setInventorySlotContents(int slotId, ItemStack itemstack) { - inventory.setInventorySlotContents(slotId, itemstack); - } + @Override + public String getInventoryName() { + return inventory.getInventoryName(); + } - @Override - public String getInventoryName() { - return inventory.getInventoryName(); - } + @Override + public int getInventoryStackLimit() { + return inventory.getInventoryStackLimit(); + } - @Override - public int getInventoryStackLimit() { - return inventory.getInventoryStackLimit(); - } + @Override + public void markDirty() { + inventory.markDirty(); + } - @Override - public void markDirty() { - inventory.markDirty(); - } + @Override + public ItemStack getStackInSlotOnClosing(int slotIndex) { + return inventory.getStackInSlotOnClosing(slotIndex); + } - @Override - public ItemStack getStackInSlotOnClosing(int slotIndex) { - return inventory.getStackInSlotOnClosing(slotIndex); - } + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return true; + } - @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return true; - } + @Override + public boolean hasCustomInventoryName() { + return true; + } - @Override - public boolean hasCustomInventoryName() { - return true; - } + @Override + public boolean isItemValidForSlot(int i, ItemStack itemstack) { + return true; + } - @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) { - return true; - } + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return true; + } - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return true; - } + @Override + public boolean isLocked(int slotIndex) { + return false; + } - @Override - public boolean isLocked(int slotIndex) { - return false; - } + @Override + public void openInventory() {} - @Override - public void openInventory() { - } + @Override + public void closeInventory() {} - @Override - public void closeInventory() { - } + /* ISIDEDINVENTORY */ + private int[][] slotMap; - /* ISIDEDINVENTORY */ - private int[][] slotMap; + @Override + public int[] getAccessibleSlotsFromSide(int side) { + if (allowAutomation) { + return slotMap[side]; + } + return Constants.SLOTS_NONE; + } - @Override - public int[] getAccessibleSlotsFromSide(int side) { - if (allowAutomation) { - return slotMap[side]; - } - return Constants.SLOTS_NONE; - } + private void configureSided() { + slotMap = new int[6][0]; - private void configureSided() { - slotMap = new int[6][0]; + int count = getSizeInventory(); + int[] slots = new int[count]; + for (int i = 0; i < count; i++) { + slots[i] = i; + } - int count = getSizeInventory(); - int[] slots = new int[count]; - for (int i = 0; i < count; i++) { - slots[i] = i; - } + for (int side : Constants.FACINGS) { + slotMap[side] = slots; + } + } - for (int side : Constants.FACINGS) { - slotMap[side] = slots; - } - } + @Override + public boolean canInsertItem(int slot, ItemStack stack, int side) { + return isItemValidForSlot(slot, stack); + } - @Override - public boolean canInsertItem(int slot, ItemStack stack, int side) { - return isItemValidForSlot(slot, stack); - } + @Override + public boolean canExtractItem(int slot, ItemStack stack, int side) { + return false; + } - @Override - public boolean canExtractItem(int slot, ItemStack stack, int side) { - return false; - } + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + InventoryUtil.readFromNBT(this, nbttagcompound); + } - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - InventoryUtil.readFromNBT(this, nbttagcompound); - } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + InventoryUtil.writeToNBT(this, nbttagcompound); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - InventoryUtil.writeToNBT(this, nbttagcompound); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeInventory(inventory); + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeInventory(inventory); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - data.readInventory(inventory); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + data.readInventory(inventory); + } } diff --git a/src/main/java/forestry/core/inventory/InventoryAdapterRestricted.java b/src/main/java/forestry/core/inventory/InventoryAdapterRestricted.java index 082879831..5d6f042d1 100644 --- a/src/main/java/forestry/core/inventory/InventoryAdapterRestricted.java +++ b/src/main/java/forestry/core/inventory/InventoryAdapterRestricted.java @@ -1,66 +1,65 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.inventory; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.core.access.IAccessHandler; -import forestry.core.config.Constants; - -public class InventoryAdapterRestricted extends InventoryAdapter { - private final IAccessHandler accessHandler; - - public InventoryAdapterRestricted(int size, String name, IAccessHandler accessHandler) { - super(size, name); - this.accessHandler = accessHandler; - } - - public InventoryAdapterRestricted(int size, String name, int stackLimit, IAccessHandler accessHandler) { - super(size, name, stackLimit); - this.accessHandler = accessHandler; - } - - @Override - public final boolean isUseableByPlayer(EntityPlayer player) { - return accessHandler.allowsViewing(player); - } - - @Override - public boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { - if (itemStack == null || !accessHandler.allowsPipeConnections()) { - return false; - } - - return canSlotAccept(slotIndex, itemStack); - } - - @Override - public int[] getAccessibleSlotsFromSide(int side) { - if (!accessHandler.allowsPipeConnections()) { - return Constants.SLOTS_NONE; - } - return super.getAccessibleSlotsFromSide(side); - } - - @Override - public final boolean canInsertItem(int slotIndex, ItemStack itemStack, int side) { - if (itemStack == null || !accessHandler.allowsPipeConnections()) { - return false; - } - return isItemValidForSlot(slotIndex, itemStack); - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemStack, int side) { - return itemStack != null && accessHandler.allowsPipeConnections(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.inventory; + +import forestry.core.access.IAccessHandler; +import forestry.core.config.Constants; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class InventoryAdapterRestricted extends InventoryAdapter { + private final IAccessHandler accessHandler; + + public InventoryAdapterRestricted(int size, String name, IAccessHandler accessHandler) { + super(size, name); + this.accessHandler = accessHandler; + } + + public InventoryAdapterRestricted(int size, String name, int stackLimit, IAccessHandler accessHandler) { + super(size, name, stackLimit); + this.accessHandler = accessHandler; + } + + @Override + public final boolean isUseableByPlayer(EntityPlayer player) { + return accessHandler.allowsViewing(player); + } + + @Override + public boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { + if (itemStack == null || !accessHandler.allowsPipeConnections()) { + return false; + } + + return canSlotAccept(slotIndex, itemStack); + } + + @Override + public int[] getAccessibleSlotsFromSide(int side) { + if (!accessHandler.allowsPipeConnections()) { + return Constants.SLOTS_NONE; + } + return super.getAccessibleSlotsFromSide(side); + } + + @Override + public final boolean canInsertItem(int slotIndex, ItemStack itemStack, int side) { + if (itemStack == null || !accessHandler.allowsPipeConnections()) { + return false; + } + return isItemValidForSlot(slotIndex, itemStack); + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack itemStack, int side) { + return itemStack != null && accessHandler.allowsPipeConnections(); + } +} diff --git a/src/main/java/forestry/core/inventory/InventoryAdapterTile.java b/src/main/java/forestry/core/inventory/InventoryAdapterTile.java index c63a62934..d4310bf65 100644 --- a/src/main/java/forestry/core/inventory/InventoryAdapterTile.java +++ b/src/main/java/forestry/core/inventory/InventoryAdapterTile.java @@ -10,32 +10,31 @@ ******************************************************************************/ package forestry.core.inventory; +import forestry.core.access.IRestrictedAccess; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import forestry.core.access.IRestrictedAccess; - public class InventoryAdapterTile extends InventoryAdapterRestricted { - protected final T tile; + protected final T tile; - public InventoryAdapterTile(T tile, int size, String name) { - this(tile, size, name, 64); - } + public InventoryAdapterTile(T tile, int size, String name) { + this(tile, size, name, 64); + } - public InventoryAdapterTile(T tile, int size, String name, int stackLimit) { - super(size, name, stackLimit, tile.getAccessHandler()); - this.tile = tile; - } + public InventoryAdapterTile(T tile, int size, String name, int stackLimit) { + super(size, name, stackLimit, tile.getAccessHandler()); + this.tile = tile; + } - @Override - public void markDirty() { - super.markDirty(); - tile.markDirty(); - } + @Override + public void markDirty() { + super.markDirty(); + tile.markDirty(); + } - @Override - public boolean canExtractItem(int slotIndex, ItemStack stack, int side) { - return false; - } + @Override + public boolean canExtractItem(int slotIndex, ItemStack stack, int side) { + return false; + } } diff --git a/src/main/java/forestry/core/inventory/InventoryAnalyzer.java b/src/main/java/forestry/core/inventory/InventoryAnalyzer.java index 44d73d33c..5b4e89937 100644 --- a/src/main/java/forestry/core/inventory/InventoryAnalyzer.java +++ b/src/main/java/forestry/core/inventory/InventoryAnalyzer.java @@ -1,65 +1,64 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.inventory; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.Fluid; - -import forestry.api.arboriculture.TreeManager; -import forestry.api.genetics.AlleleManager; -import forestry.core.fluids.FluidHelper; -import forestry.core.tiles.TileAnalyzer; -import forestry.core.utils.GeneticsUtil; -import forestry.core.utils.SlotUtil; -import forestry.plugins.PluginManager; - -public class InventoryAnalyzer extends InventoryAdapterTile { - public static final short SLOT_ANALYZE = 0; - public static final short SLOT_CAN = 1; - public static final short SLOT_INPUT_1 = 2; - public static final short SLOT_INPUT_COUNT = 6; - public static final short SLOT_OUTPUT_1 = 8; - public static final short SLOT_OUTPUT_COUNT = 4; - - public InventoryAnalyzer(TileAnalyzer analyzer) { - super(analyzer, 12, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (SlotUtil.isSlotInRange(slotIndex, SLOT_INPUT_1, SLOT_INPUT_COUNT)) { - return AlleleManager.alleleRegistry.isIndividual(itemStack) || GeneticsUtil.getGeneticEquivalent(itemStack) != null; - } else if (slotIndex == SLOT_CAN) { - Fluid fluid = FluidHelper.getFluidInContainer(itemStack); - return tile.getTankManager().accepts(fluid); - } - - return false; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack stack, int side) { - return SlotUtil.isSlotInRange(slotIndex, SLOT_OUTPUT_1, SLOT_OUTPUT_COUNT); - } - - @Override - public void setInventorySlotContents(int slotId, ItemStack itemStack) { - if (PluginManager.Module.ARBORICULTURE.isEnabled() && !TreeManager.treeRoot.isMember(itemStack)) { - ItemStack ersatz = GeneticsUtil.convertSaplingToGeneticEquivalent(itemStack); - if (ersatz != null) { - itemStack = ersatz; - } - } - - super.setInventorySlotContents(slotId, itemStack); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.inventory; + +import forestry.api.arboriculture.TreeManager; +import forestry.api.genetics.AlleleManager; +import forestry.core.fluids.FluidHelper; +import forestry.core.tiles.TileAnalyzer; +import forestry.core.utils.GeneticsUtil; +import forestry.core.utils.SlotUtil; +import forestry.plugins.PluginManager; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; + +public class InventoryAnalyzer extends InventoryAdapterTile { + public static final short SLOT_ANALYZE = 0; + public static final short SLOT_CAN = 1; + public static final short SLOT_INPUT_1 = 2; + public static final short SLOT_INPUT_COUNT = 6; + public static final short SLOT_OUTPUT_1 = 8; + public static final short SLOT_OUTPUT_COUNT = 4; + + public InventoryAnalyzer(TileAnalyzer analyzer) { + super(analyzer, 12, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (SlotUtil.isSlotInRange(slotIndex, SLOT_INPUT_1, SLOT_INPUT_COUNT)) { + return AlleleManager.alleleRegistry.isIndividual(itemStack) + || GeneticsUtil.getGeneticEquivalent(itemStack) != null; + } else if (slotIndex == SLOT_CAN) { + Fluid fluid = FluidHelper.getFluidInContainer(itemStack); + return tile.getTankManager().accepts(fluid); + } + + return false; + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack stack, int side) { + return SlotUtil.isSlotInRange(slotIndex, SLOT_OUTPUT_1, SLOT_OUTPUT_COUNT); + } + + @Override + public void setInventorySlotContents(int slotId, ItemStack itemStack) { + if (PluginManager.Module.ARBORICULTURE.isEnabled() && !TreeManager.treeRoot.isMember(itemStack)) { + ItemStack ersatz = GeneticsUtil.convertSaplingToGeneticEquivalent(itemStack); + if (ersatz != null) { + itemStack = ersatz; + } + } + + super.setInventorySlotContents(slotId, itemStack); + } +} diff --git a/src/main/java/forestry/core/inventory/InventoryEscritoire.java b/src/main/java/forestry/core/inventory/InventoryEscritoire.java index 59357c05e..428fde25c 100644 --- a/src/main/java/forestry/core/inventory/InventoryEscritoire.java +++ b/src/main/java/forestry/core/inventory/InventoryEscritoire.java @@ -1,90 +1,91 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.inventory; - -import net.minecraft.item.ItemStack; - -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IIndividual; -import forestry.core.tiles.TileEscritoire; -import forestry.core.utils.GeneticsUtil; -import forestry.core.utils.SlotUtil; - -public class InventoryEscritoire extends InventoryAdapterTile { - public static final short SLOT_ANALYZE = 0; - public static final short SLOT_RESULTS_1 = 1; - public static final short SLOTS_RESULTS_COUNT = 6; - public static final short SLOT_INPUT_1 = 7; - public static final short SLOTS_INPUT_COUNT = 5; - - public InventoryEscritoire(TileEscritoire escritoire) { - super(escritoire, 12, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex >= SLOT_INPUT_1 && slotIndex < SLOT_INPUT_1 + tile.getGame().getSampleSize(SLOTS_INPUT_COUNT)) { - ItemStack specimen = getStackInSlot(SLOT_ANALYZE); - if (specimen == null) { - return false; - } - IIndividual individual = AlleleManager.alleleRegistry.getIndividual(specimen); - return individual != null && individual.getGenome().getPrimary().getResearchSuitability(itemStack) > 0; - } - - if (slotIndex == SLOT_ANALYZE) { - return AlleleManager.alleleRegistry.isIndividual(itemStack); - } - - return false; - } - - @Override - public boolean isLocked(int slotIndex) { - if (slotIndex == SLOT_ANALYZE) { - return false; - } - - if (getStackInSlot(SLOT_ANALYZE) == null) { - return true; - } - - if (SlotUtil.isSlotInRange(slotIndex, SLOT_INPUT_1, SLOTS_INPUT_COUNT)) { - if (slotIndex >= SLOT_INPUT_1 + tile.getGame().getSampleSize(SLOTS_INPUT_COUNT)) { - return true; - } - } - - return false; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { - return SlotUtil.isSlotInRange(slotIndex, SLOT_RESULTS_1, SLOTS_RESULTS_COUNT); - } - - @Override - public void setInventorySlotContents(int slotIndex, ItemStack itemstack) { - super.setInventorySlotContents(slotIndex, itemstack); - if (tile.getWorld() == null) { - return; - } - if (slotIndex == SLOT_ANALYZE && !tile.getWorld().isRemote) { - if (!AlleleManager.alleleRegistry.isIndividual(getStackInSlot(SLOT_ANALYZE)) && getStackInSlot(SLOT_ANALYZE) != null) { - ItemStack ersatz = GeneticsUtil.convertSaplingToGeneticEquivalent(getStackInSlot(SLOT_ANALYZE)); - if (ersatz != null) { - setInventorySlotContents(SLOT_ANALYZE, ersatz); - } - } - tile.getGame().initialize(getStackInSlot(SLOT_ANALYZE)); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.inventory; + +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IIndividual; +import forestry.core.tiles.TileEscritoire; +import forestry.core.utils.GeneticsUtil; +import forestry.core.utils.SlotUtil; +import net.minecraft.item.ItemStack; + +public class InventoryEscritoire extends InventoryAdapterTile { + public static final short SLOT_ANALYZE = 0; + public static final short SLOT_RESULTS_1 = 1; + public static final short SLOTS_RESULTS_COUNT = 6; + public static final short SLOT_INPUT_1 = 7; + public static final short SLOTS_INPUT_COUNT = 5; + + public InventoryEscritoire(TileEscritoire escritoire) { + super(escritoire, 12, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex >= SLOT_INPUT_1 + && slotIndex < SLOT_INPUT_1 + tile.getGame().getSampleSize(SLOTS_INPUT_COUNT)) { + ItemStack specimen = getStackInSlot(SLOT_ANALYZE); + if (specimen == null) { + return false; + } + IIndividual individual = AlleleManager.alleleRegistry.getIndividual(specimen); + return individual != null && individual.getGenome().getPrimary().getResearchSuitability(itemStack) > 0; + } + + if (slotIndex == SLOT_ANALYZE) { + return AlleleManager.alleleRegistry.isIndividual(itemStack); + } + + return false; + } + + @Override + public boolean isLocked(int slotIndex) { + if (slotIndex == SLOT_ANALYZE) { + return false; + } + + if (getStackInSlot(SLOT_ANALYZE) == null) { + return true; + } + + if (SlotUtil.isSlotInRange(slotIndex, SLOT_INPUT_1, SLOTS_INPUT_COUNT)) { + if (slotIndex >= SLOT_INPUT_1 + tile.getGame().getSampleSize(SLOTS_INPUT_COUNT)) { + return true; + } + } + + return false; + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { + return SlotUtil.isSlotInRange(slotIndex, SLOT_RESULTS_1, SLOTS_RESULTS_COUNT); + } + + @Override + public void setInventorySlotContents(int slotIndex, ItemStack itemstack) { + super.setInventorySlotContents(slotIndex, itemstack); + if (tile.getWorld() == null) { + return; + } + if (slotIndex == SLOT_ANALYZE && !tile.getWorld().isRemote) { + if (!AlleleManager.alleleRegistry.isIndividual(getStackInSlot(SLOT_ANALYZE)) + && getStackInSlot(SLOT_ANALYZE) != null) { + ItemStack ersatz = GeneticsUtil.convertSaplingToGeneticEquivalent(getStackInSlot(SLOT_ANALYZE)); + if (ersatz != null) { + setInventorySlotContents(SLOT_ANALYZE, ersatz); + } + } + tile.getGame().initialize(getStackInSlot(SLOT_ANALYZE)); + } + } +} diff --git a/src/main/java/forestry/core/inventory/InventoryNaturalistChest.java b/src/main/java/forestry/core/inventory/InventoryNaturalistChest.java index 9f0073bb9..05e74a950 100644 --- a/src/main/java/forestry/core/inventory/InventoryNaturalistChest.java +++ b/src/main/java/forestry/core/inventory/InventoryNaturalistChest.java @@ -1,35 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.inventory; - -import net.minecraft.item.ItemStack; - -import forestry.api.genetics.ISpeciesRoot; -import forestry.core.tiles.TileNaturalistChest; - -public class InventoryNaturalistChest extends InventoryAdapterTile { - private final ISpeciesRoot speciesRoot; - - public InventoryNaturalistChest(TileNaturalistChest tile, ISpeciesRoot speciesRoot) { - super(tile, 125, "Items"); - this.speciesRoot = speciesRoot; - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemstack) { - return speciesRoot.isMember(itemstack); - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack stack, int side) { - return true; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.inventory; + +import forestry.api.genetics.ISpeciesRoot; +import forestry.core.tiles.TileNaturalistChest; +import net.minecraft.item.ItemStack; + +public class InventoryNaturalistChest extends InventoryAdapterTile { + private final ISpeciesRoot speciesRoot; + + public InventoryNaturalistChest(TileNaturalistChest tile, ISpeciesRoot speciesRoot) { + super(tile, 125, "Items"); + this.speciesRoot = speciesRoot; + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemstack) { + return speciesRoot.isMember(itemstack); + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack stack, int side) { + return true; + } +} diff --git a/src/main/java/forestry/core/inventory/InventoryPlain.java b/src/main/java/forestry/core/inventory/InventoryPlain.java index 17e7117fc..534eff40a 100644 --- a/src/main/java/forestry/core/inventory/InventoryPlain.java +++ b/src/main/java/forestry/core/inventory/InventoryPlain.java @@ -10,123 +10,119 @@ ******************************************************************************/ package forestry.core.inventory; +import forestry.api.core.INBTTagable; +import forestry.core.utils.InventoryUtil; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import forestry.api.core.INBTTagable; -import forestry.core.utils.InventoryUtil; - public class InventoryPlain implements IInventory, INBTTagable { - private final ItemStack[] contents; - private final String name; - private final int stackLimit; + private final ItemStack[] contents; + private final String name; + private final int stackLimit; - public InventoryPlain(int size, String name) { - this(size, name, 64); - } + public InventoryPlain(int size, String name) { + this(size, name, 64); + } - public InventoryPlain(int size, String name, int stackLimit) { - this.contents = new ItemStack[size]; - this.name = name; - this.stackLimit = stackLimit; - } + public InventoryPlain(int size, String name, int stackLimit) { + this.contents = new ItemStack[size]; + this.name = name; + this.stackLimit = stackLimit; + } - public InventoryPlain(IInventory tocopy) { - this(tocopy.getSizeInventory(), tocopy.getInventoryName(), tocopy.getInventoryStackLimit()); - for (int i = 0; i < tocopy.getSizeInventory(); i++) { - if (tocopy.getStackInSlot(i) != null) { - this.setInventorySlotContents(i, tocopy.getStackInSlot(i).copy()); - } else { - this.setInventorySlotContents(i, null); - } - } - } + public InventoryPlain(IInventory tocopy) { + this(tocopy.getSizeInventory(), tocopy.getInventoryName(), tocopy.getInventoryStackLimit()); + for (int i = 0; i < tocopy.getSizeInventory(); i++) { + if (tocopy.getStackInSlot(i) != null) { + this.setInventorySlotContents(i, tocopy.getStackInSlot(i).copy()); + } else { + this.setInventorySlotContents(i, null); + } + } + } - public ItemStack[] getContents() { - return contents; - } + public ItemStack[] getContents() { + return contents; + } - @Override - public int getSizeInventory() { - return contents.length; - } + @Override + public int getSizeInventory() { + return contents.length; + } - @Override - public ItemStack getStackInSlot(int slotId) { - return contents[slotId]; - } + @Override + public ItemStack getStackInSlot(int slotId) { + return contents[slotId]; + } - @Override - public ItemStack decrStackSize(int slotId, int count) { - if (contents[slotId] == null) { - return null; - } - if (contents[slotId].stackSize > count) { - return contents[slotId].splitStack(count); - } - ItemStack stack = contents[slotId]; - contents[slotId] = null; - return stack; - } + @Override + public ItemStack decrStackSize(int slotId, int count) { + if (contents[slotId] == null) { + return null; + } + if (contents[slotId].stackSize > count) { + return contents[slotId].splitStack(count); + } + ItemStack stack = contents[slotId]; + contents[slotId] = null; + return stack; + } - @Override - public void setInventorySlotContents(int slotId, ItemStack itemstack) { - contents[slotId] = itemstack; - } + @Override + public void setInventorySlotContents(int slotId, ItemStack itemstack) { + contents[slotId] = itemstack; + } - @Override - public String getInventoryName() { - return name; - } + @Override + public String getInventoryName() { + return name; + } - @Override - public int getInventoryStackLimit() { - return stackLimit; - } + @Override + public int getInventoryStackLimit() { + return stackLimit; + } - @Override - public void markDirty() { - } + @Override + public void markDirty() {} - @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return false; - } + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return false; + } - @Override - public ItemStack getStackInSlotOnClosing(int slotIndex) { - return this.getStackInSlot(slotIndex); - } + @Override + public ItemStack getStackInSlotOnClosing(int slotIndex) { + return this.getStackInSlot(slotIndex); + } - @Override - public boolean hasCustomInventoryName() { - return true; - } + @Override + public boolean hasCustomInventoryName() { + return true; + } - @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) { - return true; - } + @Override + public boolean isItemValidForSlot(int i, ItemStack itemstack) { + return true; + } - @Override - public void openInventory() { - } + @Override + public void openInventory() {} - @Override - public void closeInventory() { - } + @Override + public void closeInventory() {} - /* INBTagable */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - InventoryUtil.readFromNBT(this, nbttagcompound); - } + /* INBTagable */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + InventoryUtil.readFromNBT(this, nbttagcompound); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - InventoryUtil.writeToNBT(this, nbttagcompound); - } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + InventoryUtil.writeToNBT(this, nbttagcompound); + } } diff --git a/src/main/java/forestry/core/inventory/ItemInventory.java b/src/main/java/forestry/core/inventory/ItemInventory.java index 6ab14c64c..bfb211133 100755 --- a/src/main/java/forestry/core/inventory/ItemInventory.java +++ b/src/main/java/forestry/core/inventory/ItemInventory.java @@ -10,296 +10,291 @@ ******************************************************************************/ package forestry.core.inventory; +import forestry.core.tiles.IFilterSlotDelegate; import java.util.Random; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import forestry.core.tiles.IFilterSlotDelegate; - public abstract class ItemInventory implements IInventory, IFilterSlotDelegate { - private static final String KEY_ITEMS = "Items"; // legacy - private static final String KEY_SLOTS = "Slots"; - private static final String KEY_UID = "UID"; - private static final Random rand = new Random(); + private static final String KEY_ITEMS = "Items"; // legacy + private static final String KEY_SLOTS = "Slots"; + private static final String KEY_UID = "UID"; + private static final Random rand = new Random(); - private final EntityPlayer player; - private final ItemStack parent; - private final ItemStack[] inventoryStacks; + private final EntityPlayer player; + private final ItemStack parent; + private final ItemStack[] inventoryStacks; - public ItemInventory(EntityPlayer player, int size, ItemStack parent) { - this.player = player; - this.parent = parent; - this.inventoryStacks = new ItemStack[size]; + public ItemInventory(EntityPlayer player, int size, ItemStack parent) { + this.player = player; + this.parent = parent; + this.inventoryStacks = new ItemStack[size]; - setUID(); // Set a uid to identify the itemstack on SMP + setUID(); // Set a uid to identify the itemstack on SMP - readFromNBT(parent.getTagCompound()); - } + readFromNBT(parent.getTagCompound()); + } - public static int getOccupiedSlotCount(ItemStack itemStack) { - NBTTagCompound nbt = itemStack.getTagCompound(); - if (nbt == null) { - return 0; - } + public static int getOccupiedSlotCount(ItemStack itemStack) { + NBTTagCompound nbt = itemStack.getTagCompound(); + if (nbt == null) { + return 0; + } - if (nbt.hasKey(KEY_SLOTS)) { - NBTTagCompound slotNbt = nbt.getCompoundTag(KEY_SLOTS); - return slotNbt.func_150296_c().size(); - } + if (nbt.hasKey(KEY_SLOTS)) { + NBTTagCompound slotNbt = nbt.getCompoundTag(KEY_SLOTS); + return slotNbt.func_150296_c().size(); + } - int count = 0; - if (nbt.hasKey(KEY_ITEMS)) { // legacy since Forestry 3.6 - NBTTagList nbttaglist = nbt.getTagList(KEY_ITEMS, 10); - for (int i = 0; i < nbttaglist.tagCount(); i++) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - ItemStack itemStack1 = ItemStack.loadItemStackFromNBT(nbttagcompound1); - if (itemStack1 != null && itemStack1.stackSize > 0) { - count++; - } - } - } + int count = 0; + if (nbt.hasKey(KEY_ITEMS)) { // legacy since Forestry 3.6 + NBTTagList nbttaglist = nbt.getTagList(KEY_ITEMS, 10); + for (int i = 0; i < nbttaglist.tagCount(); i++) { + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + ItemStack itemStack1 = ItemStack.loadItemStackFromNBT(nbttagcompound1); + if (itemStack1 != null && itemStack1.stackSize > 0) { + count++; + } + } + } - return count; - } + return count; + } - private void setUID() { - ItemStack parent = getParent(); + private void setUID() { + ItemStack parent = getParent(); - if (parent.getTagCompound() == null) { - parent.setTagCompound(new NBTTagCompound()); - } + if (parent.getTagCompound() == null) { + parent.setTagCompound(new NBTTagCompound()); + } - NBTTagCompound nbt = parent.getTagCompound(); - if (!nbt.hasKey(KEY_UID)) { - nbt.setInteger(KEY_UID, rand.nextInt()); - } - } + NBTTagCompound nbt = parent.getTagCompound(); + if (!nbt.hasKey(KEY_UID)) { + nbt.setInteger(KEY_UID, rand.nextInt()); + } + } - public boolean isParentItemInventory(ItemStack itemStack) { - ItemStack parent = getParent(); - return isSameItemInventory(parent, itemStack); - } + public boolean isParentItemInventory(ItemStack itemStack) { + ItemStack parent = getParent(); + return isSameItemInventory(parent, itemStack); + } - protected ItemStack getParent() { - ItemStack equipped = player.getCurrentEquippedItem(); - if (isSameItemInventory(equipped, parent)) { - return equipped; - } - return parent; - } + protected ItemStack getParent() { + ItemStack equipped = player.getCurrentEquippedItem(); + if (isSameItemInventory(equipped, parent)) { + return equipped; + } + return parent; + } - private static boolean isSameItemInventory(ItemStack base, ItemStack comparison) { - if (base == null || comparison == null) { - return false; - } + private static boolean isSameItemInventory(ItemStack base, ItemStack comparison) { + if (base == null || comparison == null) { + return false; + } - if (base.getItem() != comparison.getItem()) { - return false; - } + if (base.getItem() != comparison.getItem()) { + return false; + } - if (!base.hasTagCompound() || !comparison.hasTagCompound()) { - return false; - } + if (!base.hasTagCompound() || !comparison.hasTagCompound()) { + return false; + } - String baseUID = base.getTagCompound().getString(KEY_UID); - String comparisonUID = comparison.getTagCompound().getString(KEY_UID); - return baseUID != null && comparisonUID != null && baseUID.equals(comparisonUID); - } + String baseUID = base.getTagCompound().getString(KEY_UID); + String comparisonUID = comparison.getTagCompound().getString(KEY_UID); + return baseUID != null && comparisonUID != null && baseUID.equals(comparisonUID); + } - public void readFromNBT(NBTTagCompound nbt) { + public void readFromNBT(NBTTagCompound nbt) { - if (nbt == null) { - return; - } + if (nbt == null) { + return; + } - if (nbt.hasKey(KEY_SLOTS)) { - NBTTagCompound nbtSlots = nbt.getCompoundTag(KEY_SLOTS); - for (int i = 0; i < inventoryStacks.length; i++) { - String slotKey = getSlotNBTKey(i); - if (nbtSlots.hasKey(slotKey)) { - NBTTagCompound itemNbt = nbtSlots.getCompoundTag(slotKey); - ItemStack itemStack = ItemStack.loadItemStackFromNBT(itemNbt); - inventoryStacks[i] = itemStack; - } else { - inventoryStacks[i] = null; - } - } - } else { + if (nbt.hasKey(KEY_SLOTS)) { + NBTTagCompound nbtSlots = nbt.getCompoundTag(KEY_SLOTS); + for (int i = 0; i < inventoryStacks.length; i++) { + String slotKey = getSlotNBTKey(i); + if (nbtSlots.hasKey(slotKey)) { + NBTTagCompound itemNbt = nbtSlots.getCompoundTag(slotKey); + ItemStack itemStack = ItemStack.loadItemStackFromNBT(itemNbt); + inventoryStacks[i] = itemStack; + } else { + inventoryStacks[i] = null; + } + } + } else { - // legacy since Forestry 3.6 - if (nbt.hasKey(KEY_ITEMS)) { - for (int i = 0; i < inventoryStacks.length; i++) { - inventoryStacks[i] = null; - } + // legacy since Forestry 3.6 + if (nbt.hasKey(KEY_ITEMS)) { + for (int i = 0; i < inventoryStacks.length; i++) { + inventoryStacks[i] = null; + } - NBTTagList nbttaglist = nbt.getTagList(KEY_ITEMS, 10); - for (int i = 0; i < nbttaglist.tagCount(); i++) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - byte byte0 = nbttagcompound1.getByte("Slot"); - if (byte0 >= 0 && byte0 < inventoryStacks.length) { - ItemStack itemStack = ItemStack.loadItemStackFromNBT(nbttagcompound1); - inventoryStacks[byte0] = itemStack; - } - } + NBTTagList nbttaglist = nbt.getTagList(KEY_ITEMS, 10); + for (int i = 0; i < nbttaglist.tagCount(); i++) { + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + byte byte0 = nbttagcompound1.getByte("Slot"); + if (byte0 >= 0 && byte0 < inventoryStacks.length) { + ItemStack itemStack = ItemStack.loadItemStackFromNBT(nbttagcompound1); + inventoryStacks[byte0] = itemStack; + } + } - writeToParentNBT(); - } - } - } + writeToParentNBT(); + } + } + } - private void writeToParentNBT() { - ItemStack parent = getParent(); - if (parent == null) { - return; - } + private void writeToParentNBT() { + ItemStack parent = getParent(); + if (parent == null) { + return; + } - NBTTagCompound nbt = parent.getTagCompound(); - NBTTagCompound slotsNbt = new NBTTagCompound(); - for (int i = 0; i < getSizeInventory(); i++) { - ItemStack itemStack = getStackInSlot(i); - if (itemStack != null) { - String slotKey = getSlotNBTKey(i); - NBTTagCompound itemNbt = new NBTTagCompound(); - itemStack.writeToNBT(itemNbt); - slotsNbt.setTag(slotKey, itemNbt); - } - } + NBTTagCompound nbt = parent.getTagCompound(); + NBTTagCompound slotsNbt = new NBTTagCompound(); + for (int i = 0; i < getSizeInventory(); i++) { + ItemStack itemStack = getStackInSlot(i); + if (itemStack != null) { + String slotKey = getSlotNBTKey(i); + NBTTagCompound itemNbt = new NBTTagCompound(); + itemStack.writeToNBT(itemNbt); + slotsNbt.setTag(slotKey, itemNbt); + } + } - nbt.setTag(KEY_SLOTS, slotsNbt); - nbt.removeTag(KEY_ITEMS); - } + nbt.setTag(KEY_SLOTS, slotsNbt); + nbt.removeTag(KEY_ITEMS); + } - private static String getSlotNBTKey(int i) { - return Integer.toString(i, Character.MAX_RADIX); - } + private static String getSlotNBTKey(int i) { + return Integer.toString(i, Character.MAX_RADIX); + } - public void onSlotClick(EntityPlayer player) { - } + public void onSlotClick(EntityPlayer player) {} - @Override - public ItemStack decrStackSize(int i, int j) { - ItemStack stack = getStackInSlot(i); - if (stack == null) { - return null; - } + @Override + public ItemStack decrStackSize(int i, int j) { + ItemStack stack = getStackInSlot(i); + if (stack == null) { + return null; + } - if (stack.stackSize <= j) { - setInventorySlotContents(i, null); - return stack; - } else { - ItemStack product = stack.splitStack(j); - setInventorySlotContents(i, stack); - return product; - } - } + if (stack.stackSize <= j) { + setInventorySlotContents(i, null); + return stack; + } else { + ItemStack product = stack.splitStack(j); + setInventorySlotContents(i, stack); + return product; + } + } - @Override - public void setInventorySlotContents(int i, ItemStack itemstack) { - if (itemstack != null && itemstack.stackSize == 0) { - itemstack = null; - } + @Override + public void setInventorySlotContents(int i, ItemStack itemstack) { + if (itemstack != null && itemstack.stackSize == 0) { + itemstack = null; + } - inventoryStacks[i] = itemstack; + inventoryStacks[i] = itemstack; - ItemStack parent = getParent(); + ItemStack parent = getParent(); - NBTTagCompound nbt = parent.getTagCompound(); - if (nbt == null) { - nbt = new NBTTagCompound(); - parent.setTagCompound(nbt); - } + NBTTagCompound nbt = parent.getTagCompound(); + if (nbt == null) { + nbt = new NBTTagCompound(); + parent.setTagCompound(nbt); + } - NBTTagCompound slotNbt; - if (!nbt.hasKey(KEY_SLOTS)) { - slotNbt = new NBTTagCompound(); - nbt.setTag(KEY_SLOTS, slotNbt); - } else { - slotNbt = nbt.getCompoundTag(KEY_SLOTS); - } + NBTTagCompound slotNbt; + if (!nbt.hasKey(KEY_SLOTS)) { + slotNbt = new NBTTagCompound(); + nbt.setTag(KEY_SLOTS, slotNbt); + } else { + slotNbt = nbt.getCompoundTag(KEY_SLOTS); + } - String slotKey = getSlotNBTKey(i); + String slotKey = getSlotNBTKey(i); - if (itemstack == null) { - slotNbt.removeTag(slotKey); - } else { - NBTTagCompound itemNbt = new NBTTagCompound(); - itemstack.writeToNBT(itemNbt); + if (itemstack == null) { + slotNbt.removeTag(slotKey); + } else { + NBTTagCompound itemNbt = new NBTTagCompound(); + itemstack.writeToNBT(itemNbt); - slotNbt.setTag(slotKey, itemNbt); - } - } + slotNbt.setTag(slotKey, itemNbt); + } + } - @Override - public ItemStack getStackInSlot(int i) { - return inventoryStacks[i]; - } + @Override + public ItemStack getStackInSlot(int i) { + return inventoryStacks[i]; + } - @Override - public int getSizeInventory() { - return inventoryStacks.length; - } + @Override + public int getSizeInventory() { + return inventoryStacks.length; + } - @Override - public String getInventoryName() { - return "BeeBag"; - } + @Override + public String getInventoryName() { + return "BeeBag"; + } - @Override - public int getInventoryStackLimit() { - return 64; - } + @Override + public int getInventoryStackLimit() { + return 64; + } - @Override - public final void markDirty() { - writeToParentNBT(); - } + @Override + public final void markDirty() { + writeToParentNBT(); + } - @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return true; - } + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return true; + } - @Override - public boolean hasCustomInventoryName() { - return true; - } + @Override + public boolean hasCustomInventoryName() { + return true; + } - @Override - public boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { - return canSlotAccept(slotIndex, itemStack); - } + @Override + public boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { + return canSlotAccept(slotIndex, itemStack); + } - @Override - public void openInventory() { - } + @Override + public void openInventory() {} - @Override - public void closeInventory() { - } + @Override + public void closeInventory() {} - @Override - public ItemStack getStackInSlotOnClosing(int slot) { - ItemStack toReturn = getStackInSlot(slot); + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + ItemStack toReturn = getStackInSlot(slot); - if (toReturn != null) { - setInventorySlotContents(slot, null); - } + if (toReturn != null) { + setInventorySlotContents(slot, null); + } - return toReturn; - } + return toReturn; + } - /* IFilterSlotDelegate */ - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return true; - } + /* IFilterSlotDelegate */ + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return true; + } - @Override - public boolean isLocked(int slotIndex) { - return false; - } + @Override + public boolean isLocked(int slotIndex) { + return false; + } } diff --git a/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java b/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java index 8759c5458..15406df4c 100644 --- a/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java +++ b/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java @@ -1,154 +1,153 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.inventory; - -import com.google.common.collect.ImmutableSet; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import forestry.api.core.IErrorSource; -import forestry.api.core.IErrorState; -import forestry.api.genetics.IBreedingTracker; -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.ISpeciesRoot; -import forestry.apiculture.items.ItemRegistryApiculture; -import forestry.core.errors.EnumErrorCode; -import forestry.plugins.PluginApiculture; -import forestry.plugins.PluginManager; - -public abstract class ItemInventoryAlyzer extends ItemInventory implements IErrorSource { - public static final int SLOT_SPECIMEN = 0; - public static final int SLOT_ANALYZE_1 = 1; - public static final int SLOT_ANALYZE_2 = 2; - public static final int SLOT_ANALYZE_3 = 3; - public static final int SLOT_ANALYZE_4 = 4; - public static final int SLOT_ANALYZE_5 = 6; - public static final int SLOT_ENERGY = 5; - - private final ISpeciesRoot speciesRoot; - - public ItemInventoryAlyzer(ISpeciesRoot speciesRoot, EntityPlayer player, ItemStack itemstack) { - super(player, 7, itemstack); - this.speciesRoot = speciesRoot; - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_ENERGY) { - return isEnergy(itemStack); - } - - if (!speciesRoot.isMember(itemStack)) { - return false; - } - - // only allow one slot to be used at a time - if (hasSpecimen() && getStackInSlot(slotIndex) == null) { - return false; - } - - if (slotIndex == SLOT_SPECIMEN) { - return true; - } - - IIndividual individual = speciesRoot.getMember(itemStack); - return individual.isAnalyzed(); - } - - @Override - public void onSlotClick(EntityPlayer player) { - // Source slot to analyze empty - ItemStack specimen = getStackInSlot(SLOT_SPECIMEN); - if (specimen == null) { - return; - } - - IIndividual individual = speciesRoot.getMember(specimen); - // No individual, abort - if (individual == null) { - return; - } - - // Analyze if necessary - if (!individual.isAnalyzed()) { - - if (PluginManager.Module.APICULTURE.isEnabled()) { - // Requires energy - if (!isEnergy(getStackInSlot(SLOT_ENERGY))) { - return; - } - } - - individual.analyze(); - if (player != null) { - IBreedingTracker breedingTracker = speciesRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); - breedingTracker.registerSpecies(individual.getGenome().getPrimary()); - breedingTracker.registerSpecies(individual.getGenome().getSecondary()); - } - - NBTTagCompound nbttagcompound = new NBTTagCompound(); - individual.writeToNBT(nbttagcompound); - specimen.setTagCompound(nbttagcompound); - - // Decrease energy - decrStackSize(SLOT_ENERGY, 1); - } - - setInventorySlotContents(SLOT_ANALYZE_1, specimen); - setInventorySlotContents(SLOT_SPECIMEN, null); - } - - @Override - public final ImmutableSet getErrorStates() { - ImmutableSet.Builder errorStates = ImmutableSet.builder(); - - if (!hasSpecimen()) { - errorStates.add(EnumErrorCode.NO_SPECIMEN); - } - - if (!isEnergy(getStackInSlot(SLOT_ENERGY))) { - errorStates.add(EnumErrorCode.NO_HONEY); - } - - return errorStates.build(); - } - - private static boolean isEnergy(ItemStack itemstack) { - if (itemstack == null || itemstack.stackSize <= 0) { - return false; - } - - ItemRegistryApiculture beeItems = PluginApiculture.items; - if (beeItems == null) { - return false; - } - - Item item = itemstack.getItem(); - return beeItems.honeyDrop == item || beeItems.honeydew == item; - } - - private boolean hasSpecimen() { - for (int i = SLOT_SPECIMEN; i <= SLOT_ANALYZE_5; i++) { - if (i == SLOT_ENERGY) { - continue; - } - - ItemStack itemStack = getStackInSlot(i); - if (itemStack != null) { - return true; - } - } - return false; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.inventory; + +import com.google.common.collect.ImmutableSet; +import forestry.api.core.IErrorSource; +import forestry.api.core.IErrorState; +import forestry.api.genetics.IBreedingTracker; +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.ISpeciesRoot; +import forestry.apiculture.items.ItemRegistryApiculture; +import forestry.core.errors.EnumErrorCode; +import forestry.plugins.PluginApiculture; +import forestry.plugins.PluginManager; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +public abstract class ItemInventoryAlyzer extends ItemInventory implements IErrorSource { + public static final int SLOT_SPECIMEN = 0; + public static final int SLOT_ANALYZE_1 = 1; + public static final int SLOT_ANALYZE_2 = 2; + public static final int SLOT_ANALYZE_3 = 3; + public static final int SLOT_ANALYZE_4 = 4; + public static final int SLOT_ANALYZE_5 = 6; + public static final int SLOT_ENERGY = 5; + + private final ISpeciesRoot speciesRoot; + + public ItemInventoryAlyzer(ISpeciesRoot speciesRoot, EntityPlayer player, ItemStack itemstack) { + super(player, 7, itemstack); + this.speciesRoot = speciesRoot; + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_ENERGY) { + return isEnergy(itemStack); + } + + if (!speciesRoot.isMember(itemStack)) { + return false; + } + + // only allow one slot to be used at a time + if (hasSpecimen() && getStackInSlot(slotIndex) == null) { + return false; + } + + if (slotIndex == SLOT_SPECIMEN) { + return true; + } + + IIndividual individual = speciesRoot.getMember(itemStack); + return individual.isAnalyzed(); + } + + @Override + public void onSlotClick(EntityPlayer player) { + // Source slot to analyze empty + ItemStack specimen = getStackInSlot(SLOT_SPECIMEN); + if (specimen == null) { + return; + } + + IIndividual individual = speciesRoot.getMember(specimen); + // No individual, abort + if (individual == null) { + return; + } + + // Analyze if necessary + if (!individual.isAnalyzed()) { + + if (PluginManager.Module.APICULTURE.isEnabled()) { + // Requires energy + if (!isEnergy(getStackInSlot(SLOT_ENERGY))) { + return; + } + } + + individual.analyze(); + if (player != null) { + IBreedingTracker breedingTracker = + speciesRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); + breedingTracker.registerSpecies(individual.getGenome().getPrimary()); + breedingTracker.registerSpecies(individual.getGenome().getSecondary()); + } + + NBTTagCompound nbttagcompound = new NBTTagCompound(); + individual.writeToNBT(nbttagcompound); + specimen.setTagCompound(nbttagcompound); + + // Decrease energy + decrStackSize(SLOT_ENERGY, 1); + } + + setInventorySlotContents(SLOT_ANALYZE_1, specimen); + setInventorySlotContents(SLOT_SPECIMEN, null); + } + + @Override + public final ImmutableSet getErrorStates() { + ImmutableSet.Builder errorStates = ImmutableSet.builder(); + + if (!hasSpecimen()) { + errorStates.add(EnumErrorCode.NO_SPECIMEN); + } + + if (!isEnergy(getStackInSlot(SLOT_ENERGY))) { + errorStates.add(EnumErrorCode.NO_HONEY); + } + + return errorStates.build(); + } + + private static boolean isEnergy(ItemStack itemstack) { + if (itemstack == null || itemstack.stackSize <= 0) { + return false; + } + + ItemRegistryApiculture beeItems = PluginApiculture.items; + if (beeItems == null) { + return false; + } + + Item item = itemstack.getItem(); + return beeItems.honeyDrop == item || beeItems.honeydew == item; + } + + private boolean hasSpecimen() { + for (int i = SLOT_SPECIMEN; i <= SLOT_ANALYZE_5; i++) { + if (i == SLOT_ENERGY) { + continue; + } + + ItemStack itemStack = getStackInSlot(i); + if (itemStack != null) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/forestry/core/inventory/ItemInventorySolderingIron.java b/src/main/java/forestry/core/inventory/ItemInventorySolderingIron.java index f5c498e5a..21fe7674e 100644 --- a/src/main/java/forestry/core/inventory/ItemInventorySolderingIron.java +++ b/src/main/java/forestry/core/inventory/ItemInventorySolderingIron.java @@ -1,218 +1,216 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.inventory; - -import com.google.common.collect.ImmutableSet; - -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import forestry.api.circuits.ChipsetManager; -import forestry.api.circuits.ICircuit; -import forestry.api.circuits.ICircuitLayout; -import forestry.api.core.IErrorSource; -import forestry.api.core.IErrorState; -import forestry.core.circuits.CircuitRecipe; -import forestry.core.circuits.CircuitRegistry; -import forestry.core.circuits.EnumCircuitBoardType; -import forestry.core.circuits.ItemCircuitBoard; -import forestry.core.circuits.SolderManager; -import forestry.core.config.Config; -import forestry.core.errors.EnumErrorCode; -import forestry.core.gui.IHintSource; -import forestry.core.utils.datastructures.RevolvingList; - -public class ItemInventorySolderingIron extends ItemInventory implements IErrorSource, IHintSource { - - private final RevolvingList layouts = new RevolvingList<>(ChipsetManager.circuitRegistry.getRegisteredLayouts().values()); - - private static final short blankSlot = 0; - private static final short finishedSlot = 1; - private static final short ingredientSlot1 = 2; - private static final short ingredientSlotCount = 4; - - public ItemInventorySolderingIron(EntityPlayer player, ItemStack itemStack) { - super(player, 6, itemStack); - - layouts.setCurrent(ChipsetManager.circuitRegistry.getDefaultLayout()); - } - - @Override - public int getInventoryStackLimit() { - return 1; - } - - public ICircuitLayout getLayout() { - return layouts.getCurrent(); - } - - public void setLayout(String uid) { - layouts.setCurrent(ChipsetManager.circuitRegistry.getLayout(uid)); - } - - public void advanceLayout() { - layouts.rotateRight(); - } - - public void regressLayout() { - layouts.rotateLeft(); - } - - private ICircuit[] getCircuits(boolean doConsume) { - - ICircuit[] circuits = new ICircuit[ingredientSlotCount]; - - for (short i = 0; i < ingredientSlotCount; i++) { - ItemStack ingredient = getStackInSlot(ingredientSlot1 + i); - if (ingredient == null) { - continue; - } - - CircuitRecipe recipe = SolderManager.getMatchingRecipe(layouts.getCurrent(), ingredient); - if (recipe == null) { - continue; - } - - // / Make sure we don't exceed this circuits limit per chipset - if (getCount(recipe.getCircuit(), circuits) >= recipe.getCircuit().getLimit()) { - continue; - } - - if (doConsume) { - decrStackSize(ingredientSlot1 + i, recipe.getResource().stackSize); - } - circuits[i] = recipe.getCircuit(); - } - - return circuits; - } - - @Override - public void onSlotClick(EntityPlayer player) { - if (layouts.getCurrent() == CircuitRegistry.DUMMY_LAYOUT) { - return; - } - - ItemStack blank = getStackInSlot(blankSlot); - // Requires blank slot - if (blank == null) { - return; - } - if (blank.stackSize > 1) { - return; - } - if (getStackInSlot(finishedSlot) != null) { - return; - } - - // Need a chipset item - if (!ChipsetManager.circuitRegistry.isChipset(blank)) { - return; - } - - // Illegal type - if (blank.getItemDamage() < 0 || blank.getItemDamage() >= EnumCircuitBoardType.values().length) { - return; - } - - EnumCircuitBoardType type = EnumCircuitBoardType.values()[blank.getItemDamage()]; - if (getCircuitCount() != type.getSockets()) { - return; - } - - ICircuit[] circuits = getCircuits(true); - - ItemStack circuitBoard = ItemCircuitBoard.createCircuitboard(type, layouts.getCurrent(), circuits); - - setInventorySlotContents(finishedSlot, circuitBoard); - setInventorySlotContents(blankSlot, null); - } - - private int getCircuitCount() { - ICircuit[] circuits = getCircuits(false); - int count = 0; - for (ICircuit circuit : circuits) { - if (circuit != null) { - count++; - } - } - return count; - } - - public static int getCount(ICircuit circuit, ICircuit[] circuits) { - int count = 0; - for (ICircuit other : circuits) { - if (other != null && other.getUID().equals(circuit.getUID())) { - count++; - } - } - return count; - } - - @Override - public ImmutableSet getErrorStates() { - ImmutableSet.Builder errorStates = ImmutableSet.builder(); - - if (layouts.getCurrent() == CircuitRegistry.DUMMY_LAYOUT) { - errorStates.add(EnumErrorCode.NO_CIRCUIT_LAYOUT); - } - - ItemStack blankCircuitBoard = getStackInSlot(blankSlot); - - if (blankCircuitBoard == null) { - errorStates.add(EnumErrorCode.NO_CIRCUIT_BOARD); - } else { - EnumCircuitBoardType type = EnumCircuitBoardType.values()[blankCircuitBoard.getItemDamage()]; - - int circuitCount = 0; - for (short i = 0; i < type.getSockets(); i++) { - if (getStackInSlot(ingredientSlot1 + i) != null) { - circuitCount++; - } - } - - if (circuitCount != type.getSockets()) { - errorStates.add(EnumErrorCode.CIRCUIT_MISMATCH); - } else { - int count = getCircuitCount(); - if (count != type.getSockets()) { - errorStates.add(EnumErrorCode.NO_CIRCUIT_LAYOUT); - } - } - } - - return errorStates.build(); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (itemStack == null) { - return false; - } - - Item item = itemStack.getItem(); - if (slotIndex == blankSlot) { - return item instanceof ItemCircuitBoard; - } else if (slotIndex >= ingredientSlot1 && slotIndex < ingredientSlot1 + ingredientSlotCount) { - CircuitRecipe recipe = SolderManager.getMatchingRecipe(layouts.getCurrent(), itemStack); - return recipe != null; - } - return false; - } - - @Override - public List getHints() { - return Config.hints.get("soldering.iron"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.inventory; + +import com.google.common.collect.ImmutableSet; +import forestry.api.circuits.ChipsetManager; +import forestry.api.circuits.ICircuit; +import forestry.api.circuits.ICircuitLayout; +import forestry.api.core.IErrorSource; +import forestry.api.core.IErrorState; +import forestry.core.circuits.CircuitRecipe; +import forestry.core.circuits.CircuitRegistry; +import forestry.core.circuits.EnumCircuitBoardType; +import forestry.core.circuits.ItemCircuitBoard; +import forestry.core.circuits.SolderManager; +import forestry.core.config.Config; +import forestry.core.errors.EnumErrorCode; +import forestry.core.gui.IHintSource; +import forestry.core.utils.datastructures.RevolvingList; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +public class ItemInventorySolderingIron extends ItemInventory implements IErrorSource, IHintSource { + + private final RevolvingList layouts = new RevolvingList<>( + ChipsetManager.circuitRegistry.getRegisteredLayouts().values()); + + private static final short blankSlot = 0; + private static final short finishedSlot = 1; + private static final short ingredientSlot1 = 2; + private static final short ingredientSlotCount = 4; + + public ItemInventorySolderingIron(EntityPlayer player, ItemStack itemStack) { + super(player, 6, itemStack); + + layouts.setCurrent(ChipsetManager.circuitRegistry.getDefaultLayout()); + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + public ICircuitLayout getLayout() { + return layouts.getCurrent(); + } + + public void setLayout(String uid) { + layouts.setCurrent(ChipsetManager.circuitRegistry.getLayout(uid)); + } + + public void advanceLayout() { + layouts.rotateRight(); + } + + public void regressLayout() { + layouts.rotateLeft(); + } + + private ICircuit[] getCircuits(boolean doConsume) { + + ICircuit[] circuits = new ICircuit[ingredientSlotCount]; + + for (short i = 0; i < ingredientSlotCount; i++) { + ItemStack ingredient = getStackInSlot(ingredientSlot1 + i); + if (ingredient == null) { + continue; + } + + CircuitRecipe recipe = SolderManager.getMatchingRecipe(layouts.getCurrent(), ingredient); + if (recipe == null) { + continue; + } + + // / Make sure we don't exceed this circuits limit per chipset + if (getCount(recipe.getCircuit(), circuits) >= recipe.getCircuit().getLimit()) { + continue; + } + + if (doConsume) { + decrStackSize(ingredientSlot1 + i, recipe.getResource().stackSize); + } + circuits[i] = recipe.getCircuit(); + } + + return circuits; + } + + @Override + public void onSlotClick(EntityPlayer player) { + if (layouts.getCurrent() == CircuitRegistry.DUMMY_LAYOUT) { + return; + } + + ItemStack blank = getStackInSlot(blankSlot); + // Requires blank slot + if (blank == null) { + return; + } + if (blank.stackSize > 1) { + return; + } + if (getStackInSlot(finishedSlot) != null) { + return; + } + + // Need a chipset item + if (!ChipsetManager.circuitRegistry.isChipset(blank)) { + return; + } + + // Illegal type + if (blank.getItemDamage() < 0 || blank.getItemDamage() >= EnumCircuitBoardType.values().length) { + return; + } + + EnumCircuitBoardType type = EnumCircuitBoardType.values()[blank.getItemDamage()]; + if (getCircuitCount() != type.getSockets()) { + return; + } + + ICircuit[] circuits = getCircuits(true); + + ItemStack circuitBoard = ItemCircuitBoard.createCircuitboard(type, layouts.getCurrent(), circuits); + + setInventorySlotContents(finishedSlot, circuitBoard); + setInventorySlotContents(blankSlot, null); + } + + private int getCircuitCount() { + ICircuit[] circuits = getCircuits(false); + int count = 0; + for (ICircuit circuit : circuits) { + if (circuit != null) { + count++; + } + } + return count; + } + + public static int getCount(ICircuit circuit, ICircuit[] circuits) { + int count = 0; + for (ICircuit other : circuits) { + if (other != null && other.getUID().equals(circuit.getUID())) { + count++; + } + } + return count; + } + + @Override + public ImmutableSet getErrorStates() { + ImmutableSet.Builder errorStates = ImmutableSet.builder(); + + if (layouts.getCurrent() == CircuitRegistry.DUMMY_LAYOUT) { + errorStates.add(EnumErrorCode.NO_CIRCUIT_LAYOUT); + } + + ItemStack blankCircuitBoard = getStackInSlot(blankSlot); + + if (blankCircuitBoard == null) { + errorStates.add(EnumErrorCode.NO_CIRCUIT_BOARD); + } else { + EnumCircuitBoardType type = EnumCircuitBoardType.values()[blankCircuitBoard.getItemDamage()]; + + int circuitCount = 0; + for (short i = 0; i < type.getSockets(); i++) { + if (getStackInSlot(ingredientSlot1 + i) != null) { + circuitCount++; + } + } + + if (circuitCount != type.getSockets()) { + errorStates.add(EnumErrorCode.CIRCUIT_MISMATCH); + } else { + int count = getCircuitCount(); + if (count != type.getSockets()) { + errorStates.add(EnumErrorCode.NO_CIRCUIT_LAYOUT); + } + } + } + + return errorStates.build(); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (itemStack == null) { + return false; + } + + Item item = itemStack.getItem(); + if (slotIndex == blankSlot) { + return item instanceof ItemCircuitBoard; + } else if (slotIndex >= ingredientSlot1 && slotIndex < ingredientSlot1 + ingredientSlotCount) { + CircuitRecipe recipe = SolderManager.getMatchingRecipe(layouts.getCurrent(), itemStack); + return recipe != null; + } + return false; + } + + @Override + public List getHints() { + return Config.hints.get("soldering.iron"); + } +} diff --git a/src/main/java/forestry/core/inventory/filters/ArrayStackFilter.java b/src/main/java/forestry/core/inventory/filters/ArrayStackFilter.java index c218fb093..2d195ac78 100755 --- a/src/main/java/forestry/core/inventory/filters/ArrayStackFilter.java +++ b/src/main/java/forestry/core/inventory/filters/ArrayStackFilter.java @@ -10,39 +10,38 @@ ******************************************************************************/ package forestry.core.inventory.filters; -import net.minecraft.item.ItemStack; - import forestry.core.utils.InventoryUtil; +import net.minecraft.item.ItemStack; /** * @author CovertJaguar */ public class ArrayStackFilter implements IStackFilter { - private final ItemStack[] stacks; + private final ItemStack[] stacks; - public ArrayStackFilter(ItemStack... stacks) { - this.stacks = stacks; - } + public ArrayStackFilter(ItemStack... stacks) { + this.stacks = stacks; + } - @Override - public boolean matches(ItemStack stack) { - if (stacks.length == 0 || !hasFilter()) { - return true; - } - return InventoryUtil.isItemEqual(stack, stacks); - } + @Override + public boolean matches(ItemStack stack) { + if (stacks.length == 0 || !hasFilter()) { + return true; + } + return InventoryUtil.isItemEqual(stack, stacks); + } - public ItemStack[] getStacks() { - return stacks; - } + public ItemStack[] getStacks() { + return stacks; + } - private boolean hasFilter() { - for (ItemStack filter : stacks) { - if (filter != null) { - return true; - } - } - return false; - } + private boolean hasFilter() { + for (ItemStack filter : stacks) { + if (filter != null) { + return true; + } + } + return false; + } } diff --git a/src/main/java/forestry/core/inventory/filters/IStackFilter.java b/src/main/java/forestry/core/inventory/filters/IStackFilter.java index 82ddf56f1..27b7f5397 100755 --- a/src/main/java/forestry/core/inventory/filters/IStackFilter.java +++ b/src/main/java/forestry/core/inventory/filters/IStackFilter.java @@ -21,5 +21,5 @@ import net.minecraft.item.ItemStack; */ public interface IStackFilter { - boolean matches(ItemStack stack); + boolean matches(ItemStack stack); } diff --git a/src/main/java/forestry/core/inventory/filters/InvertedStackFilter.java b/src/main/java/forestry/core/inventory/filters/InvertedStackFilter.java index fc041f978..f90f174f6 100755 --- a/src/main/java/forestry/core/inventory/filters/InvertedStackFilter.java +++ b/src/main/java/forestry/core/inventory/filters/InvertedStackFilter.java @@ -17,17 +17,17 @@ import net.minecraft.item.ItemStack; */ public class InvertedStackFilter implements IStackFilter { - private final IStackFilter filter; + private final IStackFilter filter; - public InvertedStackFilter(IStackFilter filter) { - this.filter = filter; - } + public InvertedStackFilter(IStackFilter filter) { + this.filter = filter; + } - @Override - public boolean matches(ItemStack stack) { - if (stack == null) { - return false; - } - return !filter.matches(stack); - } + @Override + public boolean matches(ItemStack stack) { + if (stack == null) { + return false; + } + return !filter.matches(stack); + } } diff --git a/src/main/java/forestry/core/inventory/filters/StackFilter.java b/src/main/java/forestry/core/inventory/filters/StackFilter.java index aadb69932..c5bdf1a99 100755 --- a/src/main/java/forestry/core/inventory/filters/StackFilter.java +++ b/src/main/java/forestry/core/inventory/filters/StackFilter.java @@ -24,26 +24,27 @@ import net.minecraft.tileentity.TileEntityFurnace; * @author CovertJaguar */ public enum StackFilter implements IStackFilter { + ALL { + @Override + public boolean matches(ItemStack stack) { + return true; + } + }, + FUEL { + @Override + public boolean matches(ItemStack stack) { + return TileEntityFurnace.getItemBurnTime(stack) > 0; + } + }, + FEED { + @Override + public boolean matches(ItemStack stack) { + return stack.getItem() instanceof ItemFood + || stack.getItem() == Items.wheat + || stack.getItem() instanceof ItemSeeds; + } + }; - ALL { - @Override - public boolean matches(ItemStack stack) { - return true; - } - }, - FUEL { - @Override - public boolean matches(ItemStack stack) { - return TileEntityFurnace.getItemBurnTime(stack) > 0; - } - }, - FEED { - @Override - public boolean matches(ItemStack stack) { - return stack.getItem() instanceof ItemFood || stack.getItem() == Items.wheat || stack.getItem() instanceof ItemSeeds; - } - }; - - @Override - public abstract boolean matches(ItemStack stack); + @Override + public abstract boolean matches(ItemStack stack); } diff --git a/src/main/java/forestry/core/inventory/manipulators/InventoryManipulator.java b/src/main/java/forestry/core/inventory/manipulators/InventoryManipulator.java index e01eedb5f..7cfc5f0c0 100755 --- a/src/main/java/forestry/core/inventory/manipulators/InventoryManipulator.java +++ b/src/main/java/forestry/core/inventory/manipulators/InventoryManipulator.java @@ -10,177 +10,174 @@ ******************************************************************************/ package forestry.core.inventory.manipulators; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - import forestry.core.inventory.filters.IStackFilter; import forestry.core.inventory.wrappers.IInvSlot; import forestry.core.inventory.wrappers.InventoryIterator; import forestry.core.utils.InventoryUtil; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; /** * @author CovertJaguar */ public class InventoryManipulator { - private final IInventory inv; + private final IInventory inv; - public static InventoryManipulator get(IInventory inv) { - return new InventoryManipulator(inv); - } + public static InventoryManipulator get(IInventory inv) { + return new InventoryManipulator(inv); + } - protected InventoryManipulator(IInventory inv) { - this.inv = inv; - } + protected InventoryManipulator(IInventory inv) { + this.inv = inv; + } - protected Iterable getSlots() { - return InventoryIterator.getIterable(inv); - } + protected Iterable getSlots() { + return InventoryIterator.getIterable(inv); + } - public boolean canAddStack(ItemStack stack) { - return tryAddStack(stack) == null; - } + public boolean canAddStack(ItemStack stack) { + return tryAddStack(stack) == null; + } - public ItemStack tryAddStack(ItemStack stack) { - return addStack(stack, false); - } + public ItemStack tryAddStack(ItemStack stack) { + return addStack(stack, false); + } - /** - * Attempt to add the stack to the inventory. - * - * @return The remainder - */ - public ItemStack addStack(ItemStack stack) { - return addStack(stack, true); - } + /** + * Attempt to add the stack to the inventory. + * + * @return The remainder + */ + public ItemStack addStack(ItemStack stack) { + return addStack(stack, true); + } - private ItemStack addStack(ItemStack stack, boolean doAdd) { - if (stack == null || stack.stackSize <= 0) { - return null; - } - stack = stack.copy(); - List filledSlots = new ArrayList<>(inv.getSizeInventory()); - List emptySlots = new ArrayList<>(inv.getSizeInventory()); - for (IInvSlot slot : InventoryIterator.getIterable(inv)) { - if (slot.canPutStackInSlot(stack)) { - if (slot.getStackInSlot() == null) { - emptySlots.add(slot); - } else { - filledSlots.add(slot); - } - } - } + private ItemStack addStack(ItemStack stack, boolean doAdd) { + if (stack == null || stack.stackSize <= 0) { + return null; + } + stack = stack.copy(); + List filledSlots = new ArrayList<>(inv.getSizeInventory()); + List emptySlots = new ArrayList<>(inv.getSizeInventory()); + for (IInvSlot slot : InventoryIterator.getIterable(inv)) { + if (slot.canPutStackInSlot(stack)) { + if (slot.getStackInSlot() == null) { + emptySlots.add(slot); + } else { + filledSlots.add(slot); + } + } + } - int injected = 0; - injected = tryPut(filledSlots, stack, injected, doAdd); - injected = tryPut(emptySlots, stack, injected, doAdd); - stack.stackSize -= injected; - if (stack.stackSize <= 0) { - return null; - } - return stack; - } + int injected = 0; + injected = tryPut(filledSlots, stack, injected, doAdd); + injected = tryPut(emptySlots, stack, injected, doAdd); + stack.stackSize -= injected; + if (stack.stackSize <= 0) { + return null; + } + return stack; + } - private int tryPut(List slots, ItemStack stack, int injected, boolean doAdd) { - if (injected >= stack.stackSize) { - return injected; - } - for (IInvSlot slot : slots) { - ItemStack stackInSlot = slot.getStackInSlot(); - if (stackInSlot == null || InventoryUtil.isItemEqual(stackInSlot, stack)) { - int used = addToSlot(slot, stack, stack.stackSize - injected, doAdd); - if (used > 0) { - injected += used; - if (injected >= stack.stackSize) { - return injected; - } - } - } - } - return injected; - } + private int tryPut(List slots, ItemStack stack, int injected, boolean doAdd) { + if (injected >= stack.stackSize) { + return injected; + } + for (IInvSlot slot : slots) { + ItemStack stackInSlot = slot.getStackInSlot(); + if (stackInSlot == null || InventoryUtil.isItemEqual(stackInSlot, stack)) { + int used = addToSlot(slot, stack, stack.stackSize - injected, doAdd); + if (used > 0) { + injected += used; + if (injected >= stack.stackSize) { + return injected; + } + } + } + } + return injected; + } - /** - * @param available Amount we can move - * @return Return the number of items moved. - */ - private int addToSlot(IInvSlot slot, ItemStack stack, int available, boolean doAdd) { - int max = Math.min(stack.getMaxStackSize(), inv.getInventoryStackLimit()); + /** + * @param available Amount we can move + * @return Return the number of items moved. + */ + private int addToSlot(IInvSlot slot, ItemStack stack, int available, boolean doAdd) { + int max = Math.min(stack.getMaxStackSize(), inv.getInventoryStackLimit()); - ItemStack stackInSlot = slot.getStackInSlot(); - if (stackInSlot == null) { - int wanted = Math.min(available, max); - if (doAdd) { - stackInSlot = stack.copy(); - stackInSlot.stackSize = wanted; - slot.setStackInSlot(stackInSlot); - } - return wanted; - } + ItemStack stackInSlot = slot.getStackInSlot(); + if (stackInSlot == null) { + int wanted = Math.min(available, max); + if (doAdd) { + stackInSlot = stack.copy(); + stackInSlot.stackSize = wanted; + slot.setStackInSlot(stackInSlot); + } + return wanted; + } - if (!InventoryUtil.isItemEqual(stack, stackInSlot)) { - return 0; - } + if (!InventoryUtil.isItemEqual(stack, stackInSlot)) { + return 0; + } - int wanted = max - stackInSlot.stackSize; - if (wanted <= 0) { - return 0; - } + int wanted = max - stackInSlot.stackSize; + if (wanted <= 0) { + return 0; + } - if (wanted > available) { - wanted = available; - } + if (wanted > available) { + wanted = available; + } - if (doAdd) { - stackInSlot.stackSize += wanted; - slot.setStackInSlot(stackInSlot); - } - return wanted; - } + if (doAdd) { + stackInSlot.stackSize += wanted; + slot.setStackInSlot(stackInSlot); + } + return wanted; + } - public boolean canRemoveItem(IStackFilter filter) { - return tryRemoveItem(filter) == null; - } + public boolean canRemoveItem(IStackFilter filter) { + return tryRemoveItem(filter) == null; + } - public ItemStack tryRemoveItem(IStackFilter filter) { - for (IInvSlot slot : getSlots()) { - ItemStack stack = slot.getStackInSlot(); - if (stack != null && slot.canTakeStackFromSlot(stack) && filter.matches(stack)) { - ItemStack output = stack.copy(); - output.stackSize = 1; - return output; - } - } - return null; - } + public ItemStack tryRemoveItem(IStackFilter filter) { + for (IInvSlot slot : getSlots()) { + ItemStack stack = slot.getStackInSlot(); + if (stack != null && slot.canTakeStackFromSlot(stack) && filter.matches(stack)) { + ItemStack output = stack.copy(); + output.stackSize = 1; + return output; + } + } + return null; + } - public ItemStack removeItem(IStackFilter filter) { - for (IInvSlot slot : getSlots()) { - ItemStack stack = slot.getStackInSlot(); - if (stack != null && slot.canTakeStackFromSlot(stack) && filter.matches(stack)) { - return slot.decreaseStackInSlot(); - } - } - return null; - } - - public ItemStack moveItem(IInventory dest, IStackFilter filter) { - InventoryManipulator imDest = InventoryManipulator.get(dest); - for (IInvSlot slot : getSlots()) { - ItemStack stack = slot.getStackInSlot(); - if (stack != null && slot.canTakeStackFromSlot(stack) && filter.matches(stack)) { - stack = stack.copy(); - stack.stackSize = 1; - stack = imDest.addStack(stack); - if (stack == null) { - return slot.decreaseStackInSlot(); - } - } - } - return null; - } + public ItemStack removeItem(IStackFilter filter) { + for (IInvSlot slot : getSlots()) { + ItemStack stack = slot.getStackInSlot(); + if (stack != null && slot.canTakeStackFromSlot(stack) && filter.matches(stack)) { + return slot.decreaseStackInSlot(); + } + } + return null; + } + public ItemStack moveItem(IInventory dest, IStackFilter filter) { + InventoryManipulator imDest = InventoryManipulator.get(dest); + for (IInvSlot slot : getSlots()) { + ItemStack stack = slot.getStackInSlot(); + if (stack != null && slot.canTakeStackFromSlot(stack) && filter.matches(stack)) { + stack = stack.copy(); + stack.stackSize = 1; + stack = imDest.addStack(stack); + if (stack == null) { + return slot.decreaseStackInSlot(); + } + } + } + return null; + } } diff --git a/src/main/java/forestry/core/inventory/watchers/FakeSlotChangeWatcher.java b/src/main/java/forestry/core/inventory/watchers/FakeSlotChangeWatcher.java index ee67e5b9d..eaa668f48 100644 --- a/src/main/java/forestry/core/inventory/watchers/FakeSlotChangeWatcher.java +++ b/src/main/java/forestry/core/inventory/watchers/FakeSlotChangeWatcher.java @@ -1,26 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.inventory.watchers; - -import net.minecraft.inventory.IInventory; - -public class FakeSlotChangeWatcher implements ISlotChangeWatcher { - public static final FakeSlotChangeWatcher instance = new FakeSlotChangeWatcher(); - - private FakeSlotChangeWatcher() { - - } - - @Override - public void onSlotChanged(IInventory inventory, int slot) { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.inventory.watchers; + +import net.minecraft.inventory.IInventory; + +public class FakeSlotChangeWatcher implements ISlotChangeWatcher { + public static final FakeSlotChangeWatcher instance = new FakeSlotChangeWatcher(); + + private FakeSlotChangeWatcher() {} + + @Override + public void onSlotChanged(IInventory inventory, int slot) {} +} diff --git a/src/main/java/forestry/core/inventory/watchers/FakeSlotPickupWatcher.java b/src/main/java/forestry/core/inventory/watchers/FakeSlotPickupWatcher.java index aea0999ce..7b0b97dfe 100644 --- a/src/main/java/forestry/core/inventory/watchers/FakeSlotPickupWatcher.java +++ b/src/main/java/forestry/core/inventory/watchers/FakeSlotPickupWatcher.java @@ -1,27 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.inventory.watchers; - -import net.minecraft.entity.player.EntityPlayer; - -public class FakeSlotPickupWatcher implements ISlotPickupWatcher { - - public static final FakeSlotPickupWatcher instance = new FakeSlotPickupWatcher(); - - private FakeSlotPickupWatcher() { - - } - - @Override - public void onPickupFromSlot(int slotIndex, EntityPlayer player) { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.inventory.watchers; + +import net.minecraft.entity.player.EntityPlayer; + +public class FakeSlotPickupWatcher implements ISlotPickupWatcher { + + public static final FakeSlotPickupWatcher instance = new FakeSlotPickupWatcher(); + + private FakeSlotPickupWatcher() {} + + @Override + public void onPickupFromSlot(int slotIndex, EntityPlayer player) {} +} diff --git a/src/main/java/forestry/core/inventory/watchers/ISlotChangeWatcher.java b/src/main/java/forestry/core/inventory/watchers/ISlotChangeWatcher.java index 922202be3..f5c69144f 100644 --- a/src/main/java/forestry/core/inventory/watchers/ISlotChangeWatcher.java +++ b/src/main/java/forestry/core/inventory/watchers/ISlotChangeWatcher.java @@ -1,17 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.inventory.watchers; - -import net.minecraft.inventory.IInventory; - -public interface ISlotChangeWatcher { - void onSlotChanged(IInventory inventory, int slot); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.inventory.watchers; + +import net.minecraft.inventory.IInventory; + +public interface ISlotChangeWatcher { + void onSlotChanged(IInventory inventory, int slot); +} diff --git a/src/main/java/forestry/core/inventory/watchers/ISlotPickupWatcher.java b/src/main/java/forestry/core/inventory/watchers/ISlotPickupWatcher.java index c8d8650f9..aef7156d3 100644 --- a/src/main/java/forestry/core/inventory/watchers/ISlotPickupWatcher.java +++ b/src/main/java/forestry/core/inventory/watchers/ISlotPickupWatcher.java @@ -13,5 +13,5 @@ package forestry.core.inventory.watchers; import net.minecraft.entity.player.EntityPlayer; public interface ISlotPickupWatcher { - void onPickupFromSlot(int slotIndex, EntityPlayer player); + void onPickupFromSlot(int slotIndex, EntityPlayer player); } diff --git a/src/main/java/forestry/core/inventory/wrappers/ChestWrapper.java b/src/main/java/forestry/core/inventory/wrappers/ChestWrapper.java index 66de8d811..e6b2515c1 100755 --- a/src/main/java/forestry/core/inventory/wrappers/ChestWrapper.java +++ b/src/main/java/forestry/core/inventory/wrappers/ChestWrapper.java @@ -20,179 +20,179 @@ import net.minecraft.tileentity.TileEntityChest; */ public class ChestWrapper implements IInventory { - /** - * Inventory object corresponding to double chest upper part - */ - private final TileEntityChest upperChest; - /** - * Inventory object corresponding to double chest lower part - */ - private TileEntityChest lowerChest; + /** + * Inventory object corresponding to double chest upper part + */ + private final TileEntityChest upperChest; + /** + * Inventory object corresponding to double chest lower part + */ + private TileEntityChest lowerChest; - public ChestWrapper(TileEntityChest tile) { - this.upperChest = tile; - checkChest(); - } + public ChestWrapper(TileEntityChest tile) { + this.upperChest = tile; + checkChest(); + } - private void checkChest() { - if (lowerChest == null || lowerChest.isInvalid()) { - if (upperChest.adjacentChestXNeg != null) { - lowerChest = upperChest.adjacentChestXNeg; - } else if (upperChest.adjacentChestXPos != null) { - lowerChest = upperChest.adjacentChestXPos; - } else if (upperChest.adjacentChestZNeg != null) { - lowerChest = upperChest.adjacentChestZNeg; - } else if (upperChest.adjacentChestZPos != null) { - lowerChest = upperChest.adjacentChestZPos; - } else { - lowerChest = null; - } - } - } + private void checkChest() { + if (lowerChest == null || lowerChest.isInvalid()) { + if (upperChest.adjacentChestXNeg != null) { + lowerChest = upperChest.adjacentChestXNeg; + } else if (upperChest.adjacentChestXPos != null) { + lowerChest = upperChest.adjacentChestXPos; + } else if (upperChest.adjacentChestZNeg != null) { + lowerChest = upperChest.adjacentChestZNeg; + } else if (upperChest.adjacentChestZPos != null) { + lowerChest = upperChest.adjacentChestZPos; + } else { + lowerChest = null; + } + } + } - /** - * Returns the number of slots in the inventory. - */ - @Override - public int getSizeInventory() { - checkChest(); - int size = upperChest.getSizeInventory(); - if (lowerChest != null) { - size += lowerChest.getSizeInventory(); - } - return size; - } + /** + * Returns the number of slots in the inventory. + */ + @Override + public int getSizeInventory() { + checkChest(); + int size = upperChest.getSizeInventory(); + if (lowerChest != null) { + size += lowerChest.getSizeInventory(); + } + return size; + } - /** - * Return whether the given inventory is part of this large chest. - */ - public boolean isPartOfLargeChest(IInventory inv) { - return this.upperChest == inv || this.lowerChest == inv; - } + /** + * Return whether the given inventory is part of this large chest. + */ + public boolean isPartOfLargeChest(IInventory inv) { + return this.upperChest == inv || this.lowerChest == inv; + } - /** - * Returns the name of the inventory. - */ - @Override - public String getInventoryName() { - return ""; - } + /** + * Returns the name of the inventory. + */ + @Override + public String getInventoryName() { + return ""; + } - /** - * If this returns false, the inventory name will be used as an unlocalized - * name, and translated into the player's language. Otherwise it will be - * used directly. - */ - @Override - public boolean hasCustomInventoryName() { - return false; - } + /** + * If this returns false, the inventory name will be used as an unlocalized + * name, and translated into the player's language. Otherwise it will be + * used directly. + */ + @Override + public boolean hasCustomInventoryName() { + return false; + } - /** - * Returns the stack in slot i - */ - @Override - public ItemStack getStackInSlot(int slot) { - checkChest(); - if (slot >= upperChest.getSizeInventory() && lowerChest != null) { - return lowerChest.getStackInSlot(slot - upperChest.getSizeInventory()); - } - return upperChest.getStackInSlot(slot); - } + /** + * Returns the stack in slot i + */ + @Override + public ItemStack getStackInSlot(int slot) { + checkChest(); + if (slot >= upperChest.getSizeInventory() && lowerChest != null) { + return lowerChest.getStackInSlot(slot - upperChest.getSizeInventory()); + } + return upperChest.getStackInSlot(slot); + } - /** - * Removes from an inventory slot (first arg) up to a specified number - * (second arg) of items and returns them in a new stack. - */ - @Override - public ItemStack decrStackSize(int slot, int amout) { - checkChest(); - if (slot >= upperChest.getSizeInventory() && lowerChest != null) { - return lowerChest.decrStackSize(slot - upperChest.getSizeInventory(), amout); - } - return upperChest.decrStackSize(slot, amout); - } + /** + * Removes from an inventory slot (first arg) up to a specified number + * (second arg) of items and returns them in a new stack. + */ + @Override + public ItemStack decrStackSize(int slot, int amout) { + checkChest(); + if (slot >= upperChest.getSizeInventory() && lowerChest != null) { + return lowerChest.decrStackSize(slot - upperChest.getSizeInventory(), amout); + } + return upperChest.decrStackSize(slot, amout); + } - /** - * When some containers are closed they call this on each slot, then drop - * whatever it returns as an EntityItem - like when you close a workbench - * GUI. - */ - @Override - public ItemStack getStackInSlotOnClosing(int slot) { - checkChest(); - if (slot >= upperChest.getSizeInventory() && lowerChest != null) { - return lowerChest.getStackInSlotOnClosing(slot - upperChest.getSizeInventory()); - } - return upperChest.getStackInSlotOnClosing(slot); - } + /** + * When some containers are closed they call this on each slot, then drop + * whatever it returns as an EntityItem - like when you close a workbench + * GUI. + */ + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + checkChest(); + if (slot >= upperChest.getSizeInventory() && lowerChest != null) { + return lowerChest.getStackInSlotOnClosing(slot - upperChest.getSizeInventory()); + } + return upperChest.getStackInSlotOnClosing(slot); + } - /** - * Sets the given item stack to the specified slot in the inventory (can be - * crafting or armor sections). - */ - @Override - public void setInventorySlotContents(int slot, ItemStack stack) { - checkChest(); - if (slot >= this.upperChest.getSizeInventory() && lowerChest != null) { - lowerChest.setInventorySlotContents(slot - upperChest.getSizeInventory(), stack); - } else { - upperChest.setInventorySlotContents(slot, stack); - } - } + /** + * Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). + */ + @Override + public void setInventorySlotContents(int slot, ItemStack stack) { + checkChest(); + if (slot >= this.upperChest.getSizeInventory() && lowerChest != null) { + lowerChest.setInventorySlotContents(slot - upperChest.getSizeInventory(), stack); + } else { + upperChest.setInventorySlotContents(slot, stack); + } + } - /** - * Returns the maximum stack size for a inventory slot. Seems to always be - * 64, possibly will be extended. *Isn't this more of a set than a get?* - */ - @Override - public int getInventoryStackLimit() { - return this.upperChest.getInventoryStackLimit(); - } + /** + * Returns the maximum stack size for a inventory slot. Seems to always be + * 64, possibly will be extended. *Isn't this more of a set than a get?* + */ + @Override + public int getInventoryStackLimit() { + return this.upperChest.getInventoryStackLimit(); + } - /** - * Called when an the contents of an Inventory change, usually - */ - @Override - public void markDirty() { - this.upperChest.markDirty(); - if (lowerChest != null) { - lowerChest.markDirty(); - } - } + /** + * Called when an the contents of an Inventory change, usually + */ + @Override + public void markDirty() { + this.upperChest.markDirty(); + if (lowerChest != null) { + lowerChest.markDirty(); + } + } - /** - * Do not make give this method the name canInteractWith because it clashes - * with Container - */ - @Override - public boolean isUseableByPlayer(EntityPlayer player) { - return this.upperChest.isUseableByPlayer(player) && (lowerChest == null || lowerChest.isUseableByPlayer(player)); - } + /** + * Do not make give this method the name canInteractWith because it clashes + * with Container + */ + @Override + public boolean isUseableByPlayer(EntityPlayer player) { + return this.upperChest.isUseableByPlayer(player) + && (lowerChest == null || lowerChest.isUseableByPlayer(player)); + } - @Override - public void openInventory() { - this.upperChest.openInventory(); - if (lowerChest != null) { - lowerChest.openInventory(); - } - } + @Override + public void openInventory() { + this.upperChest.openInventory(); + if (lowerChest != null) { + lowerChest.openInventory(); + } + } - @Override - public void closeInventory() { - this.upperChest.closeInventory(); - if (lowerChest != null) { - lowerChest.closeInventory(); - } - } - - /** - * Returns true if automation is allowed to insert the given stack (ignoring - * stack size) into the given slot. - */ - @Override - public boolean isItemValidForSlot(int slot, ItemStack stack) { - return true; - } + @Override + public void closeInventory() { + this.upperChest.closeInventory(); + if (lowerChest != null) { + lowerChest.closeInventory(); + } + } + /** + * Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + @Override + public boolean isItemValidForSlot(int slot, ItemStack stack) { + return true; + } } diff --git a/src/main/java/forestry/core/inventory/wrappers/IInvSlot.java b/src/main/java/forestry/core/inventory/wrappers/IInvSlot.java index 895c67b35..3764845a4 100755 --- a/src/main/java/forestry/core/inventory/wrappers/IInvSlot.java +++ b/src/main/java/forestry/core/inventory/wrappers/IInvSlot.java @@ -17,16 +17,15 @@ import net.minecraft.item.ItemStack; */ public interface IInvSlot { - boolean canPutStackInSlot(ItemStack stack); + boolean canPutStackInSlot(ItemStack stack); - boolean canTakeStackFromSlot(ItemStack stack); + boolean canTakeStackFromSlot(ItemStack stack); - ItemStack decreaseStackInSlot(); + ItemStack decreaseStackInSlot(); - ItemStack getStackInSlot(); + ItemStack getStackInSlot(); - void setStackInSlot(ItemStack stack); - - int getIndex(); + void setStackInSlot(ItemStack stack); + int getIndex(); } diff --git a/src/main/java/forestry/core/inventory/wrappers/InventoryCopy.java b/src/main/java/forestry/core/inventory/wrappers/InventoryCopy.java index 72282766a..fc8fe5a69 100755 --- a/src/main/java/forestry/core/inventory/wrappers/InventoryCopy.java +++ b/src/main/java/forestry/core/inventory/wrappers/InventoryCopy.java @@ -10,12 +10,11 @@ ******************************************************************************/ package forestry.core.inventory.wrappers; +import forestry.core.utils.InventoryUtil; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import forestry.core.utils.InventoryUtil; - /** * Creates a deep copy of an existing IInventory. * @@ -26,93 +25,90 @@ import forestry.core.utils.InventoryUtil; */ public class InventoryCopy implements IInventory { - private final IInventory orignal; - private final ItemStack contents[]; + private final IInventory orignal; + private final ItemStack contents[]; - public InventoryCopy(IInventory orignal) { - this.orignal = orignal; - contents = new ItemStack[orignal.getSizeInventory()]; - InventoryUtil.deepCopyInventoryContents(orignal, this); - } + public InventoryCopy(IInventory orignal) { + this.orignal = orignal; + contents = new ItemStack[orignal.getSizeInventory()]; + InventoryUtil.deepCopyInventoryContents(orignal, this); + } - @Override - public int getSizeInventory() { - return contents.length; - } + @Override + public int getSizeInventory() { + return contents.length; + } - @Override - public ItemStack getStackInSlot(int i) { - return contents[i]; - } + @Override + public ItemStack getStackInSlot(int i) { + return contents[i]; + } - @Override - public ItemStack decrStackSize(int i, int j) { - if (contents[i] != null) { - if (contents[i].stackSize <= j) { - ItemStack itemstack = contents[i]; - contents[i] = null; - markDirty(); - return itemstack; - } - ItemStack itemstack1 = contents[i].splitStack(j); - if (contents[i].stackSize <= 0) { - contents[i] = null; - } - markDirty(); - return itemstack1; - } else { - return null; - } - } + @Override + public ItemStack decrStackSize(int i, int j) { + if (contents[i] != null) { + if (contents[i].stackSize <= j) { + ItemStack itemstack = contents[i]; + contents[i] = null; + markDirty(); + return itemstack; + } + ItemStack itemstack1 = contents[i].splitStack(j); + if (contents[i].stackSize <= 0) { + contents[i] = null; + } + markDirty(); + return itemstack1; + } else { + return null; + } + } - @Override - public void setInventorySlotContents(int i, ItemStack itemstack) { - contents[i] = itemstack; - if (itemstack != null && itemstack.stackSize > getInventoryStackLimit()) { - itemstack.stackSize = getInventoryStackLimit(); - } - markDirty(); - } + @Override + public void setInventorySlotContents(int i, ItemStack itemstack) { + contents[i] = itemstack; + if (itemstack != null && itemstack.stackSize > getInventoryStackLimit()) { + itemstack.stackSize = getInventoryStackLimit(); + } + markDirty(); + } - @Override - public String getInventoryName() { - return orignal.getInventoryName(); - } + @Override + public String getInventoryName() { + return orignal.getInventoryName(); + } - @Override - public int getInventoryStackLimit() { - return orignal.getInventoryStackLimit(); - } + @Override + public int getInventoryStackLimit() { + return orignal.getInventoryStackLimit(); + } - @Override - public void markDirty() { - } + @Override + public void markDirty() {} - @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return true; - } + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return true; + } - @Override - public void openInventory() { - } + @Override + public void openInventory() {} - @Override - public void closeInventory() { - } + @Override + public void closeInventory() {} - @Override - public ItemStack getStackInSlotOnClosing(int slot) { - return orignal.getStackInSlotOnClosing(slot); - } + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + return orignal.getStackInSlotOnClosing(slot); + } - @Override - public boolean hasCustomInventoryName() { - return orignal.hasCustomInventoryName(); - } + @Override + public boolean hasCustomInventoryName() { + return orignal.hasCustomInventoryName(); + } - @Override - public boolean isItemValidForSlot(int slot, ItemStack stack) { - return orignal.isItemValidForSlot(slot, stack); - } + @Override + public boolean isItemValidForSlot(int slot, ItemStack stack) { + return orignal.isItemValidForSlot(slot, stack); + } } diff --git a/src/main/java/forestry/core/inventory/wrappers/InventoryIterator.java b/src/main/java/forestry/core/inventory/wrappers/InventoryIterator.java index ef32ff9cf..eb8c09786 100755 --- a/src/main/java/forestry/core/inventory/wrappers/InventoryIterator.java +++ b/src/main/java/forestry/core/inventory/wrappers/InventoryIterator.java @@ -11,7 +11,6 @@ package forestry.core.inventory.wrappers; import java.util.Iterator; - import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; @@ -21,81 +20,79 @@ import net.minecraft.item.ItemStack; */ public class InventoryIterator implements Iterable { - public static Iterable getIterable(IInventory inv) { - if (inv instanceof ISidedInventory) { - return new SidedInventoryIterator((ISidedInventory) inv); - } - return new InventoryIterator(inv); - } + public static Iterable getIterable(IInventory inv) { + if (inv instanceof ISidedInventory) { + return new SidedInventoryIterator((ISidedInventory) inv); + } + return new InventoryIterator(inv); + } - private final IInventory inv; - private final int invSize; + private final IInventory inv; + private final int invSize; - private InventoryIterator(IInventory inv) { - this.inv = inv; - this.invSize = inv != null ? inv.getSizeInventory() : 0; - } + private InventoryIterator(IInventory inv) { + this.inv = inv; + this.invSize = inv != null ? inv.getSizeInventory() : 0; + } - @Override - public Iterator iterator() { - return new Iterator() { - int slot = 0; + @Override + public Iterator iterator() { + return new Iterator() { + int slot = 0; - @Override - public boolean hasNext() { - return slot < invSize; - } + @Override + public boolean hasNext() { + return slot < invSize; + } - @Override - public IInvSlot next() { - return new InvSlot(slot++); - } + @Override + public IInvSlot next() { + return new InvSlot(slot++); + } - @Override - public void remove() { - throw new UnsupportedOperationException("Remove not supported."); - } + @Override + public void remove() { + throw new UnsupportedOperationException("Remove not supported."); + } + }; + } - }; - } + private class InvSlot implements IInvSlot { - private class InvSlot implements IInvSlot { + private final int slot; - private final int slot; + public InvSlot(int slot) { + this.slot = slot; + } - public InvSlot(int slot) { - this.slot = slot; - } + @Override + public ItemStack getStackInSlot() { + return inv.getStackInSlot(slot); + } - @Override - public ItemStack getStackInSlot() { - return inv.getStackInSlot(slot); - } + @Override + public void setStackInSlot(ItemStack stack) { + inv.setInventorySlotContents(slot, stack); + } - @Override - public void setStackInSlot(ItemStack stack) { - inv.setInventorySlotContents(slot, stack); - } + @Override + public boolean canPutStackInSlot(ItemStack stack) { + return inv.isItemValidForSlot(slot, stack); + } - @Override - public boolean canPutStackInSlot(ItemStack stack) { - return inv.isItemValidForSlot(slot, stack); - } + @Override + public boolean canTakeStackFromSlot(ItemStack stack) { + return true; + } - @Override - public boolean canTakeStackFromSlot(ItemStack stack) { - return true; - } + @Override + public ItemStack decreaseStackInSlot() { + return inv.decrStackSize(slot, 1); + } - @Override - public ItemStack decreaseStackInSlot() { - return inv.decrStackSize(slot, 1); - } - - @Override - public int getIndex() { - return slot; - } - - } + @Override + public int getIndex() { + return slot; + } + } } diff --git a/src/main/java/forestry/core/inventory/wrappers/InventoryMapper.java b/src/main/java/forestry/core/inventory/wrappers/InventoryMapper.java index 8956af0e8..34be919df 100755 --- a/src/main/java/forestry/core/inventory/wrappers/InventoryMapper.java +++ b/src/main/java/forestry/core/inventory/wrappers/InventoryMapper.java @@ -13,7 +13,6 @@ package forestry.core.inventory.wrappers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - import net.minecraftforge.common.util.ForgeDirection; /** @@ -25,125 +24,124 @@ import net.minecraftforge.common.util.ForgeDirection; */ public class InventoryMapper implements IInventory { - private final IInventory inv; - private final int start; - private final int size; - private int stackSizeLimit = -1; - private boolean checkItems = true; + private final IInventory inv; + private final int start; + private final int size; + private int stackSizeLimit = -1; + private boolean checkItems = true; - public InventoryMapper(IInventory inv, ForgeDirection side) { - this(inv, getInventoryStart(inv, side), getInventorySize(inv, side)); - } + public InventoryMapper(IInventory inv, ForgeDirection side) { + this(inv, getInventoryStart(inv, side), getInventorySize(inv, side)); + } - public InventoryMapper(IInventory inv) { - this(inv, 0, inv.getSizeInventory(), true); - } + public InventoryMapper(IInventory inv) { + this(inv, 0, inv.getSizeInventory(), true); + } - public InventoryMapper(IInventory inv, boolean checkItems) { - this(inv, 0, inv.getSizeInventory(), checkItems); - } + public InventoryMapper(IInventory inv, boolean checkItems) { + this(inv, 0, inv.getSizeInventory(), checkItems); + } - /** - * Creates a new InventoryMapper - * - * @param inv The backing inventory - * @param start The starting index - * @param size The size of the new inventory, take care not to exceed the - * end of the backing inventory - */ - public InventoryMapper(IInventory inv, int start, int size) { - this(inv, start, size, true); - } + /** + * Creates a new InventoryMapper + * + * @param inv The backing inventory + * @param start The starting index + * @param size The size of the new inventory, take care not to exceed the + * end of the backing inventory + */ + public InventoryMapper(IInventory inv, int start, int size) { + this(inv, start, size, true); + } - public InventoryMapper(IInventory inv, int start, int size, boolean checkItems) { - this.inv = inv; - this.start = start; - this.size = size; - this.checkItems = checkItems; - } + public InventoryMapper(IInventory inv, int start, int size, boolean checkItems) { + this.inv = inv; + this.start = start; + this.size = size; + this.checkItems = checkItems; + } - protected static int getInventorySize(IInventory inv, ForgeDirection side) { - return inv.getSizeInventory(); - } + protected static int getInventorySize(IInventory inv, ForgeDirection side) { + return inv.getSizeInventory(); + } - protected static int getInventoryStart(IInventory inv, ForgeDirection side) { - return 0; - } + protected static int getInventoryStart(IInventory inv, ForgeDirection side) { + return 0; + } - public IInventory getBaseInventory() { - return inv; - } + public IInventory getBaseInventory() { + return inv; + } - @Override - public int getSizeInventory() { - return size; - } + @Override + public int getSizeInventory() { + return size; + } - @Override - public ItemStack getStackInSlot(int slot) { - return inv.getStackInSlot(start + slot); - } + @Override + public ItemStack getStackInSlot(int slot) { + return inv.getStackInSlot(start + slot); + } - @Override - public ItemStack decrStackSize(int slot, int amount) { - return inv.decrStackSize(start + slot, amount); - } + @Override + public ItemStack decrStackSize(int slot, int amount) { + return inv.decrStackSize(start + slot, amount); + } - @Override - public void setInventorySlotContents(int slot, ItemStack itemstack) { - inv.setInventorySlotContents(start + slot, itemstack); - } + @Override + public void setInventorySlotContents(int slot, ItemStack itemstack) { + inv.setInventorySlotContents(start + slot, itemstack); + } - @Override - public String getInventoryName() { - return inv.getInventoryName(); - } + @Override + public String getInventoryName() { + return inv.getInventoryName(); + } - public void setStackSizeLimit(int limit) { - stackSizeLimit = limit; - } + public void setStackSizeLimit(int limit) { + stackSizeLimit = limit; + } - @Override - public int getInventoryStackLimit() { - return stackSizeLimit > 0 ? stackSizeLimit : inv.getInventoryStackLimit(); - } + @Override + public int getInventoryStackLimit() { + return stackSizeLimit > 0 ? stackSizeLimit : inv.getInventoryStackLimit(); + } - @Override - public void markDirty() { - inv.markDirty(); - } + @Override + public void markDirty() { + inv.markDirty(); + } - @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return inv.isUseableByPlayer(entityplayer); - } + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return inv.isUseableByPlayer(entityplayer); + } - @Override - public void openInventory() { - inv.openInventory(); - } + @Override + public void openInventory() { + inv.openInventory(); + } - @Override - public void closeInventory() { - inv.closeInventory(); - } + @Override + public void closeInventory() { + inv.closeInventory(); + } - @Override - public ItemStack getStackInSlotOnClosing(int slot) { - return inv.getStackInSlotOnClosing(start + slot); - } + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + return inv.getStackInSlotOnClosing(start + slot); + } - @Override - public boolean hasCustomInventoryName() { - return inv.hasCustomInventoryName(); - } - - @Override - public boolean isItemValidForSlot(int slot, ItemStack stack) { - if (checkItems) { - return inv.isItemValidForSlot(start + slot, stack); - } - return true; - } + @Override + public boolean hasCustomInventoryName() { + return inv.hasCustomInventoryName(); + } + @Override + public boolean isItemValidForSlot(int slot, ItemStack stack) { + if (checkItems) { + return inv.isItemValidForSlot(start + slot, stack); + } + return true; + } } diff --git a/src/main/java/forestry/core/inventory/wrappers/SidedInventoryIterator.java b/src/main/java/forestry/core/inventory/wrappers/SidedInventoryIterator.java index 71ca7007a..5c0e9a363 100755 --- a/src/main/java/forestry/core/inventory/wrappers/SidedInventoryIterator.java +++ b/src/main/java/forestry/core/inventory/wrappers/SidedInventoryIterator.java @@ -11,7 +11,6 @@ package forestry.core.inventory.wrappers; import java.util.Iterator; - import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; @@ -20,73 +19,71 @@ import net.minecraft.item.ItemStack; */ public class SidedInventoryIterator implements Iterable { - private final ISidedInventory inv; + private final ISidedInventory inv; - SidedInventoryIterator(ISidedInventory inv) { - this.inv = inv; - } + SidedInventoryIterator(ISidedInventory inv) { + this.inv = inv; + } - @Override - public Iterator iterator() { - return new Iterator() { - final int[] slots = inv.getAccessibleSlotsFromSide(0); - int index = 0; + @Override + public Iterator iterator() { + return new Iterator() { + final int[] slots = inv.getAccessibleSlotsFromSide(0); + int index = 0; - @Override - public boolean hasNext() { - return slots != null && index < slots.length; - } + @Override + public boolean hasNext() { + return slots != null && index < slots.length; + } - @Override - public IInvSlot next() { - return new InvSlot(slots[index++]); - } + @Override + public IInvSlot next() { + return new InvSlot(slots[index++]); + } - @Override - public void remove() { - throw new UnsupportedOperationException("Remove not supported."); - } + @Override + public void remove() { + throw new UnsupportedOperationException("Remove not supported."); + } + }; + } - }; - } + private class InvSlot implements IInvSlot { - private class InvSlot implements IInvSlot { + private final int slot; - private final int slot; + public InvSlot(int slot) { + this.slot = slot; + } - public InvSlot(int slot) { - this.slot = slot; - } + @Override + public ItemStack getStackInSlot() { + return inv.getStackInSlot(slot); + } - @Override - public ItemStack getStackInSlot() { - return inv.getStackInSlot(slot); - } + @Override + public void setStackInSlot(ItemStack stack) { + inv.setInventorySlotContents(slot, stack); + } - @Override - public void setStackInSlot(ItemStack stack) { - inv.setInventorySlotContents(slot, stack); - } + @Override + public boolean canPutStackInSlot(ItemStack stack) { + return inv.canInsertItem(slot, stack, 0); + } - @Override - public boolean canPutStackInSlot(ItemStack stack) { - return inv.canInsertItem(slot, stack, 0); - } + @Override + public boolean canTakeStackFromSlot(ItemStack stack) { + return inv.canExtractItem(slot, stack, 0); + } - @Override - public boolean canTakeStackFromSlot(ItemStack stack) { - return inv.canExtractItem(slot, stack, 0); - } + @Override + public ItemStack decreaseStackInSlot() { + return inv.decrStackSize(slot, 1); + } - @Override - public ItemStack decreaseStackInSlot() { - return inv.decrStackSize(slot, 1); - } - - @Override - public int getIndex() { - return slot; - } - - } + @Override + public int getIndex() { + return slot; + } + } } diff --git a/src/main/java/forestry/core/inventory/wrappers/SidedInventoryMapper.java b/src/main/java/forestry/core/inventory/wrappers/SidedInventoryMapper.java index 1f9a525c9..a0bf9f166 100755 --- a/src/main/java/forestry/core/inventory/wrappers/SidedInventoryMapper.java +++ b/src/main/java/forestry/core/inventory/wrappers/SidedInventoryMapper.java @@ -14,7 +14,6 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; - import net.minecraftforge.common.util.ForgeDirection; /** @@ -25,102 +24,101 @@ import net.minecraftforge.common.util.ForgeDirection; */ public class SidedInventoryMapper implements ISidedInventory { - private final ISidedInventory inv; - private final int side; - private boolean checkItems = true; + private final ISidedInventory inv; + private final int side; + private boolean checkItems = true; - public SidedInventoryMapper(ISidedInventory inv, ForgeDirection side) { - this(inv, side, true); - } + public SidedInventoryMapper(ISidedInventory inv, ForgeDirection side) { + this(inv, side, true); + } - public SidedInventoryMapper(ISidedInventory inv, ForgeDirection side, boolean checkItems) { - this.inv = inv; - this.side = side.ordinal(); - this.checkItems = checkItems; - } + public SidedInventoryMapper(ISidedInventory inv, ForgeDirection side, boolean checkItems) { + this.inv = inv; + this.side = side.ordinal(); + this.checkItems = checkItems; + } - public IInventory getBaseInventory() { - return inv; - } + public IInventory getBaseInventory() { + return inv; + } - @Override - public int getSizeInventory() { - return inv.getSizeInventory(); - } + @Override + public int getSizeInventory() { + return inv.getSizeInventory(); + } - @Override - public ItemStack getStackInSlot(int slot) { - return inv.getStackInSlot(slot); - } + @Override + public ItemStack getStackInSlot(int slot) { + return inv.getStackInSlot(slot); + } - @Override - public ItemStack decrStackSize(int slot, int amount) { - return inv.decrStackSize(slot, amount); - } + @Override + public ItemStack decrStackSize(int slot, int amount) { + return inv.decrStackSize(slot, amount); + } - @Override - public void setInventorySlotContents(int slot, ItemStack itemstack) { - inv.setInventorySlotContents(slot, itemstack); - } + @Override + public void setInventorySlotContents(int slot, ItemStack itemstack) { + inv.setInventorySlotContents(slot, itemstack); + } - @Override - public String getInventoryName() { - return inv.getInventoryName(); - } + @Override + public String getInventoryName() { + return inv.getInventoryName(); + } - @Override - public int getInventoryStackLimit() { - return inv.getInventoryStackLimit(); - } + @Override + public int getInventoryStackLimit() { + return inv.getInventoryStackLimit(); + } - @Override - public void markDirty() { - inv.markDirty(); - } + @Override + public void markDirty() { + inv.markDirty(); + } - @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return inv.isUseableByPlayer(entityplayer); - } + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return inv.isUseableByPlayer(entityplayer); + } - @Override - public void openInventory() { - inv.openInventory(); - } + @Override + public void openInventory() { + inv.openInventory(); + } - @Override - public void closeInventory() { - inv.closeInventory(); - } + @Override + public void closeInventory() { + inv.closeInventory(); + } - @Override - public ItemStack getStackInSlotOnClosing(int slot) { - return inv.getStackInSlotOnClosing(slot); - } + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + return inv.getStackInSlotOnClosing(slot); + } - @Override - public boolean hasCustomInventoryName() { - return inv.hasCustomInventoryName(); - } + @Override + public boolean hasCustomInventoryName() { + return inv.hasCustomInventoryName(); + } - @Override - public boolean isItemValidForSlot(int slot, ItemStack stack) { - return !checkItems || inv.isItemValidForSlot(slot, stack); - } + @Override + public boolean isItemValidForSlot(int slot, ItemStack stack) { + return !checkItems || inv.isItemValidForSlot(slot, stack); + } - @Override - public int[] getAccessibleSlotsFromSide(int s) { - return inv.getAccessibleSlotsFromSide(side); - } + @Override + public int[] getAccessibleSlotsFromSide(int s) { + return inv.getAccessibleSlotsFromSide(side); + } - @Override - public boolean canInsertItem(int slot, ItemStack stack, int s) { - return !checkItems || inv.canInsertItem(slot, stack, side); - } - - @Override - public boolean canExtractItem(int slot, ItemStack stack, int s) { - return !checkItems || inv.canExtractItem(slot, stack, side); - } + @Override + public boolean canInsertItem(int slot, ItemStack stack, int s) { + return !checkItems || inv.canInsertItem(slot, stack, side); + } + @Override + public boolean canExtractItem(int slot, ItemStack stack, int s) { + return !checkItems || inv.canExtractItem(slot, stack, side); + } } diff --git a/src/main/java/forestry/core/items/EnumContainerType.java b/src/main/java/forestry/core/items/EnumContainerType.java index 7036ed309..bb4f49823 100644 --- a/src/main/java/forestry/core/items/EnumContainerType.java +++ b/src/main/java/forestry/core/items/EnumContainerType.java @@ -1,30 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.items; - -public enum EnumContainerType { - GLASS("glass"), - JAR("jar"), - CAN("can"), - CAPSULE("waxCapsule"), - REFRACTORY("refractory"), - BUCKET("bucket"); - - private final String name; - - EnumContainerType(String name) { - this.name = name; - } - - public String getContainerNameKey() { - return name; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.items; + +public enum EnumContainerType { + GLASS("glass"), + JAR("jar"), + CAN("can"), + CAPSULE("waxCapsule"), + REFRACTORY("refractory"), + BUCKET("bucket"); + + private final String name; + + EnumContainerType(String name) { + this.name = name; + } + + public String getContainerNameKey() { + return name; + } +} diff --git a/src/main/java/forestry/core/items/EnumElectronTube.java b/src/main/java/forestry/core/items/EnumElectronTube.java index 6aa5b501f..4da5cd27e 100644 --- a/src/main/java/forestry/core/items/EnumElectronTube.java +++ b/src/main/java/forestry/core/items/EnumElectronTube.java @@ -1,86 +1,89 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.items; - -import forestry.api.recipes.RecipeManagers; -import forestry.core.fluids.Fluids; -import forestry.core.recipes.RecipeUtil; -import forestry.plugins.PluginCore; -import net.minecraft.item.ItemStack; - -import java.awt.Color; - -public enum EnumElectronTube implements ItemOverlay.IOverlayInfo { - COPPER(new Color(0xe3b78e)), - TIN(new Color(0xE6F8FF)), - BRONZE(new Color(0xddc276)), - IRON(new Color(0xCCCCCC)), - GOLD(new Color(0xffff8b)), - DIAMOND(new Color(0x8CF5E3)), - OBSIDIAN(new Color(0x866bc0)), - BLAZE(new Color(0xd96600), new Color(0xFFF87E)), - RUBBER(new Color(0x444444)), - EMERALD(new Color(0x00CC41)), - APATITE(new Color(0x579CD9)), - LAPIS(new Color(0x1c57c6)), - ENDER(new Color(0x33adad), new Color(0x255661)), - URANIUM(new Color(0xFF00CC41), new Color(0x33adad)); - - public static final EnumElectronTube[] VALUES = values(); - - private final String name; - private final int primaryColor; - private final int secondaryColor; - - EnumElectronTube(Color secondaryColor) { - this(secondaryColor, Color.WHITE); - } - - EnumElectronTube(Color secondaryColor, Color primaryColor) { - this.name = "ex-" + ordinal(); - this.primaryColor = primaryColor.getRGB(); - this.secondaryColor = secondaryColor.getRGB(); - } - - @Override - public String getName() { - return name; - } - - @Override - public int getPrimaryColor() { - return primaryColor; - } - - @Override - public int getSecondaryColor() { - return secondaryColor; - } - - @Override - public boolean isSecret() { - return false; - } - - public void registerTubeRecipe(ItemStack stack) { - if (stack != null){ - for (Object stackOreDict : RecipeUtil.getOreDictRecipeEquivalents(stack)) { - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), PluginCore.items.tubes.get(this, 4), - new Object[]{" X ", "#X#", "XXX", '#', "dustRedstone", 'X', stackOreDict}); - } - } - } - - public void registerTubeRecipe(String stack) { - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), PluginCore.items.tubes.get(this, 4), - new Object[]{" X ", "#X#", "XXX", '#', "dustRedstone", 'X', stack}); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.items; + +import forestry.api.recipes.RecipeManagers; +import forestry.core.fluids.Fluids; +import forestry.core.recipes.RecipeUtil; +import forestry.plugins.PluginCore; +import java.awt.Color; +import net.minecraft.item.ItemStack; + +public enum EnumElectronTube implements ItemOverlay.IOverlayInfo { + COPPER(new Color(0xe3b78e)), + TIN(new Color(0xE6F8FF)), + BRONZE(new Color(0xddc276)), + IRON(new Color(0xCCCCCC)), + GOLD(new Color(0xffff8b)), + DIAMOND(new Color(0x8CF5E3)), + OBSIDIAN(new Color(0x866bc0)), + BLAZE(new Color(0xd96600), new Color(0xFFF87E)), + RUBBER(new Color(0x444444)), + EMERALD(new Color(0x00CC41)), + APATITE(new Color(0x579CD9)), + LAPIS(new Color(0x1c57c6)), + ENDER(new Color(0x33adad), new Color(0x255661)), + URANIUM(new Color(0xFF00CC41), new Color(0x33adad)); + + public static final EnumElectronTube[] VALUES = values(); + + private final String name; + private final int primaryColor; + private final int secondaryColor; + + EnumElectronTube(Color secondaryColor) { + this(secondaryColor, Color.WHITE); + } + + EnumElectronTube(Color secondaryColor, Color primaryColor) { + this.name = "ex-" + ordinal(); + this.primaryColor = primaryColor.getRGB(); + this.secondaryColor = secondaryColor.getRGB(); + } + + @Override + public String getName() { + return name; + } + + @Override + public int getPrimaryColor() { + return primaryColor; + } + + @Override + public int getSecondaryColor() { + return secondaryColor; + } + + @Override + public boolean isSecret() { + return false; + } + + public void registerTubeRecipe(ItemStack stack) { + if (stack != null) { + for (Object stackOreDict : RecipeUtil.getOreDictRecipeEquivalents(stack)) { + RecipeManagers.fabricatorManager.addRecipe( + null, Fluids.GLASS.getFluid(500), PluginCore.items.tubes.get(this, 4), new Object[] { + " X ", "#X#", "XXX", '#', "dustRedstone", 'X', stackOreDict + }); + } + } + } + + public void registerTubeRecipe(String stack) { + RecipeManagers.fabricatorManager.addRecipe( + null, Fluids.GLASS.getFluid(500), PluginCore.items.tubes.get(this, 4), new Object[] { + " X ", "#X#", "XXX", '#', "dustRedstone", 'X', stack + }); + } +} diff --git a/src/main/java/forestry/core/items/ICraftingPlan.java b/src/main/java/forestry/core/items/ICraftingPlan.java index 7f793474d..c911ab9e7 100644 --- a/src/main/java/forestry/core/items/ICraftingPlan.java +++ b/src/main/java/forestry/core/items/ICraftingPlan.java @@ -13,5 +13,5 @@ package forestry.core.items; import net.minecraft.item.ItemStack; public interface ICraftingPlan { - ItemStack planUsed(ItemStack plan, ItemStack result); + ItemStack planUsed(ItemStack plan, ItemStack result); } diff --git a/src/main/java/forestry/core/items/ItemArmorNaturalist.java b/src/main/java/forestry/core/items/ItemArmorNaturalist.java index d849edb5e..f22b59c09 100755 --- a/src/main/java/forestry/core/items/ItemArmorNaturalist.java +++ b/src/main/java/forestry/core/items/ItemArmorNaturalist.java @@ -10,6 +10,13 @@ ******************************************************************************/ package forestry.core.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.core.IArmorNaturalist; +import forestry.core.CreativeTabForestry; +import forestry.core.config.Constants; +import forestry.core.render.TextureManager; +import forestry.core.utils.StringUtil; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; @@ -17,58 +24,48 @@ import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.core.IArmorNaturalist; -import forestry.core.CreativeTabForestry; -import forestry.core.config.Constants; -import forestry.core.render.TextureManager; -import forestry.core.utils.StringUtil; - public class ItemArmorNaturalist extends ItemArmor implements IArmorNaturalist { - public ItemArmorNaturalist() { - super(ArmorMaterial.CLOTH, 0, 0); - this.setMaxDamage(100); - setCreativeTab(CreativeTabForestry.tabForestry); - } + public ItemArmorNaturalist() { + super(ArmorMaterial.CLOTH, 0, 0); + this.setMaxDamage(100); + setCreativeTab(CreativeTabForestry.tabForestry); + } - @Override - public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) { - return Constants.ID + ":" + Constants.TEXTURE_NATURALIST_ARMOR_PRIMARY; - } + @Override + public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) { + return Constants.ID + ":" + Constants.TEXTURE_NATURALIST_ARMOR_PRIMARY; + } - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - itemIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this)); - } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + itemIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this)); + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamageForRenderPass(int par1, int par2) { - return itemIcon; - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamageForRenderPass(int par1, int par2) { + return itemIcon; + } - @Override - public boolean requiresMultipleRenderPasses() { - return false; - } + @Override + public boolean requiresMultipleRenderPasses() { + return false; + } - @Override - public int getColorFromItemStack(ItemStack itemstack, int renderPass) { - return 0xffffff; - } + @Override + public int getColorFromItemStack(ItemStack itemstack, int renderPass) { + return 0xffffff; + } - @Override - public boolean hasColor(ItemStack itemstack) { - return false; - } - - @Override - public boolean canSeePollination(EntityPlayer player, ItemStack armor, boolean doSee) { - return armorType == 0; - } + @Override + public boolean hasColor(ItemStack itemstack) { + return false; + } + @Override + public boolean canSeePollination(EntityPlayer player, ItemStack armor, boolean doSee) { + return armorType == 0; + } } diff --git a/src/main/java/forestry/core/items/ItemAssemblyKit.java b/src/main/java/forestry/core/items/ItemAssemblyKit.java index 2a99e3ec5..38c31d19f 100755 --- a/src/main/java/forestry/core/items/ItemAssemblyKit.java +++ b/src/main/java/forestry/core/items/ItemAssemblyKit.java @@ -16,20 +16,21 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.World; public class ItemAssemblyKit extends ItemForestry { - private final ItemStack assembled; + private final ItemStack assembled; - public ItemAssemblyKit(ItemStack assembled) { - maxStackSize = 24; - this.assembled = assembled; - } + public ItemAssemblyKit(ItemStack assembled) { + maxStackSize = 24; + this.assembled = assembled; + } - @Override - public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { - if (!world.isRemote) { - itemstack.stackSize--; - EntityItem entity = new EntityItem(world, entityplayer.posX, entityplayer.posY, entityplayer.posZ, assembled.copy()); - world.spawnEntityInWorld(entity); - } - return itemstack; - } + @Override + public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { + if (!world.isRemote) { + itemstack.stackSize--; + EntityItem entity = + new EntityItem(world, entityplayer.posX, entityplayer.posY, entityplayer.posZ, assembled.copy()); + world.spawnEntityInWorld(entity); + } + return itemstack; + } } diff --git a/src/main/java/forestry/core/items/ItemBlockForestry.java b/src/main/java/forestry/core/items/ItemBlockForestry.java index 2940ca1de..952d6b850 100644 --- a/src/main/java/forestry/core/items/ItemBlockForestry.java +++ b/src/main/java/forestry/core/items/ItemBlockForestry.java @@ -10,6 +10,10 @@ ******************************************************************************/ package forestry.core.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.tiles.TileForestry; +import forestry.core.tiles.TileUtil; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; @@ -17,57 +21,62 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.tiles.TileForestry; -import forestry.core.tiles.TileUtil; - public class ItemBlockForestry extends ItemBlock { - public ItemBlockForestry(Block block) { - super(block); - setMaxDamage(0); - setHasSubtypes(true); - } + public ItemBlockForestry(Block block) { + super(block); + setMaxDamage(0); + setHasSubtypes(true); + } - @Override - public int getMetadata(int i) { - return i; - } + @Override + public int getMetadata(int i) { + return i; + } - protected Block getBlock() { - return field_150939_a; - } + protected Block getBlock() { + return field_150939_a; + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamage(int meta) { - return this.getBlock().getIcon(1, meta); - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamage(int meta) { + return this.getBlock().getIcon(1, meta); + } - @Override - public String getUnlocalizedName(ItemStack itemstack) { - return getBlock().getUnlocalizedName() + "." + itemstack.getItemDamage(); - } + @Override + public String getUnlocalizedName(ItemStack itemstack) { + return getBlock().getUnlocalizedName() + "." + itemstack.getItemDamage(); + } - @Override - public boolean placeBlockAt(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metadata) { - boolean placed = super.placeBlockAt(stack, player, world, x, y, z, side, hitX, hitY, hitZ, metadata); + @Override + public boolean placeBlockAt( + ItemStack stack, + EntityPlayer player, + World world, + int x, + int y, + int z, + int side, + float hitX, + float hitY, + float hitZ, + int metadata) { + boolean placed = super.placeBlockAt(stack, player, world, x, y, z, side, hitX, hitY, hitZ, metadata); - TileForestry tile = TileUtil.getTile(world, x, y, z, TileForestry.class); + TileForestry tile = TileUtil.getTile(world, x, y, z, TileForestry.class); - if (tile != null) { - if (stack.getItem() instanceof ItemBlockNBT && stack.hasTagCompound()) { - tile.readFromNBT(stack.getTagCompound()); - tile.xCoord = x; - tile.yCoord = y; - tile.zCoord = z; - } + if (tile != null) { + if (stack.getItem() instanceof ItemBlockNBT && stack.hasTagCompound()) { + tile.readFromNBT(stack.getTagCompound()); + tile.xCoord = x; + tile.yCoord = y; + tile.zCoord = z; + } - tile.rotateAfterPlacement(player, side); - } + tile.rotateAfterPlacement(player, side); + } - return placed; - } + return placed; + } } diff --git a/src/main/java/forestry/core/items/ItemBlockNBT.java b/src/main/java/forestry/core/items/ItemBlockNBT.java index b446aed33..540e88800 100644 --- a/src/main/java/forestry/core/items/ItemBlockNBT.java +++ b/src/main/java/forestry/core/items/ItemBlockNBT.java @@ -11,24 +11,23 @@ package forestry.core.items; import java.util.List; - import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; public class ItemBlockNBT extends ItemBlockForestry { - public ItemBlockNBT(Block block) { - super(block); - } + public ItemBlockNBT(Block block) { + super(block); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void addInformation(ItemStack itemstack, EntityPlayer player, List info, boolean par4) { - if (!itemstack.hasTagCompound()) { - return; - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void addInformation(ItemStack itemstack, EntityPlayer player, List info, boolean par4) { + if (!itemstack.hasTagCompound()) { + return; + } - info.add("There are still some scribbles on this."); - } + info.add("There are still some scribbles on this."); + } } diff --git a/src/main/java/forestry/core/items/ItemBlockTyped.java b/src/main/java/forestry/core/items/ItemBlockTyped.java index 9271a9128..8a7b84bb8 100644 --- a/src/main/java/forestry/core/items/ItemBlockTyped.java +++ b/src/main/java/forestry/core/items/ItemBlockTyped.java @@ -10,34 +10,33 @@ ******************************************************************************/ package forestry.core.items; +import forestry.core.blocks.IItemTyped; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; -import forestry.core.blocks.IItemTyped; - /** * For blocks whose type depends on metadata. * This allows control over which localized name maps to which meta value. */ public class ItemBlockTyped extends ItemBlockForestry { - public ItemBlockTyped(Block block) { - super(block); - } + public ItemBlockTyped(Block block) { + super(block); + } - @Override - @SuppressWarnings("rawtypes") - public String getUnlocalizedName(ItemStack itemstack) { - Block block = getBlock(); - if (block instanceof IItemTyped) { - IItemTyped blockTyped = (IItemTyped) block; - Enum type = blockTyped.getTypeFromMeta(itemstack.getItemDamage()); - if (type != null) { - return getBlock().getUnlocalizedName() + "." + type.ordinal(); - } else { - return null; - } - } - return super.getUnlocalizedName(itemstack); - } + @Override + @SuppressWarnings("rawtypes") + public String getUnlocalizedName(ItemStack itemstack) { + Block block = getBlock(); + if (block instanceof IItemTyped) { + IItemTyped blockTyped = (IItemTyped) block; + Enum type = blockTyped.getTypeFromMeta(itemstack.getItemDamage()); + if (type != null) { + return getBlock().getUnlocalizedName() + "." + type.ordinal(); + } else { + return null; + } + } + return super.getUnlocalizedName(itemstack); + } } diff --git a/src/main/java/forestry/core/items/ItemCraftingMaterial.java b/src/main/java/forestry/core/items/ItemCraftingMaterial.java index a1cba582e..8208ccc37 100644 --- a/src/main/java/forestry/core/items/ItemCraftingMaterial.java +++ b/src/main/java/forestry/core/items/ItemCraftingMaterial.java @@ -10,105 +10,103 @@ ******************************************************************************/ package forestry.core.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.render.TextureManager; import java.util.List; - import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.render.TextureManager; - public class ItemCraftingMaterial extends ItemForestry { - private final String[] definition = new String[]{"pulsatingDust", "pulsatingMesh", "silkWisp", "wovenSilk", "dissipationCharge", "iceShard", "scentedPaneling"}; + private final String[] definition = new String[] { + "pulsatingDust", "pulsatingMesh", "silkWisp", "wovenSilk", "dissipationCharge", "iceShard", "scentedPaneling" + }; - public ItemCraftingMaterial() { - super(); - setMaxDamage(0); - setHasSubtypes(true); - } + public ItemCraftingMaterial() { + super(); + setMaxDamage(0); + setHasSubtypes(true); + } - @Override - public boolean isDamageable() { - return false; - } + @Override + public boolean isDamageable() { + return false; + } - @Override - public boolean isRepairable() { - return false; - } + @Override + public boolean isRepairable() { + return false; + } - @Override - public String getUnlocalizedName(ItemStack stack) { - if (stack.getItemDamage() >= definition.length || stack.getItemDamage() < 0) { - return "item.forestry.unknown"; - } else { - return super.getUnlocalizedName(stack) + "." + definition[stack.getItemDamage()]; - } - } + @Override + public String getUnlocalizedName(ItemStack stack) { + if (stack.getItemDamage() >= definition.length || stack.getItemDamage() < 0) { + return "item.forestry.unknown"; + } else { + return super.getUnlocalizedName(stack) + "." + definition[stack.getItemDamage()]; + } + } - /* ICONS */ - @SideOnly(Side.CLIENT) - private IIcon[] icons; + /* ICONS */ + @SideOnly(Side.CLIENT) + private IIcon[] icons; - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { - icons = new IIcon[definition.length]; - for (int i = 0; i < definition.length; i++) { - icons[i] = TextureManager.registerTex(register, definition[i]); - } + icons = new IIcon[definition.length]; + for (int i = 0; i < definition.length; i++) { + icons[i] = TextureManager.registerTex(register, definition[i]); + } + } - } + @Override + public IIcon getIconFromDamage(int damage) { + if (damage >= definition.length || damage < 0) { + return icons[0]; + } else { + return icons[damage]; + } + } - @Override - public IIcon getIconFromDamage(int damage) { - if (damage >= definition.length || damage < 0) { - return icons[0]; - } else { - return icons[damage]; - } - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + for (int i = 0; i < 7; i++) { + itemList.add(new ItemStack(this, 1, i)); + } + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - for (int i = 0; i < 7; i++) { - itemList.add(new ItemStack(this, 1, i)); - } - } + public ItemStack getPulsatingDust() { + return new ItemStack(this, 1, 0); + } - public ItemStack getPulsatingDust() { - return new ItemStack(this, 1, 0); - } + public ItemStack getPulsatingMesh() { + return new ItemStack(this, 1, 1); + } - public ItemStack getPulsatingMesh() { - return new ItemStack(this, 1, 1); - } + public ItemStack getSilkWisp() { + return new ItemStack(this, 1, 2); + } - public ItemStack getSilkWisp() { - return new ItemStack(this, 1, 2); - } + public ItemStack getWovenSilk() { + return new ItemStack(this, 1, 3); + } - public ItemStack getWovenSilk() { - return new ItemStack(this, 1, 3); - } + public ItemStack getDissipationCharge() { + return new ItemStack(this, 1, 4); + } - public ItemStack getDissipationCharge() { - return new ItemStack(this, 1, 4); - } + public ItemStack getIceShard(int amount) { + return new ItemStack(this, amount, 5); + } - public ItemStack getIceShard(int amount) { - return new ItemStack(this, amount, 5); - } - - public ItemStack getScentedPaneling() { - return new ItemStack(this, 1, 6); - } + public ItemStack getScentedPaneling() { + return new ItemStack(this, 1, 6); + } } diff --git a/src/main/java/forestry/core/items/ItemCrated.java b/src/main/java/forestry/core/items/ItemCrated.java index 5cb3deb48..4aeb25eed 100755 --- a/src/main/java/forestry/core/items/ItemCrated.java +++ b/src/main/java/forestry/core/items/ItemCrated.java @@ -10,69 +10,67 @@ ******************************************************************************/ package forestry.core.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.proxy.Proxies; +import forestry.core.render.TextureManager; +import forestry.core.utils.ItemStackUtil; +import forestry.core.utils.StringUtil; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.proxy.Proxies; -import forestry.core.render.TextureManager; -import forestry.core.utils.ItemStackUtil; -import forestry.core.utils.StringUtil; - public class ItemCrated extends ItemForestry { - private final ItemStack contained; - private final boolean usesOreDict; + private final ItemStack contained; + private final boolean usesOreDict; - public ItemCrated(ItemStack contained, boolean usesOreDict) { - this.contained = contained; - this.usesOreDict = usesOreDict; - } + public ItemCrated(ItemStack contained, boolean usesOreDict) { + this.contained = contained; + this.usesOreDict = usesOreDict; + } - public boolean usesOreDict() { - return usesOreDict; - } + public boolean usesOreDict() { + return usesOreDict; + } - public ItemStack getContained() { - return contained; - } + public ItemStack getContained() { + return contained; + } - @Override - public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { - if (!world.isRemote) { - if (contained == null || itemstack.stackSize == 0) { - return itemstack; - } + @Override + public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { + if (!world.isRemote) { + if (contained == null || itemstack.stackSize == 0) { + return itemstack; + } - itemstack.stackSize--; + itemstack.stackSize--; - ItemStack dropStack = contained.copy(); - dropStack.stackSize = 9; - ItemStackUtil.dropItemStackAsEntity(dropStack, world, entityplayer.posX, entityplayer.posY, entityplayer.posZ, 40); - } - return itemstack; - } + ItemStack dropStack = contained.copy(); + dropStack.stackSize = 9; + ItemStackUtil.dropItemStackAsEntity( + dropStack, world, entityplayer.posX, entityplayer.posY, entityplayer.posZ, 40); + } + return itemstack; + } - @Override - public String getItemStackDisplayName(ItemStack itemstack) { - if (contained == null) { - return StatCollector.translateToLocal("item.for.crate.name"); - } else { - String containedName = Proxies.common.getDisplayName(contained); - return StringUtil.localizeAndFormat("item.crated.grammar", containedName); - } - } - - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - String textureName = (contained == null) ? "crate" : "crate-filled"; - itemIcon = TextureManager.registerTex(register, textureName); - } + @Override + public String getItemStackDisplayName(ItemStack itemstack) { + if (contained == null) { + return StatCollector.translateToLocal("item.for.crate.name"); + } else { + String containedName = Proxies.common.getDisplayName(contained); + return StringUtil.localizeAndFormat("item.crated.grammar", containedName); + } + } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + String textureName = (contained == null) ? "crate" : "crate-filled"; + itemIcon = TextureManager.registerTex(register, textureName); + } } diff --git a/src/main/java/forestry/core/items/ItemElectronTube.java b/src/main/java/forestry/core/items/ItemElectronTube.java index a088c6dcf..7caa4fbbf 100644 --- a/src/main/java/forestry/core/items/ItemElectronTube.java +++ b/src/main/java/forestry/core/items/ItemElectronTube.java @@ -1,89 +1,87 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.items; - -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Multimap; - -import java.util.Collection; -import java.util.List; - -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumChatFormatting; - -import forestry.api.circuits.ChipsetManager; -import forestry.api.circuits.ICircuit; -import forestry.api.circuits.ICircuitLayout; -import forestry.core.CreativeTabForestry; -import forestry.core.circuits.SolderManager; -import forestry.core.config.Config; -import forestry.core.proxy.Proxies; -import forestry.core.utils.StringUtil; - -public class ItemElectronTube extends ItemOverlay { - - public ItemElectronTube() { - super(CreativeTabForestry.tabForestry, EnumElectronTube.VALUES); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { - Multimap circuits = getCircuits(itemstack); - if (circuits.size() > 0) { - if (Proxies.common.isShiftDown()) { - for (ICircuitLayout circuitLayout : circuits.keys()) { - String circuitLayoutName = circuitLayout.getUsage(); - list.add(EnumChatFormatting.WHITE.toString() + EnumChatFormatting.UNDERLINE + circuitLayoutName); - for (ICircuit circuit : circuits.get(circuitLayout)) { - circuit.addTooltip(list); - } - } - } else { - list.add(EnumChatFormatting.ITALIC + "<" + StringUtil.localize("gui.tooltip.tmi") + ">"); - } - } else { - list.add("<" + StringUtil.localize("gui.noeffect") + ">"); - } - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - for (int i = 0; i < overlays.length; i++) { - if (Config.isDebug || !overlays[i].isSecret()) { - ItemStack itemStack = new ItemStack(this, 1, i); - if (Config.isDebug || getCircuits(itemStack).size() > 0) { - itemList.add(itemStack); - } - } - } - } - - private static Multimap getCircuits(ItemStack itemStack) { - Multimap circuits = ArrayListMultimap.create(); - Collection allLayouts = ChipsetManager.circuitRegistry.getRegisteredLayouts().values(); - for (ICircuitLayout circuitLayout : allLayouts) { - ICircuit circuit = SolderManager.getCircuit(circuitLayout, itemStack); - if (circuit != null) { - circuits.put(circuitLayout, circuit); - } - } - return circuits; - } - - public ItemStack get(EnumElectronTube type, int amount) { - return new ItemStack(this, amount, type.ordinal()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.items; + +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Multimap; +import forestry.api.circuits.ChipsetManager; +import forestry.api.circuits.ICircuit; +import forestry.api.circuits.ICircuitLayout; +import forestry.core.CreativeTabForestry; +import forestry.core.circuits.SolderManager; +import forestry.core.config.Config; +import forestry.core.proxy.Proxies; +import forestry.core.utils.StringUtil; +import java.util.Collection; +import java.util.List; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; + +public class ItemElectronTube extends ItemOverlay { + + public ItemElectronTube() { + super(CreativeTabForestry.tabForestry, EnumElectronTube.VALUES); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { + Multimap circuits = getCircuits(itemstack); + if (circuits.size() > 0) { + if (Proxies.common.isShiftDown()) { + for (ICircuitLayout circuitLayout : circuits.keys()) { + String circuitLayoutName = circuitLayout.getUsage(); + list.add(EnumChatFormatting.WHITE.toString() + EnumChatFormatting.UNDERLINE + circuitLayoutName); + for (ICircuit circuit : circuits.get(circuitLayout)) { + circuit.addTooltip(list); + } + } + } else { + list.add(EnumChatFormatting.ITALIC + "<" + StringUtil.localize("gui.tooltip.tmi") + ">"); + } + } else { + list.add("<" + StringUtil.localize("gui.noeffect") + ">"); + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + for (int i = 0; i < overlays.length; i++) { + if (Config.isDebug || !overlays[i].isSecret()) { + ItemStack itemStack = new ItemStack(this, 1, i); + if (Config.isDebug || getCircuits(itemStack).size() > 0) { + itemList.add(itemStack); + } + } + } + } + + private static Multimap getCircuits(ItemStack itemStack) { + Multimap circuits = ArrayListMultimap.create(); + Collection allLayouts = + ChipsetManager.circuitRegistry.getRegisteredLayouts().values(); + for (ICircuitLayout circuitLayout : allLayouts) { + ICircuit circuit = SolderManager.getCircuit(circuitLayout, itemStack); + if (circuit != null) { + circuits.put(circuitLayout, circuit); + } + } + return circuits; + } + + public ItemStack get(EnumElectronTube type, int amount) { + return new ItemStack(this, amount, type.ordinal()); + } +} diff --git a/src/main/java/forestry/core/items/ItemForestry.java b/src/main/java/forestry/core/items/ItemForestry.java index df4e3185f..acb702eea 100755 --- a/src/main/java/forestry/core/items/ItemForestry.java +++ b/src/main/java/forestry/core/items/ItemForestry.java @@ -10,44 +10,41 @@ ******************************************************************************/ package forestry.core.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.CreativeTabForestry; +import forestry.core.render.TextureManager; +import forestry.core.utils.StringUtil; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; - import net.minecraftforge.oredict.OreDictionary; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.CreativeTabForestry; -import forestry.core.render.TextureManager; -import forestry.core.utils.StringUtil; - public class ItemForestry extends Item { - public ItemForestry() { - setCreativeTab(CreativeTabForestry.tabForestry); - } + public ItemForestry() { + setCreativeTab(CreativeTabForestry.tabForestry); + } - public ItemForestry(CreativeTabs creativeTab) { - setCreativeTab(creativeTab); - } + public ItemForestry(CreativeTabs creativeTab) { + setCreativeTab(creativeTab); + } - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - itemIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this)); - } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + itemIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this)); + } - public ItemStack getItemStack() { - return new ItemStack(this); - } + public ItemStack getItemStack() { + return new ItemStack(this); + } - public ItemStack getItemStack(int amount) { - return new ItemStack(this, amount); - } + public ItemStack getItemStack(int amount) { + return new ItemStack(this, amount); + } - public ItemStack getWildcard() { - return new ItemStack(this, 1, OreDictionary.WILDCARD_VALUE); - } + public ItemStack getWildcard() { + return new ItemStack(this, 1, OreDictionary.WILDCARD_VALUE); + } } diff --git a/src/main/java/forestry/core/items/ItemForestryBonemeal.java b/src/main/java/forestry/core/items/ItemForestryBonemeal.java index 7da2cc0de..4e1d404db 100644 --- a/src/main/java/forestry/core/items/ItemForestryBonemeal.java +++ b/src/main/java/forestry/core/items/ItemForestryBonemeal.java @@ -1,30 +1,40 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.items; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemDye; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -public class ItemForestryBonemeal extends ItemForestry { - @Override - public boolean onItemUse(ItemStack itemstack, EntityPlayer player, World world, int x, int y, int z, int par7, float facingX, float facingY, float facingZ) { - if (ItemDye.applyBonemeal(itemstack, world, x, y, z, player)) { - if (!world.isRemote) { - world.playAuxSFX(2005, x, y, z, 0); - } - - return true; - } - return super.onItemUse(itemstack, player, world, x, y, z, par7, facingX, facingY, facingZ); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.items; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemDye; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; + +public class ItemForestryBonemeal extends ItemForestry { + @Override + public boolean onItemUse( + ItemStack itemstack, + EntityPlayer player, + World world, + int x, + int y, + int z, + int par7, + float facingX, + float facingY, + float facingZ) { + if (ItemDye.applyBonemeal(itemstack, world, x, y, z, player)) { + if (!world.isRemote) { + world.playAuxSFX(2005, x, y, z, 0); + } + + return true; + } + return super.onItemUse(itemstack, player, world, x, y, z, par7, facingX, facingY, facingZ); + } +} diff --git a/src/main/java/forestry/core/items/ItemForestryFood.java b/src/main/java/forestry/core/items/ItemForestryFood.java index 7deb69877..39a897d7d 100755 --- a/src/main/java/forestry/core/items/ItemForestryFood.java +++ b/src/main/java/forestry/core/items/ItemForestryFood.java @@ -10,49 +10,46 @@ ******************************************************************************/ package forestry.core.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.CreativeTabForestry; +import forestry.core.render.TextureManager; +import forestry.core.utils.StringUtil; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.EnumAction; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.CreativeTabForestry; -import forestry.core.render.TextureManager; -import forestry.core.utils.StringUtil; - public class ItemForestryFood extends ItemFood { - private boolean isDrink = false; + private boolean isDrink = false; - public ItemForestryFood(int heal) { - this(heal, 0.6f); - } + public ItemForestryFood(int heal) { + this(heal, 0.6f); + } - public ItemForestryFood(int heal, float saturation) { - super(heal, saturation, false); - setCreativeTab(CreativeTabForestry.tabForestry); - } + public ItemForestryFood(int heal, float saturation) { + super(heal, saturation, false); + setCreativeTab(CreativeTabForestry.tabForestry); + } - @Override - public EnumAction getItemUseAction(ItemStack itemstack) { - if (isDrink) { - return EnumAction.drink; - } else { - return EnumAction.eat; - } - } + @Override + public EnumAction getItemUseAction(ItemStack itemstack) { + if (isDrink) { + return EnumAction.drink; + } else { + return EnumAction.eat; + } + } - public ItemForestryFood setIsDrink() { - isDrink = true; - return this; - } - - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - itemIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this)); - } + public ItemForestryFood setIsDrink() { + isDrink = true; + return this; + } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + itemIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this)); + } } diff --git a/src/main/java/forestry/core/items/ItemForestryMultiPass.java b/src/main/java/forestry/core/items/ItemForestryMultiPass.java index 90eb18409..5ec539ea6 100644 --- a/src/main/java/forestry/core/items/ItemForestryMultiPass.java +++ b/src/main/java/forestry/core/items/ItemForestryMultiPass.java @@ -10,41 +10,39 @@ ******************************************************************************/ package forestry.core.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.render.TextureManager; +import forestry.core.utils.StringUtil; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.render.TextureManager; -import forestry.core.utils.StringUtil; - public class ItemForestryMultiPass extends ItemForestry { - /* ICONS */ - @SideOnly(Side.CLIENT) - private IIcon[] icons; + /* ICONS */ + @SideOnly(Side.CLIENT) + private IIcon[] icons; - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - icons = new IIcon[2]; - icons[0] = TextureManager.registerTex(register, StringUtil.cleanItemName(this) + ".0"); - icons[1] = TextureManager.registerTex(register, StringUtil.cleanItemName(this) + ".1"); - } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + icons = new IIcon[2]; + icons[0] = TextureManager.registerTex(register, StringUtil.cleanItemName(this) + ".0"); + icons[1] = TextureManager.registerTex(register, StringUtil.cleanItemName(this) + ".1"); + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamageForRenderPass(int i, int pass) { - if (pass > 0) { - return icons[0]; - } else { - return icons[1]; - } - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamageForRenderPass(int i, int pass) { + if (pass > 0) { + return icons[0]; + } else { + return icons[1]; + } + } - @Override - public boolean requiresMultipleRenderPasses() { - return true; - } + @Override + public boolean requiresMultipleRenderPasses() { + return true; + } } diff --git a/src/main/java/forestry/core/items/ItemForestryTool.java b/src/main/java/forestry/core/items/ItemForestryTool.java index 27b8bdec4..bc606c09c 100755 --- a/src/main/java/forestry/core/items/ItemForestryTool.java +++ b/src/main/java/forestry/core/items/ItemForestryTool.java @@ -10,76 +10,74 @@ ******************************************************************************/ package forestry.core.items; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import forestry.core.utils.ItemStackUtil; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; - import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; - -import forestry.core.utils.ItemStackUtil; - public class ItemForestryTool extends ItemForestry { - private final ItemStack remnants; - private float efficiencyOnProperMaterial; + private final ItemStack remnants; + private float efficiencyOnProperMaterial; - public ItemForestryTool(ItemStack remnants) { - this.maxStackSize = 1; - efficiencyOnProperMaterial = 6F; - setMaxDamage(200); - this.remnants = remnants; - if (remnants != null) { - MinecraftForge.EVENT_BUS.register(this); - } - } + public ItemForestryTool(ItemStack remnants) { + this.maxStackSize = 1; + efficiencyOnProperMaterial = 6F; + setMaxDamage(200); + this.remnants = remnants; + if (remnants != null) { + MinecraftForge.EVENT_BUS.register(this); + } + } - public void setEfficiencyOnProperMaterial(float efficiencyOnProperMaterial) { - this.efficiencyOnProperMaterial = efficiencyOnProperMaterial; - } + public void setEfficiencyOnProperMaterial(float efficiencyOnProperMaterial) { + this.efficiencyOnProperMaterial = efficiencyOnProperMaterial; + } - @Override - public float getDigSpeed(ItemStack itemstack, Block block, int metadata) { - if (ForgeHooks.isToolEffective(itemstack, block, metadata)) { - return efficiencyOnProperMaterial; - } + @Override + public float getDigSpeed(ItemStack itemstack, Block block, int metadata) { + if (ForgeHooks.isToolEffective(itemstack, block, metadata)) { + return efficiencyOnProperMaterial; + } - return super.getDigSpeed(itemstack, block, metadata); - } + return super.getDigSpeed(itemstack, block, metadata); + } - @Override - public boolean canHarvestBlock(Block block, ItemStack stack) { - return ForgeHooks.canToolHarvestBlock(block, 0, stack); - } + @Override + public boolean canHarvestBlock(Block block, ItemStack stack) { + return ForgeHooks.canToolHarvestBlock(block, 0, stack); + } - @SubscribeEvent - public void onDestroyCurrentItem(PlayerDestroyItemEvent event) { - if (event.original == null || event.original.getItem() != this) { - return; - } + @SubscribeEvent + public void onDestroyCurrentItem(PlayerDestroyItemEvent event) { + if (event.original == null || event.original.getItem() != this) { + return; + } - EntityPlayer player = event.entityPlayer; - World world = player.worldObj; + EntityPlayer player = event.entityPlayer; + World world = player.worldObj; - if (!world.isRemote && remnants != null) { - ItemStackUtil.dropItemStackAsEntity(remnants.copy(), world, player.posX, player.posY, player.posZ); - } - } + if (!world.isRemote && remnants != null) { + ItemStackUtil.dropItemStackAsEntity(remnants.copy(), world, player.posX, player.posY, player.posZ); + } + } - @Override - public boolean onBlockDestroyed(ItemStack itemstack, World world, Block block, int x, int y, int z, EntityLivingBase entityliving) { - if (block.getBlockHardness(world, x, y, z) != 0) { - itemstack.damageItem(1, entityliving); - } - return true; - } + @Override + public boolean onBlockDestroyed( + ItemStack itemstack, World world, Block block, int x, int y, int z, EntityLivingBase entityliving) { + if (block.getBlockHardness(world, x, y, z) != 0) { + itemstack.damageItem(1, entityliving); + } + return true; + } - @Override - public boolean isFull3D() { - return true; - } + @Override + public boolean isFull3D() { + return true; + } } diff --git a/src/main/java/forestry/core/items/ItemFruit.java b/src/main/java/forestry/core/items/ItemFruit.java index 9c3d15f17..321a1a85f 100755 --- a/src/main/java/forestry/core/items/ItemFruit.java +++ b/src/main/java/forestry/core/items/ItemFruit.java @@ -10,102 +10,106 @@ ******************************************************************************/ package forestry.core.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.render.TextureManager; +import forestry.plugins.PluginCore; import java.util.List; import java.util.Locale; - import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.render.TextureManager; -import forestry.plugins.PluginCore; - public class ItemFruit extends ItemForestryFood { - public enum EnumFruit { - CHERRY("cropCherry"), WALNUT("cropWalnut"), CHESTNUT("cropChestnut"), LEMON("cropLemon"), PLUM("cropPlum"), DATES("cropDate"), PAPAYA("cropPapaya");//, COCONUT("cropCoconut"); - public static final EnumFruit[] VALUES = values(); + public enum EnumFruit { + CHERRY("cropCherry"), + WALNUT("cropWalnut"), + CHESTNUT("cropChestnut"), + LEMON("cropLemon"), + PLUM("cropPlum"), + DATES("cropDate"), + PAPAYA("cropPapaya"); // , COCONUT("cropCoconut"); + public static final EnumFruit[] VALUES = values(); - private final String oreDict; + private final String oreDict; - EnumFruit(String oreDict) { - this.oreDict = oreDict; - } + EnumFruit(String oreDict) { + this.oreDict = oreDict; + } - private static IIcon[] icons; + private static IIcon[] icons; - public static void registerIcons(IIconRegister register) { - icons = new IIcon[VALUES.length]; - for (int i = 0; i < VALUES.length; i++) { - icons[i] = TextureManager.registerTex(register, "fruits/" + VALUES[i].toString().toLowerCase(Locale.ENGLISH)); - } - } + public static void registerIcons(IIconRegister register) { + icons = new IIcon[VALUES.length]; + for (int i = 0; i < VALUES.length; i++) { + icons[i] = TextureManager.registerTex( + register, "fruits/" + VALUES[i].toString().toLowerCase(Locale.ENGLISH)); + } + } - public IIcon getIcon() { - return icons[ordinal()]; - } + public IIcon getIcon() { + return icons[ordinal()]; + } - public ItemStack getStack() { - return getStack(1); - } + public ItemStack getStack() { + return getStack(1); + } - public ItemStack getStack(int qty) { - return new ItemStack(PluginCore.items.fruits, qty, ordinal()); - } + public ItemStack getStack(int qty) { + return new ItemStack(PluginCore.items.fruits, qty, ordinal()); + } - public String getOreDict() { - return oreDict; - } - } + public String getOreDict() { + return oreDict; + } + } - public ItemFruit() { - super(1, 0.2f); - setMaxDamage(0); - setHasSubtypes(true); - } + public ItemFruit() { + super(1, 0.2f); + setMaxDamage(0); + setHasSubtypes(true); + } - @Override - public boolean isDamageable() { - return false; - } + @Override + public boolean isDamageable() { + return false; + } - @Override - public boolean isRepairable() { - return false; - } + @Override + public boolean isRepairable() { + return false; + } - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - EnumFruit.registerIcons(register); - } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + EnumFruit.registerIcons(register); + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamage(int meta) { - return EnumFruit.values()[meta].getIcon(); - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamage(int meta) { + return EnumFruit.values()[meta].getIcon(); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - for (int i = 0; i < EnumFruit.values().length; i++) { - itemList.add(new ItemStack(this, 1, i)); - } - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + for (int i = 0; i < EnumFruit.values().length; i++) { + itemList.add(new ItemStack(this, 1, i)); + } + } - @Override - public String getUnlocalizedName(ItemStack stack) { - if (stack.getItemDamage() < 0 || stack.getItemDamage() >= EnumFruit.VALUES.length) { - return null; - } - - return super.getUnlocalizedName(stack) + "." + EnumFruit.VALUES[stack.getItemDamage()].name().toLowerCase(Locale.ENGLISH); - } + @Override + public String getUnlocalizedName(ItemStack stack) { + if (stack.getItemDamage() < 0 || stack.getItemDamage() >= EnumFruit.VALUES.length) { + return null; + } + return super.getUnlocalizedName(stack) + "." + + EnumFruit.VALUES[stack.getItemDamage()].name().toLowerCase(Locale.ENGLISH); + } } diff --git a/src/main/java/forestry/core/items/ItemLiquidContainer.java b/src/main/java/forestry/core/items/ItemLiquidContainer.java index 6b445dd08..65a753b43 100755 --- a/src/main/java/forestry/core/items/ItemLiquidContainer.java +++ b/src/main/java/forestry/core/items/ItemLiquidContainer.java @@ -10,12 +10,18 @@ ******************************************************************************/ package forestry.core.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.CreativeTabForestry; +import forestry.core.fluids.BlockForestryFluid; +import forestry.core.fluids.FluidHelper; +import forestry.core.proxy.Proxies; +import forestry.core.render.TextureManager; import java.awt.Color; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Random; - import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -28,325 +34,330 @@ import net.minecraft.util.IIcon; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.MovingObjectPosition.MovingObjectType; import net.minecraft.world.World; - import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.IFluidBlock; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.CreativeTabForestry; -import forestry.core.fluids.BlockForestryFluid; -import forestry.core.fluids.FluidHelper; -import forestry.core.proxy.Proxies; -import forestry.core.render.TextureManager; - public class ItemLiquidContainer extends ItemForestry { - private static final Map buckets = new HashMap<>(); + private static final Map buckets = new HashMap<>(); - private boolean isDrink = false; - private boolean isAlwaysEdible = false; + private boolean isDrink = false; + private boolean isAlwaysEdible = false; - private int healAmount = 0; - private float saturationModifier = 0.0f; + private int healAmount = 0; + private float saturationModifier = 0.0f; - private final EnumContainerType type; - private final Block contents; - private final Color color; + private final EnumContainerType type; + private final Block contents; + private final Color color; - public ItemLiquidContainer(EnumContainerType type, Block contents, Color color) { - super(CreativeTabForestry.tabForestry); - this.type = type; - this.contents = contents; - this.color = color; - if (type == EnumContainerType.BUCKET) { - setContainerItem(Items.bucket); - this.maxStackSize = 1; - buckets.put(contents, this); - } - } + public ItemLiquidContainer(EnumContainerType type, Block contents, Color color) { + super(CreativeTabForestry.tabForestry); + this.type = type; + this.contents = contents; + this.color = color; + if (type == EnumContainerType.BUCKET) { + setContainerItem(Items.bucket); + this.maxStackSize = 1; + buckets.put(contents, this); + } + } - public static ItemLiquidContainer getExistingBucket(Block contents) { - return buckets.get(contents); - } + public static ItemLiquidContainer getExistingBucket(Block contents) { + return buckets.get(contents); + } - private static int getMatchingSlot(EntityPlayer player, ItemStack stack) { + private static int getMatchingSlot(EntityPlayer player, ItemStack stack) { - for (int slot = 0; slot < player.inventory.mainInventory.length; slot++) { - ItemStack slotStack = player.inventory.getStackInSlot(slot); + for (int slot = 0; slot < player.inventory.mainInventory.length; slot++) { + ItemStack slotStack = player.inventory.getStackInSlot(slot); - if (slotStack == null) { - return slot; - } + if (slotStack == null) { + return slot; + } - if (!slotStack.isItemEqual(stack)) { - continue; - } + if (!slotStack.isItemEqual(stack)) { + continue; + } - int space = slotStack.getMaxStackSize() - slotStack.stackSize; - if (space >= stack.stackSize) { - return slot; - } - } + int space = slotStack.getMaxStackSize() - slotStack.stackSize; + if (space >= stack.stackSize) { + return slot; + } + } - return -1; - } + return -1; + } - @Override - public ItemStack onEaten(ItemStack itemstack, World world, EntityPlayer entityplayer) { - if (!isDrink) { - return itemstack; - } + @Override + public ItemStack onEaten(ItemStack itemstack, World world, EntityPlayer entityplayer) { + if (!isDrink) { + return itemstack; + } - itemstack.stackSize--; - entityplayer.getFoodStats().addStats(healAmount, saturationModifier); - world.playSoundAtEntity(entityplayer, "random.burp", 0.5F, world.rand.nextFloat() * 0.1F + 0.9F); - /* - * if (!world.isRemote && potionId > 0 && world.rand.nextFloat() < potionEffectProbability) entityplayer.addPotionEffect(new PotionEffect(potionId, - * potionDuration * 20, potionAmplifier)); - */ + itemstack.stackSize--; + entityplayer.getFoodStats().addStats(healAmount, saturationModifier); + world.playSoundAtEntity(entityplayer, "random.burp", 0.5F, world.rand.nextFloat() * 0.1F + 0.9F); + /* + * if (!world.isRemote && potionId > 0 && world.rand.nextFloat() < potionEffectProbability) entityplayer.addPotionEffect(new PotionEffect(potionId, + * potionDuration * 20, potionAmplifier)); + */ - return itemstack; - } + return itemstack; + } - @Override - public int getMaxItemUseDuration(ItemStack itemstack) { - if (isDrink) { - return 32; - } else { - return super.getMaxItemUseDuration(itemstack); - } - } + @Override + public int getMaxItemUseDuration(ItemStack itemstack) { + if (isDrink) { + return 32; + } else { + return super.getMaxItemUseDuration(itemstack); + } + } - @Override - public EnumAction getItemUseAction(ItemStack itemstack) { - if (isDrink) { - return EnumAction.drink; - } else { - return EnumAction.none; - } - } + @Override + public EnumAction getItemUseAction(ItemStack itemstack) { + if (isDrink) { + return EnumAction.drink; + } else { + return EnumAction.none; + } + } - @Override - public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { + @Override + public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { - if (world.isRemote) { - return itemstack; - } + if (world.isRemote) { + return itemstack; + } - // / DRINKS can be drunk - if (isDrink) { - if (entityplayer.canEat(isAlwaysEdible)) { - entityplayer.setItemInUse(itemstack, getMaxItemUseDuration(itemstack)); - } - return itemstack; - } + // / DRINKS can be drunk + if (isDrink) { + if (entityplayer.canEat(isAlwaysEdible)) { + entityplayer.setItemInUse(itemstack, getMaxItemUseDuration(itemstack)); + } + return itemstack; + } - // / Otherwise check empty container - MovingObjectPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(world, entityplayer, true); - if (movingobjectposition != null && movingobjectposition.typeOfHit == MovingObjectType.BLOCK) { + // / Otherwise check empty container + MovingObjectPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(world, entityplayer, true); + if (movingobjectposition != null && movingobjectposition.typeOfHit == MovingObjectType.BLOCK) { - int x = movingobjectposition.blockX; - int y = movingobjectposition.blockY; - int z = movingobjectposition.blockZ; - Block targetedBlock = world.getBlock(x, y, z); + int x = movingobjectposition.blockX; + int y = movingobjectposition.blockY; + int z = movingobjectposition.blockZ; + Block targetedBlock = world.getBlock(x, y, z); - FluidStack fluid = null; + FluidStack fluid = null; - if (targetedBlock instanceof IFluidBlock) { - fluid = ((IFluidBlock) targetedBlock).drain(world, x, y, z, false); - } else { - if (targetedBlock == Blocks.water || targetedBlock == Blocks.flowing_water) { - fluid = new FluidStack(FluidRegistry.WATER, 1000); - } else if (targetedBlock == Blocks.lava || targetedBlock == Blocks.flowing_lava) { - fluid = new FluidStack(FluidRegistry.LAVA, 1000); - } - } + if (targetedBlock instanceof IFluidBlock) { + fluid = ((IFluidBlock) targetedBlock).drain(world, x, y, z, false); + } else { + if (targetedBlock == Blocks.water || targetedBlock == Blocks.flowing_water) { + fluid = new FluidStack(FluidRegistry.WATER, 1000); + } else if (targetedBlock == Blocks.lava || targetedBlock == Blocks.flowing_lava) { + fluid = new FluidStack(FluidRegistry.LAVA, 1000); + } + } - if (fluid == null || fluid.amount <= 0 && this.type == EnumContainerType.BUCKET) { - return tryPlaceLiquid(itemstack, world, entityplayer, movingobjectposition); - } + if (fluid == null || fluid.amount <= 0 && this.type == EnumContainerType.BUCKET) { + return tryPlaceLiquid(itemstack, world, entityplayer, movingobjectposition); + } - ItemStack filledContainer = FluidHelper.getFilledContainer(fluid.getFluid(), itemstack); - if (filledContainer == null) { - return itemstack; - } + ItemStack filledContainer = FluidHelper.getFilledContainer(fluid.getFluid(), itemstack); + if (filledContainer == null) { + return itemstack; + } - // Search for a slot to stow a filled container in player's - // inventory - int slot = getMatchingSlot(entityplayer, filledContainer); - if (slot < 0) { - return itemstack; - } + // Search for a slot to stow a filled container in player's + // inventory + int slot = getMatchingSlot(entityplayer, filledContainer); + if (slot < 0) { + return itemstack; + } - if (entityplayer.inventory.getStackInSlot(slot) == null) { - entityplayer.inventory.setInventorySlotContents(slot, filledContainer.copy()); - } else { - entityplayer.inventory.getStackInSlot(slot).stackSize++; - } + if (entityplayer.inventory.getStackInSlot(slot) == null) { + entityplayer.inventory.setInventorySlotContents(slot, filledContainer.copy()); + } else { + entityplayer.inventory.getStackInSlot(slot).stackSize++; + } - // Remove consumed liquid block in world - if (targetedBlock instanceof IFluidBlock) { - ((IFluidBlock) targetedBlock).drain(world, x, y, z, true); - } else { - world.setBlockToAir(x, y, z); - } + // Remove consumed liquid block in world + if (targetedBlock instanceof IFluidBlock) { + ((IFluidBlock) targetedBlock).drain(world, x, y, z, true); + } else { + world.setBlockToAir(x, y, z); + } - // Remove consumed empty container - itemstack.stackSize--; + // Remove consumed empty container + itemstack.stackSize--; - // Notify player that his inventory has changed. - Proxies.net.inventoryChangeNotify(entityplayer); + // Notify player that his inventory has changed. + Proxies.net.inventoryChangeNotify(entityplayer); - return itemstack; - } + return itemstack; + } - return itemstack; + return itemstack; + } - } + private ItemStack tryPlaceLiquid( + ItemStack itemstack, World world, EntityPlayer player, MovingObjectPosition movingobjectposition) { - private ItemStack tryPlaceLiquid(ItemStack itemstack, World world, EntityPlayer player, MovingObjectPosition movingobjectposition) { + if (this.type != EnumContainerType.BUCKET) { + return itemstack; + } - if (this.type != EnumContainerType.BUCKET) { - return itemstack; - } + if (this.contents == Blocks.air) { + return new ItemStack(Items.bucket); + } - if (this.contents == Blocks.air) { - return new ItemStack(Items.bucket); - } + int x = movingobjectposition.blockX; + int y = movingobjectposition.blockY; + int z = movingobjectposition.blockZ; - int x = movingobjectposition.blockX; - int y = movingobjectposition.blockY; - int z = movingobjectposition.blockZ; + switch (movingobjectposition.sideHit) { + case 0: + --y; + break; + case 1: + ++y; + break; + case 2: + --z; + break; + case 3: + ++z; + break; + case 4: + --x; + break; + case 5: + ++x; + break; + } - switch (movingobjectposition.sideHit) { - case 0: - --y; - break; - case 1: - ++y; - break; - case 2: - --z; - break; - case 3: - ++z; - break; - case 4: - --x; - break; - case 5: - ++x; - break; - } + if (!player.canPlayerEdit(x, y, z, movingobjectposition.sideHit, itemstack)) { + return itemstack; + } - if (!player.canPlayerEdit(x, y, z, movingobjectposition.sideHit, itemstack)) { - return itemstack; - } + if (this.tryPlaceLiquidAtPosition(world, x, y, z) && !player.capabilities.isCreativeMode) { + return new ItemStack(Items.bucket); + } - if (this.tryPlaceLiquidAtPosition(world, x, y, z) && !player.capabilities.isCreativeMode) { - return new ItemStack(Items.bucket); - } + return itemstack; + } - return itemstack; - } + private boolean tryPlaceLiquidAtPosition(World world, int x, int y, int z) { + if (this.contents == Blocks.air) { + return false; + } else { + Material material = world.getBlock(x, y, z).getMaterial(); + boolean isLiquid = !material.isSolid(); - private boolean tryPlaceLiquidAtPosition(World world, int x, int y, int z) { - if (this.contents == Blocks.air) { - return false; - } else { - Material material = world.getBlock(x, y, z).getMaterial(); - boolean isLiquid = !material.isSolid(); + if (!world.isAirBlock(x, y, z) && !isLiquid) { + return false; + } else { + // Can't put down liquids in the nether. + // Explode if it's flammable, evaporate otherwise. + if (world.provider.isHellWorld && this.contents != Blocks.flowing_lava) { + int flammability = contents.getFlammability(world, x, y, z, ForgeDirection.UNKNOWN); + if (contents instanceof BlockForestryFluid && flammability > 0) { + // Explosion size is determined by flammability, up to size 4. + float explosionSize = 4F * flammability / 300F; + world.newExplosion(null, x, y, z, explosionSize, true, true); + return true; + } else { + Random random = world.rand; + world.playSoundEffect( + x + 0.5, + y + 0.5F, + z + 0.5F, + "random.fizz", + 0.5F, + 2.6F + (random.nextFloat() - random.nextFloat()) * 0.8F); - if (!world.isAirBlock(x, y, z) && !isLiquid) { - return false; - } else { - // Can't put down liquids in the nether. - // Explode if it's flammable, evaporate otherwise. - if (world.provider.isHellWorld && this.contents != Blocks.flowing_lava) { - int flammability = contents.getFlammability(world, x, y, z, ForgeDirection.UNKNOWN); - if (contents instanceof BlockForestryFluid && flammability > 0) { - // Explosion size is determined by flammability, up to size 4. - float explosionSize = 4F * flammability / 300F; - world.newExplosion(null, x, y, z, explosionSize, true, true); - return true; - } else { - Random random = world.rand; - world.playSoundEffect(x + 0.5, y + 0.5F, z + 0.5F, "random.fizz", 0.5F, 2.6F + (random.nextFloat() - random.nextFloat()) * 0.8F); + for (int l = 0; l < 8; ++l) { + world.spawnParticle( + "largesmoke", + x + random.nextDouble(), + y + random.nextDouble(), + z + random.nextDouble(), + 0.0, + 0.0, + 0.0); + } + } + } else { + if (!world.isRemote && isLiquid && !material.isLiquid()) { + world.func_147480_a(x, y, z, true); + } - for (int l = 0; l < 8; ++l) { - world.spawnParticle("largesmoke", x + random.nextDouble(), y + random.nextDouble(), z + random.nextDouble(), 0.0, 0.0, 0.0); - } - } - } else { - if (!world.isRemote && isLiquid && !material.isLiquid()) { - world.func_147480_a(x, y, z, true); - } + world.setBlock(x, y, z, this.contents, 0, 3); + } - world.setBlock(x, y, z, this.contents, 0, 3); - } + return true; + } + } + } - return true; - } - } - } + public ItemLiquidContainer setDrink(int healAmount, float saturationModifier) { + isDrink = true; + this.healAmount = healAmount; + this.saturationModifier = saturationModifier; + return this; + } - public ItemLiquidContainer setDrink(int healAmount, float saturationModifier) { - isDrink = true; - this.healAmount = healAmount; - this.saturationModifier = saturationModifier; - return this; - } + /* + * public ItemLiquidContainer setPotionEffect(int i, int j, int k, float f) { potionId = i; potionDuration = j; potionAmplifier = k; potionEffectProbability + * = f; return this; } + */ + public ItemLiquidContainer setAlwaysEdible() { + isAlwaysEdible = true; + return this; + } - /* - * public ItemLiquidContainer setPotionEffect(int i, int j, int k, float f) { potionId = i; potionDuration = j; potionAmplifier = k; potionEffectProbability - * = f; return this; } - */ - public ItemLiquidContainer setAlwaysEdible() { - isAlwaysEdible = true; - return this; - } + /* ICONS */ + @SideOnly(Side.CLIENT) + private IIcon[] icons; - /* ICONS */ - @SideOnly(Side.CLIENT) - private IIcon[] icons; + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + icons = new IIcon[2]; + icons[0] = TextureManager.registerTex( + register, "liquids/" + type.toString().toLowerCase(Locale.ENGLISH) + ".bottle"); + icons[1] = TextureManager.registerTex( + register, "liquids/" + type.toString().toLowerCase(Locale.ENGLISH) + ".contents"); + } - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - icons = new IIcon[2]; - icons[0] = TextureManager.registerTex(register, "liquids/" + type.toString().toLowerCase(Locale.ENGLISH) + ".bottle"); - icons[1] = TextureManager.registerTex(register, "liquids/" + type.toString().toLowerCase(Locale.ENGLISH) + ".contents"); - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamageForRenderPass(int i, int j) { + if (j > 0 && color != null) { + return icons[1]; + } else { + return icons[0]; + } + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamageForRenderPass(int i, int j) { - if (j > 0 && color != null) { - return icons[1]; - } else { - return icons[0]; - } - } + // Return true to enable color overlay + @Override + public boolean requiresMultipleRenderPasses() { + return true; + } - // Return true to enable color overlay - @Override - public boolean requiresMultipleRenderPasses() { - return true; - } + @Override + public int getColorFromItemStack(ItemStack itemstack, int j) { + if (j > 0 && color != null) { + return color.getRGB() & 0xffffff; // remove alpha + } else { + return 0xffffff; + } + } - @Override - public int getColorFromItemStack(ItemStack itemstack, int j) { - if (j > 0 && color != null) { - return color.getRGB() & 0xffffff; // remove alpha - } else { - return 0xffffff; - } - } - - public EnumContainerType getType() { - return type; - } + public EnumContainerType getType() { + return type; + } } diff --git a/src/main/java/forestry/core/items/ItemOverlay.java b/src/main/java/forestry/core/items/ItemOverlay.java index d579db164..57e9f6bd4 100755 --- a/src/main/java/forestry/core/items/ItemOverlay.java +++ b/src/main/java/forestry/core/items/ItemOverlay.java @@ -10,117 +10,113 @@ ******************************************************************************/ package forestry.core.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.config.Config; +import forestry.core.render.TextureManager; +import forestry.core.utils.StringUtil; import java.util.List; - import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.config.Config; -import forestry.core.render.TextureManager; -import forestry.core.utils.StringUtil; - public class ItemOverlay extends ItemForestry { - public interface IOverlayInfo { - String getName(); + public interface IOverlayInfo { + String getName(); - int getPrimaryColor(); + int getPrimaryColor(); - int getSecondaryColor(); + int getSecondaryColor(); - boolean isSecret(); - } + boolean isSecret(); + } - protected final IOverlayInfo[] overlays; + protected final IOverlayInfo[] overlays; - public ItemOverlay(CreativeTabs tab, IOverlayInfo... overlays) { - setMaxDamage(0); - setHasSubtypes(true); - setCreativeTab(tab); + public ItemOverlay(CreativeTabs tab, IOverlayInfo... overlays) { + setMaxDamage(0); + setHasSubtypes(true); + setCreativeTab(tab); - this.overlays = overlays; - } + this.overlays = overlays; + } - @Override - public boolean isDamageable() { - return false; - } + @Override + public boolean isDamageable() { + return false; + } - @Override - public boolean isRepairable() { - return false; - } + @Override + public boolean isRepairable() { + return false; + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - for (int i = 0; i < overlays.length; i++) { - if (Config.isDebug || !overlays[i].isSecret()) { - itemList.add(new ItemStack(this, 1, i)); - } - } - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + for (int i = 0; i < overlays.length; i++) { + if (Config.isDebug || !overlays[i].isSecret()) { + itemList.add(new ItemStack(this, 1, i)); + } + } + } - /* ICONS */ - @SideOnly(Side.CLIENT) - private IIcon primaryIcon; - @SideOnly(Side.CLIENT) - private IIcon secondaryIcon; + /* ICONS */ + @SideOnly(Side.CLIENT) + private IIcon primaryIcon; - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - primaryIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this) + ".0"); - if (overlays[0].getSecondaryColor() != 0) { - secondaryIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this) + ".1"); - } - } + @SideOnly(Side.CLIENT) + private IIcon secondaryIcon; - @Override - @SideOnly(Side.CLIENT) - public IIcon getIconFromDamageForRenderPass(int i, int j) { - if (i < 0 || i >= overlays.length) - return null; - if (j > 0 && overlays[i].getSecondaryColor() != 0) { - return secondaryIcon; - } else { - return primaryIcon; - } - } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + primaryIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this) + ".0"); + if (overlays[0].getSecondaryColor() != 0) { + secondaryIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this) + ".1"); + } + } - @Override - public int getRenderPasses(int metadata) { - return metadata < 0 || metadata >= overlays.length ? 0 : overlays[metadata].getSecondaryColor() != 0 ? 2 : 1; - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIconFromDamageForRenderPass(int i, int j) { + if (i < 0 || i >= overlays.length) return null; + if (j > 0 && overlays[i].getSecondaryColor() != 0) { + return secondaryIcon; + } else { + return primaryIcon; + } + } - @Override - public boolean requiresMultipleRenderPasses() { - return true; - } + @Override + public int getRenderPasses(int metadata) { + return metadata < 0 || metadata >= overlays.length ? 0 : overlays[metadata].getSecondaryColor() != 0 ? 2 : 1; + } - @Override - public String getUnlocalizedName(ItemStack stack) { - if (stack.getItemDamage() < 0 || stack.getItemDamage() >= overlays.length) { - return null; - } + @Override + public boolean requiresMultipleRenderPasses() { + return true; + } - return super.getUnlocalizedName(stack) + "." + overlays[stack.getItemDamage()].getName(); - } + @Override + public String getUnlocalizedName(ItemStack stack) { + if (stack.getItemDamage() < 0 || stack.getItemDamage() >= overlays.length) { + return null; + } - @Override - public int getColorFromItemStack(ItemStack itemstack, int j) { - if (itemstack.getItemDamage() < 0 || itemstack.getItemDamage() >= overlays.length) - return 0; - IOverlayInfo overlayInfo = overlays[itemstack.getItemDamage()]; - if (j == 0 || overlayInfo.getSecondaryColor() == 0) { - return overlayInfo.getPrimaryColor(); - } else { - return overlayInfo.getSecondaryColor(); - } - } + return super.getUnlocalizedName(stack) + "." + overlays[stack.getItemDamage()].getName(); + } + + @Override + public int getColorFromItemStack(ItemStack itemstack, int j) { + if (itemstack.getItemDamage() < 0 || itemstack.getItemDamage() >= overlays.length) return 0; + IOverlayInfo overlayInfo = overlays[itemstack.getItemDamage()]; + if (j == 0 || overlayInfo.getSecondaryColor() == 0) { + return overlayInfo.getPrimaryColor(); + } else { + return overlayInfo.getSecondaryColor(); + } + } } diff --git a/src/main/java/forestry/core/items/ItemPipette.java b/src/main/java/forestry/core/items/ItemPipette.java index 97faf869c..7ffcde563 100755 --- a/src/main/java/forestry/core/items/ItemPipette.java +++ b/src/main/java/forestry/core/items/ItemPipette.java @@ -10,152 +10,150 @@ ******************************************************************************/ package forestry.core.items; -import java.util.List; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.IIcon; - -import net.minecraftforge.fluids.FluidStack; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.core.IToolPipette; import forestry.core.config.Constants; import forestry.core.fluids.PipetteContents; import forestry.core.render.TextureManager; import forestry.core.utils.StringUtil; +import java.util.List; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.IIcon; +import net.minecraftforge.fluids.FluidStack; public class ItemPipette extends ItemForestry implements IToolPipette { - public ItemPipette() { - super(); - setMaxStackSize(1); - setFull3D(); - } + public ItemPipette() { + super(); + setMaxStackSize(1); + setFull3D(); + } - /** - * @return true if the item's stackTagCompound needs to be synchronized over SMP. - */ - @Override - public boolean getShareTag() { - return true; - } + /** + * @return true if the item's stackTagCompound needs to be synchronized over SMP. + */ + @Override + public boolean getShareTag() { + return true; + } - @Override - public boolean canPipette(ItemStack itemstack) { - PipetteContents contained = new PipetteContents(itemstack.getTagCompound()); - return !contained.isFull(); - } + @Override + public boolean canPipette(ItemStack itemstack) { + PipetteContents contained = new PipetteContents(itemstack.getTagCompound()); + return !contained.isFull(); + } - @Override - public int fill(ItemStack itemstack, FluidStack liquid, boolean doFill) { - PipetteContents contained = new PipetteContents(itemstack.getTagCompound()); + @Override + public int fill(ItemStack itemstack, FluidStack liquid, boolean doFill) { + PipetteContents contained = new PipetteContents(itemstack.getTagCompound()); - int limit = getCapacity(itemstack); - int filled; + int limit = getCapacity(itemstack); + int filled; - if (contained.getContents() == null) { - if (liquid.amount > limit) { - filled = limit; - } else { - filled = liquid.amount; - } + if (contained.getContents() == null) { + if (liquid.amount > limit) { + filled = limit; + } else { + filled = liquid.amount; + } - contained.setContents(new FluidStack(liquid, filled)); - filled = liquid.amount; - } else { - if (contained.getContents().amount >= limit) { - return 0; - } - if (!contained.getContents().isFluidEqual(liquid)) { - return 0; - } + contained.setContents(new FluidStack(liquid, filled)); + filled = liquid.amount; + } else { + if (contained.getContents().amount >= limit) { + return 0; + } + if (!contained.getContents().isFluidEqual(liquid)) { + return 0; + } - int space = limit - contained.getContents().amount; + int space = limit - contained.getContents().amount; - if (liquid.amount > space) { - filled = space; - } else { - filled = liquid.amount; - } + if (liquid.amount > space) { + filled = space; + } else { + filled = liquid.amount; + } - contained.getContents().amount += filled; - } + contained.getContents().amount += filled; + } - if (doFill) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - contained.writeToNBT(nbttagcompound); - itemstack.setTagCompound(nbttagcompound); - itemstack.setItemDamage(1); - } + if (doFill) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + contained.writeToNBT(nbttagcompound); + itemstack.setTagCompound(nbttagcompound); + itemstack.setItemDamage(1); + } - return filled; - } + return filled; + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { - PipetteContents contained = new PipetteContents(itemstack.getTagCompound()); - contained.addTooltip(list); - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { + PipetteContents contained = new PipetteContents(itemstack.getTagCompound()); + contained.addTooltip(list); + } - /* ICONS */ - @SideOnly(Side.CLIENT) - private IIcon primaryIcon; - @SideOnly(Side.CLIENT) - private IIcon secondaryIcon; + /* ICONS */ + @SideOnly(Side.CLIENT) + private IIcon primaryIcon; - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - primaryIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this) + ".0"); - secondaryIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this) + ".1"); - } + @SideOnly(Side.CLIENT) + private IIcon secondaryIcon; - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamage(int damage) { - if (damage <= 0) { - return primaryIcon; - } else { - return secondaryIcon; - } - } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + primaryIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this) + ".0"); + secondaryIcon = TextureManager.registerTex(register, StringUtil.cleanItemName(this) + ".1"); + } - @Override - public FluidStack drain(ItemStack pipette, int maxDrain, boolean doDrain) { - PipetteContents contained = new PipetteContents(pipette.getTagCompound()); - if (contained.getContents() == null || contained.getContents().getFluid().getID() <= 0) { - return null; - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamage(int damage) { + if (damage <= 0) { + return primaryIcon; + } else { + return secondaryIcon; + } + } - int drained = maxDrain; - if (contained.getContents().amount < drained) { - drained = contained.getContents().amount; - } + @Override + public FluidStack drain(ItemStack pipette, int maxDrain, boolean doDrain) { + PipetteContents contained = new PipetteContents(pipette.getTagCompound()); + if (contained.getContents() == null + || contained.getContents().getFluid().getID() <= 0) { + return null; + } - if (doDrain) { - contained.getContents().amount -= drained; + int drained = maxDrain; + if (contained.getContents().amount < drained) { + drained = contained.getContents().amount; + } - if (contained.getContents().amount <= 0) { - pipette.setTagCompound(null); - pipette.setItemDamage(0); - } else { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - contained.writeToNBT(nbttagcompound); - pipette.setTagCompound(nbttagcompound); - } - } + if (doDrain) { + contained.getContents().amount -= drained; - return new FluidStack(contained.getContents(), drained); - } + if (contained.getContents().amount <= 0) { + pipette.setTagCompound(null); + pipette.setItemDamage(0); + } else { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + contained.writeToNBT(nbttagcompound); + pipette.setTagCompound(nbttagcompound); + } + } - @Override - public int getCapacity(ItemStack pipette) { - return Constants.BUCKET_VOLUME; - } + return new FluidStack(contained.getContents(), drained); + } + + @Override + public int getCapacity(ItemStack pipette) { + return Constants.BUCKET_VOLUME; + } } diff --git a/src/main/java/forestry/core/items/ItemRegistry.java b/src/main/java/forestry/core/items/ItemRegistry.java index ac94836d4..c29ae991f 100644 --- a/src/main/java/forestry/core/items/ItemRegistry.java +++ b/src/main/java/forestry/core/items/ItemRegistry.java @@ -1,29 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.items; - -import net.minecraft.item.Item; - -import cpw.mods.fml.common.registry.GameRegistry; - -import forestry.core.utils.StringUtil; -import forestry.plugins.PluginManager; - -public abstract class ItemRegistry { - protected static T registerItem(T item, String name) { - if (PluginManager.getStage() != PluginManager.Stage.SETUP) { - throw new RuntimeException("Tried to register Item outside of Setup"); - } - item.setUnlocalizedName("for." + name); - GameRegistry.registerItem(item, StringUtil.cleanItemName(item)); - return item; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.items; + +import cpw.mods.fml.common.registry.GameRegistry; +import forestry.core.utils.StringUtil; +import forestry.plugins.PluginManager; +import net.minecraft.item.Item; + +public abstract class ItemRegistry { + protected static T registerItem(T item, String name) { + if (PluginManager.getStage() != PluginManager.Stage.SETUP) { + throw new RuntimeException("Tried to register Item outside of Setup"); + } + item.setUnlocalizedName("for." + name); + GameRegistry.registerItem(item, StringUtil.cleanItemName(item)); + return item; + } +} diff --git a/src/main/java/forestry/core/items/ItemRegistryCore.java b/src/main/java/forestry/core/items/ItemRegistryCore.java index 3cad50545..b83010f2f 100644 --- a/src/main/java/forestry/core/items/ItemRegistryCore.java +++ b/src/main/java/forestry/core/items/ItemRegistryCore.java @@ -1,192 +1,190 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.items; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.oredict.OreDictionary; - -import forestry.api.core.Tabs; -import forestry.core.circuits.ItemCircuitBoard; -import forestry.core.genetics.ItemResearchNote; - -public class ItemRegistryCore extends ItemRegistry { - /* Fertilizer */ - public final ItemForestry fertilizerBio; - public final ItemForestryBonemeal fertilizerCompound; - - /* Gems */ - public final ItemForestry apatite; - - /* Research */ - public final ItemResearchNote researchNote; - - /* Ingots */ - public final ItemForestry ingotCopper; - public final ItemForestry ingotTin; - public final ItemForestry ingotBronze; - - /* Tools */ - public final ItemWrench wrench; - public final ItemPipette pipette; - - /* Packaged Tools */ - public final ItemForestry carton; - public final ItemForestry brokenBronzePickaxe; - public final ItemForestry brokenBronzeShovel; - public final ItemForestryTool bronzePickaxe; - public final ItemForestryTool bronzeShovel; - public final ItemAssemblyKit kitShovel; - public final ItemAssemblyKit kitPickaxe; - - /* Machine Parts */ - public final ItemForestry sturdyCasing; - public final ItemForestry hardenedCasing; - public final ItemForestry impregnatedCasing; - public final ItemForestry gearBronze; - public final ItemForestry gearCopper; - public final ItemForestry gearTin; - - /* Soldering */ - public final ItemSolderingIron solderingIron; - public final ItemCircuitBoard circuitboards; - public final ItemElectronTube tubes; - - /* Armor */ - public final ItemArmorNaturalist spectacles; - - /* Peat */ - public final ItemForestry peat; - public final ItemForestry ash; - public final ItemForestry bituminousPeat; - - /* Moistener */ - public final ItemForestry mouldyWheat; - public final ItemForestry decayingWheat; - public final ItemForestry mulch; - - /* Rainmaker */ - public final ItemForestry iodineCharge; - public final ItemForestry phosphor; - - /* Misc */ - public final ItemCraftingMaterial craftingMaterial; - public final ItemForestry stickImpregnated; - public final ItemForestry woodPulp; - public final ItemForestry beeswax; - public final ItemForestry refractoryWax; - public final ItemFruit fruits; - - public ItemRegistryCore() { - fertilizerBio = registerItem(new ItemForestry(), "fertilizerBio"); - fertilizerCompound = registerItem(new ItemForestryBonemeal(), "fertilizerCompound"); - - apatite = registerItem(new ItemForestry(), "apatite"); - OreDictionary.registerOre("gemApatite", apatite); - - researchNote = registerItem(new ItemResearchNote(), "researchNote"); - - ingotCopper = registerItem(new ItemForestry(), "ingotCopper"); - OreDictionary.registerOre("ingotCopper", ingotCopper); - - ingotTin = registerItem(new ItemForestry(), "ingotTin"); - OreDictionary.registerOre("ingotTin", ingotTin); - - ingotBronze = registerItem(new ItemForestry(), "ingotBronze"); - OreDictionary.registerOre("ingotBronze", ingotBronze); - - wrench = registerItem(new ItemWrench(), "wrench"); - pipette = registerItem(new ItemPipette(), "pipette"); - - sturdyCasing = registerItem(new ItemForestry(), "sturdyMachine"); - hardenedCasing = registerItem(new ItemForestry(), "hardenedMachine"); - impregnatedCasing = registerItem(new ItemForestry(), "impregnatedCasing"); - - craftingMaterial = registerItem(new ItemCraftingMaterial(), "craftingMaterial"); - - spectacles = registerItem(new ItemArmorNaturalist(), "naturalistHelmet"); - - peat = registerItem(new ItemForestry(), "peat"); - OreDictionary.registerOre("brickPeat", peat); - - ash = registerItem(new ItemForestry(), "ash"); - OreDictionary.registerOre("dustAsh", ash); - - bituminousPeat = registerItem(new ItemForestry(), "bituminousPeat"); - - gearBronze = registerItem(new ItemForestry(), "gearBronze"); - OreDictionary.registerOre("gearBronze", gearBronze); - gearCopper = registerItem(new ItemForestry(), "gearCopper"); - OreDictionary.registerOre("gearCopper", gearCopper); - gearTin = registerItem(new ItemForestry(), "gearTin"); - OreDictionary.registerOre("gearTin", gearTin); - - circuitboards = registerItem(new ItemCircuitBoard(), "chipsets"); - - solderingIron = new ItemSolderingIron(); - solderingIron.setMaxDamage(5).setFull3D(); - registerItem(solderingIron, "solderingIron"); - - tubes = registerItem(new ItemElectronTube(), "thermionicTubes"); - - // / CARTONS - carton = registerItem(new ItemForestry(), "carton"); - - // / CRAFTING CARPENTER - stickImpregnated = registerItem(new ItemForestry(), "oakStick"); - woodPulp = registerItem(new ItemForestry(), "woodPulp"); - OreDictionary.registerOre("pulpWood", woodPulp); - - // / RECLAMATION - brokenBronzePickaxe = registerItem(new ItemForestry(), "brokenBronzePickaxe"); - brokenBronzeShovel = registerItem(new ItemForestry(), "brokenBronzeShovel"); - - // / TOOLS - bronzePickaxe = new ItemForestryTool(new ItemStack(brokenBronzePickaxe)); - bronzePickaxe.setHarvestLevel("pickaxe", 3); - registerItem(bronzePickaxe, "bronzePickaxe"); - - bronzeShovel = new ItemForestryTool(new ItemStack(brokenBronzeShovel)); - bronzeShovel.setHarvestLevel("shovel", 3); - registerItem(bronzeShovel, "bronzeShovel"); - - // / ASSEMBLY KITS - kitShovel = new ItemAssemblyKit(new ItemStack(bronzeShovel)); - registerItem(kitShovel, "kitShovel"); - - kitPickaxe = new ItemAssemblyKit(new ItemStack(bronzePickaxe)); - registerItem(kitPickaxe, "kitPickaxe"); - - // / MOISTENER RESOURCES - mouldyWheat = registerItem(new ItemForestry(), "mouldyWheat"); - decayingWheat = registerItem(new ItemForestry(), "decayingWheat"); - mulch = registerItem(new ItemForestry(), "mulch"); - - // / RAINMAKER SUBSTRATES - iodineCharge = registerItem(new ItemForestry(), "iodineCapsule"); - - phosphor = registerItem(new ItemForestry(), "phosphor"); - - // / BEE RESOURCES - beeswax = registerItem(new ItemForestry(), "beeswax"); - beeswax.setCreativeTab(Tabs.tabApiculture); - OreDictionary.registerOre("itemBeeswax", beeswax); - - refractoryWax = registerItem(new ItemForestry(), "refractoryWax"); - - // FRUITS - fruits = registerItem(new ItemFruit(), "fruits"); - for (ItemFruit.EnumFruit def : ItemFruit.EnumFruit.values()) { - ItemStack fruit = new ItemStack(fruits, 1, def.ordinal()); - OreDictionary.registerOre(def.getOreDict(), fruit); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.items; + +import forestry.api.core.Tabs; +import forestry.core.circuits.ItemCircuitBoard; +import forestry.core.genetics.ItemResearchNote; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; + +public class ItemRegistryCore extends ItemRegistry { + /* Fertilizer */ + public final ItemForestry fertilizerBio; + public final ItemForestryBonemeal fertilizerCompound; + + /* Gems */ + public final ItemForestry apatite; + + /* Research */ + public final ItemResearchNote researchNote; + + /* Ingots */ + public final ItemForestry ingotCopper; + public final ItemForestry ingotTin; + public final ItemForestry ingotBronze; + + /* Tools */ + public final ItemWrench wrench; + public final ItemPipette pipette; + + /* Packaged Tools */ + public final ItemForestry carton; + public final ItemForestry brokenBronzePickaxe; + public final ItemForestry brokenBronzeShovel; + public final ItemForestryTool bronzePickaxe; + public final ItemForestryTool bronzeShovel; + public final ItemAssemblyKit kitShovel; + public final ItemAssemblyKit kitPickaxe; + + /* Machine Parts */ + public final ItemForestry sturdyCasing; + public final ItemForestry hardenedCasing; + public final ItemForestry impregnatedCasing; + public final ItemForestry gearBronze; + public final ItemForestry gearCopper; + public final ItemForestry gearTin; + + /* Soldering */ + public final ItemSolderingIron solderingIron; + public final ItemCircuitBoard circuitboards; + public final ItemElectronTube tubes; + + /* Armor */ + public final ItemArmorNaturalist spectacles; + + /* Peat */ + public final ItemForestry peat; + public final ItemForestry ash; + public final ItemForestry bituminousPeat; + + /* Moistener */ + public final ItemForestry mouldyWheat; + public final ItemForestry decayingWheat; + public final ItemForestry mulch; + + /* Rainmaker */ + public final ItemForestry iodineCharge; + public final ItemForestry phosphor; + + /* Misc */ + public final ItemCraftingMaterial craftingMaterial; + public final ItemForestry stickImpregnated; + public final ItemForestry woodPulp; + public final ItemForestry beeswax; + public final ItemForestry refractoryWax; + public final ItemFruit fruits; + + public ItemRegistryCore() { + fertilizerBio = registerItem(new ItemForestry(), "fertilizerBio"); + fertilizerCompound = registerItem(new ItemForestryBonemeal(), "fertilizerCompound"); + + apatite = registerItem(new ItemForestry(), "apatite"); + OreDictionary.registerOre("gemApatite", apatite); + + researchNote = registerItem(new ItemResearchNote(), "researchNote"); + + ingotCopper = registerItem(new ItemForestry(), "ingotCopper"); + OreDictionary.registerOre("ingotCopper", ingotCopper); + + ingotTin = registerItem(new ItemForestry(), "ingotTin"); + OreDictionary.registerOre("ingotTin", ingotTin); + + ingotBronze = registerItem(new ItemForestry(), "ingotBronze"); + OreDictionary.registerOre("ingotBronze", ingotBronze); + + wrench = registerItem(new ItemWrench(), "wrench"); + pipette = registerItem(new ItemPipette(), "pipette"); + + sturdyCasing = registerItem(new ItemForestry(), "sturdyMachine"); + hardenedCasing = registerItem(new ItemForestry(), "hardenedMachine"); + impregnatedCasing = registerItem(new ItemForestry(), "impregnatedCasing"); + + craftingMaterial = registerItem(new ItemCraftingMaterial(), "craftingMaterial"); + + spectacles = registerItem(new ItemArmorNaturalist(), "naturalistHelmet"); + + peat = registerItem(new ItemForestry(), "peat"); + OreDictionary.registerOre("brickPeat", peat); + + ash = registerItem(new ItemForestry(), "ash"); + OreDictionary.registerOre("dustAsh", ash); + + bituminousPeat = registerItem(new ItemForestry(), "bituminousPeat"); + + gearBronze = registerItem(new ItemForestry(), "gearBronze"); + OreDictionary.registerOre("gearBronze", gearBronze); + gearCopper = registerItem(new ItemForestry(), "gearCopper"); + OreDictionary.registerOre("gearCopper", gearCopper); + gearTin = registerItem(new ItemForestry(), "gearTin"); + OreDictionary.registerOre("gearTin", gearTin); + + circuitboards = registerItem(new ItemCircuitBoard(), "chipsets"); + + solderingIron = new ItemSolderingIron(); + solderingIron.setMaxDamage(5).setFull3D(); + registerItem(solderingIron, "solderingIron"); + + tubes = registerItem(new ItemElectronTube(), "thermionicTubes"); + + // / CARTONS + carton = registerItem(new ItemForestry(), "carton"); + + // / CRAFTING CARPENTER + stickImpregnated = registerItem(new ItemForestry(), "oakStick"); + woodPulp = registerItem(new ItemForestry(), "woodPulp"); + OreDictionary.registerOre("pulpWood", woodPulp); + + // / RECLAMATION + brokenBronzePickaxe = registerItem(new ItemForestry(), "brokenBronzePickaxe"); + brokenBronzeShovel = registerItem(new ItemForestry(), "brokenBronzeShovel"); + + // / TOOLS + bronzePickaxe = new ItemForestryTool(new ItemStack(brokenBronzePickaxe)); + bronzePickaxe.setHarvestLevel("pickaxe", 3); + registerItem(bronzePickaxe, "bronzePickaxe"); + + bronzeShovel = new ItemForestryTool(new ItemStack(brokenBronzeShovel)); + bronzeShovel.setHarvestLevel("shovel", 3); + registerItem(bronzeShovel, "bronzeShovel"); + + // / ASSEMBLY KITS + kitShovel = new ItemAssemblyKit(new ItemStack(bronzeShovel)); + registerItem(kitShovel, "kitShovel"); + + kitPickaxe = new ItemAssemblyKit(new ItemStack(bronzePickaxe)); + registerItem(kitPickaxe, "kitPickaxe"); + + // / MOISTENER RESOURCES + mouldyWheat = registerItem(new ItemForestry(), "mouldyWheat"); + decayingWheat = registerItem(new ItemForestry(), "decayingWheat"); + mulch = registerItem(new ItemForestry(), "mulch"); + + // / RAINMAKER SUBSTRATES + iodineCharge = registerItem(new ItemForestry(), "iodineCapsule"); + + phosphor = registerItem(new ItemForestry(), "phosphor"); + + // / BEE RESOURCES + beeswax = registerItem(new ItemForestry(), "beeswax"); + beeswax.setCreativeTab(Tabs.tabApiculture); + OreDictionary.registerOre("itemBeeswax", beeswax); + + refractoryWax = registerItem(new ItemForestry(), "refractoryWax"); + + // FRUITS + fruits = registerItem(new ItemFruit(), "fruits"); + for (ItemFruit.EnumFruit def : ItemFruit.EnumFruit.values()) { + ItemStack fruit = new ItemStack(fruits, 1, def.ordinal()); + OreDictionary.registerOre(def.getOreDict(), fruit); + } + } +} diff --git a/src/main/java/forestry/core/items/ItemRegistryFluids.java b/src/main/java/forestry/core/items/ItemRegistryFluids.java index 52f870705..055a1efb7 100644 --- a/src/main/java/forestry/core/items/ItemRegistryFluids.java +++ b/src/main/java/forestry/core/items/ItemRegistryFluids.java @@ -1,56 +1,54 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.items; - -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.Table; - -import net.minecraft.init.Blocks; - -import forestry.core.fluids.Fluids; - -public class ItemRegistryFluids extends ItemRegistry { - public final ItemLiquidContainer canEmpty; - public final ItemLiquidContainer waxCapsuleEmpty; - public final ItemLiquidContainer refractoryEmpty; - - private final Table containers = HashBasedTable.create(); - - public ItemLiquidContainer getContainer(EnumContainerType type, Fluids fluid) { - return containers.get(type, fluid.getFluid().getName()); - } - - public ItemRegistryFluids() { - canEmpty = registerEmptyContainer(EnumContainerType.CAN, "canEmpty"); - waxCapsuleEmpty = registerEmptyContainer(EnumContainerType.CAPSULE, "waxCapsule"); - refractoryEmpty = registerEmptyContainer(EnumContainerType.REFRACTORY, "refractoryEmpty"); - - - for (Fluids fluidType : Fluids.values()) { - if (fluidType.getFluid() == null) { - continue; - } - for (EnumContainerType type : fluidType.getContainerTypes()) { - ItemLiquidContainer liquidContainer = new ItemLiquidContainer(type, fluidType.getBlock(), fluidType.getColor()); - fluidType.setProperties(liquidContainer); - - String name = type.getContainerNameKey() + fluidType.getContainerNameKey(); - registerItem(liquidContainer, name); - - containers.put(type, fluidType.getFluid().getName(), liquidContainer); - } - } - } - - private static ItemLiquidContainer registerEmptyContainer(EnumContainerType type, String name) { - return registerItem(new ItemLiquidContainer(type, Blocks.air, null), name); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.items; + +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.Table; +import forestry.core.fluids.Fluids; +import net.minecraft.init.Blocks; + +public class ItemRegistryFluids extends ItemRegistry { + public final ItemLiquidContainer canEmpty; + public final ItemLiquidContainer waxCapsuleEmpty; + public final ItemLiquidContainer refractoryEmpty; + + private final Table containers = HashBasedTable.create(); + + public ItemLiquidContainer getContainer(EnumContainerType type, Fluids fluid) { + return containers.get(type, fluid.getFluid().getName()); + } + + public ItemRegistryFluids() { + canEmpty = registerEmptyContainer(EnumContainerType.CAN, "canEmpty"); + waxCapsuleEmpty = registerEmptyContainer(EnumContainerType.CAPSULE, "waxCapsule"); + refractoryEmpty = registerEmptyContainer(EnumContainerType.REFRACTORY, "refractoryEmpty"); + + for (Fluids fluidType : Fluids.values()) { + if (fluidType.getFluid() == null) { + continue; + } + for (EnumContainerType type : fluidType.getContainerTypes()) { + ItemLiquidContainer liquidContainer = + new ItemLiquidContainer(type, fluidType.getBlock(), fluidType.getColor()); + fluidType.setProperties(liquidContainer); + + String name = type.getContainerNameKey() + fluidType.getContainerNameKey(); + registerItem(liquidContainer, name); + + containers.put(type, fluidType.getFluid().getName(), liquidContainer); + } + } + } + + private static ItemLiquidContainer registerEmptyContainer(EnumContainerType type, String name) { + return registerItem(new ItemLiquidContainer(type, Blocks.air, null), name); + } +} diff --git a/src/main/java/forestry/core/items/ItemScoop.java b/src/main/java/forestry/core/items/ItemScoop.java index a958d2e21..8b9423ea4 100755 --- a/src/main/java/forestry/core/items/ItemScoop.java +++ b/src/main/java/forestry/core/items/ItemScoop.java @@ -14,11 +14,11 @@ import forestry.api.core.IToolScoop; import forestry.api.core.Tabs; public class ItemScoop extends ItemForestryTool implements IToolScoop { - public ItemScoop() { - super(null); - setEfficiencyOnProperMaterial(4.0f); - setMaxDamage(10); - setCreativeTab(Tabs.tabApiculture); - setMaxStackSize(1); - } + public ItemScoop() { + super(null); + setEfficiencyOnProperMaterial(4.0f); + setMaxDamage(10); + setCreativeTab(Tabs.tabApiculture); + setMaxStackSize(1); + } } diff --git a/src/main/java/forestry/core/items/ItemSolderingIron.java b/src/main/java/forestry/core/items/ItemSolderingIron.java index cde00a5cf..ccce2d229 100644 --- a/src/main/java/forestry/core/items/ItemSolderingIron.java +++ b/src/main/java/forestry/core/items/ItemSolderingIron.java @@ -1,31 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.items; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.core.circuits.ContainerSolderingIron; -import forestry.core.circuits.GuiSolderingIron; -import forestry.core.circuits.ISolderingIron; -import forestry.core.inventory.ItemInventorySolderingIron; - -public class ItemSolderingIron extends ItemWithGui implements ISolderingIron { - @Override - public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { - return new GuiSolderingIron(player, new ItemInventorySolderingIron(player, heldItem)); - } - - @Override - public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { - return new ContainerSolderingIron(player, new ItemInventorySolderingIron(player, heldItem)); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.items; + +import forestry.core.circuits.ContainerSolderingIron; +import forestry.core.circuits.GuiSolderingIron; +import forestry.core.circuits.ISolderingIron; +import forestry.core.inventory.ItemInventorySolderingIron; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class ItemSolderingIron extends ItemWithGui implements ISolderingIron { + @Override + public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { + return new GuiSolderingIron(player, new ItemInventorySolderingIron(player, heldItem)); + } + + @Override + public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { + return new ContainerSolderingIron(player, new ItemInventorySolderingIron(player, heldItem)); + } +} diff --git a/src/main/java/forestry/core/items/ItemWithGui.java b/src/main/java/forestry/core/items/ItemWithGui.java index 2ceadba53..c07840033 100644 --- a/src/main/java/forestry/core/items/ItemWithGui.java +++ b/src/main/java/forestry/core/items/ItemWithGui.java @@ -10,41 +10,40 @@ ******************************************************************************/ package forestry.core.items; +import forestry.core.gui.ContainerItemInventory; +import forestry.core.gui.GuiHandler; +import forestry.core.gui.IGuiHandlerItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import forestry.core.gui.ContainerItemInventory; -import forestry.core.gui.GuiHandler; -import forestry.core.gui.IGuiHandlerItem; - public abstract class ItemWithGui extends ItemForestry implements IGuiHandlerItem { - public ItemWithGui() { - setMaxStackSize(1); - } + public ItemWithGui() { + setMaxStackSize(1); + } - @Override - public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { - if (!world.isRemote) { - openGui(entityplayer); - } + @Override + public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { + if (!world.isRemote) { + openGui(entityplayer); + } - return itemstack; - } + return itemstack; + } - protected void openGui(EntityPlayer entityplayer) { - GuiHandler.openGui(entityplayer, this); - } + protected void openGui(EntityPlayer entityplayer) { + GuiHandler.openGui(entityplayer, this); + } - @Override - public boolean onDroppedByPlayer(ItemStack itemstack, EntityPlayer player) { - if (itemstack != null && - player instanceof EntityPlayerMP && - player.openContainer instanceof ContainerItemInventory) { - player.closeScreen(); - } + @Override + public boolean onDroppedByPlayer(ItemStack itemstack, EntityPlayer player) { + if (itemstack != null + && player instanceof EntityPlayerMP + && player.openContainer instanceof ContainerItemInventory) { + player.closeScreen(); + } - return super.onDroppedByPlayer(itemstack, player); - } + return super.onDroppedByPlayer(itemstack, player); + } } diff --git a/src/main/java/forestry/core/items/ItemWrench.java b/src/main/java/forestry/core/items/ItemWrench.java index 7e31ab177..a1317053d 100755 --- a/src/main/java/forestry/core/items/ItemWrench.java +++ b/src/main/java/forestry/core/items/ItemWrench.java @@ -10,42 +10,47 @@ ******************************************************************************/ package forestry.core.items; +import buildcraft.api.tools.IToolWrench; +import cpw.mods.fml.common.Optional; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; - import net.minecraftforge.common.util.ForgeDirection; -import cpw.mods.fml.common.Optional; - -import buildcraft.api.tools.IToolWrench; - @Optional.Interface(iface = "buildcraft.api.tools.IToolWrench", modid = "BuildCraftAPI|tools") public class ItemWrench extends ItemForestry implements IToolWrench { - public ItemWrench() { - super(); - setHarvestLevel("wrench", 0); - } + public ItemWrench() { + super(); + setHarvestLevel("wrench", 0); + } - @Override - public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { - Block block = world.getBlock(x, y, z); - if (block.rotateBlock(world, x, y, z, ForgeDirection.getOrientation(side))) { - player.swingItem(); - return !world.isRemote; - } - return false; - } + @Override + public boolean onItemUseFirst( + ItemStack stack, + EntityPlayer player, + World world, + int x, + int y, + int z, + int side, + float hitX, + float hitY, + float hitZ) { + Block block = world.getBlock(x, y, z); + if (block.rotateBlock(world, x, y, z, ForgeDirection.getOrientation(side))) { + player.swingItem(); + return !world.isRemote; + } + return false; + } - @Override - public boolean canWrench(EntityPlayer player, int x, int y, int z) { - return true; - } - - @Override - public void wrenchUsed(EntityPlayer player, int x, int y, int z) { - } + @Override + public boolean canWrench(EntityPlayer player, int x, int y, int z) { + return true; + } + @Override + public void wrenchUsed(EntityPlayer player, int x, int y, int z) {} } diff --git a/src/main/java/forestry/core/multiblock/FakeMultiblockController.java b/src/main/java/forestry/core/multiblock/FakeMultiblockController.java index 515ab7a48..8c9876dbc 100644 --- a/src/main/java/forestry/core/multiblock/FakeMultiblockController.java +++ b/src/main/java/forestry/core/multiblock/FakeMultiblockController.java @@ -1,202 +1,166 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.multiblock; - -import javax.annotation.Nonnull; -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.Set; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; - -import forestry.api.core.EnumHumidity; -import forestry.api.core.EnumTemperature; -import forestry.api.core.IErrorLogic; -import forestry.api.multiblock.IMultiblockComponent; -import forestry.core.access.EnumAccess; -import forestry.core.access.FakeAccessHandler; -import forestry.core.access.IAccessHandler; -import forestry.core.errors.FakeErrorLogic; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; - -public abstract class FakeMultiblockController implements IMultiblockControllerInternal { - @Override - public void attachBlock(IMultiblockComponent part) { - - } - - @Override - public void detachBlock(IMultiblockComponent part, boolean chunkUnloading) { - - } - - @Override - public void checkIfMachineIsWhole() { - - } - - @Override - public void assimilate(IMultiblockControllerInternal other) { - - } - - @Override - public void _onAssimilated(IMultiblockControllerInternal otherController) { - - } - - @Override - public void onAssimilated(IMultiblockControllerInternal assimilator) { - - } - - @Override - public void updateMultiblockEntity() { - - } - - @Override - public ChunkCoordinates getReferenceCoord() { - return null; - } - - @Override - public void recalculateMinMaxCoords() { - - } - - @Override - public void formatDescriptionPacket(NBTTagCompound data) { - - } - - @Override - public void decodeDescriptionPacket(NBTTagCompound data) { - - } - - @Override - public World getWorld() { - return null; - } - - @Override - public boolean isEmpty() { - return true; - } - - @Override - public boolean shouldConsume(IMultiblockControllerInternal otherController) { - return false; - } - - @Override - public String getPartsListString() { - return ""; - } - - @Override - public void auditParts() { - - } - - @Nonnull - @Override - public Set checkForDisconnections() { - return Collections.emptySet(); - } - - @Nonnull - @Override - public Set detachAllBlocks() { - return Collections.emptySet(); - } - - @Override - public boolean isAssembled() { - return false; - } - - @Override - public void reassemble() { - - } - - @Override - public String getLastValidationError() { - return null; - } - - @Override - @Nonnull - public Collection getComponents() { - return Collections.emptyList(); - } - - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - - } - - @Override - public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { - - } - - @Override - public IAccessHandler getAccessHandler() { - return FakeAccessHandler.getInstance(); - } - - @Override - public EnumTemperature getTemperature() { - return EnumTemperature.NORMAL; - } - - @Override - public EnumHumidity getHumidity() { - return EnumHumidity.NORMAL; - } - - @Override - public float getExactTemperature() { - return 0.5f; - } - - @Override - public float getExactHumidity() { - return 0.5f; - } - - @Override - public IErrorLogic getErrorLogic() { - return FakeErrorLogic.instance; - } - - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - - } - - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import forestry.api.core.EnumHumidity; +import forestry.api.core.EnumTemperature; +import forestry.api.core.IErrorLogic; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.core.access.EnumAccess; +import forestry.core.access.FakeAccessHandler; +import forestry.core.access.IAccessHandler; +import forestry.core.errors.FakeErrorLogic; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.Set; +import javax.annotation.Nonnull; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; + +public abstract class FakeMultiblockController implements IMultiblockControllerInternal { + @Override + public void attachBlock(IMultiblockComponent part) {} + + @Override + public void detachBlock(IMultiblockComponent part, boolean chunkUnloading) {} + + @Override + public void checkIfMachineIsWhole() {} + + @Override + public void assimilate(IMultiblockControllerInternal other) {} + + @Override + public void _onAssimilated(IMultiblockControllerInternal otherController) {} + + @Override + public void onAssimilated(IMultiblockControllerInternal assimilator) {} + + @Override + public void updateMultiblockEntity() {} + + @Override + public ChunkCoordinates getReferenceCoord() { + return null; + } + + @Override + public void recalculateMinMaxCoords() {} + + @Override + public void formatDescriptionPacket(NBTTagCompound data) {} + + @Override + public void decodeDescriptionPacket(NBTTagCompound data) {} + + @Override + public World getWorld() { + return null; + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + public boolean shouldConsume(IMultiblockControllerInternal otherController) { + return false; + } + + @Override + public String getPartsListString() { + return ""; + } + + @Override + public void auditParts() {} + + @Nonnull + @Override + public Set checkForDisconnections() { + return Collections.emptySet(); + } + + @Nonnull + @Override + public Set detachAllBlocks() { + return Collections.emptySet(); + } + + @Override + public boolean isAssembled() { + return false; + } + + @Override + public void reassemble() {} + + @Override + public String getLastValidationError() { + return null; + } + + @Override + @Nonnull + public Collection getComponents() { + return Collections.emptyList(); + } + + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) {} + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) {} + + @Override + public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) {} + + @Override + public IAccessHandler getAccessHandler() { + return FakeAccessHandler.getInstance(); + } + + @Override + public EnumTemperature getTemperature() { + return EnumTemperature.NORMAL; + } + + @Override + public EnumHumidity getHumidity() { + return EnumHumidity.NORMAL; + } + + @Override + public float getExactTemperature() { + return 0.5f; + } + + @Override + public float getExactHumidity() { + return 0.5f; + } + + @Override + public IErrorLogic getErrorLogic() { + return FakeErrorLogic.instance; + } + + @Override + public void writeGuiData(DataOutputStreamForestry data) throws IOException {} + + @Override + public void readGuiData(DataInputStreamForestry data) throws IOException {} +} diff --git a/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java b/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java index 540fb75ab..5f65f5072 100644 --- a/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java +++ b/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java @@ -1,143 +1,142 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.multiblock; - -import javax.annotation.Nonnull; -import java.util.Set; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; - -import forestry.api.core.IErrorLogicSource; -import forestry.api.core.INBTTagable; -import forestry.api.multiblock.IMultiblockComponent; -import forestry.api.multiblock.IMultiblockController; -import forestry.core.access.IRestrictedAccess; -import forestry.core.network.IStreamableGui; -import forestry.core.tiles.IClimatised; - -// internal implementation of IMultiblockController -public interface IMultiblockControllerInternal extends IMultiblockController, INBTTagable, IRestrictedAccess, IErrorLogicSource, IClimatised, IStreamableGui { - /** - * Attach a new part to this machine. - * @param part The part to add. - */ - void attachBlock(IMultiblockComponent part); - - /** - * Call to detach a block from this machine. Generally, this should be called - * when the tile entity is being released, e.g. on block destruction. - * @param part The part to detach from this machine. - * @param chunkUnloading Is this entity detaching due to the chunk unloading? If true, the multiblock will be paused instead of broken. - */ - void detachBlock(IMultiblockComponent part, boolean chunkUnloading); - - /** - * Check if the machine is whole or not. - * If the machine was not whole, but now is, assemble the machine. - * If the machine was whole, but no longer is, disassemble the machine. - */ - void checkIfMachineIsWhole(); - - /** - * Assimilate another controller into this controller. - * Acquire all of the other controller's blocks and attach them - * to this one. - * - * @param other The controller to merge into this one. - */ - void assimilate(IMultiblockControllerInternal other); - - /** - * Called when this machine is consumed by another controller. - * Essentially, forcibly tear down this object. - * @param otherController The controller consuming this controller. - */ - void _onAssimilated(IMultiblockControllerInternal otherController); - - /** - * Callback. Called after this controller is assimilated into another controller. - * All blocks have been stripped out of this object and handed over to the - * other controller. - * This is intended primarily for cleanup. - * @param assimilator The controller which has assimilated this controller. - */ - void onAssimilated(IMultiblockControllerInternal assimilator); - - /** - * Driver for the update loop. If the machine is assembled, runs - * the game logic update method. - */ - void updateMultiblockEntity(); - - /** - * @return The reference coordinate, the block with the lowest x, y, z coordinates, evaluated in that order. - */ - ChunkCoordinates getReferenceCoord(); - - /** - * Force this multiblock to recalculate its minimum and maximum coordinates - * from the list of connected parts. - */ - void recalculateMinMaxCoords(); - - /** - * Called when the save delegate's tile entity is being asked for its description packet - * @param data A fresh compound tag to write your multiblock data into - */ - void formatDescriptionPacket(NBTTagCompound data); - - /** - * Called when the save delegate's tile entity receiving a description packet - * @param data A compound tag containing multiblock data to import - */ - void decodeDescriptionPacket(NBTTagCompound data); - - World getWorld(); - - /** - * @return True if this controller has no associated blocks, false otherwise - */ - boolean isEmpty(); - - /** - * Tests whether this multiblock should consume the other multiblock - * and become the new multiblock master when the two multiblocks - * are adjacent. Assumes both multiblocks are the same type. - * @param otherController The other multiblock controller. - * @return True if this multiblock should consume the other, false otherwise. - */ - boolean shouldConsume(IMultiblockControllerInternal otherController); - - String getPartsListString(); - - /** - * Checks all of the parts in the controller. If any are dead or do not exist in the world, they are removed. - */ - void auditParts(); - - /** - * Called when this machine may need to check for blocks that are no - * longer physically connected to the reference coordinate. - * @return the parts that were disconnected and removed - */ - @Nonnull - Set checkForDisconnections(); - - /** - * Detach all parts. Return a set of all parts which still - * have a valid tile entity. Chunk-safe. - * @return A set of all parts which still have a valid tile entity. - */ - @Nonnull - Set detachAllBlocks(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import forestry.api.core.IErrorLogicSource; +import forestry.api.core.INBTTagable; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.api.multiblock.IMultiblockController; +import forestry.core.access.IRestrictedAccess; +import forestry.core.network.IStreamableGui; +import forestry.core.tiles.IClimatised; +import java.util.Set; +import javax.annotation.Nonnull; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; + +// internal implementation of IMultiblockController +public interface IMultiblockControllerInternal + extends IMultiblockController, INBTTagable, IRestrictedAccess, IErrorLogicSource, IClimatised, IStreamableGui { + /** + * Attach a new part to this machine. + * @param part The part to add. + */ + void attachBlock(IMultiblockComponent part); + + /** + * Call to detach a block from this machine. Generally, this should be called + * when the tile entity is being released, e.g. on block destruction. + * @param part The part to detach from this machine. + * @param chunkUnloading Is this entity detaching due to the chunk unloading? If true, the multiblock will be paused instead of broken. + */ + void detachBlock(IMultiblockComponent part, boolean chunkUnloading); + + /** + * Check if the machine is whole or not. + * If the machine was not whole, but now is, assemble the machine. + * If the machine was whole, but no longer is, disassemble the machine. + */ + void checkIfMachineIsWhole(); + + /** + * Assimilate another controller into this controller. + * Acquire all of the other controller's blocks and attach them + * to this one. + * + * @param other The controller to merge into this one. + */ + void assimilate(IMultiblockControllerInternal other); + + /** + * Called when this machine is consumed by another controller. + * Essentially, forcibly tear down this object. + * @param otherController The controller consuming this controller. + */ + void _onAssimilated(IMultiblockControllerInternal otherController); + + /** + * Callback. Called after this controller is assimilated into another controller. + * All blocks have been stripped out of this object and handed over to the + * other controller. + * This is intended primarily for cleanup. + * @param assimilator The controller which has assimilated this controller. + */ + void onAssimilated(IMultiblockControllerInternal assimilator); + + /** + * Driver for the update loop. If the machine is assembled, runs + * the game logic update method. + */ + void updateMultiblockEntity(); + + /** + * @return The reference coordinate, the block with the lowest x, y, z coordinates, evaluated in that order. + */ + ChunkCoordinates getReferenceCoord(); + + /** + * Force this multiblock to recalculate its minimum and maximum coordinates + * from the list of connected parts. + */ + void recalculateMinMaxCoords(); + + /** + * Called when the save delegate's tile entity is being asked for its description packet + * @param data A fresh compound tag to write your multiblock data into + */ + void formatDescriptionPacket(NBTTagCompound data); + + /** + * Called when the save delegate's tile entity receiving a description packet + * @param data A compound tag containing multiblock data to import + */ + void decodeDescriptionPacket(NBTTagCompound data); + + World getWorld(); + + /** + * @return True if this controller has no associated blocks, false otherwise + */ + boolean isEmpty(); + + /** + * Tests whether this multiblock should consume the other multiblock + * and become the new multiblock master when the two multiblocks + * are adjacent. Assumes both multiblocks are the same type. + * @param otherController The other multiblock controller. + * @return True if this multiblock should consume the other, false otherwise. + */ + boolean shouldConsume(IMultiblockControllerInternal otherController); + + String getPartsListString(); + + /** + * Checks all of the parts in the controller. If any are dead or do not exist in the world, they are removed. + */ + void auditParts(); + + /** + * Called when this machine may need to check for blocks that are no + * longer physically connected to the reference coordinate. + * @return the parts that were disconnected and removed + */ + @Nonnull + Set checkForDisconnections(); + + /** + * Detach all parts. Return a set of all parts which still + * have a valid tile entity. Chunk-safe. + * @return A set of all parts which still have a valid tile entity. + */ + @Nonnull + Set detachAllBlocks(); +} diff --git a/src/main/java/forestry/core/multiblock/IMultiblockSizeLimits.java b/src/main/java/forestry/core/multiblock/IMultiblockSizeLimits.java index 8aa575f4f..088216aa5 100644 --- a/src/main/java/forestry/core/multiblock/IMultiblockSizeLimits.java +++ b/src/main/java/forestry/core/multiblock/IMultiblockSizeLimits.java @@ -1,60 +1,60 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.multiblock; - -public interface IMultiblockSizeLimits { - /** - * Helper method so we don't check for a whole machine until we have enough blocks - * to actually assemble it. This isn't as simple as xmax*ymax*zmax for non-cubic machines - * or for machines with hollow/complex interiors. - * @return The minimum number of blocks connected to the machine for it to be assembled. - */ - int getMinimumNumberOfBlocksForAssembledMachine(); - - /** - * Returns the maximum X dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable - * dimension checking in X. (This is not recommended.) - * @return The maximum X dimension size of the machine, or -1 - */ - int getMaximumXSize(); - - /** - * Returns the maximum Z dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable - * dimension checking in X. (This is not recommended.) - * @return The maximum Z dimension size of the machine, or -1 - */ - int getMaximumZSize(); - - /** - * Returns the maximum Y dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable - * dimension checking in X. (This is not recommended.) - * @return The maximum Y dimension size of the machine, or -1 - */ - int getMaximumYSize(); - - /** - * Returns the minimum X dimension size of the machine. Must be at least 1, because nothing else makes sense. - * @return The minimum X dimension size of the machine - */ - int getMinimumXSize(); - - /** - * Returns the minimum Y dimension size of the machine. Must be at least 1, because nothing else makes sense. - * @return The minimum Y dimension size of the machine - */ - int getMinimumYSize(); - - /** - * Returns the minimum Z dimension size of the machine. Must be at least 1, because nothing else makes sense. - * @return The minimum Z dimension size of the machine - */ - int getMinimumZSize(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +public interface IMultiblockSizeLimits { + /** + * Helper method so we don't check for a whole machine until we have enough blocks + * to actually assemble it. This isn't as simple as xmax*ymax*zmax for non-cubic machines + * or for machines with hollow/complex interiors. + * @return The minimum number of blocks connected to the machine for it to be assembled. + */ + int getMinimumNumberOfBlocksForAssembledMachine(); + + /** + * Returns the maximum X dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable + * dimension checking in X. (This is not recommended.) + * @return The maximum X dimension size of the machine, or -1 + */ + int getMaximumXSize(); + + /** + * Returns the maximum Z dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable + * dimension checking in X. (This is not recommended.) + * @return The maximum Z dimension size of the machine, or -1 + */ + int getMaximumZSize(); + + /** + * Returns the maximum Y dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable + * dimension checking in X. (This is not recommended.) + * @return The maximum Y dimension size of the machine, or -1 + */ + int getMaximumYSize(); + + /** + * Returns the minimum X dimension size of the machine. Must be at least 1, because nothing else makes sense. + * @return The minimum X dimension size of the machine + */ + int getMinimumXSize(); + + /** + * Returns the minimum Y dimension size of the machine. Must be at least 1, because nothing else makes sense. + * @return The minimum Y dimension size of the machine + */ + int getMinimumYSize(); + + /** + * Returns the minimum Z dimension size of the machine. Must be at least 1, because nothing else makes sense. + * @return The minimum Z dimension size of the machine + */ + int getMinimumZSize(); +} diff --git a/src/main/java/forestry/core/multiblock/MultiblockClientTickHandler.java b/src/main/java/forestry/core/multiblock/MultiblockClientTickHandler.java index df3a4b6eb..7fd75ca37 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockClientTickHandler.java +++ b/src/main/java/forestry/core/multiblock/MultiblockClientTickHandler.java @@ -1,16 +1,15 @@ package forestry.core.multiblock; -import net.minecraft.client.Minecraft; - import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; +import net.minecraft.client.Minecraft; public class MultiblockClientTickHandler { - @SubscribeEvent - public void onClientTick(TickEvent.ClientTickEvent event) { - if (event.phase == TickEvent.Phase.START) { - MultiblockRegistry.tickStart(Minecraft.getMinecraft().theWorld); - } - } + @SubscribeEvent + public void onClientTick(TickEvent.ClientTickEvent event) { + if (event.phase == TickEvent.Phase.START) { + MultiblockRegistry.tickStart(Minecraft.getMinecraft().theWorld); + } + } } diff --git a/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java b/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java index 61d3da004..5fc9ab607 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java +++ b/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java @@ -1,6 +1,8 @@ package forestry.core.multiblock; -import javax.annotation.Nonnull; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.core.utils.Log; +import forestry.core.utils.StringUtil; import java.util.Collection; import java.util.Collections; import java.util.HashSet; @@ -8,7 +10,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.Set; - +import javax.annotation.Nonnull; import net.minecraft.block.Block; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; @@ -17,10 +19,6 @@ import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; -import forestry.api.multiblock.IMultiblockComponent; -import forestry.core.utils.Log; -import forestry.core.utils.StringUtil; - /** * This class contains the base logic for "multiblock controllers". Conceptually, they are * meta-TileEntities. They govern the logic for an associated group of TileEntities. @@ -28,856 +26,879 @@ import forestry.core.utils.StringUtil; * Subordinate TileEntities implement the IMultiblockComponent class and, generally, should not have an update() loop. */ public abstract class MultiblockControllerBase implements IMultiblockControllerInternal { - // Multiblock stuff - do not mess with - protected World worldObj; - - // Ticks - private static final Random rand = new Random(); - private int tickCount = rand.nextInt(256); - - // Disassembled -> Assembled; Assembled -> Disassembled OR Paused; Paused -> Assembled - protected enum AssemblyState { - Disassembled, Assembled, Paused - } - - protected AssemblyState assemblyState; - - protected HashSet connectedParts; - - /** This is a deterministically-picked coordinate that identifies this - * multiblock uniquely in its dimension. - * Currently, this is the coord with the lowest X, Y and Z coordinates, in that order of evaluation. - * i.e. If something has a lower X but higher Y/Z coordinates, it will still be the reference. - * If something has the same X but a lower Y coordinate, it will be the reference. Etc. - */ - private ChunkCoordinates referenceCoord; - - /** - * Minimum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine - * is not a cube/rectangular prism. - */ - private ChunkCoordinates minimumCoord; - - /** - * Maximum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine - * is not a cube/rectangular prism. - */ - private ChunkCoordinates maximumCoord; - - /** - * Set to true whenever a part is removed from this controller. - */ - private boolean shouldCheckForDisconnections; - - /** - * Set whenever we validate the multiblock - */ - private MultiblockValidationException lastValidationException; - - protected MultiblockControllerBase(World world) { - this.worldObj = world; - this.connectedParts = new HashSet<>(); - - this.referenceCoord = null; - this.assemblyState = AssemblyState.Disassembled; - - this.minimumCoord = null; - this.maximumCoord = null; - - this.shouldCheckForDisconnections = true; - this.lastValidationException = null; - } - - @Override - @Nonnull - public Collection getComponents() { - return Collections.unmodifiableCollection(connectedParts); - } - - /** - * Call when a block with cached save-delegate data is added to the multiblock. - * The part will be notified that the data has been used after this call completes. - * @param part The NBT tag containing this controller's data. - */ - protected abstract void onAttachedPartWithMultiblockData(IMultiblockComponent part, NBTTagCompound data); - - @Override - public void attachBlock(IMultiblockComponent part) { - ChunkCoordinates coord = part.getCoordinates(); - - if (!connectedParts.add(part)) { - Log.warning("[%s] Controller %s is double-adding part %d @ %s. This is unusual. " + - "If you encounter odd behavior, please tear down the machine and rebuild it.", - (worldObj.isRemote ? "CLIENT" : "SERVER"), hashCode(), part.hashCode(), coord); - } - - MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); - - logic.setController(this); - this.onBlockAdded(part); - - if (logic.hasMultiblockSaveData()) { - NBTTagCompound savedData = logic.getMultiblockSaveData(); - onAttachedPartWithMultiblockData(part, savedData); - logic.onMultiblockDataAssimilated(); - } - - if (this.referenceCoord == null) { - referenceCoord = coord; - logic.becomeMultiblockSaveDelegate(); - } else if (coord.compareTo(referenceCoord) < 0) { - TileEntity te = this.worldObj.getTileEntity(referenceCoord.posX, referenceCoord.posY, referenceCoord.posZ); - if (te instanceof IMultiblockComponent) { - IMultiblockComponent tePart = (IMultiblockComponent) te; - MultiblockLogic teLogic = (MultiblockLogic) tePart.getMultiblockLogic(); - teLogic.forfeitMultiblockSaveDelegate(); - } - - referenceCoord = coord; - logic.becomeMultiblockSaveDelegate(); - } else { - logic.forfeitMultiblockSaveDelegate(); - } - - if (minimumCoord != null) { - if (coord.posX < minimumCoord.posX) { - minimumCoord.posX = coord.posX; - } - if (coord.posY < minimumCoord.posY) { - minimumCoord.posY = coord.posY; - } - if (coord.posZ < minimumCoord.posZ) { - minimumCoord.posZ = coord.posZ; - } - } - - if (maximumCoord != null) { - if (coord.posX > maximumCoord.posX) { - maximumCoord.posX = coord.posX; - } - if (coord.posY > maximumCoord.posY) { - maximumCoord.posY = coord.posY; - } - if (coord.posZ > maximumCoord.posZ) { - maximumCoord.posZ = coord.posZ; - } - } - - MultiblockRegistry.addDirtyController(worldObj, this); - } - - /** - * Called when a new part is added to the machine. Good time to register things into lists. - * @param newPart The part being added. - */ - protected abstract void onBlockAdded(IMultiblockComponent newPart); - - /** - * Called when a part is removed from the machine. Good time to clean up lists. - * @param oldPart The part being removed. - */ - protected abstract void onBlockRemoved(IMultiblockComponent oldPart); - - /** - * Called when a machine is assembled from a disassembled state. - */ - protected void onMachineAssembled() { - - } - - /** - * Called when a machine is restored to the assembled state from a paused state. - */ - protected void onMachineRestored() { - - } - - /** - * Called when a machine is paused from an assembled state - * This generally only happens due to chunk-loads and other "system" events. - */ - protected void onMachinePaused() { - - } - - /** - * Called when a machine is disassembled from an assembled state. - * This happens due to user or in-game actions (e.g. explosions) - */ - protected void onMachineDisassembled() { - - } - - /** - * Callback whenever a part is removed (or will very shortly be removed) from a controller. - * Do housekeeping/callbacks, also nulls min/max coords. - * @param part The part being removed. - */ - private void onDetachBlock(IMultiblockComponent part) { - // Strip out this part - MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); - logic.setController(null); - this.onBlockRemoved(part); - logic.forfeitMultiblockSaveDelegate(); - - minimumCoord = maximumCoord = null; - - if (referenceCoord != null && referenceCoord.equals(part.getCoordinates())) { - referenceCoord = null; - } - - shouldCheckForDisconnections = true; - } - - @Override - public void detachBlock(IMultiblockComponent part, boolean chunkUnloading) { - if (chunkUnloading && this.assemblyState == AssemblyState.Assembled) { - this.assemblyState = AssemblyState.Paused; - this.onMachinePaused(); - } - - // Strip out this part - onDetachBlock(part); - if (!connectedParts.remove(part)) { - ChunkCoordinates partCoords = part.getCoordinates(); - Log.warning("[%s] Double-removing part (%d) @ %d, %d, %d, this is unexpected and may cause problems. " + - "If you encounter anomalies, please tear down the reactor and rebuild it.", - worldObj.isRemote ? "CLIENT" : "SERVER", part.hashCode(), partCoords.posX, partCoords.posY, partCoords.posZ); - } - - if (connectedParts.isEmpty()) { - // Destroy/unregister - MultiblockRegistry.addDeadController(this.worldObj, this); - return; - } - - MultiblockRegistry.addDirtyController(this.worldObj, this); - - // Find new save delegate if we need to. - if (referenceCoord == null) { - selectNewReferenceCoord(); - } - } - - @Override - public String getLastValidationError() { - if (lastValidationException == null) { - return null; - } - return lastValidationException.getMessage(); - } - - @Override - public void reassemble() { - MultiblockRegistry.addDirtyController(worldObj, this); - } - - /** - * Checks if a machine is whole. If not, throws an exception with the reason why. - */ - protected abstract void isMachineWhole() throws MultiblockValidationException; - - @Override - public void checkIfMachineIsWhole() { - AssemblyState oldState = this.assemblyState; - boolean isWhole; - lastValidationException = null; - try { - isMachineWhole(); - isWhole = true; - } catch (MultiblockValidationException e) { - lastValidationException = e; - isWhole = false; - } - - if (isWhole) { - // This will alter assembly state - assembleMachine(oldState); - } else if (oldState == AssemblyState.Assembled) { - // This will alter assembly state - disassembleMachine(); - } - // Else Paused, do nothing - } - - /** - * Called when a machine becomes "whole" and should begin - * functioning as a game-logically finished machine. - * Calls onMachineAssembled on all attached parts. - */ - private void assembleMachine(AssemblyState oldState) { - this.assemblyState = AssemblyState.Assembled; - - for (IMultiblockComponent part : connectedParts) { - part.onMachineAssembled(this, getMinimumCoord(), getMaximumCoord()); - } - - if (oldState == AssemblyState.Paused) { - onMachineRestored(); - } else { - onMachineAssembled(); - } - } - - /** - * Called when the machine needs to be disassembled. - * It is not longer "whole" and should not be functional, usually - * as a result of a block being removed. - * Calls onMachineBroken on all attached parts. - */ - private void disassembleMachine() { - this.assemblyState = AssemblyState.Disassembled; - - for (IMultiblockComponent part : connectedParts) { - part.onMachineBroken(); - } - - onMachineDisassembled(); - } - - @Override - public void assimilate(IMultiblockControllerInternal other) { - ChunkCoordinates otherReferenceCoord = other.getReferenceCoord(); - if (otherReferenceCoord != null && getReferenceCoord().compareTo(otherReferenceCoord) >= 0) { - throw new IllegalArgumentException("The controller with the lowest minimum-coord value must consume the one with the higher coords"); - } - - Set partsToAcquire = new HashSet<>(other.getComponents()); - - // releases all blocks and references gently so they can be incorporated into another multiblock - other._onAssimilated(this); - - for (IMultiblockComponent acquiredPart : partsToAcquire) { - // By definition, none of these can be the minimum block. - if (isInvalid(acquiredPart)) { - continue; - } - - connectedParts.add(acquiredPart); - MultiblockLogic logic = (MultiblockLogic) acquiredPart.getMultiblockLogic(); - logic.setController(this); - this.onBlockAdded(acquiredPart); - } - - this.onAssimilate(other); - other.onAssimilated(this); - } - - /** - * Called when this machine is consumed by another controller. - * Essentially, forcibly tear down this object. - * @param otherController The controller consuming this controller. - */ - @Override - public void _onAssimilated(IMultiblockControllerInternal otherController) { - if (referenceCoord != null) { - if (worldObj.getChunkProvider().chunkExists(referenceCoord.posX >> 4, referenceCoord.posZ >> 4)) { - TileEntity te = this.worldObj.getTileEntity(referenceCoord.posX, referenceCoord.posY, referenceCoord.posZ); - if (te instanceof IMultiblockComponent) { - IMultiblockComponent part = (IMultiblockComponent) te; - MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); - logic.forfeitMultiblockSaveDelegate(); - } - } - this.referenceCoord = null; - } - - connectedParts.clear(); - } - - /** - * Callback. Called after this controller assimilates all the blocks - * from another controller. - * Use this to absorb that controller's game data. - * @param assimilated The controller whose uniqueness was added to our own. - */ - protected abstract void onAssimilate(IMultiblockControllerInternal assimilated); - - /** - * Callback. Called after this controller is assimilated into another controller. - * All blocks have been stripped out of this object and handed over to the - * other controller. - * This is intended primarily for cleanup. - * @param assimilator The controller which has assimilated this controller. - */ - @Override - public abstract void onAssimilated(IMultiblockControllerInternal assimilator); - - @Override - public final void updateMultiblockEntity() { - tickCount++; - - if (connectedParts.isEmpty()) { - // This shouldn't happen, but just in case... - MultiblockRegistry.addDeadController(this.worldObj, this); - return; - } - - if (this.assemblyState != AssemblyState.Assembled) { - // Not assembled - don't run game logic - return; - } - - if (worldObj.isRemote) { - updateClient(tickCount); - } else if (updateServer(tickCount)) { - // If this returns true, the server has changed its internal data. - // If our chunks are loaded (they should be), we must mark our chunks as dirty. - if (minimumCoord != null && maximumCoord != null && - this.worldObj.checkChunksExist(minimumCoord.posX, minimumCoord.posY, minimumCoord.posZ, - maximumCoord.posX, maximumCoord.posY, maximumCoord.posZ)) { - int minChunkX = minimumCoord.posX >> 4; - int minChunkZ = minimumCoord.posZ >> 4; - int maxChunkX = maximumCoord.posX >> 4; - int maxChunkZ = maximumCoord.posZ >> 4; - - for (int x = minChunkX; x <= maxChunkX; x++) { - for (int z = minChunkZ; z <= maxChunkZ; z++) { - // Ensure that we save our data, even if the our save delegate is in has no TEs. - Chunk chunkToSave = this.worldObj.getChunkFromChunkCoords(x, z); - chunkToSave.setChunkModified(); - } - } - } - } - // Else: Server, but no need to save data. - } - - /** - * The server-side update loop! Use this similarly to a TileEntity's update loop. - * You do not need to call your superclass' update() if you're directly - * derived from MultiblockControllerBase. This is a callback. - * Note that this will only be called when the machine is assembled. - * @return True if the multiblock should save data, i.e. its internal game state has changed. False otherwise. - */ - protected abstract boolean updateServer(int tickCount); - - /** - * Client-side update loop. Generally, this shouldn't do anything, but if you want - * to do some interpolation or something, do it here. - */ - protected abstract void updateClient(int tickCount); - - protected final boolean updateOnInterval(int tickInterval) { - return tickCount % tickInterval == 0; - } - - // Validation helpers - - /** - * @param level the level of the block on the multiblock, starting at 0 for the bottom. - * @param world World object for the world in which this controller is located. - * @param x X coordinate of the block being tested - * @param y Y coordinate of the block being tested - * @param z Z coordinate of the block being tested - * @throws MultiblockValidationException if the tested block is not allowed on the machine's side faces - */ - protected void isBlockGoodForExteriorLevel(int level, World world, int x, int y, int z) throws MultiblockValidationException { - Block block = world.getBlock(x, y, z); - throw new MultiblockValidationException(StringUtil.localizeAndFormatRaw("for.multiblock.error.invalid.interior", x, y, z, block.getLocalizedName())); - } - - /** - * The interior is any block that does not touch blocks outside the machine. - * @param world World object for the world in which this controller is located. - * @param x X coordinate of the block being tested - * @param y Y coordinate of the block being tested - * @param z Z coordinate of the block being tested - * @throws MultiblockValidationException if the tested block is not allowed in the machine's interior - */ - protected void isBlockGoodForInterior(World world, int x, int y, int z) throws MultiblockValidationException { - Block block = world.getBlock(x, y, z); - throw new MultiblockValidationException(StringUtil.localizeAndFormatRaw("for.multiblock.error.invalid.interior", x, y, z, block.getLocalizedName())); - } - - @Override - public ChunkCoordinates getReferenceCoord() { - if (referenceCoord == null) { - selectNewReferenceCoord(); - } - return referenceCoord; - } - - /** - * @return The number of blocks connected to this controller. - */ - public int getNumConnectedBlocks() { - return connectedParts.size(); - } - - @Override - public void recalculateMinMaxCoords() { - minimumCoord = new ChunkCoordinates(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); - maximumCoord = new ChunkCoordinates(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); - - for (IMultiblockComponent part : connectedParts) { - ChunkCoordinates partCoords = part.getCoordinates(); - if (partCoords.posX < minimumCoord.posX) { - minimumCoord.posX = partCoords.posX; - } - if (partCoords.posX > maximumCoord.posX) { - maximumCoord.posX = partCoords.posX; - } - if (partCoords.posY < minimumCoord.posY) { - minimumCoord.posY = partCoords.posY; - } - if (partCoords.posY > maximumCoord.posY) { - maximumCoord.posY = partCoords.posY; - } - if (partCoords.posZ < minimumCoord.posZ) { - minimumCoord.posZ = partCoords.posZ; - } - if (partCoords.posZ > maximumCoord.posZ) { - maximumCoord.posZ = partCoords.posZ; - } - } - } - - /** - * @return The minimum bounding-box coordinate containing this machine's blocks. - */ - protected ChunkCoordinates getMinimumCoord() { - if (minimumCoord == null) { - recalculateMinMaxCoords(); - } - return new ChunkCoordinates(minimumCoord); - } - - /** - * @return The maximum bounding-box coordinate containing this machine's blocks. - */ - protected ChunkCoordinates getMaximumCoord() { - if (maximumCoord == null) { - recalculateMinMaxCoords(); - } - return new ChunkCoordinates(maximumCoord); - } - - protected final ChunkCoordinates getCenterCoord() { - ChunkCoordinates minCoord = getMinimumCoord(); - ChunkCoordinates maxCoord = getMaximumCoord(); - - return new ChunkCoordinates( - (minCoord.posX + maxCoord.posX) / 2, - (minCoord.posY + maxCoord.posY) / 2, - (minCoord.posZ + maxCoord.posZ) / 2 - ); - } - - protected final ChunkCoordinates getTopCenterCoord() { - ChunkCoordinates minCoord = getMinimumCoord(); - ChunkCoordinates maxCoord = getMaximumCoord(); - - return new ChunkCoordinates( - (minCoord.posX + maxCoord.posX) / 2, - maxCoord.posY, - (minCoord.posZ + maxCoord.posZ) / 2 - ); - } - - protected final boolean isCoordInMultiblock(int x, int y, int z) { - return (x >= minimumCoord.posX && x <= maximumCoord.posX) && (y >= minimumCoord.posY && y <= maximumCoord.posY) && (z >= minimumCoord.posZ && z <= maximumCoord.posZ); - } - - @Override - public boolean isEmpty() { - return connectedParts.isEmpty(); - } - - @Override - public boolean shouldConsume(IMultiblockControllerInternal otherController) { - if (!otherController.getClass().equals(getClass())) { - throw new IllegalArgumentException("Attempting to merge two multiblocks with different master classes - this should never happen!"); - } - - if (otherController == this) { - return false; - } // Don't be silly, don't eat yourself. - - int res = _shouldConsume(otherController); - if (res < 0) { - return true; - } else if (res > 0) { - return false; - } else { - // Strip dead parts from both and retry - Log.warning("[%s] Encountered two controllers with the same reference coordinate. Auditing connected parts and retrying.", worldObj.isRemote ? "CLIENT" : "SERVER"); - auditParts(); - otherController.auditParts(); - - res = _shouldConsume(otherController); - if (res < 0) { - return true; - } else if (res > 0) { - return false; - } else { - Log.severe("My Controller (%d): size (%d), parts: %s", hashCode(), connectedParts.size(), getPartsListString()); - Log.severe("Other Controller (%d): size (%d), coords: %s", otherController.hashCode(), otherController.getComponents().size(), otherController.getPartsListString()); - throw new IllegalArgumentException("[" + (worldObj.isRemote ? "CLIENT" : "SERVER") + "] " + - "Two controllers with the same reference coord that somehow both have valid parts - this should never happen!"); - } - - } - } - - private int _shouldConsume(IMultiblockControllerInternal otherController) { - ChunkCoordinates myCoord = getReferenceCoord(); - ChunkCoordinates theirCoord = otherController.getReferenceCoord(); - - // Always consume other controllers if their reference coordinate is null - this means they're empty and can be assimilated on the cheap - if (theirCoord == null) { - return -1; - } else { - return myCoord.compareTo(theirCoord); - } - } - - @Override - public String getPartsListString() { - StringBuilder sb = new StringBuilder(); - boolean first = true; - for (IMultiblockComponent part : connectedParts) { - if (!first) { - sb.append(", "); - } - ChunkCoordinates partCoord = part.getCoordinates(); - sb.append(String.format("(%d: %d, %d, %d)", part.hashCode(), partCoord.posX, partCoord.posY, partCoord.posZ)); - first = false; - } - - return sb.toString(); - } - - @Override - public void auditParts() { - HashSet deadParts = new HashSet<>(); - for (IMultiblockComponent part : connectedParts) { - ChunkCoordinates partCoord = part.getCoordinates(); - if (isInvalid(part) || worldObj.getTileEntity(partCoord.posX, partCoord.posY, partCoord.posZ) != part) { - onDetachBlock(part); - deadParts.add(part); - } - } - - connectedParts.removeAll(deadParts); - Log.warning("[%s] Controller found %d dead parts during an audit, %d parts remain attached", worldObj.isRemote ? "CLIENT" : "SERVER", deadParts.size(), connectedParts.size()); - } - - @Override - @Nonnull - public Set checkForDisconnections() { - if (!this.shouldCheckForDisconnections) { - return Collections.emptySet(); - } - - if (this.isEmpty()) { - MultiblockRegistry.addDeadController(worldObj, this); - return Collections.emptySet(); - } - - IChunkProvider chunkProvider = worldObj.getChunkProvider(); - - // Invalidate our reference coord, we'll recalculate it shortly - referenceCoord = null; - - // Reset visitations and find the minimum coordinate - Set deadParts = new HashSet<>(); - ChunkCoordinates c; - IMultiblockComponent referencePart = null; - - int originalSize = connectedParts.size(); - - for (IMultiblockComponent part : connectedParts) { - // This happens during chunk unload. - ChunkCoordinates partCoord = part.getCoordinates(); - if (!chunkProvider.chunkExists(partCoord.posX >> 4, partCoord.posZ >> 4) || isInvalid(part)) { - deadParts.add(part); - onDetachBlock(part); - continue; - } - - if (worldObj.getTileEntity(partCoord.posX, partCoord.posY, partCoord.posZ) != part) { - deadParts.add(part); - onDetachBlock(part); - continue; - } - - MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); - - logic.setUnvisited(); - logic.forfeitMultiblockSaveDelegate(); - - c = part.getCoordinates(); - if (referenceCoord == null) { - referenceCoord = c; - referencePart = part; - } else if (c.compareTo(referenceCoord) < 0) { - referenceCoord = c; - referencePart = part; - } - } - - connectedParts.removeAll(deadParts); - deadParts.clear(); - - if (referencePart == null || isEmpty()) { - // There are no valid parts remaining. The entire multiblock was unloaded during a chunk unload. Halt. - shouldCheckForDisconnections = false; - MultiblockRegistry.addDeadController(worldObj, this); - return Collections.emptySet(); - } else { - MultiblockLogic logic = (MultiblockLogic) referencePart.getMultiblockLogic(); - logic.becomeMultiblockSaveDelegate(); - } - - // Now visit all connected parts, breadth-first, starting from reference coord's part - IMultiblockComponent part; - LinkedList partsToCheck = new LinkedList<>(); - - partsToCheck.add(referencePart); - - while (!partsToCheck.isEmpty()) { - part = partsToCheck.removeFirst(); - MultiblockLogic partLogic = (MultiblockLogic) part.getMultiblockLogic(); - partLogic.setVisited(); - - List nearbyParts = MultiblockUtil.getNeighboringParts(worldObj, part); // Chunk-safe on server, but not on client - for (IMultiblockComponent nearbyPart : nearbyParts) { - // Ignore different machines - MultiblockLogic nearbyPartLogic = (MultiblockLogic) nearbyPart.getMultiblockLogic(); - if (nearbyPartLogic.getController() != this) { - continue; - } - - if (!nearbyPartLogic.isVisited()) { - nearbyPartLogic.setVisited(); - partsToCheck.add(nearbyPart); - } - } - } - - // Finally, remove all parts that remain disconnected. - Set removedParts = new HashSet<>(); - for (IMultiblockComponent orphanCandidate : connectedParts) { - MultiblockLogic logic = (MultiblockLogic) orphanCandidate.getMultiblockLogic(); - if (!logic.isVisited()) { - deadParts.add(orphanCandidate); - onDetachBlock(orphanCandidate); - removedParts.add(orphanCandidate); - } - } - - // Trim any blocks that were invalid, or were removed. - connectedParts.removeAll(deadParts); - - // Cleanup. Not necessary, really. - deadParts.clear(); - - // Juuuust in case. - if (referenceCoord == null) { - selectNewReferenceCoord(); - } - - // We've run the checks from here on out. - shouldCheckForDisconnections = false; - - return removedParts; - } - - @Override - @Nonnull - public Set detachAllBlocks() { - if (worldObj == null) { - return new HashSet<>(); - } - - IChunkProvider chunkProvider = worldObj.getChunkProvider(); - for (IMultiblockComponent part : connectedParts) { - ChunkCoordinates partCoord = part.getCoordinates(); - if (chunkProvider.chunkExists(partCoord.posX >> 4, partCoord.posZ >> 4)) { - onDetachBlock(part); - } - } - - Set detachedParts = connectedParts; - connectedParts = new HashSet<>(); - return detachedParts; - } - - /** - * @return True if this multiblock machine is considered assembled and ready to go. - */ - @Override - public boolean isAssembled() { - return this.assemblyState == AssemblyState.Assembled; - } - - private void selectNewReferenceCoord() { - IChunkProvider chunkProvider = worldObj.getChunkProvider(); - IMultiblockComponent theChosenOne = null; - referenceCoord = null; - - for (IMultiblockComponent part : connectedParts) { - ChunkCoordinates partCoord = part.getCoordinates(); - if (isInvalid(part) || !chunkProvider.chunkExists(partCoord.posX >> 4, partCoord.posZ >> 4)) { - // Chunk is unloading, skip this coord to prevent chunk thrashing - continue; - } - - if (referenceCoord == null || referenceCoord.compareTo(partCoord) > 0) { - referenceCoord = part.getCoordinates(); - theChosenOne = part; - } - } - - if (theChosenOne != null) { - MultiblockLogic logic = (MultiblockLogic) theChosenOne.getMultiblockLogic(); - logic.becomeMultiblockSaveDelegate(); - } - } - - /** - * Marks the reference coord dirty & updateable. - * - * On the server, this will mark the for a data-update, so that - * nearby clients will receive an updated description packet from the server - * after a short time. The block's chunk will also be marked dirty and the - * block's chunk will be saved to disk the next time chunks are saved. - * - * On the client, this will mark the block for a rendering update. - */ - protected void markReferenceCoordForUpdate() { - ChunkCoordinates rc = getReferenceCoord(); - if (worldObj != null && rc != null) { - worldObj.markBlockForUpdate(rc.posX, rc.posY, rc.posZ); - } - } - - /** - * Marks the reference coord dirty. - * - * On the server, this marks the reference coord's chunk as dirty; the block (and chunk) - * will be saved to disk the next time chunks are saved. This does NOT mark it dirty for - * a description-packet update. - * - * On the client, does nothing. - * @see MultiblockControllerBase#markReferenceCoordForUpdate() - */ - protected void markReferenceCoordDirty() { - if (worldObj == null || worldObj.isRemote) { - return; - } - - ChunkCoordinates referenceCoord = getReferenceCoord(); - if (referenceCoord == null) { - return; - } - - TileEntity saveTe = worldObj.getTileEntity(referenceCoord.posX, referenceCoord.posY, referenceCoord.posZ); - worldObj.markTileEntityChunkModified(referenceCoord.posX, referenceCoord.posY, referenceCoord.posZ, saveTe); - } - - private static boolean isInvalid(IMultiblockComponent part) { - return part instanceof TileEntity && ((TileEntity) part).isInvalid(); - } + // Multiblock stuff - do not mess with + protected World worldObj; + + // Ticks + private static final Random rand = new Random(); + private int tickCount = rand.nextInt(256); + + // Disassembled -> Assembled; Assembled -> Disassembled OR Paused; Paused -> Assembled + protected enum AssemblyState { + Disassembled, + Assembled, + Paused + } + + protected AssemblyState assemblyState; + + protected HashSet connectedParts; + + /** This is a deterministically-picked coordinate that identifies this + * multiblock uniquely in its dimension. + * Currently, this is the coord with the lowest X, Y and Z coordinates, in that order of evaluation. + * i.e. If something has a lower X but higher Y/Z coordinates, it will still be the reference. + * If something has the same X but a lower Y coordinate, it will be the reference. Etc. + */ + private ChunkCoordinates referenceCoord; + + /** + * Minimum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine + * is not a cube/rectangular prism. + */ + private ChunkCoordinates minimumCoord; + + /** + * Maximum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine + * is not a cube/rectangular prism. + */ + private ChunkCoordinates maximumCoord; + + /** + * Set to true whenever a part is removed from this controller. + */ + private boolean shouldCheckForDisconnections; + + /** + * Set whenever we validate the multiblock + */ + private MultiblockValidationException lastValidationException; + + protected MultiblockControllerBase(World world) { + this.worldObj = world; + this.connectedParts = new HashSet<>(); + + this.referenceCoord = null; + this.assemblyState = AssemblyState.Disassembled; + + this.minimumCoord = null; + this.maximumCoord = null; + + this.shouldCheckForDisconnections = true; + this.lastValidationException = null; + } + + @Override + @Nonnull + public Collection getComponents() { + return Collections.unmodifiableCollection(connectedParts); + } + + /** + * Call when a block with cached save-delegate data is added to the multiblock. + * The part will be notified that the data has been used after this call completes. + * @param part The NBT tag containing this controller's data. + */ + protected abstract void onAttachedPartWithMultiblockData(IMultiblockComponent part, NBTTagCompound data); + + @Override + public void attachBlock(IMultiblockComponent part) { + ChunkCoordinates coord = part.getCoordinates(); + + if (!connectedParts.add(part)) { + Log.warning( + "[%s] Controller %s is double-adding part %d @ %s. This is unusual. " + + "If you encounter odd behavior, please tear down the machine and rebuild it.", + (worldObj.isRemote ? "CLIENT" : "SERVER"), hashCode(), part.hashCode(), coord); + } + + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); + + logic.setController(this); + this.onBlockAdded(part); + + if (logic.hasMultiblockSaveData()) { + NBTTagCompound savedData = logic.getMultiblockSaveData(); + onAttachedPartWithMultiblockData(part, savedData); + logic.onMultiblockDataAssimilated(); + } + + if (this.referenceCoord == null) { + referenceCoord = coord; + logic.becomeMultiblockSaveDelegate(); + } else if (coord.compareTo(referenceCoord) < 0) { + TileEntity te = this.worldObj.getTileEntity(referenceCoord.posX, referenceCoord.posY, referenceCoord.posZ); + if (te instanceof IMultiblockComponent) { + IMultiblockComponent tePart = (IMultiblockComponent) te; + MultiblockLogic teLogic = (MultiblockLogic) tePart.getMultiblockLogic(); + teLogic.forfeitMultiblockSaveDelegate(); + } + + referenceCoord = coord; + logic.becomeMultiblockSaveDelegate(); + } else { + logic.forfeitMultiblockSaveDelegate(); + } + + if (minimumCoord != null) { + if (coord.posX < minimumCoord.posX) { + minimumCoord.posX = coord.posX; + } + if (coord.posY < minimumCoord.posY) { + minimumCoord.posY = coord.posY; + } + if (coord.posZ < minimumCoord.posZ) { + minimumCoord.posZ = coord.posZ; + } + } + + if (maximumCoord != null) { + if (coord.posX > maximumCoord.posX) { + maximumCoord.posX = coord.posX; + } + if (coord.posY > maximumCoord.posY) { + maximumCoord.posY = coord.posY; + } + if (coord.posZ > maximumCoord.posZ) { + maximumCoord.posZ = coord.posZ; + } + } + + MultiblockRegistry.addDirtyController(worldObj, this); + } + + /** + * Called when a new part is added to the machine. Good time to register things into lists. + * @param newPart The part being added. + */ + protected abstract void onBlockAdded(IMultiblockComponent newPart); + + /** + * Called when a part is removed from the machine. Good time to clean up lists. + * @param oldPart The part being removed. + */ + protected abstract void onBlockRemoved(IMultiblockComponent oldPart); + + /** + * Called when a machine is assembled from a disassembled state. + */ + protected void onMachineAssembled() {} + + /** + * Called when a machine is restored to the assembled state from a paused state. + */ + protected void onMachineRestored() {} + + /** + * Called when a machine is paused from an assembled state + * This generally only happens due to chunk-loads and other "system" events. + */ + protected void onMachinePaused() {} + + /** + * Called when a machine is disassembled from an assembled state. + * This happens due to user or in-game actions (e.g. explosions) + */ + protected void onMachineDisassembled() {} + + /** + * Callback whenever a part is removed (or will very shortly be removed) from a controller. + * Do housekeeping/callbacks, also nulls min/max coords. + * @param part The part being removed. + */ + private void onDetachBlock(IMultiblockComponent part) { + // Strip out this part + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); + logic.setController(null); + this.onBlockRemoved(part); + logic.forfeitMultiblockSaveDelegate(); + + minimumCoord = maximumCoord = null; + + if (referenceCoord != null && referenceCoord.equals(part.getCoordinates())) { + referenceCoord = null; + } + + shouldCheckForDisconnections = true; + } + + @Override + public void detachBlock(IMultiblockComponent part, boolean chunkUnloading) { + if (chunkUnloading && this.assemblyState == AssemblyState.Assembled) { + this.assemblyState = AssemblyState.Paused; + this.onMachinePaused(); + } + + // Strip out this part + onDetachBlock(part); + if (!connectedParts.remove(part)) { + ChunkCoordinates partCoords = part.getCoordinates(); + Log.warning( + "[%s] Double-removing part (%d) @ %d, %d, %d, this is unexpected and may cause problems. " + + "If you encounter anomalies, please tear down the reactor and rebuild it.", + worldObj.isRemote ? "CLIENT" : "SERVER", + part.hashCode(), + partCoords.posX, + partCoords.posY, + partCoords.posZ); + } + + if (connectedParts.isEmpty()) { + // Destroy/unregister + MultiblockRegistry.addDeadController(this.worldObj, this); + return; + } + + MultiblockRegistry.addDirtyController(this.worldObj, this); + + // Find new save delegate if we need to. + if (referenceCoord == null) { + selectNewReferenceCoord(); + } + } + + @Override + public String getLastValidationError() { + if (lastValidationException == null) { + return null; + } + return lastValidationException.getMessage(); + } + + @Override + public void reassemble() { + MultiblockRegistry.addDirtyController(worldObj, this); + } + + /** + * Checks if a machine is whole. If not, throws an exception with the reason why. + */ + protected abstract void isMachineWhole() throws MultiblockValidationException; + + @Override + public void checkIfMachineIsWhole() { + AssemblyState oldState = this.assemblyState; + boolean isWhole; + lastValidationException = null; + try { + isMachineWhole(); + isWhole = true; + } catch (MultiblockValidationException e) { + lastValidationException = e; + isWhole = false; + } + + if (isWhole) { + // This will alter assembly state + assembleMachine(oldState); + } else if (oldState == AssemblyState.Assembled) { + // This will alter assembly state + disassembleMachine(); + } + // Else Paused, do nothing + } + + /** + * Called when a machine becomes "whole" and should begin + * functioning as a game-logically finished machine. + * Calls onMachineAssembled on all attached parts. + */ + private void assembleMachine(AssemblyState oldState) { + this.assemblyState = AssemblyState.Assembled; + + for (IMultiblockComponent part : connectedParts) { + part.onMachineAssembled(this, getMinimumCoord(), getMaximumCoord()); + } + + if (oldState == AssemblyState.Paused) { + onMachineRestored(); + } else { + onMachineAssembled(); + } + } + + /** + * Called when the machine needs to be disassembled. + * It is not longer "whole" and should not be functional, usually + * as a result of a block being removed. + * Calls onMachineBroken on all attached parts. + */ + private void disassembleMachine() { + this.assemblyState = AssemblyState.Disassembled; + + for (IMultiblockComponent part : connectedParts) { + part.onMachineBroken(); + } + + onMachineDisassembled(); + } + + @Override + public void assimilate(IMultiblockControllerInternal other) { + ChunkCoordinates otherReferenceCoord = other.getReferenceCoord(); + if (otherReferenceCoord != null && getReferenceCoord().compareTo(otherReferenceCoord) >= 0) { + throw new IllegalArgumentException( + "The controller with the lowest minimum-coord value must consume the one with the higher coords"); + } + + Set partsToAcquire = new HashSet<>(other.getComponents()); + + // releases all blocks and references gently so they can be incorporated into another multiblock + other._onAssimilated(this); + + for (IMultiblockComponent acquiredPart : partsToAcquire) { + // By definition, none of these can be the minimum block. + if (isInvalid(acquiredPart)) { + continue; + } + + connectedParts.add(acquiredPart); + MultiblockLogic logic = (MultiblockLogic) acquiredPart.getMultiblockLogic(); + logic.setController(this); + this.onBlockAdded(acquiredPart); + } + + this.onAssimilate(other); + other.onAssimilated(this); + } + + /** + * Called when this machine is consumed by another controller. + * Essentially, forcibly tear down this object. + * @param otherController The controller consuming this controller. + */ + @Override + public void _onAssimilated(IMultiblockControllerInternal otherController) { + if (referenceCoord != null) { + if (worldObj.getChunkProvider().chunkExists(referenceCoord.posX >> 4, referenceCoord.posZ >> 4)) { + TileEntity te = + this.worldObj.getTileEntity(referenceCoord.posX, referenceCoord.posY, referenceCoord.posZ); + if (te instanceof IMultiblockComponent) { + IMultiblockComponent part = (IMultiblockComponent) te; + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); + logic.forfeitMultiblockSaveDelegate(); + } + } + this.referenceCoord = null; + } + + connectedParts.clear(); + } + + /** + * Callback. Called after this controller assimilates all the blocks + * from another controller. + * Use this to absorb that controller's game data. + * @param assimilated The controller whose uniqueness was added to our own. + */ + protected abstract void onAssimilate(IMultiblockControllerInternal assimilated); + + /** + * Callback. Called after this controller is assimilated into another controller. + * All blocks have been stripped out of this object and handed over to the + * other controller. + * This is intended primarily for cleanup. + * @param assimilator The controller which has assimilated this controller. + */ + @Override + public abstract void onAssimilated(IMultiblockControllerInternal assimilator); + + @Override + public final void updateMultiblockEntity() { + tickCount++; + + if (connectedParts.isEmpty()) { + // This shouldn't happen, but just in case... + MultiblockRegistry.addDeadController(this.worldObj, this); + return; + } + + if (this.assemblyState != AssemblyState.Assembled) { + // Not assembled - don't run game logic + return; + } + + if (worldObj.isRemote) { + updateClient(tickCount); + } else if (updateServer(tickCount)) { + // If this returns true, the server has changed its internal data. + // If our chunks are loaded (they should be), we must mark our chunks as dirty. + if (minimumCoord != null + && maximumCoord != null + && this.worldObj.checkChunksExist( + minimumCoord.posX, + minimumCoord.posY, + minimumCoord.posZ, + maximumCoord.posX, + maximumCoord.posY, + maximumCoord.posZ)) { + int minChunkX = minimumCoord.posX >> 4; + int minChunkZ = minimumCoord.posZ >> 4; + int maxChunkX = maximumCoord.posX >> 4; + int maxChunkZ = maximumCoord.posZ >> 4; + + for (int x = minChunkX; x <= maxChunkX; x++) { + for (int z = minChunkZ; z <= maxChunkZ; z++) { + // Ensure that we save our data, even if the our save delegate is in has no TEs. + Chunk chunkToSave = this.worldObj.getChunkFromChunkCoords(x, z); + chunkToSave.setChunkModified(); + } + } + } + } + // Else: Server, but no need to save data. + } + + /** + * The server-side update loop! Use this similarly to a TileEntity's update loop. + * You do not need to call your superclass' update() if you're directly + * derived from MultiblockControllerBase. This is a callback. + * Note that this will only be called when the machine is assembled. + * @return True if the multiblock should save data, i.e. its internal game state has changed. False otherwise. + */ + protected abstract boolean updateServer(int tickCount); + + /** + * Client-side update loop. Generally, this shouldn't do anything, but if you want + * to do some interpolation or something, do it here. + */ + protected abstract void updateClient(int tickCount); + + protected final boolean updateOnInterval(int tickInterval) { + return tickCount % tickInterval == 0; + } + + // Validation helpers + + /** + * @param level the level of the block on the multiblock, starting at 0 for the bottom. + * @param world World object for the world in which this controller is located. + * @param x X coordinate of the block being tested + * @param y Y coordinate of the block being tested + * @param z Z coordinate of the block being tested + * @throws MultiblockValidationException if the tested block is not allowed on the machine's side faces + */ + protected void isBlockGoodForExteriorLevel(int level, World world, int x, int y, int z) + throws MultiblockValidationException { + Block block = world.getBlock(x, y, z); + throw new MultiblockValidationException(StringUtil.localizeAndFormatRaw( + "for.multiblock.error.invalid.interior", x, y, z, block.getLocalizedName())); + } + + /** + * The interior is any block that does not touch blocks outside the machine. + * @param world World object for the world in which this controller is located. + * @param x X coordinate of the block being tested + * @param y Y coordinate of the block being tested + * @param z Z coordinate of the block being tested + * @throws MultiblockValidationException if the tested block is not allowed in the machine's interior + */ + protected void isBlockGoodForInterior(World world, int x, int y, int z) throws MultiblockValidationException { + Block block = world.getBlock(x, y, z); + throw new MultiblockValidationException(StringUtil.localizeAndFormatRaw( + "for.multiblock.error.invalid.interior", x, y, z, block.getLocalizedName())); + } + + @Override + public ChunkCoordinates getReferenceCoord() { + if (referenceCoord == null) { + selectNewReferenceCoord(); + } + return referenceCoord; + } + + /** + * @return The number of blocks connected to this controller. + */ + public int getNumConnectedBlocks() { + return connectedParts.size(); + } + + @Override + public void recalculateMinMaxCoords() { + minimumCoord = new ChunkCoordinates(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); + maximumCoord = new ChunkCoordinates(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); + + for (IMultiblockComponent part : connectedParts) { + ChunkCoordinates partCoords = part.getCoordinates(); + if (partCoords.posX < minimumCoord.posX) { + minimumCoord.posX = partCoords.posX; + } + if (partCoords.posX > maximumCoord.posX) { + maximumCoord.posX = partCoords.posX; + } + if (partCoords.posY < minimumCoord.posY) { + minimumCoord.posY = partCoords.posY; + } + if (partCoords.posY > maximumCoord.posY) { + maximumCoord.posY = partCoords.posY; + } + if (partCoords.posZ < minimumCoord.posZ) { + minimumCoord.posZ = partCoords.posZ; + } + if (partCoords.posZ > maximumCoord.posZ) { + maximumCoord.posZ = partCoords.posZ; + } + } + } + + /** + * @return The minimum bounding-box coordinate containing this machine's blocks. + */ + protected ChunkCoordinates getMinimumCoord() { + if (minimumCoord == null) { + recalculateMinMaxCoords(); + } + return new ChunkCoordinates(minimumCoord); + } + + /** + * @return The maximum bounding-box coordinate containing this machine's blocks. + */ + protected ChunkCoordinates getMaximumCoord() { + if (maximumCoord == null) { + recalculateMinMaxCoords(); + } + return new ChunkCoordinates(maximumCoord); + } + + protected final ChunkCoordinates getCenterCoord() { + ChunkCoordinates minCoord = getMinimumCoord(); + ChunkCoordinates maxCoord = getMaximumCoord(); + + return new ChunkCoordinates( + (minCoord.posX + maxCoord.posX) / 2, + (minCoord.posY + maxCoord.posY) / 2, + (minCoord.posZ + maxCoord.posZ) / 2); + } + + protected final ChunkCoordinates getTopCenterCoord() { + ChunkCoordinates minCoord = getMinimumCoord(); + ChunkCoordinates maxCoord = getMaximumCoord(); + + return new ChunkCoordinates( + (minCoord.posX + maxCoord.posX) / 2, maxCoord.posY, (minCoord.posZ + maxCoord.posZ) / 2); + } + + protected final boolean isCoordInMultiblock(int x, int y, int z) { + return (x >= minimumCoord.posX && x <= maximumCoord.posX) + && (y >= minimumCoord.posY && y <= maximumCoord.posY) + && (z >= minimumCoord.posZ && z <= maximumCoord.posZ); + } + + @Override + public boolean isEmpty() { + return connectedParts.isEmpty(); + } + + @Override + public boolean shouldConsume(IMultiblockControllerInternal otherController) { + if (!otherController.getClass().equals(getClass())) { + throw new IllegalArgumentException( + "Attempting to merge two multiblocks with different master classes - this should never happen!"); + } + + if (otherController == this) { + return false; + } // Don't be silly, don't eat yourself. + + int res = _shouldConsume(otherController); + if (res < 0) { + return true; + } else if (res > 0) { + return false; + } else { + // Strip dead parts from both and retry + Log.warning( + "[%s] Encountered two controllers with the same reference coordinate. Auditing connected parts and retrying.", + worldObj.isRemote ? "CLIENT" : "SERVER"); + auditParts(); + otherController.auditParts(); + + res = _shouldConsume(otherController); + if (res < 0) { + return true; + } else if (res > 0) { + return false; + } else { + Log.severe( + "My Controller (%d): size (%d), parts: %s", + hashCode(), connectedParts.size(), getPartsListString()); + Log.severe( + "Other Controller (%d): size (%d), coords: %s", + otherController.hashCode(), + otherController.getComponents().size(), + otherController.getPartsListString()); + throw new IllegalArgumentException( + "[" + (worldObj.isRemote ? "CLIENT" : "SERVER") + "] " + + "Two controllers with the same reference coord that somehow both have valid parts - this should never happen!"); + } + } + } + + private int _shouldConsume(IMultiblockControllerInternal otherController) { + ChunkCoordinates myCoord = getReferenceCoord(); + ChunkCoordinates theirCoord = otherController.getReferenceCoord(); + + // Always consume other controllers if their reference coordinate is null - this means they're empty and can be + // assimilated on the cheap + if (theirCoord == null) { + return -1; + } else { + return myCoord.compareTo(theirCoord); + } + } + + @Override + public String getPartsListString() { + StringBuilder sb = new StringBuilder(); + boolean first = true; + for (IMultiblockComponent part : connectedParts) { + if (!first) { + sb.append(", "); + } + ChunkCoordinates partCoord = part.getCoordinates(); + sb.append( + String.format("(%d: %d, %d, %d)", part.hashCode(), partCoord.posX, partCoord.posY, partCoord.posZ)); + first = false; + } + + return sb.toString(); + } + + @Override + public void auditParts() { + HashSet deadParts = new HashSet<>(); + for (IMultiblockComponent part : connectedParts) { + ChunkCoordinates partCoord = part.getCoordinates(); + if (isInvalid(part) || worldObj.getTileEntity(partCoord.posX, partCoord.posY, partCoord.posZ) != part) { + onDetachBlock(part); + deadParts.add(part); + } + } + + connectedParts.removeAll(deadParts); + Log.warning( + "[%s] Controller found %d dead parts during an audit, %d parts remain attached", + worldObj.isRemote ? "CLIENT" : "SERVER", deadParts.size(), connectedParts.size()); + } + + @Override + @Nonnull + public Set checkForDisconnections() { + if (!this.shouldCheckForDisconnections) { + return Collections.emptySet(); + } + + if (this.isEmpty()) { + MultiblockRegistry.addDeadController(worldObj, this); + return Collections.emptySet(); + } + + IChunkProvider chunkProvider = worldObj.getChunkProvider(); + + // Invalidate our reference coord, we'll recalculate it shortly + referenceCoord = null; + + // Reset visitations and find the minimum coordinate + Set deadParts = new HashSet<>(); + ChunkCoordinates c; + IMultiblockComponent referencePart = null; + + int originalSize = connectedParts.size(); + + for (IMultiblockComponent part : connectedParts) { + // This happens during chunk unload. + ChunkCoordinates partCoord = part.getCoordinates(); + if (!chunkProvider.chunkExists(partCoord.posX >> 4, partCoord.posZ >> 4) || isInvalid(part)) { + deadParts.add(part); + onDetachBlock(part); + continue; + } + + if (worldObj.getTileEntity(partCoord.posX, partCoord.posY, partCoord.posZ) != part) { + deadParts.add(part); + onDetachBlock(part); + continue; + } + + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); + + logic.setUnvisited(); + logic.forfeitMultiblockSaveDelegate(); + + c = part.getCoordinates(); + if (referenceCoord == null) { + referenceCoord = c; + referencePart = part; + } else if (c.compareTo(referenceCoord) < 0) { + referenceCoord = c; + referencePart = part; + } + } + + connectedParts.removeAll(deadParts); + deadParts.clear(); + + if (referencePart == null || isEmpty()) { + // There are no valid parts remaining. The entire multiblock was unloaded during a chunk unload. Halt. + shouldCheckForDisconnections = false; + MultiblockRegistry.addDeadController(worldObj, this); + return Collections.emptySet(); + } else { + MultiblockLogic logic = (MultiblockLogic) referencePart.getMultiblockLogic(); + logic.becomeMultiblockSaveDelegate(); + } + + // Now visit all connected parts, breadth-first, starting from reference coord's part + IMultiblockComponent part; + LinkedList partsToCheck = new LinkedList<>(); + + partsToCheck.add(referencePart); + + while (!partsToCheck.isEmpty()) { + part = partsToCheck.removeFirst(); + MultiblockLogic partLogic = (MultiblockLogic) part.getMultiblockLogic(); + partLogic.setVisited(); + + List nearbyParts = + MultiblockUtil.getNeighboringParts(worldObj, part); // Chunk-safe on server, but not on client + for (IMultiblockComponent nearbyPart : nearbyParts) { + // Ignore different machines + MultiblockLogic nearbyPartLogic = (MultiblockLogic) nearbyPart.getMultiblockLogic(); + if (nearbyPartLogic.getController() != this) { + continue; + } + + if (!nearbyPartLogic.isVisited()) { + nearbyPartLogic.setVisited(); + partsToCheck.add(nearbyPart); + } + } + } + + // Finally, remove all parts that remain disconnected. + Set removedParts = new HashSet<>(); + for (IMultiblockComponent orphanCandidate : connectedParts) { + MultiblockLogic logic = (MultiblockLogic) orphanCandidate.getMultiblockLogic(); + if (!logic.isVisited()) { + deadParts.add(orphanCandidate); + onDetachBlock(orphanCandidate); + removedParts.add(orphanCandidate); + } + } + + // Trim any blocks that were invalid, or were removed. + connectedParts.removeAll(deadParts); + + // Cleanup. Not necessary, really. + deadParts.clear(); + + // Juuuust in case. + if (referenceCoord == null) { + selectNewReferenceCoord(); + } + + // We've run the checks from here on out. + shouldCheckForDisconnections = false; + + return removedParts; + } + + @Override + @Nonnull + public Set detachAllBlocks() { + if (worldObj == null) { + return new HashSet<>(); + } + + IChunkProvider chunkProvider = worldObj.getChunkProvider(); + for (IMultiblockComponent part : connectedParts) { + ChunkCoordinates partCoord = part.getCoordinates(); + if (chunkProvider.chunkExists(partCoord.posX >> 4, partCoord.posZ >> 4)) { + onDetachBlock(part); + } + } + + Set detachedParts = connectedParts; + connectedParts = new HashSet<>(); + return detachedParts; + } + + /** + * @return True if this multiblock machine is considered assembled and ready to go. + */ + @Override + public boolean isAssembled() { + return this.assemblyState == AssemblyState.Assembled; + } + + private void selectNewReferenceCoord() { + IChunkProvider chunkProvider = worldObj.getChunkProvider(); + IMultiblockComponent theChosenOne = null; + referenceCoord = null; + + for (IMultiblockComponent part : connectedParts) { + ChunkCoordinates partCoord = part.getCoordinates(); + if (isInvalid(part) || !chunkProvider.chunkExists(partCoord.posX >> 4, partCoord.posZ >> 4)) { + // Chunk is unloading, skip this coord to prevent chunk thrashing + continue; + } + + if (referenceCoord == null || referenceCoord.compareTo(partCoord) > 0) { + referenceCoord = part.getCoordinates(); + theChosenOne = part; + } + } + + if (theChosenOne != null) { + MultiblockLogic logic = (MultiblockLogic) theChosenOne.getMultiblockLogic(); + logic.becomeMultiblockSaveDelegate(); + } + } + + /** + * Marks the reference coord dirty & updateable. + * + * On the server, this will mark the for a data-update, so that + * nearby clients will receive an updated description packet from the server + * after a short time. The block's chunk will also be marked dirty and the + * block's chunk will be saved to disk the next time chunks are saved. + * + * On the client, this will mark the block for a rendering update. + */ + protected void markReferenceCoordForUpdate() { + ChunkCoordinates rc = getReferenceCoord(); + if (worldObj != null && rc != null) { + worldObj.markBlockForUpdate(rc.posX, rc.posY, rc.posZ); + } + } + + /** + * Marks the reference coord dirty. + * + * On the server, this marks the reference coord's chunk as dirty; the block (and chunk) + * will be saved to disk the next time chunks are saved. This does NOT mark it dirty for + * a description-packet update. + * + * On the client, does nothing. + * @see MultiblockControllerBase#markReferenceCoordForUpdate() + */ + protected void markReferenceCoordDirty() { + if (worldObj == null || worldObj.isRemote) { + return; + } + + ChunkCoordinates referenceCoord = getReferenceCoord(); + if (referenceCoord == null) { + return; + } + + TileEntity saveTe = worldObj.getTileEntity(referenceCoord.posX, referenceCoord.posY, referenceCoord.posZ); + worldObj.markTileEntityChunkModified(referenceCoord.posX, referenceCoord.posY, referenceCoord.posZ, saveTe); + } + + private static boolean isInvalid(IMultiblockComponent part) { + return part instanceof TileEntity && ((TileEntity) part).isInvalid(); + } } diff --git a/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java b/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java index 879be8d47..f16ed90a8 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java @@ -1,182 +1,180 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.multiblock; - -import com.google.common.collect.HashMultiset; -import com.google.common.collect.Multiset; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - -import com.mojang.authlib.GameProfile; - -import forestry.api.core.ForestryAPI; -import forestry.api.core.IErrorLogic; -import forestry.api.core.IErrorLogicSource; -import forestry.api.multiblock.IMultiblockComponent; -import forestry.core.access.AccessHandler; -import forestry.core.access.IAccessHandler; -import forestry.core.access.IRestrictedAccess; -import forestry.core.inventory.FakeInventoryAdapter; -import forestry.core.inventory.IInventoryAdapter; -import forestry.core.tiles.ILocatable; - -public abstract class MultiblockControllerForestry extends MultiblockControllerBase implements ISidedInventory, IRestrictedAccess, IErrorLogicSource, ILocatable { - private final AccessHandler accessHandler; - private final IErrorLogic errorLogic; - - protected MultiblockControllerForestry(World world) { - super(world); - - this.accessHandler = new AccessHandler(this); - this.errorLogic = ForestryAPI.errorStateRegistry.createErrorLogic(); - } - - @Override - public IAccessHandler getAccessHandler() { - return accessHandler; - } - - @Override - public IErrorLogic getErrorLogic() { - return errorLogic; - } - - @Override - protected void onMachineAssembled() { - super.onMachineAssembled(); - - if (worldObj.isRemote) { - return; - } - - // Figure out who owns the multiblock, by majority - - Multiset owners = HashMultiset.create(); - for (IMultiblockComponent part : connectedParts) { - GameProfile owner = part.getOwner(); - if (owner != null) { - owners.add(owner); - } - } - - GameProfile owner = null; - int max = 0; - for (Multiset.Entry entry : owners.entrySet()) { - int count = entry.getCount(); - if (count > max) { - max = count; - owner = entry.getElement(); - } - } - - getAccessHandler().setOwner(owner); - } - - /* INBTTagable */ - @Override - public void writeToNBT(NBTTagCompound data) { - accessHandler.writeToNBT(data); - } - - @Override - public void readFromNBT(NBTTagCompound data) { - accessHandler.readFromNBT(data); - } - - /* INVENTORY */ - public IInventoryAdapter getInternalInventory() { - return FakeInventoryAdapter.instance(); - } - - @Override - public void markDirty() { - getInternalInventory().markDirty(); - } - - @Override - public final int getSizeInventory() { - return getInternalInventory().getSizeInventory(); - } - - @Override - public final ItemStack getStackInSlot(int slotIndex) { - return getInternalInventory().getStackInSlot(slotIndex); - } - - @Override - public final ItemStack decrStackSize(int slotIndex, int amount) { - return getInternalInventory().decrStackSize(slotIndex, amount); - } - - @Override - public final ItemStack getStackInSlotOnClosing(int slotIndex) { - return getInternalInventory().getStackInSlotOnClosing(slotIndex); - } - - @Override - public final void setInventorySlotContents(int slotIndex, ItemStack itemstack) { - getInternalInventory().setInventorySlotContents(slotIndex, itemstack); - } - - @Override - public final int getInventoryStackLimit() { - return getInternalInventory().getInventoryStackLimit(); - } - - @Override - public final void openInventory() { - getInternalInventory().openInventory(); - } - - @Override - public final void closeInventory() { - getInternalInventory().closeInventory(); - } - - @Override - public final String getInventoryName() { - return getInternalInventory().getInventoryName(); - } - - @Override - public final boolean isUseableByPlayer(EntityPlayer player) { - return getInternalInventory().isUseableByPlayer(player); - } - - @Override - public final boolean hasCustomInventoryName() { - return getInternalInventory().hasCustomInventoryName(); - } - - @Override - public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { - return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); - } - - @Override - public final int[] getAccessibleSlotsFromSide(int side) { - return getInternalInventory().getAccessibleSlotsFromSide(side); - } - - @Override - public final boolean canInsertItem(int slotIndex, ItemStack itemStack, int side) { - return getInternalInventory().canInsertItem(slotIndex, itemStack, side); - } - - @Override - public final boolean canExtractItem(int slotIndex, ItemStack itemStack, int side) { - return getInternalInventory().canExtractItem(slotIndex, itemStack, side); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import com.google.common.collect.HashMultiset; +import com.google.common.collect.Multiset; +import com.mojang.authlib.GameProfile; +import forestry.api.core.ForestryAPI; +import forestry.api.core.IErrorLogic; +import forestry.api.core.IErrorLogicSource; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.core.access.AccessHandler; +import forestry.core.access.IAccessHandler; +import forestry.core.access.IRestrictedAccess; +import forestry.core.inventory.FakeInventoryAdapter; +import forestry.core.inventory.IInventoryAdapter; +import forestry.core.tiles.ILocatable; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +public abstract class MultiblockControllerForestry extends MultiblockControllerBase + implements ISidedInventory, IRestrictedAccess, IErrorLogicSource, ILocatable { + private final AccessHandler accessHandler; + private final IErrorLogic errorLogic; + + protected MultiblockControllerForestry(World world) { + super(world); + + this.accessHandler = new AccessHandler(this); + this.errorLogic = ForestryAPI.errorStateRegistry.createErrorLogic(); + } + + @Override + public IAccessHandler getAccessHandler() { + return accessHandler; + } + + @Override + public IErrorLogic getErrorLogic() { + return errorLogic; + } + + @Override + protected void onMachineAssembled() { + super.onMachineAssembled(); + + if (worldObj.isRemote) { + return; + } + + // Figure out who owns the multiblock, by majority + + Multiset owners = HashMultiset.create(); + for (IMultiblockComponent part : connectedParts) { + GameProfile owner = part.getOwner(); + if (owner != null) { + owners.add(owner); + } + } + + GameProfile owner = null; + int max = 0; + for (Multiset.Entry entry : owners.entrySet()) { + int count = entry.getCount(); + if (count > max) { + max = count; + owner = entry.getElement(); + } + } + + getAccessHandler().setOwner(owner); + } + + /* INBTTagable */ + @Override + public void writeToNBT(NBTTagCompound data) { + accessHandler.writeToNBT(data); + } + + @Override + public void readFromNBT(NBTTagCompound data) { + accessHandler.readFromNBT(data); + } + + /* INVENTORY */ + public IInventoryAdapter getInternalInventory() { + return FakeInventoryAdapter.instance(); + } + + @Override + public void markDirty() { + getInternalInventory().markDirty(); + } + + @Override + public final int getSizeInventory() { + return getInternalInventory().getSizeInventory(); + } + + @Override + public final ItemStack getStackInSlot(int slotIndex) { + return getInternalInventory().getStackInSlot(slotIndex); + } + + @Override + public final ItemStack decrStackSize(int slotIndex, int amount) { + return getInternalInventory().decrStackSize(slotIndex, amount); + } + + @Override + public final ItemStack getStackInSlotOnClosing(int slotIndex) { + return getInternalInventory().getStackInSlotOnClosing(slotIndex); + } + + @Override + public final void setInventorySlotContents(int slotIndex, ItemStack itemstack) { + getInternalInventory().setInventorySlotContents(slotIndex, itemstack); + } + + @Override + public final int getInventoryStackLimit() { + return getInternalInventory().getInventoryStackLimit(); + } + + @Override + public final void openInventory() { + getInternalInventory().openInventory(); + } + + @Override + public final void closeInventory() { + getInternalInventory().closeInventory(); + } + + @Override + public final String getInventoryName() { + return getInternalInventory().getInventoryName(); + } + + @Override + public final boolean isUseableByPlayer(EntityPlayer player) { + return getInternalInventory().isUseableByPlayer(player); + } + + @Override + public final boolean hasCustomInventoryName() { + return getInternalInventory().hasCustomInventoryName(); + } + + @Override + public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { + return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); + } + + @Override + public final int[] getAccessibleSlotsFromSide(int side) { + return getInternalInventory().getAccessibleSlotsFromSide(side); + } + + @Override + public final boolean canInsertItem(int slotIndex, ItemStack itemStack, int side) { + return getInternalInventory().canInsertItem(slotIndex, itemStack, side); + } + + @Override + public final boolean canExtractItem(int slotIndex, ItemStack itemStack, int side) { + return getInternalInventory().canExtractItem(slotIndex, itemStack, side); + } +} diff --git a/src/main/java/forestry/core/multiblock/MultiblockEventHandler.java b/src/main/java/forestry/core/multiblock/MultiblockEventHandler.java index 0bb1e7161..fcbc63722 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockEventHandler.java +++ b/src/main/java/forestry/core/multiblock/MultiblockEventHandler.java @@ -1,13 +1,11 @@ package forestry.core.multiblock; -import net.minecraft.world.World; -import net.minecraft.world.chunk.Chunk; - -import net.minecraftforge.event.world.ChunkEvent; -import net.minecraftforge.event.world.WorldEvent; - import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.event.world.ChunkEvent; +import net.minecraftforge.event.world.WorldEvent; /** * In your mod, subscribe this on both the client and server sides side to handle chunk @@ -16,16 +14,16 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; * process any blocks that are in chunks which are still loading. */ public class MultiblockEventHandler { - @SubscribeEvent(priority = EventPriority.NORMAL) - public void onChunkLoad(ChunkEvent.Load loadEvent) { - Chunk chunk = loadEvent.getChunk(); - World world = loadEvent.world; - MultiblockRegistry.onChunkLoaded(world, chunk.xPosition, chunk.zPosition); - } + @SubscribeEvent(priority = EventPriority.NORMAL) + public void onChunkLoad(ChunkEvent.Load loadEvent) { + Chunk chunk = loadEvent.getChunk(); + World world = loadEvent.world; + MultiblockRegistry.onChunkLoaded(world, chunk.xPosition, chunk.zPosition); + } - // Cleanup, for nice memory usageness - @SubscribeEvent(priority = EventPriority.NORMAL) - public void onWorldUnload(WorldEvent.Unload unloadWorldEvent) { - MultiblockRegistry.onWorldUnloaded(unloadWorldEvent.world); - } + // Cleanup, for nice memory usageness + @SubscribeEvent(priority = EventPriority.NORMAL) + public void onWorldUnload(WorldEvent.Unload unloadWorldEvent) { + MultiblockRegistry.onWorldUnloaded(unloadWorldEvent.world); + } } diff --git a/src/main/java/forestry/core/multiblock/MultiblockLogic.java b/src/main/java/forestry/core/multiblock/MultiblockLogic.java index 337b94c44..e1604c339 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockLogic.java +++ b/src/main/java/forestry/core/multiblock/MultiblockLogic.java @@ -1,204 +1,205 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.multiblock; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; - -import forestry.api.multiblock.IMultiblockComponent; -import forestry.api.multiblock.IMultiblockLogic; -import forestry.core.utils.Log; - -public abstract class MultiblockLogic implements IMultiblockLogic { - private final Class controllerClass; - private boolean visited; - private boolean saveMultiblockData; - private NBTTagCompound cachedMultiblockData; - protected T controller; - - protected MultiblockLogic(Class controllerClass) { - this.controllerClass = controllerClass; - this.controller = null; - this.visited = false; - this.saveMultiblockData = false; - this.cachedMultiblockData = null; - } - - public void setController(IMultiblockControllerInternal controller) { - if (controller == null) { - this.controller = null; - } else if (controllerClass.isAssignableFrom(controller.getClass())) { - this.controller = controllerClass.cast(controller); - } - } - - public Class getControllerClass() { - return controllerClass; - } - - @Override - public abstract T getController(); - - public abstract T createNewController(World world); - - /** - * This is called when a block is being marked as valid by the chunk, but has not yet fully - * been placed into the world's TileEntity cache. this.worldObj, xCoord, yCoord and zCoord have - * been initialized, but any attempts to read data about the world can cause infinite loops - - * if you call getTileEntity on this TileEntity's coordinate from within validate(), you will - * blow your call stack. - * - * TL;DR: Here there be dragons. - * @see net.minecraft.tileentity.TileEntity#validate() - */ - @Override - public void validate(World world, IMultiblockComponent part) { - MultiblockRegistry.onPartAdded(world, part); - } - - /** - * Called when a block is removed by game actions, such as a player breaking the block - * or the block being changed into another block. - * @see net.minecraft.tileentity.TileEntity#invalidate() - */ - @Override - public final void invalidate(World world, IMultiblockComponent part) { - detachSelf(world, part, false); - } - - /** - * Called from Minecraft's tile entity loop, after all tile entities have been ticked, - * as the chunk in which this tile entity is contained is unloading. - * Happens before the Forge TickEnd event. - * @see net.minecraft.tileentity.TileEntity#onChunkUnload() - */ - @Override - public final void onChunkUnload(World world, IMultiblockComponent part) { - detachSelf(world, part, true); - } - - /* - * Detaches this block from its controller. Calls detachBlock() and clears the controller member. - */ - protected void detachSelf(World world, IMultiblockComponent part, boolean chunkUnloading) { - if (this.controller != null) { - // Clean part out of controller - this.controller.detachBlock(part, chunkUnloading); - - // The above should call onDetached, but, just in case... - this.controller = null; - } - - // Clean part out of lists in the registry - MultiblockRegistry.onPartRemovedFromWorld(world, part); - } - - @Override - public void readFromNBT(NBTTagCompound data) { - // We can't directly initialize a multiblock controller yet, so we cache the data here until - // we receive a validate() call, which creates the controller and hands off the cached data. - if (data.hasKey("multiblockData")) { - this.cachedMultiblockData = data.getCompoundTag("multiblockData"); - } - } - - @Override - public void writeToNBT(NBTTagCompound data) { - if (isMultiblockSaveDelegate() && isConnected()) { - NBTTagCompound multiblockData = new NBTTagCompound(); - this.controller.writeToNBT(multiblockData); - data.setTag("multiblockData", multiblockData); - } - } - - public final void assertDetached(IMultiblockComponent part) { - if (this.controller != null) { - ChunkCoordinates coords = part.getCoordinates(); - Log.info("[assert] Part @ (%d, %d, %d) should be detached already, but detected that it was not. This is not a fatal error, and will be repaired, but is unusual.", coords.posX, coords.posY, coords.posZ); - this.controller = null; - } - } - - @Override - public final boolean isConnected() { - return (controller != null); - } - - public final void becomeMultiblockSaveDelegate() { - this.saveMultiblockData = true; - } - - public final void forfeitMultiblockSaveDelegate() { - this.saveMultiblockData = false; - } - - public final boolean isMultiblockSaveDelegate() { - return this.saveMultiblockData; - } - - public final void setUnvisited() { - this.visited = false; - } - - public final void setVisited() { - this.visited = true; - } - - public final boolean isVisited() { - return this.visited; - } - - public final boolean hasMultiblockSaveData() { - return this.cachedMultiblockData != null; - } - - public final NBTTagCompound getMultiblockSaveData() { - return this.cachedMultiblockData; - } - - public final void onMultiblockDataAssimilated() { - this.cachedMultiblockData = null; - } - - /** - * Override this to easily modify the description packet's data without having - * to worry about sending the packet itself. - * Decode this data in decodeDescriptionPacket. - * @param packetData An NBT compound tag into which you should write your custom description data. - */ - @Override - public void encodeDescriptionPacket(NBTTagCompound packetData) { - if (this.isMultiblockSaveDelegate() && isConnected()) { - NBTTagCompound tag = new NBTTagCompound(); - controller.formatDescriptionPacket(tag); - packetData.setTag("multiblockData", tag); - } - } - - /** - * Override this to easily read in data from a TileEntity's description packet. - * Encoded in encodeDescriptionPacket. - * @param packetData The NBT data from the tile entity's description packet. - */ - @Override - public void decodeDescriptionPacket(NBTTagCompound packetData) { - if (packetData.hasKey("multiblockData")) { - NBTTagCompound tag = packetData.getCompoundTag("multiblockData"); - if (isConnected()) { - controller.decodeDescriptionPacket(tag); - } else { - // This part hasn't been added to a machine yet, so cache the data. - this.cachedMultiblockData = tag; - } - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import forestry.api.multiblock.IMultiblockComponent; +import forestry.api.multiblock.IMultiblockLogic; +import forestry.core.utils.Log; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; + +public abstract class MultiblockLogic implements IMultiblockLogic { + private final Class controllerClass; + private boolean visited; + private boolean saveMultiblockData; + private NBTTagCompound cachedMultiblockData; + protected T controller; + + protected MultiblockLogic(Class controllerClass) { + this.controllerClass = controllerClass; + this.controller = null; + this.visited = false; + this.saveMultiblockData = false; + this.cachedMultiblockData = null; + } + + public void setController(IMultiblockControllerInternal controller) { + if (controller == null) { + this.controller = null; + } else if (controllerClass.isAssignableFrom(controller.getClass())) { + this.controller = controllerClass.cast(controller); + } + } + + public Class getControllerClass() { + return controllerClass; + } + + @Override + public abstract T getController(); + + public abstract T createNewController(World world); + + /** + * This is called when a block is being marked as valid by the chunk, but has not yet fully + * been placed into the world's TileEntity cache. this.worldObj, xCoord, yCoord and zCoord have + * been initialized, but any attempts to read data about the world can cause infinite loops - + * if you call getTileEntity on this TileEntity's coordinate from within validate(), you will + * blow your call stack. + * + * TL;DR: Here there be dragons. + * @see net.minecraft.tileentity.TileEntity#validate() + */ + @Override + public void validate(World world, IMultiblockComponent part) { + MultiblockRegistry.onPartAdded(world, part); + } + + /** + * Called when a block is removed by game actions, such as a player breaking the block + * or the block being changed into another block. + * @see net.minecraft.tileentity.TileEntity#invalidate() + */ + @Override + public final void invalidate(World world, IMultiblockComponent part) { + detachSelf(world, part, false); + } + + /** + * Called from Minecraft's tile entity loop, after all tile entities have been ticked, + * as the chunk in which this tile entity is contained is unloading. + * Happens before the Forge TickEnd event. + * @see net.minecraft.tileentity.TileEntity#onChunkUnload() + */ + @Override + public final void onChunkUnload(World world, IMultiblockComponent part) { + detachSelf(world, part, true); + } + + /* + * Detaches this block from its controller. Calls detachBlock() and clears the controller member. + */ + protected void detachSelf(World world, IMultiblockComponent part, boolean chunkUnloading) { + if (this.controller != null) { + // Clean part out of controller + this.controller.detachBlock(part, chunkUnloading); + + // The above should call onDetached, but, just in case... + this.controller = null; + } + + // Clean part out of lists in the registry + MultiblockRegistry.onPartRemovedFromWorld(world, part); + } + + @Override + public void readFromNBT(NBTTagCompound data) { + // We can't directly initialize a multiblock controller yet, so we cache the data here until + // we receive a validate() call, which creates the controller and hands off the cached data. + if (data.hasKey("multiblockData")) { + this.cachedMultiblockData = data.getCompoundTag("multiblockData"); + } + } + + @Override + public void writeToNBT(NBTTagCompound data) { + if (isMultiblockSaveDelegate() && isConnected()) { + NBTTagCompound multiblockData = new NBTTagCompound(); + this.controller.writeToNBT(multiblockData); + data.setTag("multiblockData", multiblockData); + } + } + + public final void assertDetached(IMultiblockComponent part) { + if (this.controller != null) { + ChunkCoordinates coords = part.getCoordinates(); + Log.info( + "[assert] Part @ (%d, %d, %d) should be detached already, but detected that it was not. This is not a fatal error, and will be repaired, but is unusual.", + coords.posX, coords.posY, coords.posZ); + this.controller = null; + } + } + + @Override + public final boolean isConnected() { + return (controller != null); + } + + public final void becomeMultiblockSaveDelegate() { + this.saveMultiblockData = true; + } + + public final void forfeitMultiblockSaveDelegate() { + this.saveMultiblockData = false; + } + + public final boolean isMultiblockSaveDelegate() { + return this.saveMultiblockData; + } + + public final void setUnvisited() { + this.visited = false; + } + + public final void setVisited() { + this.visited = true; + } + + public final boolean isVisited() { + return this.visited; + } + + public final boolean hasMultiblockSaveData() { + return this.cachedMultiblockData != null; + } + + public final NBTTagCompound getMultiblockSaveData() { + return this.cachedMultiblockData; + } + + public final void onMultiblockDataAssimilated() { + this.cachedMultiblockData = null; + } + + /** + * Override this to easily modify the description packet's data without having + * to worry about sending the packet itself. + * Decode this data in decodeDescriptionPacket. + * @param packetData An NBT compound tag into which you should write your custom description data. + */ + @Override + public void encodeDescriptionPacket(NBTTagCompound packetData) { + if (this.isMultiblockSaveDelegate() && isConnected()) { + NBTTagCompound tag = new NBTTagCompound(); + controller.formatDescriptionPacket(tag); + packetData.setTag("multiblockData", tag); + } + } + + /** + * Override this to easily read in data from a TileEntity's description packet. + * Encoded in encodeDescriptionPacket. + * @param packetData The NBT data from the tile entity's description packet. + */ + @Override + public void decodeDescriptionPacket(NBTTagCompound packetData) { + if (packetData.hasKey("multiblockData")) { + NBTTagCompound tag = packetData.getCompoundTag("multiblockData"); + if (isConnected()) { + controller.decodeDescriptionPacket(tag); + } else { + // This part hasn't been added to a machine yet, so cache the data. + this.cachedMultiblockData = tag; + } + } + } +} diff --git a/src/main/java/forestry/core/multiblock/MultiblockLogicFactory.java b/src/main/java/forestry/core/multiblock/MultiblockLogicFactory.java index d60294a3d..03773e79e 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockLogicFactory.java +++ b/src/main/java/forestry/core/multiblock/MultiblockLogicFactory.java @@ -1,30 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.multiblock; - -import forestry.api.multiblock.IMultiblockLogicAlveary; -import forestry.api.multiblock.IMultiblockLogicFactory; -import forestry.api.multiblock.IMultiblockLogicFarm; -import forestry.apiculture.multiblock.MultiblockLogicAlveary; -import forestry.farming.multiblock.MultiblockLogicFarm; - -public class MultiblockLogicFactory implements IMultiblockLogicFactory { - - @Override - public IMultiblockLogicAlveary createAlvearyLogic() { - return new MultiblockLogicAlveary(); - } - - @Override - public IMultiblockLogicFarm createFarmLogic() { - return new MultiblockLogicFarm(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import forestry.api.multiblock.IMultiblockLogicAlveary; +import forestry.api.multiblock.IMultiblockLogicFactory; +import forestry.api.multiblock.IMultiblockLogicFarm; +import forestry.apiculture.multiblock.MultiblockLogicAlveary; +import forestry.farming.multiblock.MultiblockLogicFarm; + +public class MultiblockLogicFactory implements IMultiblockLogicFactory { + + @Override + public IMultiblockLogicAlveary createAlvearyLogic() { + return new MultiblockLogicAlveary(); + } + + @Override + public IMultiblockLogicFarm createFarmLogic() { + return new MultiblockLogicFarm(); + } +} diff --git a/src/main/java/forestry/core/multiblock/MultiblockRegistry.java b/src/main/java/forestry/core/multiblock/MultiblockRegistry.java index 73d87c5b5..6b1bfca9e 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockRegistry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockRegistry.java @@ -1,13 +1,11 @@ package forestry.core.multiblock; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import net.minecraft.world.World; - import forestry.api.multiblock.IMultiblockComponent; import forestry.core.utils.Log; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import net.minecraft.world.World; /** * This is a very static singleton registry class which directs incoming events to sub-objects, which @@ -15,116 +13,116 @@ import forestry.core.utils.Log; * @author Erogenous Beef */ public class MultiblockRegistry { - // World > WorldRegistry map - private static final Map registries = new HashMap<>(); - - /** - * Called before Tile Entities are ticked in the world. Do bookkeeping here. - * @param world The world being ticked - */ - public static void tickStart(World world) { - if (registries.containsKey(world)) { - MultiblockWorldRegistry registry = registries.get(world); - registry.processMultiblockChanges(); - registry.tickStart(); - } - } - - /** - * Called when the world has finished loading a chunk. - * @param world The world which has finished loading a chunk - * @param chunkX The X coordinate of the chunk - * @param chunkZ The Z coordinate of the chunk - */ - public static void onChunkLoaded(World world, int chunkX, int chunkZ) { - if (registries.containsKey(world)) { - registries.get(world).onChunkLoaded(chunkX, chunkZ); - } - } + // World > WorldRegistry map + private static final Map registries = new HashMap<>(); - /** - * Register a new part in the system. The part has been created either through user action or via a chunk loading. - * @param world The world into which this part is loading. - * @param part The part being loaded. - */ - public static void onPartAdded(World world, IMultiblockComponent part) { - MultiblockWorldRegistry registry = getOrCreateRegistry(world); - registry.onPartAdded(part); - } - - /** - * Call to remove a part from world lists. - * @param world The world from which a multiblock part is being removed. - * @param part The part being removed. - */ - public static void onPartRemovedFromWorld(World world, IMultiblockComponent part) { - if (registries.containsKey(world)) { - registries.get(world).onPartRemovedFromWorld(part); - } - - } + /** + * Called before Tile Entities are ticked in the world. Do bookkeeping here. + * @param world The world being ticked + */ + public static void tickStart(World world) { + if (registries.containsKey(world)) { + MultiblockWorldRegistry registry = registries.get(world); + registry.processMultiblockChanges(); + registry.tickStart(); + } + } - - /** - * Called whenever a world is unloaded. Unload the relevant registry, if we have one. - * @param world The world being unloaded. - */ - public static void onWorldUnloaded(World world) { - if (registries.containsKey(world)) { - registries.get(world).onWorldUnloaded(); - registries.remove(world); - } - } + /** + * Called when the world has finished loading a chunk. + * @param world The world which has finished loading a chunk + * @param chunkX The X coordinate of the chunk + * @param chunkZ The Z coordinate of the chunk + */ + public static void onChunkLoaded(World world, int chunkX, int chunkZ) { + if (registries.containsKey(world)) { + registries.get(world).onChunkLoaded(chunkX, chunkZ); + } + } - /** - * Call to mark a controller as dirty. Dirty means that parts have - * been added or removed this tick. - * @param world The world containing the multiblock - * @param controller The dirty controller - */ - public static void addDirtyController(World world, IMultiblockControllerInternal controller) { - if (registries.containsKey(world)) { - registries.get(world).addDirtyController(controller); - } else { - throw new IllegalArgumentException("Adding a dirty controller to a world that has no registered controllers!"); - } - } - - /** - * Call to mark a controller as dead. It should only be marked as dead - * when it has no connected parts. It will be removed after the next world tick. - * @param world The world formerly containing the multiblock - * @param controller The dead controller - */ - public static void addDeadController(World world, IMultiblockControllerInternal controller) { - if (registries.containsKey(world)) { - registries.get(world).addDeadController(controller); - } else { - Log.warning("Controller %d in world %s marked as dead, but that world is not tracked! Controller is being ignored.", controller.hashCode(), world); - } - } + /** + * Register a new part in the system. The part has been created either through user action or via a chunk loading. + * @param world The world into which this part is loading. + * @param part The part being loaded. + */ + public static void onPartAdded(World world, IMultiblockComponent part) { + MultiblockWorldRegistry registry = getOrCreateRegistry(world); + registry.onPartAdded(part); + } - /** - * @param world The world whose controllers you wish to retrieve. - * @return An unmodifiable set of controllers active in the given world, or null if there are none. - */ - public static Set getControllersFromWorld(World world) { - if (registries.containsKey(world)) { - return registries.get(world).getControllers(); - } - return null; - } - - /// *** PRIVATE HELPERS *** /// - - private static MultiblockWorldRegistry getOrCreateRegistry(World world) { - if (registries.containsKey(world)) { - return registries.get(world); - } else { - MultiblockWorldRegistry newRegistry = new MultiblockWorldRegistry(world); - registries.put(world, newRegistry); - return newRegistry; - } - } + /** + * Call to remove a part from world lists. + * @param world The world from which a multiblock part is being removed. + * @param part The part being removed. + */ + public static void onPartRemovedFromWorld(World world, IMultiblockComponent part) { + if (registries.containsKey(world)) { + registries.get(world).onPartRemovedFromWorld(part); + } + } + /** + * Called whenever a world is unloaded. Unload the relevant registry, if we have one. + * @param world The world being unloaded. + */ + public static void onWorldUnloaded(World world) { + if (registries.containsKey(world)) { + registries.get(world).onWorldUnloaded(); + registries.remove(world); + } + } + + /** + * Call to mark a controller as dirty. Dirty means that parts have + * been added or removed this tick. + * @param world The world containing the multiblock + * @param controller The dirty controller + */ + public static void addDirtyController(World world, IMultiblockControllerInternal controller) { + if (registries.containsKey(world)) { + registries.get(world).addDirtyController(controller); + } else { + throw new IllegalArgumentException( + "Adding a dirty controller to a world that has no registered controllers!"); + } + } + + /** + * Call to mark a controller as dead. It should only be marked as dead + * when it has no connected parts. It will be removed after the next world tick. + * @param world The world formerly containing the multiblock + * @param controller The dead controller + */ + public static void addDeadController(World world, IMultiblockControllerInternal controller) { + if (registries.containsKey(world)) { + registries.get(world).addDeadController(controller); + } else { + Log.warning( + "Controller %d in world %s marked as dead, but that world is not tracked! Controller is being ignored.", + controller.hashCode(), world); + } + } + + /** + * @param world The world whose controllers you wish to retrieve. + * @return An unmodifiable set of controllers active in the given world, or null if there are none. + */ + public static Set getControllersFromWorld(World world) { + if (registries.containsKey(world)) { + return registries.get(world).getControllers(); + } + return null; + } + + /// *** PRIVATE HELPERS *** /// + + private static MultiblockWorldRegistry getOrCreateRegistry(World world) { + if (registries.containsKey(world)) { + return registries.get(world); + } else { + MultiblockWorldRegistry newRegistry = new MultiblockWorldRegistry(world); + registries.put(world, newRegistry); + return newRegistry; + } + } } diff --git a/src/main/java/forestry/core/multiblock/MultiblockServerTickHandler.java b/src/main/java/forestry/core/multiblock/MultiblockServerTickHandler.java index 2b63b4690..be14027b7 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockServerTickHandler.java +++ b/src/main/java/forestry/core/multiblock/MultiblockServerTickHandler.java @@ -14,10 +14,10 @@ import cpw.mods.fml.common.gameevent.TickEvent; */ public class MultiblockServerTickHandler { - @SubscribeEvent - public void onWorldTick(TickEvent.WorldTickEvent event) { - if (event.phase == TickEvent.Phase.START) { - MultiblockRegistry.tickStart(event.world); - } - } + @SubscribeEvent + public void onWorldTick(TickEvent.WorldTickEvent event) { + if (event.phase == TickEvent.Phase.START) { + MultiblockRegistry.tickStart(event.world); + } + } } diff --git a/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java b/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java index 5e871b1b5..aa1609a33 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java @@ -1,192 +1,191 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.multiblock; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTUtil; -import net.minecraft.world.World; - -import com.mojang.authlib.GameProfile; - -import forestry.api.multiblock.IMultiblockLogic; -import forestry.api.multiblock.MultiblockTileEntityBase; -import forestry.core.config.Constants; -import forestry.core.gui.GuiHandler; -import forestry.core.gui.IGuiHandlerTile; -import forestry.core.inventory.FakeInventoryAdapter; -import forestry.core.inventory.IInventoryAdapter; -import forestry.core.tiles.IFilterSlotDelegate; -import forestry.core.tiles.ILocatable; - -public abstract class MultiblockTileEntityForestry extends MultiblockTileEntityBase implements ISidedInventory, IFilterSlotDelegate, ILocatable, IGuiHandlerTile { - private GameProfile owner; - - public MultiblockTileEntityForestry(T multiblockLogic) { - super(multiblockLogic); - } - - /** - * Called by a structure block when it is right clicked by a player. - */ - public void openGui(EntityPlayer player) { - GuiHandler.openGui(player, this); - } - - @Override - public void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - - if (data.hasKey("owner")) { - owner = NBTUtil.func_152459_a(data.getCompoundTag("owner")); - } - - getInternalInventory().readFromNBT(data); - } - - @Override - public void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - - if (this.owner != null) { - NBTTagCompound nbt = new NBTTagCompound(); - NBTUtil.func_152460_a(nbt, owner); - nbt.removeTag("Properties"); - data.setTag("owner", nbt); - } - - getInternalInventory().writeToNBT(data); - } - - /* INVENTORY */ - public IInventoryAdapter getInternalInventory() { - return FakeInventoryAdapter.instance(); - } - - public boolean allowsAutomation() { - return false; - } - - @Override - public final int getSizeInventory() { - return getInternalInventory().getSizeInventory(); - } - - @Override - public final ItemStack getStackInSlot(int slotIndex) { - return getInternalInventory().getStackInSlot(slotIndex); - } - - @Override - public final ItemStack decrStackSize(int slotIndex, int amount) { - return getInternalInventory().decrStackSize(slotIndex, amount); - } - - @Override - public final ItemStack getStackInSlotOnClosing(int slotIndex) { - return getInternalInventory().getStackInSlotOnClosing(slotIndex); - } - - @Override - public final void setInventorySlotContents(int slotIndex, ItemStack itemstack) { - getInternalInventory().setInventorySlotContents(slotIndex, itemstack); - } - - @Override - public final int getInventoryStackLimit() { - return getInternalInventory().getInventoryStackLimit(); - } - - @Override - public final void openInventory() { - getInternalInventory().openInventory(); - } - - @Override - public final void closeInventory() { - getInternalInventory().closeInventory(); - } - - @Override - public final String getInventoryName() { - return getInternalInventory().getInventoryName(); - } - - @Override - public final boolean isUseableByPlayer(EntityPlayer player) { - return getInternalInventory().isUseableByPlayer(player); - } - - @Override - public final boolean hasCustomInventoryName() { - return getInternalInventory().hasCustomInventoryName(); - } - - @Override - public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { - return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); - } - - @Override - public final int[] getAccessibleSlotsFromSide(int side) { - if (allowsAutomation()) { - return getInternalInventory().getAccessibleSlotsFromSide(side); - } else { - return Constants.SLOTS_NONE; - } - } - - @Override - public final boolean canInsertItem(int slotIndex, ItemStack itemStack, int side) { - if (allowsAutomation()) { - return getInternalInventory().canInsertItem(slotIndex, itemStack, side); - } else { - return false; - } - } - - @Override - public final boolean canExtractItem(int slotIndex, ItemStack itemStack, int side) { - if (allowsAutomation()) { - return getInternalInventory().canExtractItem(slotIndex, itemStack, side); - } else { - return false; - } - } - - @Override - public final boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return getInternalInventory().canSlotAccept(slotIndex, itemStack); - } - - @Override - public final boolean isLocked(int slotIndex) { - return getInternalInventory().isLocked(slotIndex); - } - - /* ILocatable */ - @Override - public final World getWorld() { - return worldObj; - } - - /* IMultiblockComponent */ - @Override - public final GameProfile getOwner() { - return owner; - } - - public final void setOwner(GameProfile owner) { - this.owner = owner; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import com.mojang.authlib.GameProfile; +import forestry.api.multiblock.IMultiblockLogic; +import forestry.api.multiblock.MultiblockTileEntityBase; +import forestry.core.config.Constants; +import forestry.core.gui.GuiHandler; +import forestry.core.gui.IGuiHandlerTile; +import forestry.core.inventory.FakeInventoryAdapter; +import forestry.core.inventory.IInventoryAdapter; +import forestry.core.tiles.IFilterSlotDelegate; +import forestry.core.tiles.ILocatable; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTUtil; +import net.minecraft.world.World; + +public abstract class MultiblockTileEntityForestry extends MultiblockTileEntityBase + implements ISidedInventory, IFilterSlotDelegate, ILocatable, IGuiHandlerTile { + private GameProfile owner; + + public MultiblockTileEntityForestry(T multiblockLogic) { + super(multiblockLogic); + } + + /** + * Called by a structure block when it is right clicked by a player. + */ + public void openGui(EntityPlayer player) { + GuiHandler.openGui(player, this); + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + + if (data.hasKey("owner")) { + owner = NBTUtil.func_152459_a(data.getCompoundTag("owner")); + } + + getInternalInventory().readFromNBT(data); + } + + @Override + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + + if (this.owner != null) { + NBTTagCompound nbt = new NBTTagCompound(); + NBTUtil.func_152460_a(nbt, owner); + nbt.removeTag("Properties"); + data.setTag("owner", nbt); + } + + getInternalInventory().writeToNBT(data); + } + + /* INVENTORY */ + public IInventoryAdapter getInternalInventory() { + return FakeInventoryAdapter.instance(); + } + + public boolean allowsAutomation() { + return false; + } + + @Override + public final int getSizeInventory() { + return getInternalInventory().getSizeInventory(); + } + + @Override + public final ItemStack getStackInSlot(int slotIndex) { + return getInternalInventory().getStackInSlot(slotIndex); + } + + @Override + public final ItemStack decrStackSize(int slotIndex, int amount) { + return getInternalInventory().decrStackSize(slotIndex, amount); + } + + @Override + public final ItemStack getStackInSlotOnClosing(int slotIndex) { + return getInternalInventory().getStackInSlotOnClosing(slotIndex); + } + + @Override + public final void setInventorySlotContents(int slotIndex, ItemStack itemstack) { + getInternalInventory().setInventorySlotContents(slotIndex, itemstack); + } + + @Override + public final int getInventoryStackLimit() { + return getInternalInventory().getInventoryStackLimit(); + } + + @Override + public final void openInventory() { + getInternalInventory().openInventory(); + } + + @Override + public final void closeInventory() { + getInternalInventory().closeInventory(); + } + + @Override + public final String getInventoryName() { + return getInternalInventory().getInventoryName(); + } + + @Override + public final boolean isUseableByPlayer(EntityPlayer player) { + return getInternalInventory().isUseableByPlayer(player); + } + + @Override + public final boolean hasCustomInventoryName() { + return getInternalInventory().hasCustomInventoryName(); + } + + @Override + public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { + return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); + } + + @Override + public final int[] getAccessibleSlotsFromSide(int side) { + if (allowsAutomation()) { + return getInternalInventory().getAccessibleSlotsFromSide(side); + } else { + return Constants.SLOTS_NONE; + } + } + + @Override + public final boolean canInsertItem(int slotIndex, ItemStack itemStack, int side) { + if (allowsAutomation()) { + return getInternalInventory().canInsertItem(slotIndex, itemStack, side); + } else { + return false; + } + } + + @Override + public final boolean canExtractItem(int slotIndex, ItemStack itemStack, int side) { + if (allowsAutomation()) { + return getInternalInventory().canExtractItem(slotIndex, itemStack, side); + } else { + return false; + } + } + + @Override + public final boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return getInternalInventory().canSlotAccept(slotIndex, itemStack); + } + + @Override + public final boolean isLocked(int slotIndex) { + return getInternalInventory().isLocked(slotIndex); + } + + /* ILocatable */ + @Override + public final World getWorld() { + return worldObj; + } + + /* IMultiblockComponent */ + @Override + public final GameProfile getOwner() { + return owner; + } + + public final void setOwner(GameProfile owner) { + this.owner = owner; + } +} diff --git a/src/main/java/forestry/core/multiblock/MultiblockUtil.java b/src/main/java/forestry/core/multiblock/MultiblockUtil.java index 6fc01d37a..5308d3b62 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockUtil.java +++ b/src/main/java/forestry/core/multiblock/MultiblockUtil.java @@ -1,61 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.multiblock; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.api.multiblock.IMultiblockComponent; - -public class MultiblockUtil { - /** - * Returns an array containing references to neighboring IMultiblockComponent tile entities. - * Primarily a utility method. Only works after tileentity construction. - * - * This method is chunk-safe on the server; it will not query for parts in chunks that are unloaded. - * Note that no method is chunk-safe on the client, because ChunkProviderClient is stupid. - * @return An array of references to neighboring IMultiblockComponent tile entities. - */ - public static List getNeighboringParts(World world, IMultiblockComponent part) { - ChunkCoordinates partCoord = part.getCoordinates(); - - List neighbors = new ArrayList<>(ForgeDirection.VALID_DIRECTIONS.length); - for (ForgeDirection forgeDirection : ForgeDirection.VALID_DIRECTIONS) { - ChunkCoordinates neighborCoord = new ChunkCoordinates(partCoord); - neighborCoord.posX += forgeDirection.offsetX; - neighborCoord.posY += forgeDirection.offsetY; - neighborCoord.posZ += forgeDirection.offsetZ; - neighbors.add(neighborCoord); - } - - List neighborParts = new ArrayList<>(); - IChunkProvider chunkProvider = world.getChunkProvider(); - for (ChunkCoordinates neighbor : neighbors) { - if (!chunkProvider.chunkExists(neighbor.posX >> 4, neighbor.posZ >> 4)) { - // Chunk not loaded, skip it. - continue; - } - - TileEntity te = world.getTileEntity(neighbor.posX, neighbor.posY, neighbor.posZ); - if (te instanceof IMultiblockComponent) { - neighborParts.add((IMultiblockComponent) te); - } - } - return neighborParts; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import forestry.api.multiblock.IMultiblockComponent; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; +import net.minecraft.world.chunk.IChunkProvider; +import net.minecraftforge.common.util.ForgeDirection; + +public class MultiblockUtil { + /** + * Returns an array containing references to neighboring IMultiblockComponent tile entities. + * Primarily a utility method. Only works after tileentity construction. + * + * This method is chunk-safe on the server; it will not query for parts in chunks that are unloaded. + * Note that no method is chunk-safe on the client, because ChunkProviderClient is stupid. + * @return An array of references to neighboring IMultiblockComponent tile entities. + */ + public static List getNeighboringParts(World world, IMultiblockComponent part) { + ChunkCoordinates partCoord = part.getCoordinates(); + + List neighbors = new ArrayList<>(ForgeDirection.VALID_DIRECTIONS.length); + for (ForgeDirection forgeDirection : ForgeDirection.VALID_DIRECTIONS) { + ChunkCoordinates neighborCoord = new ChunkCoordinates(partCoord); + neighborCoord.posX += forgeDirection.offsetX; + neighborCoord.posY += forgeDirection.offsetY; + neighborCoord.posZ += forgeDirection.offsetZ; + neighbors.add(neighborCoord); + } + + List neighborParts = new ArrayList<>(); + IChunkProvider chunkProvider = world.getChunkProvider(); + for (ChunkCoordinates neighbor : neighbors) { + if (!chunkProvider.chunkExists(neighbor.posX >> 4, neighbor.posZ >> 4)) { + // Chunk not loaded, skip it. + continue; + } + + TileEntity te = world.getTileEntity(neighbor.posX, neighbor.posY, neighbor.posZ); + if (te instanceof IMultiblockComponent) { + neighborParts.add((IMultiblockComponent) te); + } + } + return neighborParts; + } +} diff --git a/src/main/java/forestry/core/multiblock/MultiblockValidationException.java b/src/main/java/forestry/core/multiblock/MultiblockValidationException.java index b0cda81f1..54ebd3d73 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockValidationException.java +++ b/src/main/java/forestry/core/multiblock/MultiblockValidationException.java @@ -7,7 +7,7 @@ package forestry.core.multiblock; */ public class MultiblockValidationException extends Exception { - public MultiblockValidationException(String reason) { - super(reason); - } + public MultiblockValidationException(String reason) { + super(reason); + } } diff --git a/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java b/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java index d4e0a2985..f97d7a65b 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java @@ -1,5 +1,8 @@ package forestry.core.multiblock; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.api.multiblock.IMultiblockLogic; +import forestry.core.utils.Log; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -7,17 +10,12 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; - import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; -import forestry.api.multiblock.IMultiblockComponent; -import forestry.api.multiblock.IMultiblockLogic; -import forestry.core.utils.Log; - /** * This class manages all the multiblock controllers that exist in a given world, * either client- or server-side. @@ -27,428 +25,433 @@ import forestry.core.utils.Log; */ public class MultiblockWorldRegistry { - private World worldObj; - - private final Set controllers; // Active controllers - private final Set dirtyControllers; // Controllers whose parts lists have changed - private final Set deadControllers; // Controllers which are empty + private World worldObj; - // A list of orphan parts - parts which currently have no master, but should seek one this tick - // Indexed by the hashed chunk coordinate - // This can be added-to asynchronously via chunk loads! - private Set orphanedParts; + private final Set controllers; // Active controllers + private final Set dirtyControllers; // Controllers whose parts lists have changed + private final Set deadControllers; // Controllers which are empty - // A list of parts which have been detached during internal operations - private final Set detachedParts; - - // A list of parts whose chunks have not yet finished loading - // They will be added to the orphan list when they are finished loading. - // Indexed by the hashed chunk coordinate - // This can be added-to asynchronously via chunk loads! - private final HashMap> partsAwaitingChunkLoad; - - // Mutexes to protect lists which may be changed due to asynchronous events, such as chunk loads - private final Object partsAwaitingChunkLoadMutex; - private final Object orphanedPartsMutex; - - public MultiblockWorldRegistry(World world) { - worldObj = world; - - controllers = new HashSet<>(); - deadControllers = new HashSet<>(); - dirtyControllers = new HashSet<>(); - - detachedParts = new HashSet<>(); - orphanedParts = new HashSet<>(); + // A list of orphan parts - parts which currently have no master, but should seek one this tick + // Indexed by the hashed chunk coordinate + // This can be added-to asynchronously via chunk loads! + private Set orphanedParts; - partsAwaitingChunkLoad = new HashMap<>(); - partsAwaitingChunkLoadMutex = new Object(); - orphanedPartsMutex = new Object(); - } - - /** - * Called before Tile Entities are ticked in the world. Run game logic. - */ - public void tickStart() { - if (controllers.size() > 0) { - for (IMultiblockControllerInternal controller : controllers) { - if (controller.getWorld() == worldObj && controller.getWorld().isRemote == worldObj.isRemote) { - if (controller.isEmpty()) { - // This happens on the server when the user breaks the last block. It's fine. - // Mark 'er dead and move on. - deadControllers.add(controller); - } else { - // Run the game logic for this world - controller.updateMultiblockEntity(); - } - } - } - } - } - - /** - * Called prior to processing multiblock controllers. Do bookkeeping. - */ - public void processMultiblockChanges() { - IChunkProvider chunkProvider = worldObj.getChunkProvider(); - ChunkCoordinates coord; + // A list of parts which have been detached during internal operations + private final Set detachedParts; - // Merge pools - sets of adjacent machines which should be merged later on in processing - List> mergePools = null; - if (orphanedParts.size() > 0) { - Set orphansToProcess = null; - - // Keep the synchronized block small. We can't iterate over orphanedParts directly - // because the client does not know which chunks are actually loaded, so attachToNeighbors() - // is not chunk-safe on the client, because Minecraft is stupid. - // It's possible to polyfill this, but the polyfill is too slow for comfort. - synchronized (orphanedPartsMutex) { - if (orphanedParts.size() > 0) { - orphansToProcess = orphanedParts; - orphanedParts = new HashSet<>(); - } - } - - if (orphansToProcess != null && orphansToProcess.size() > 0) { - Set compatibleControllers; - - // Process orphaned blocks - // These are blocks that exist in a valid chunk and require a controller - for (IMultiblockComponent orphan : orphansToProcess) { - coord = orphan.getCoordinates(); - if (!chunkProvider.chunkExists(coord.posX >> 4, coord.posZ >> 4)) { - continue; - } + // A list of parts whose chunks have not yet finished loading + // They will be added to the orphan list when they are finished loading. + // Indexed by the hashed chunk coordinate + // This can be added-to asynchronously via chunk loads! + private final HashMap> partsAwaitingChunkLoad; - // This can occur on slow machines. - if (orphan instanceof TileEntity && ((TileEntity) orphan).isInvalid()) { - continue; - } + // Mutexes to protect lists which may be changed due to asynchronous events, such as chunk loads + private final Object partsAwaitingChunkLoadMutex; + private final Object orphanedPartsMutex; - if (worldObj.getTileEntity(coord.posX, coord.posY, coord.posZ) != orphan) { - // This block has been replaced by another. - continue; - } - - // THIS IS THE ONLY PLACE WHERE PARTS ATTACH TO MACHINES - // Try to attach to a neighbor's master controller - compatibleControllers = attachToNeighbors(orphan); - if (compatibleControllers.size() == 0) { - // FOREVER ALONE! Create and register a new controller. - // THIS IS THE ONLY PLACE WHERE NEW CONTROLLERS ARE CREATED. - MultiblockLogic logic = (MultiblockLogic) orphan.getMultiblockLogic(); - IMultiblockControllerInternal newController = logic.createNewController(worldObj); - newController.attachBlock(orphan); - this.controllers.add(newController); - } else if (compatibleControllers.size() > 1) { - if (mergePools == null) { - mergePools = new ArrayList<>(); - } + public MultiblockWorldRegistry(World world) { + worldObj = world; - // THIS IS THE ONLY PLACE WHERE MERGES ARE DETECTED - // Multiple compatible controllers indicates an impending merge. - // Locate the appropriate merge pool(s) - List> candidatePools = new ArrayList<>(); - for (Set candidatePool : mergePools) { - if (!Collections.disjoint(candidatePool, compatibleControllers)) { - // They share at least one element, so that means they will all touch after the merge - candidatePools.add(candidatePool); - } - } - - if (candidatePools.size() <= 0) { - // No pools nearby, create a new merge pool - mergePools.add(compatibleControllers); - } else if (candidatePools.size() == 1) { - // Only one pool nearby, simply add to that one - candidatePools.get(0).addAll(compatibleControllers); - } else { - // Multiple pools- merge into one, then add the compatible controllers - Set masterPool = candidatePools.get(0); - Set consumedPool; - for (int i = 1; i < candidatePools.size(); i++) { - consumedPool = candidatePools.get(i); - masterPool.addAll(consumedPool); - mergePools.remove(consumedPool); - } - masterPool.addAll(compatibleControllers); - } - } - } - } - } + controllers = new HashSet<>(); + deadControllers = new HashSet<>(); + dirtyControllers = new HashSet<>(); - if (mergePools != null && mergePools.size() > 0) { - // Process merges - any machines that have been marked for merge should be merged - // into the "master" machine. - // To do this, we combine lists of machines that are touching one another and therefore - // should voltron the fuck up. - for (Set mergePool : mergePools) { - // Search for the new master machine, which will take over all the blocks contained in the other machines - IMultiblockControllerInternal newMaster = null; - for (IMultiblockControllerInternal controller : mergePool) { - if (newMaster == null || controller.shouldConsume(newMaster)) { - newMaster = controller; - } - } - - if (newMaster == null) { - Log.severe("Multiblock system checked a merge pool of size %d, found no master candidates. This should never happen.", mergePool.size()); - } else { - // Merge all the other machines into the master machine, then unregister them - addDirtyController(newMaster); - for (IMultiblockControllerInternal controller : mergePool) { - if (controller != newMaster) { - newMaster.assimilate(controller); - addDeadController(controller); - addDirtyController(newMaster); - } - } - } - } - } + detachedParts = new HashSet<>(); + orphanedParts = new HashSet<>(); - // Process splits and assembly - // Any controllers which have had parts removed must be checked to see if some parts are no longer - // physically connected to their master. - if (dirtyControllers.size() > 0) { - for (IMultiblockControllerInternal controller : dirtyControllers) { - if (controller == null) { - continue; - } - // Tell the machine to check if any parts are disconnected. - // It should return a set of parts which are no longer connected. - // POSTCONDITION: The controller must have informed those parts that - // they are no longer connected to this machine. - Set newlyDetachedParts = controller.checkForDisconnections(); - - if (!controller.isEmpty()) { - controller.recalculateMinMaxCoords(); - controller.checkIfMachineIsWhole(); - } else { - addDeadController(controller); - } - - if (newlyDetachedParts.size() > 0) { - // Controller has shed some parts - add them to the detached list for delayed processing - detachedParts.addAll(newlyDetachedParts); - } - } - - dirtyControllers.clear(); - } - - // Unregister dead controllers - if (deadControllers.size() > 0) { - for (IMultiblockControllerInternal controller : deadControllers) { - // Go through any controllers which have marked themselves as potentially dead. - // Validate that they are empty/dead, then unregister them. - if (!controller.isEmpty()) { - Log.severe("Found a non-empty controller. Forcing it to shed its blocks and die. This should never happen!"); - detachedParts.addAll(controller.detachAllBlocks()); - } + partsAwaitingChunkLoad = new HashMap<>(); + partsAwaitingChunkLoadMutex = new Object(); + orphanedPartsMutex = new Object(); + } - // THIS IS THE ONLY PLACE WHERE CONTROLLERS ARE UNREGISTERED. - this.controllers.remove(controller); - } - - deadControllers.clear(); - } - - // Process detached blocks - // Any blocks which have been detached this tick should be moved to the orphaned - // list, and will be checked next tick to see if their chunk is still loaded. - for (IMultiblockComponent part : detachedParts) { - // Ensure parts know they're detached - MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); - logic.assertDetached(part); - } - - addAllOrphanedPartsThreadsafe(detachedParts); - detachedParts.clear(); - } + /** + * Called before Tile Entities are ticked in the world. Run game logic. + */ + public void tickStart() { + if (controllers.size() > 0) { + for (IMultiblockControllerInternal controller : controllers) { + if (controller.getWorld() == worldObj && controller.getWorld().isRemote == worldObj.isRemote) { + if (controller.isEmpty()) { + // This happens on the server when the user breaks the last block. It's fine. + // Mark 'er dead and move on. + deadControllers.add(controller); + } else { + // Run the game logic for this world + controller.updateMultiblockEntity(); + } + } + } + } + } - ///// Multiblock Connection Base Logic - private Set attachToNeighbors(IMultiblockComponent part) { - Set controllers = new HashSet<>(); - IMultiblockControllerInternal bestController = null; + /** + * Called prior to processing multiblock controllers. Do bookkeeping. + */ + public void processMultiblockChanges() { + IChunkProvider chunkProvider = worldObj.getChunkProvider(); + ChunkCoordinates coord; - MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); - Class controllerClass = logic.getControllerClass(); - // Look for a compatible controller in our neighboring parts. - List partsToCheck = MultiblockUtil.getNeighboringParts(worldObj, part); - for (IMultiblockComponent neighborPart : partsToCheck) { - IMultiblockLogic neighborLogic = neighborPart.getMultiblockLogic(); - if (neighborLogic.isConnected()) { - IMultiblockControllerInternal candidate = (IMultiblockControllerInternal) neighborLogic.getController(); - if (!controllerClass.isAssignableFrom(candidate.getClass())) { - // Skip multiblocks with incompatible types - continue; - } + // Merge pools - sets of adjacent machines which should be merged later on in processing + List> mergePools = null; + if (orphanedParts.size() > 0) { + Set orphansToProcess = null; - if (!controllers.contains(candidate) && (bestController == null || candidate.shouldConsume(bestController))) { - bestController = candidate; - } + // Keep the synchronized block small. We can't iterate over orphanedParts directly + // because the client does not know which chunks are actually loaded, so attachToNeighbors() + // is not chunk-safe on the client, because Minecraft is stupid. + // It's possible to polyfill this, but the polyfill is too slow for comfort. + synchronized (orphanedPartsMutex) { + if (orphanedParts.size() > 0) { + orphansToProcess = orphanedParts; + orphanedParts = new HashSet<>(); + } + } - controllers.add(candidate); - } - } + if (orphansToProcess != null && orphansToProcess.size() > 0) { + Set compatibleControllers; - // If we've located a valid neighboring controller, attach to it. - if (bestController != null) { - // attachBlock will call onAttached, which will set the controller. - bestController.attachBlock(part); - } + // Process orphaned blocks + // These are blocks that exist in a valid chunk and require a controller + for (IMultiblockComponent orphan : orphansToProcess) { + coord = orphan.getCoordinates(); + if (!chunkProvider.chunkExists(coord.posX >> 4, coord.posZ >> 4)) { + continue; + } - return controllers; - } + // This can occur on slow machines. + if (orphan instanceof TileEntity && ((TileEntity) orphan).isInvalid()) { + continue; + } - /** - * Called when a multiblock part is added to the world, either via chunk-load or user action. - * If its chunk is loaded, it will be processed during the next tick. - * If the chunk is not loaded, it will be added to a list of objects waiting for a chunkload. - * @param part The part which is being added to this world. - */ - public void onPartAdded(IMultiblockComponent part) { - ChunkCoordinates worldLocation = part.getCoordinates(); - - if (!worldObj.getChunkProvider().chunkExists(worldLocation.posX >> 4, worldLocation.posZ >> 4)) { - // Part goes into the waiting-for-chunk-load list - Set partSet; - long chunkHash = ChunkCoordIntPair.chunkXZ2Int(worldLocation.posX >> 4, worldLocation.posZ >> 4); - synchronized (partsAwaitingChunkLoadMutex) { - if (!partsAwaitingChunkLoad.containsKey(chunkHash)) { - partSet = new HashSet<>(); - partsAwaitingChunkLoad.put(chunkHash, partSet); - } else { - partSet = partsAwaitingChunkLoad.get(chunkHash); - } - - partSet.add(part); - } - } else { - // Part goes into the orphan queue, to be checked this tick - addOrphanedPartThreadsafe(part); - } - } - - /** - * Called when a part is removed from the world, via user action or via chunk unloads. - * This part is removed from any lists in which it may be, and its machine is marked for recalculation. - * @param part The part which is being removed. - */ - public void onPartRemovedFromWorld(IMultiblockComponent part) { - ChunkCoordinates coord = part.getCoordinates(); - if (coord != null) { - long hash = ChunkCoordIntPair.chunkXZ2Int(coord.posX >> 4, coord.posZ >> 4); - - if (partsAwaitingChunkLoad.containsKey(hash)) { - synchronized (partsAwaitingChunkLoadMutex) { - if (partsAwaitingChunkLoad.containsKey(hash)) { - partsAwaitingChunkLoad.get(hash).remove(part); - if (partsAwaitingChunkLoad.get(hash).size() <= 0) { - partsAwaitingChunkLoad.remove(hash); - } - } - } - } - } + if (worldObj.getTileEntity(coord.posX, coord.posY, coord.posZ) != orphan) { + // This block has been replaced by another. + continue; + } - detachedParts.remove(part); - if (orphanedParts.contains(part)) { - synchronized (orphanedPartsMutex) { - orphanedParts.remove(part); - } - } + // THIS IS THE ONLY PLACE WHERE PARTS ATTACH TO MACHINES + // Try to attach to a neighbor's master controller + compatibleControllers = attachToNeighbors(orphan); + if (compatibleControllers.size() == 0) { + // FOREVER ALONE! Create and register a new controller. + // THIS IS THE ONLY PLACE WHERE NEW CONTROLLERS ARE CREATED. + MultiblockLogic logic = (MultiblockLogic) orphan.getMultiblockLogic(); + IMultiblockControllerInternal newController = logic.createNewController(worldObj); + newController.attachBlock(orphan); + this.controllers.add(newController); + } else if (compatibleControllers.size() > 1) { + if (mergePools == null) { + mergePools = new ArrayList<>(); + } - MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); - logic.assertDetached(part); - } + // THIS IS THE ONLY PLACE WHERE MERGES ARE DETECTED + // Multiple compatible controllers indicates an impending merge. + // Locate the appropriate merge pool(s) + List> candidatePools = new ArrayList<>(); + for (Set candidatePool : mergePools) { + if (!Collections.disjoint(candidatePool, compatibleControllers)) { + // They share at least one element, so that means they will all touch after the merge + candidatePools.add(candidatePool); + } + } - /** - * Called when the world which this World Registry represents is fully unloaded from the system. - * Does some housekeeping just to be nice. - */ - public void onWorldUnloaded() { - controllers.clear(); - deadControllers.clear(); - dirtyControllers.clear(); - - detachedParts.clear(); - - synchronized (partsAwaitingChunkLoadMutex) { - partsAwaitingChunkLoad.clear(); - } - - synchronized (orphanedPartsMutex) { - orphanedParts.clear(); - } - - worldObj = null; - } + if (candidatePools.size() <= 0) { + // No pools nearby, create a new merge pool + mergePools.add(compatibleControllers); + } else if (candidatePools.size() == 1) { + // Only one pool nearby, simply add to that one + candidatePools.get(0).addAll(compatibleControllers); + } else { + // Multiple pools- merge into one, then add the compatible controllers + Set masterPool = candidatePools.get(0); + Set consumedPool; + for (int i = 1; i < candidatePools.size(); i++) { + consumedPool = candidatePools.get(i); + masterPool.addAll(consumedPool); + mergePools.remove(consumedPool); + } + masterPool.addAll(compatibleControllers); + } + } + } + } + } - /** - * Called when a chunk has finished loading. Adds all of the parts which are awaiting - * load to the list of parts which are orphans and therefore will be added to machines - * after the next world tick. - * - * @param chunkX Chunk X coordinate (world coordate >> 4) of the chunk that was loaded - * @param chunkZ Chunk Z coordinate (world coordate >> 4) of the chunk that was loaded - */ - public void onChunkLoaded(int chunkX, int chunkZ) { - long chunkHash = ChunkCoordIntPair.chunkXZ2Int(chunkX, chunkZ); - if (partsAwaitingChunkLoad.containsKey(chunkHash)) { - synchronized (partsAwaitingChunkLoadMutex) { - if (partsAwaitingChunkLoad.containsKey(chunkHash)) { - addAllOrphanedPartsThreadsafe(partsAwaitingChunkLoad.get(chunkHash)); - partsAwaitingChunkLoad.remove(chunkHash); - } - } - } - } + if (mergePools != null && mergePools.size() > 0) { + // Process merges - any machines that have been marked for merge should be merged + // into the "master" machine. + // To do this, we combine lists of machines that are touching one another and therefore + // should voltron the fuck up. + for (Set mergePool : mergePools) { + // Search for the new master machine, which will take over all the blocks contained in the other + // machines + IMultiblockControllerInternal newMaster = null; + for (IMultiblockControllerInternal controller : mergePool) { + if (newMaster == null || controller.shouldConsume(newMaster)) { + newMaster = controller; + } + } - /** - * Registers a controller as dead. It will be cleaned up at the end of the next world tick. - * Note that a controller must shed all of its blocks before being marked as dead, or the system - * will complain at you. - * - * @param deadController The controller which is dead. - */ - public void addDeadController(IMultiblockControllerInternal deadController) { - this.deadControllers.add(deadController); - } + if (newMaster == null) { + Log.severe( + "Multiblock system checked a merge pool of size %d, found no master candidates. This should never happen.", + mergePool.size()); + } else { + // Merge all the other machines into the master machine, then unregister them + addDirtyController(newMaster); + for (IMultiblockControllerInternal controller : mergePool) { + if (controller != newMaster) { + newMaster.assimilate(controller); + addDeadController(controller); + addDirtyController(newMaster); + } + } + } + } + } - /** - * Registers a controller as dirty - its list of attached blocks has changed, and it - * must be re-checked for assembly and, possibly, for orphans. - * - * @param dirtyController The dirty controller. - */ - public void addDirtyController(IMultiblockControllerInternal dirtyController) { - this.dirtyControllers.add(dirtyController); - } - - /** - * Use this only if you know what you're doing. You should rarely need to iterate - * over all controllers in a world! - * - * @return An (unmodifiable) set of controllers which are active in this world. - */ - public Set getControllers() { - return Collections.unmodifiableSet(controllers); - } + // Process splits and assembly + // Any controllers which have had parts removed must be checked to see if some parts are no longer + // physically connected to their master. + if (dirtyControllers.size() > 0) { + for (IMultiblockControllerInternal controller : dirtyControllers) { + if (controller == null) { + continue; + } + // Tell the machine to check if any parts are disconnected. + // It should return a set of parts which are no longer connected. + // POSTCONDITION: The controller must have informed those parts that + // they are no longer connected to this machine. + Set newlyDetachedParts = controller.checkForDisconnections(); - /* *** PRIVATE HELPERS *** */ - - private void addOrphanedPartThreadsafe(IMultiblockComponent part) { - synchronized (orphanedPartsMutex) { - orphanedParts.add(part); - } - } - - private void addAllOrphanedPartsThreadsafe(Collection parts) { - synchronized (orphanedPartsMutex) { - orphanedParts.addAll(parts); - } - } + if (!controller.isEmpty()) { + controller.recalculateMinMaxCoords(); + controller.checkIfMachineIsWhole(); + } else { + addDeadController(controller); + } + + if (newlyDetachedParts.size() > 0) { + // Controller has shed some parts - add them to the detached list for delayed processing + detachedParts.addAll(newlyDetachedParts); + } + } + + dirtyControllers.clear(); + } + + // Unregister dead controllers + if (deadControllers.size() > 0) { + for (IMultiblockControllerInternal controller : deadControllers) { + // Go through any controllers which have marked themselves as potentially dead. + // Validate that they are empty/dead, then unregister them. + if (!controller.isEmpty()) { + Log.severe( + "Found a non-empty controller. Forcing it to shed its blocks and die. This should never happen!"); + detachedParts.addAll(controller.detachAllBlocks()); + } + + // THIS IS THE ONLY PLACE WHERE CONTROLLERS ARE UNREGISTERED. + this.controllers.remove(controller); + } + + deadControllers.clear(); + } + + // Process detached blocks + // Any blocks which have been detached this tick should be moved to the orphaned + // list, and will be checked next tick to see if their chunk is still loaded. + for (IMultiblockComponent part : detachedParts) { + // Ensure parts know they're detached + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); + logic.assertDetached(part); + } + + addAllOrphanedPartsThreadsafe(detachedParts); + detachedParts.clear(); + } + + ///// Multiblock Connection Base Logic + private Set attachToNeighbors(IMultiblockComponent part) { + Set controllers = new HashSet<>(); + IMultiblockControllerInternal bestController = null; + + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); + Class controllerClass = logic.getControllerClass(); + // Look for a compatible controller in our neighboring parts. + List partsToCheck = MultiblockUtil.getNeighboringParts(worldObj, part); + for (IMultiblockComponent neighborPart : partsToCheck) { + IMultiblockLogic neighborLogic = neighborPart.getMultiblockLogic(); + if (neighborLogic.isConnected()) { + IMultiblockControllerInternal candidate = (IMultiblockControllerInternal) neighborLogic.getController(); + if (!controllerClass.isAssignableFrom(candidate.getClass())) { + // Skip multiblocks with incompatible types + continue; + } + + if (!controllers.contains(candidate) + && (bestController == null || candidate.shouldConsume(bestController))) { + bestController = candidate; + } + + controllers.add(candidate); + } + } + + // If we've located a valid neighboring controller, attach to it. + if (bestController != null) { + // attachBlock will call onAttached, which will set the controller. + bestController.attachBlock(part); + } + + return controllers; + } + + /** + * Called when a multiblock part is added to the world, either via chunk-load or user action. + * If its chunk is loaded, it will be processed during the next tick. + * If the chunk is not loaded, it will be added to a list of objects waiting for a chunkload. + * @param part The part which is being added to this world. + */ + public void onPartAdded(IMultiblockComponent part) { + ChunkCoordinates worldLocation = part.getCoordinates(); + + if (!worldObj.getChunkProvider().chunkExists(worldLocation.posX >> 4, worldLocation.posZ >> 4)) { + // Part goes into the waiting-for-chunk-load list + Set partSet; + long chunkHash = ChunkCoordIntPair.chunkXZ2Int(worldLocation.posX >> 4, worldLocation.posZ >> 4); + synchronized (partsAwaitingChunkLoadMutex) { + if (!partsAwaitingChunkLoad.containsKey(chunkHash)) { + partSet = new HashSet<>(); + partsAwaitingChunkLoad.put(chunkHash, partSet); + } else { + partSet = partsAwaitingChunkLoad.get(chunkHash); + } + + partSet.add(part); + } + } else { + // Part goes into the orphan queue, to be checked this tick + addOrphanedPartThreadsafe(part); + } + } + + /** + * Called when a part is removed from the world, via user action or via chunk unloads. + * This part is removed from any lists in which it may be, and its machine is marked for recalculation. + * @param part The part which is being removed. + */ + public void onPartRemovedFromWorld(IMultiblockComponent part) { + ChunkCoordinates coord = part.getCoordinates(); + if (coord != null) { + long hash = ChunkCoordIntPair.chunkXZ2Int(coord.posX >> 4, coord.posZ >> 4); + + if (partsAwaitingChunkLoad.containsKey(hash)) { + synchronized (partsAwaitingChunkLoadMutex) { + if (partsAwaitingChunkLoad.containsKey(hash)) { + partsAwaitingChunkLoad.get(hash).remove(part); + if (partsAwaitingChunkLoad.get(hash).size() <= 0) { + partsAwaitingChunkLoad.remove(hash); + } + } + } + } + } + + detachedParts.remove(part); + if (orphanedParts.contains(part)) { + synchronized (orphanedPartsMutex) { + orphanedParts.remove(part); + } + } + + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); + logic.assertDetached(part); + } + + /** + * Called when the world which this World Registry represents is fully unloaded from the system. + * Does some housekeeping just to be nice. + */ + public void onWorldUnloaded() { + controllers.clear(); + deadControllers.clear(); + dirtyControllers.clear(); + + detachedParts.clear(); + + synchronized (partsAwaitingChunkLoadMutex) { + partsAwaitingChunkLoad.clear(); + } + + synchronized (orphanedPartsMutex) { + orphanedParts.clear(); + } + + worldObj = null; + } + + /** + * Called when a chunk has finished loading. Adds all of the parts which are awaiting + * load to the list of parts which are orphans and therefore will be added to machines + * after the next world tick. + * + * @param chunkX Chunk X coordinate (world coordate >> 4) of the chunk that was loaded + * @param chunkZ Chunk Z coordinate (world coordate >> 4) of the chunk that was loaded + */ + public void onChunkLoaded(int chunkX, int chunkZ) { + long chunkHash = ChunkCoordIntPair.chunkXZ2Int(chunkX, chunkZ); + if (partsAwaitingChunkLoad.containsKey(chunkHash)) { + synchronized (partsAwaitingChunkLoadMutex) { + if (partsAwaitingChunkLoad.containsKey(chunkHash)) { + addAllOrphanedPartsThreadsafe(partsAwaitingChunkLoad.get(chunkHash)); + partsAwaitingChunkLoad.remove(chunkHash); + } + } + } + } + + /** + * Registers a controller as dead. It will be cleaned up at the end of the next world tick. + * Note that a controller must shed all of its blocks before being marked as dead, or the system + * will complain at you. + * + * @param deadController The controller which is dead. + */ + public void addDeadController(IMultiblockControllerInternal deadController) { + this.deadControllers.add(deadController); + } + + /** + * Registers a controller as dirty - its list of attached blocks has changed, and it + * must be re-checked for assembly and, possibly, for orphans. + * + * @param dirtyController The dirty controller. + */ + public void addDirtyController(IMultiblockControllerInternal dirtyController) { + this.dirtyControllers.add(dirtyController); + } + + /** + * Use this only if you know what you're doing. You should rarely need to iterate + * over all controllers in a world! + * + * @return An (unmodifiable) set of controllers which are active in this world. + */ + public Set getControllers() { + return Collections.unmodifiableSet(controllers); + } + + /* *** PRIVATE HELPERS *** */ + + private void addOrphanedPartThreadsafe(IMultiblockComponent part) { + synchronized (orphanedPartsMutex) { + orphanedParts.add(part); + } + } + + private void addAllOrphanedPartsThreadsafe(Collection parts) { + synchronized (orphanedPartsMutex) { + orphanedParts.addAll(parts); + } + } } diff --git a/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java b/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java index 43213c138..f407c9608 100644 --- a/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java +++ b/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java @@ -1,129 +1,138 @@ package forestry.core.multiblock; +import forestry.api.multiblock.IMultiblockComponent; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -import forestry.api.multiblock.IMultiblockComponent; - public abstract class RectangularMultiblockControllerBase extends MultiblockControllerForestry { - private final IMultiblockSizeLimits sizeLimits; + private final IMultiblockSizeLimits sizeLimits; - protected RectangularMultiblockControllerBase(World world, IMultiblockSizeLimits sizeLimits) { - super(world); - this.sizeLimits = sizeLimits; - } + protected RectangularMultiblockControllerBase(World world, IMultiblockSizeLimits sizeLimits) { + super(world); + this.sizeLimits = sizeLimits; + } - @Override - protected void isMachineWhole() throws MultiblockValidationException { - int minX = sizeLimits.getMinimumXSize(); - int minY = sizeLimits.getMinimumYSize(); - int minZ = sizeLimits.getMinimumZSize(); + @Override + protected void isMachineWhole() throws MultiblockValidationException { + int minX = sizeLimits.getMinimumXSize(); + int minY = sizeLimits.getMinimumYSize(); + int minZ = sizeLimits.getMinimumZSize(); - if (connectedParts.size() < sizeLimits.getMinimumNumberOfBlocksForAssembledMachine()) { - throw new MultiblockValidationException(StatCollector.translateToLocalFormatted("for.multiblock.error.small", minX, minY, minZ)); - } - - ChunkCoordinates maximumCoord = getMaximumCoord(); - ChunkCoordinates minimumCoord = getMinimumCoord(); - - // Quickly check for exceeded dimensions - int deltaX = maximumCoord.posX - minimumCoord.posX + 1; - int deltaY = maximumCoord.posY - minimumCoord.posY + 1; - int deltaZ = maximumCoord.posZ - minimumCoord.posZ + 1; - - int maxX = sizeLimits.getMaximumXSize(); - int maxY = sizeLimits.getMaximumYSize(); - int maxZ = sizeLimits.getMaximumZSize(); + if (connectedParts.size() < sizeLimits.getMinimumNumberOfBlocksForAssembledMachine()) { + throw new MultiblockValidationException( + StatCollector.translateToLocalFormatted("for.multiblock.error.small", minX, minY, minZ)); + } - if (maxX > 0 && deltaX > maxX) { - throw new MultiblockValidationException(StatCollector.translateToLocalFormatted("for.multiblock.error.large.x", maxX)); - } - if (maxY > 0 && deltaY > maxY) { - throw new MultiblockValidationException(StatCollector.translateToLocalFormatted("for.multiblock.error.large.y", maxY)); - } - if (maxZ > 0 && deltaZ > maxZ) { - throw new MultiblockValidationException(StatCollector.translateToLocalFormatted("for.multiblock.error.large.z", maxZ)); - } - if (deltaX < minX) { - throw new MultiblockValidationException(StatCollector.translateToLocalFormatted("for.multiblock.error.small.x", minX)); - } - if (deltaY < minY) { - throw new MultiblockValidationException(StatCollector.translateToLocalFormatted("for.multiblock.error.small.y", minY)); - } - if (deltaZ < minZ) { - throw new MultiblockValidationException(StatCollector.translateToLocalFormatted("for.multiblock.error.small.z", minZ)); - } + ChunkCoordinates maximumCoord = getMaximumCoord(); + ChunkCoordinates minimumCoord = getMinimumCoord(); - // Now we run a simple check on each block within that volume. - // Any block deviating = NO DEAL SIR - TileEntity te; - IMultiblockComponent part; - Class myClass = this.getClass(); + // Quickly check for exceeded dimensions + int deltaX = maximumCoord.posX - minimumCoord.posX + 1; + int deltaY = maximumCoord.posY - minimumCoord.posY + 1; + int deltaZ = maximumCoord.posZ - minimumCoord.posZ + 1; - for (int x = minimumCoord.posX; x <= maximumCoord.posX; x++) { - for (int y = minimumCoord.posY; y <= maximumCoord.posY; y++) { - for (int z = minimumCoord.posZ; z <= maximumCoord.posZ; z++) { - // Okay, figure out what sort of block this should be. - - te = this.worldObj.getTileEntity(x, y, z); - if (te instanceof IMultiblockComponent) { - part = (IMultiblockComponent) te; - - // Ensure this part should actually be allowed within a cube of this controller's type - if (!myClass.equals(part.getMultiblockLogic().getController().getClass())) { - throw new MultiblockValidationException(StatCollector.translateToLocalFormatted("for.multiblock.error.invalid.part", x, y, z, myClass.getSimpleName())); - } - } else { - // This is permitted so that we can incorporate certain non-multiblock parts inside interiors - part = null; - } - - // Validate block type against both part-level and material-level validators. - int extremes = 0; - if (x == minimumCoord.posX) { - extremes++; - } - if (y == minimumCoord.posY) { - extremes++; - } - if (z == minimumCoord.posZ) { - extremes++; - } - - if (x == maximumCoord.posX) { - extremes++; - } - if (y == maximumCoord.posY) { - extremes++; - } - if (z == maximumCoord.posZ) { - extremes++; - } - - if (extremes >= 1) { - // Side - int exteriorLevel = y - minimumCoord.posY; - if (part != null) { - isGoodForExteriorLevel(part, exteriorLevel); - } else { - isBlockGoodForExteriorLevel(exteriorLevel, this.worldObj, x, y, z); - } - } else { - if (part != null) { - isGoodForInterior(part); - } else { - isBlockGoodForInterior(this.worldObj, x, y, z); - } - } - } - } - } - } + int maxX = sizeLimits.getMaximumXSize(); + int maxY = sizeLimits.getMaximumYSize(); + int maxZ = sizeLimits.getMaximumZSize(); - protected abstract void isGoodForExteriorLevel(IMultiblockComponent part, int level) throws MultiblockValidationException; + if (maxX > 0 && deltaX > maxX) { + throw new MultiblockValidationException( + StatCollector.translateToLocalFormatted("for.multiblock.error.large.x", maxX)); + } + if (maxY > 0 && deltaY > maxY) { + throw new MultiblockValidationException( + StatCollector.translateToLocalFormatted("for.multiblock.error.large.y", maxY)); + } + if (maxZ > 0 && deltaZ > maxZ) { + throw new MultiblockValidationException( + StatCollector.translateToLocalFormatted("for.multiblock.error.large.z", maxZ)); + } + if (deltaX < minX) { + throw new MultiblockValidationException( + StatCollector.translateToLocalFormatted("for.multiblock.error.small.x", minX)); + } + if (deltaY < minY) { + throw new MultiblockValidationException( + StatCollector.translateToLocalFormatted("for.multiblock.error.small.y", minY)); + } + if (deltaZ < minZ) { + throw new MultiblockValidationException( + StatCollector.translateToLocalFormatted("for.multiblock.error.small.z", minZ)); + } - protected abstract void isGoodForInterior(IMultiblockComponent part) throws MultiblockValidationException; + // Now we run a simple check on each block within that volume. + // Any block deviating = NO DEAL SIR + TileEntity te; + IMultiblockComponent part; + Class myClass = this.getClass(); + + for (int x = minimumCoord.posX; x <= maximumCoord.posX; x++) { + for (int y = minimumCoord.posY; y <= maximumCoord.posY; y++) { + for (int z = minimumCoord.posZ; z <= maximumCoord.posZ; z++) { + // Okay, figure out what sort of block this should be. + + te = this.worldObj.getTileEntity(x, y, z); + if (te instanceof IMultiblockComponent) { + part = (IMultiblockComponent) te; + + // Ensure this part should actually be allowed within a cube of this controller's type + if (!myClass.equals( + part.getMultiblockLogic().getController().getClass())) { + throw new MultiblockValidationException(StatCollector.translateToLocalFormatted( + "for.multiblock.error.invalid.part", x, y, z, myClass.getSimpleName())); + } + } else { + // This is permitted so that we can incorporate certain non-multiblock parts inside interiors + part = null; + } + + // Validate block type against both part-level and material-level validators. + int extremes = 0; + if (x == minimumCoord.posX) { + extremes++; + } + if (y == minimumCoord.posY) { + extremes++; + } + if (z == minimumCoord.posZ) { + extremes++; + } + + if (x == maximumCoord.posX) { + extremes++; + } + if (y == maximumCoord.posY) { + extremes++; + } + if (z == maximumCoord.posZ) { + extremes++; + } + + if (extremes >= 1) { + // Side + int exteriorLevel = y - minimumCoord.posY; + if (part != null) { + isGoodForExteriorLevel(part, exteriorLevel); + } else { + isBlockGoodForExteriorLevel(exteriorLevel, this.worldObj, x, y, z); + } + } else { + if (part != null) { + isGoodForInterior(part); + } else { + isBlockGoodForInterior(this.worldObj, x, y, z); + } + } + } + } + } + } + + protected abstract void isGoodForExteriorLevel(IMultiblockComponent part, int level) + throws MultiblockValidationException; + + protected abstract void isGoodForInterior(IMultiblockComponent part) throws MultiblockValidationException; } diff --git a/src/main/java/forestry/core/network/DataInputStreamForestry.java b/src/main/java/forestry/core/network/DataInputStreamForestry.java index 9dad78abb..4db7963ad 100644 --- a/src/main/java/forestry/core/network/DataInputStreamForestry.java +++ b/src/main/java/forestry/core/network/DataInputStreamForestry.java @@ -1,153 +1,152 @@ -package forestry.core.network; - -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InvalidObjectException; -import java.util.Collection; -import java.util.List; - -import net.minecraft.inventory.IInventory; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - -import cpw.mods.fml.common.registry.GameData; - -public class DataInputStreamForestry extends DataInputStream { - - public DataInputStreamForestry(InputStream in) { - super(in); - } - - public ItemStack readItemStack() throws IOException { - ItemStack itemstack = null; - String itemName = readUTF(); - - if (!itemName.isEmpty()) { - Item item = GameData.getItemRegistry().getRaw(itemName); - byte stackSize = readByte(); - int meta = readVarInt(); - itemstack = new ItemStack(item, stackSize, meta); - - if (item.isDamageable() || item.getShareTag()) { - itemstack.stackTagCompound = readNBTTagCompound(); - } - } - - return itemstack; - } - - public ItemStack[] readItemStacks() throws IOException { - int stackCount = readVarInt(); - - ItemStack[] itemStacks = new ItemStack[stackCount]; - for (int i = 0; i < stackCount; i++) { - itemStacks[i] = readItemStack(); - } - - return itemStacks; - } - - public void readItemStacks(Collection itemStacks) throws IOException { - itemStacks.clear(); - - int stackCount = readVarInt(); - for (int i = 0; i < stackCount; i++) { - itemStacks.add(readItemStack()); - } - } - - public void readInventory(IInventory inventory) throws IOException { - int size = readVarInt(); - - for (int i = 0; i < size; i++) { - ItemStack stack = readItemStack(); - inventory.setInventorySlotContents(i, stack); - } - } - - public T readStreamable(Class streamableClass) throws IOException { - if (readBoolean()) { - try { - T streamable = streamableClass.newInstance(); - streamable.readData(this); - return streamable; - } catch (ReflectiveOperationException e) { - throw new InvalidObjectException("Failed to read Streamable for class " + streamableClass + " with error " + e); - } - } - return null; - } - - public void readStreamables(List outputList, Class streamableClass) throws IOException { - outputList.clear(); - int length = readVarInt(); - if (length > 0) { - for (int i = 0; i < length; i++) { - T streamable = readStreamable(streamableClass); - outputList.add(streamable); - } - } - } - - /** - * Reads a compressed int from the buffer. To do so it maximally reads 5 byte-sized chunks whose most significant - * bit dictates whether another byte should be read. - */ - public int readVarInt() throws IOException { - int varInt = 0; - int size = 0; - byte b0; - - do { - b0 = readByte(); - varInt |= (b0 & 127) << size++ * 7; - - if (size > 5) { - throw new InvalidObjectException("VarInt too big"); - } - } while ((b0 & 128) == 128); - - return varInt; - } - - public > T readEnum(T[] enumValues) throws IOException { - int ordinal; - if (enumValues.length <= 256) { - ordinal = readByte(); - } else { - ordinal = readVarInt(); - } - return enumValues[ordinal]; - } - - public NBTTagCompound readNBTTagCompound() throws IOException { - int length = readVarInt(); - - if (length < 0) { - return null; - } else { - byte[] compressed = new byte[length]; - readFully(compressed); - return CompressedStreamTools.readCompressed(new ByteArrayInputStream(compressed)); - } - } - - public FluidStack readFluidStack() throws IOException { - int fluidId = readVarInt(); - Fluid fluid = FluidRegistry.getFluid(fluidId); - if (fluid == null) { - return null; - } - - int amount = readVarInt(); - return new FluidStack(fluid, amount); - } -} +package forestry.core.network; + +import cpw.mods.fml.common.registry.GameData; +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InvalidObjectException; +import java.util.Collection; +import java.util.List; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; + +public class DataInputStreamForestry extends DataInputStream { + + public DataInputStreamForestry(InputStream in) { + super(in); + } + + public ItemStack readItemStack() throws IOException { + ItemStack itemstack = null; + String itemName = readUTF(); + + if (!itemName.isEmpty()) { + Item item = GameData.getItemRegistry().getRaw(itemName); + byte stackSize = readByte(); + int meta = readVarInt(); + itemstack = new ItemStack(item, stackSize, meta); + + if (item.isDamageable() || item.getShareTag()) { + itemstack.stackTagCompound = readNBTTagCompound(); + } + } + + return itemstack; + } + + public ItemStack[] readItemStacks() throws IOException { + int stackCount = readVarInt(); + + ItemStack[] itemStacks = new ItemStack[stackCount]; + for (int i = 0; i < stackCount; i++) { + itemStacks[i] = readItemStack(); + } + + return itemStacks; + } + + public void readItemStacks(Collection itemStacks) throws IOException { + itemStacks.clear(); + + int stackCount = readVarInt(); + for (int i = 0; i < stackCount; i++) { + itemStacks.add(readItemStack()); + } + } + + public void readInventory(IInventory inventory) throws IOException { + int size = readVarInt(); + + for (int i = 0; i < size; i++) { + ItemStack stack = readItemStack(); + inventory.setInventorySlotContents(i, stack); + } + } + + public T readStreamable(Class streamableClass) throws IOException { + if (readBoolean()) { + try { + T streamable = streamableClass.newInstance(); + streamable.readData(this); + return streamable; + } catch (ReflectiveOperationException e) { + throw new InvalidObjectException( + "Failed to read Streamable for class " + streamableClass + " with error " + e); + } + } + return null; + } + + public void readStreamables(List outputList, Class streamableClass) + throws IOException { + outputList.clear(); + int length = readVarInt(); + if (length > 0) { + for (int i = 0; i < length; i++) { + T streamable = readStreamable(streamableClass); + outputList.add(streamable); + } + } + } + + /** + * Reads a compressed int from the buffer. To do so it maximally reads 5 byte-sized chunks whose most significant + * bit dictates whether another byte should be read. + */ + public int readVarInt() throws IOException { + int varInt = 0; + int size = 0; + byte b0; + + do { + b0 = readByte(); + varInt |= (b0 & 127) << size++ * 7; + + if (size > 5) { + throw new InvalidObjectException("VarInt too big"); + } + } while ((b0 & 128) == 128); + + return varInt; + } + + public > T readEnum(T[] enumValues) throws IOException { + int ordinal; + if (enumValues.length <= 256) { + ordinal = readByte(); + } else { + ordinal = readVarInt(); + } + return enumValues[ordinal]; + } + + public NBTTagCompound readNBTTagCompound() throws IOException { + int length = readVarInt(); + + if (length < 0) { + return null; + } else { + byte[] compressed = new byte[length]; + readFully(compressed); + return CompressedStreamTools.readCompressed(new ByteArrayInputStream(compressed)); + } + } + + public FluidStack readFluidStack() throws IOException { + int fluidId = readVarInt(); + Fluid fluid = FluidRegistry.getFluid(fluidId); + if (fluid == null) { + return null; + } + + int amount = readVarInt(); + return new FluidStack(fluid, amount); + } +} diff --git a/src/main/java/forestry/core/network/DataOutputStreamForestry.java b/src/main/java/forestry/core/network/DataOutputStreamForestry.java index 9caff858d..4a237e571 100644 --- a/src/main/java/forestry/core/network/DataOutputStreamForestry.java +++ b/src/main/java/forestry/core/network/DataOutputStreamForestry.java @@ -1,123 +1,120 @@ -package forestry.core.network; - -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Collection; -import java.util.List; - -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.fluids.FluidStack; - -import cpw.mods.fml.common.registry.GameData; - -public class DataOutputStreamForestry extends DataOutputStream { - - public DataOutputStreamForestry(OutputStream out) { - super(out); - } - - public void writeItemStack(ItemStack itemstack) throws IOException { - if (itemstack == null) { - writeUTF(""); - } else { - writeUTF(GameData.getItemRegistry().getNameForObject(itemstack.getItem())); - writeByte(itemstack.stackSize); - writeVarInt(itemstack.getItemDamage()); - - if (itemstack.getItem().isDamageable() || itemstack.getItem().getShareTag()) { - writeNBTTagCompound(itemstack.stackTagCompound); - } - } - } - - public void writeItemStacks(ItemStack[] itemStacks) throws IOException { - writeVarInt(itemStacks.length); - for (ItemStack itemstack : itemStacks) { - writeItemStack(itemstack); - } - } - - public void writeItemStacks(Collection itemStacks) throws IOException { - writeVarInt(itemStacks.size()); - for (ItemStack itemstack : itemStacks) { - writeItemStack(itemstack); - } - } - - public void writeInventory(IInventory inventory) throws IOException { - int size = inventory.getSizeInventory(); - writeVarInt(size); - - for (int i = 0; i < size; i++) { - ItemStack stack = inventory.getStackInSlot(i); - writeItemStack(stack); - } - } - - public void writeStreamable(IStreamable streamable) throws IOException { - if (streamable != null) { - writeBoolean(true); - streamable.writeData(this); - } else { - writeBoolean(false); - } - } - - public void writeStreamables(List streamables) throws IOException { - if (streamables == null) { - writeVarInt(0); - } else { - writeVarInt(streamables.size()); - for (IStreamable streamable : streamables) { - writeStreamable(streamable); - } - } - } - - /** - * Writes a compressed int to the buffer. The smallest number of bytes to fit the passed int will be written. Of - * each such byte only 7 bits will be used to describe the actual value since its most significant bit dictates - * whether the next byte is part of that same int. Micro-optimization for int values that are expected to have - * values below 128. - */ - public void writeVarInt(int varInt) throws IOException { - while ((varInt & -128) != 0) { - writeByte(varInt & 127 | 128); - varInt >>>= 7; - } - - writeByte(varInt); - } - - public > void writeEnum(T enumValue, T[] enumValues) throws IOException { - if (enumValues.length <= 256) { - writeByte(enumValue.ordinal()); - } else { - writeVarInt(enumValue.ordinal()); - } - } - - public void writeNBTTagCompound(NBTTagCompound nbttagcompound) throws IOException { - if (nbttagcompound == null) { - writeVarInt(-1); - } else { - byte[] compressed = CompressedStreamTools.compress(nbttagcompound); - writeVarInt((short) compressed.length); - write(compressed); - } - } - - public void writeFluidStack(FluidStack fluidStack) throws IOException { - if (fluidStack == null) { - writeVarInt(-1); - } else { - writeVarInt(fluidStack.getFluidID()); - writeVarInt(fluidStack.amount); - } - } -} +package forestry.core.network; + +import cpw.mods.fml.common.registry.GameData; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Collection; +import java.util.List; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.FluidStack; + +public class DataOutputStreamForestry extends DataOutputStream { + + public DataOutputStreamForestry(OutputStream out) { + super(out); + } + + public void writeItemStack(ItemStack itemstack) throws IOException { + if (itemstack == null) { + writeUTF(""); + } else { + writeUTF(GameData.getItemRegistry().getNameForObject(itemstack.getItem())); + writeByte(itemstack.stackSize); + writeVarInt(itemstack.getItemDamage()); + + if (itemstack.getItem().isDamageable() || itemstack.getItem().getShareTag()) { + writeNBTTagCompound(itemstack.stackTagCompound); + } + } + } + + public void writeItemStacks(ItemStack[] itemStacks) throws IOException { + writeVarInt(itemStacks.length); + for (ItemStack itemstack : itemStacks) { + writeItemStack(itemstack); + } + } + + public void writeItemStacks(Collection itemStacks) throws IOException { + writeVarInt(itemStacks.size()); + for (ItemStack itemstack : itemStacks) { + writeItemStack(itemstack); + } + } + + public void writeInventory(IInventory inventory) throws IOException { + int size = inventory.getSizeInventory(); + writeVarInt(size); + + for (int i = 0; i < size; i++) { + ItemStack stack = inventory.getStackInSlot(i); + writeItemStack(stack); + } + } + + public void writeStreamable(IStreamable streamable) throws IOException { + if (streamable != null) { + writeBoolean(true); + streamable.writeData(this); + } else { + writeBoolean(false); + } + } + + public void writeStreamables(List streamables) throws IOException { + if (streamables == null) { + writeVarInt(0); + } else { + writeVarInt(streamables.size()); + for (IStreamable streamable : streamables) { + writeStreamable(streamable); + } + } + } + + /** + * Writes a compressed int to the buffer. The smallest number of bytes to fit the passed int will be written. Of + * each such byte only 7 bits will be used to describe the actual value since its most significant bit dictates + * whether the next byte is part of that same int. Micro-optimization for int values that are expected to have + * values below 128. + */ + public void writeVarInt(int varInt) throws IOException { + while ((varInt & -128) != 0) { + writeByte(varInt & 127 | 128); + varInt >>>= 7; + } + + writeByte(varInt); + } + + public > void writeEnum(T enumValue, T[] enumValues) throws IOException { + if (enumValues.length <= 256) { + writeByte(enumValue.ordinal()); + } else { + writeVarInt(enumValue.ordinal()); + } + } + + public void writeNBTTagCompound(NBTTagCompound nbttagcompound) throws IOException { + if (nbttagcompound == null) { + writeVarInt(-1); + } else { + byte[] compressed = CompressedStreamTools.compress(nbttagcompound); + writeVarInt((short) compressed.length); + write(compressed); + } + } + + public void writeFluidStack(FluidStack fluidStack) throws IOException { + if (fluidStack == null) { + writeVarInt(-1); + } else { + writeVarInt(fluidStack.getFluidID()); + writeVarInt(fluidStack.amount); + } + } +} diff --git a/src/main/java/forestry/core/network/ForestryPacket.java b/src/main/java/forestry/core/network/ForestryPacket.java index 339e251ea..85b2e9b70 100755 --- a/src/main/java/forestry/core/network/ForestryPacket.java +++ b/src/main/java/forestry/core/network/ForestryPacket.java @@ -10,33 +10,29 @@ ******************************************************************************/ package forestry.core.network; +import cpw.mods.fml.common.network.internal.FMLProxyPacket; +import io.netty.buffer.Unpooled; import java.io.ByteArrayOutputStream; import java.io.IOException; -import cpw.mods.fml.common.network.internal.FMLProxyPacket; - -import io.netty.buffer.Unpooled; - public abstract class ForestryPacket implements IForestryPacket { - private final IPacketId id = getPacketId(); + private final IPacketId id = getPacketId(); - public final FMLProxyPacket getPacket() { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - DataOutputStreamForestry data = new DataOutputStreamForestry(bytes); + public final FMLProxyPacket getPacket() { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStreamForestry data = new DataOutputStreamForestry(bytes); - try { - data.writeByte(id.ordinal()); - writeData(data); - } catch (IOException e) { - e.printStackTrace(); - } + try { + data.writeByte(id.ordinal()); + writeData(data); + } catch (IOException e) { + e.printStackTrace(); + } - return new FMLProxyPacket(Unpooled.wrappedBuffer(bytes.toByteArray()), PacketHandler.channelId); - } + return new FMLProxyPacket(Unpooled.wrappedBuffer(bytes.toByteArray()), PacketHandler.channelId); + } - protected void writeData(DataOutputStreamForestry data) throws IOException { - } + protected void writeData(DataOutputStreamForestry data) throws IOException {} - public void readData(DataInputStreamForestry data) throws IOException { - } + public void readData(DataInputStreamForestry data) throws IOException {} } diff --git a/src/main/java/forestry/core/network/IForestryPacket.java b/src/main/java/forestry/core/network/IForestryPacket.java index e0a77b2a3..f5377173b 100644 --- a/src/main/java/forestry/core/network/IForestryPacket.java +++ b/src/main/java/forestry/core/network/IForestryPacket.java @@ -1,23 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -import java.io.IOException; - -import cpw.mods.fml.common.network.internal.FMLProxyPacket; - -public interface IForestryPacket { - void readData(DataInputStreamForestry data) throws IOException; - - FMLProxyPacket getPacket(); - - IPacketId getPacketId(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network; + +import cpw.mods.fml.common.network.internal.FMLProxyPacket; +import java.io.IOException; + +public interface IForestryPacket { + void readData(DataInputStreamForestry data) throws IOException; + + FMLProxyPacket getPacket(); + + IPacketId getPacketId(); +} diff --git a/src/main/java/forestry/core/network/IForestryPacketClient.java b/src/main/java/forestry/core/network/IForestryPacketClient.java index 17a100617..45c20687e 100644 --- a/src/main/java/forestry/core/network/IForestryPacketClient.java +++ b/src/main/java/forestry/core/network/IForestryPacketClient.java @@ -1,22 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; - -public interface IForestryPacketClient extends IForestryPacket { - void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException; - - @Override - PacketIdClient getPacketId(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network; + +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; + +public interface IForestryPacketClient extends IForestryPacket { + void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException; + + @Override + PacketIdClient getPacketId(); +} diff --git a/src/main/java/forestry/core/network/IForestryPacketServer.java b/src/main/java/forestry/core/network/IForestryPacketServer.java index 2c36c6a2f..eb81fadbb 100644 --- a/src/main/java/forestry/core/network/IForestryPacketServer.java +++ b/src/main/java/forestry/core/network/IForestryPacketServer.java @@ -1,22 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayerMP; - -public interface IForestryPacketServer extends IForestryPacket { - void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException; - - @Override - PacketIdServer getPacketId(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network; + +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayerMP; + +public interface IForestryPacketServer extends IForestryPacket { + void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException; + + @Override + PacketIdServer getPacketId(); +} diff --git a/src/main/java/forestry/core/network/ILocatedPacket.java b/src/main/java/forestry/core/network/ILocatedPacket.java index 47400a405..ad8bc6aec 100755 --- a/src/main/java/forestry/core/network/ILocatedPacket.java +++ b/src/main/java/forestry/core/network/ILocatedPacket.java @@ -11,9 +11,9 @@ package forestry.core.network; public interface ILocatedPacket { - int getPosX(); + int getPosX(); - int getPosY(); + int getPosY(); - int getPosZ(); + int getPosZ(); } diff --git a/src/main/java/forestry/core/network/IPacketId.java b/src/main/java/forestry/core/network/IPacketId.java index d31d37cd7..0582c64cb 100644 --- a/src/main/java/forestry/core/network/IPacketId.java +++ b/src/main/java/forestry/core/network/IPacketId.java @@ -1,15 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -public interface IPacketId { - int ordinal(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network; + +public interface IPacketId { + int ordinal(); +} diff --git a/src/main/java/forestry/core/network/IPacketRegistry.java b/src/main/java/forestry/core/network/IPacketRegistry.java index ba9673329..4aceea840 100644 --- a/src/main/java/forestry/core/network/IPacketRegistry.java +++ b/src/main/java/forestry/core/network/IPacketRegistry.java @@ -1,15 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -public interface IPacketRegistry { - void registerPackets(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network; + +public interface IPacketRegistry { + void registerPackets(); +} diff --git a/src/main/java/forestry/core/network/IStreamable.java b/src/main/java/forestry/core/network/IStreamable.java index 7c7127e63..cac088037 100644 --- a/src/main/java/forestry/core/network/IStreamable.java +++ b/src/main/java/forestry/core/network/IStreamable.java @@ -1,19 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -import java.io.IOException; - -public interface IStreamable { - void writeData(DataOutputStreamForestry data) throws IOException; - - void readData(DataInputStreamForestry data) throws IOException; -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network; + +import java.io.IOException; + +public interface IStreamable { + void writeData(DataOutputStreamForestry data) throws IOException; + + void readData(DataInputStreamForestry data) throws IOException; +} diff --git a/src/main/java/forestry/core/network/IStreamableGui.java b/src/main/java/forestry/core/network/IStreamableGui.java index d71587008..3c7313f03 100644 --- a/src/main/java/forestry/core/network/IStreamableGui.java +++ b/src/main/java/forestry/core/network/IStreamableGui.java @@ -1,19 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -import java.io.IOException; - -public interface IStreamableGui { - void writeGuiData(DataOutputStreamForestry data) throws IOException; - - void readGuiData(DataInputStreamForestry data) throws IOException; -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network; + +import java.io.IOException; + +public interface IStreamableGui { + void writeGuiData(DataOutputStreamForestry data) throws IOException; + + void readGuiData(DataInputStreamForestry data) throws IOException; +} diff --git a/src/main/java/forestry/core/network/PacketHandler.java b/src/main/java/forestry/core/network/PacketHandler.java index a31fdb6b3..2cc270aa7 100644 --- a/src/main/java/forestry/core/network/PacketHandler.java +++ b/src/main/java/forestry/core/network/PacketHandler.java @@ -10,71 +10,66 @@ ******************************************************************************/ package forestry.core.network; -import java.io.InputStream; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.NetHandlerPlayServer; - import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.network.FMLEventChannel; import cpw.mods.fml.common.network.FMLNetworkEvent.ClientCustomPacketEvent; import cpw.mods.fml.common.network.FMLNetworkEvent.ServerCustomPacketEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.network.internal.FMLProxyPacket; - import forestry.core.proxy.Proxies; - import io.netty.buffer.ByteBufInputStream; +import java.io.InputStream; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.network.NetHandlerPlayServer; public class PacketHandler { - public static final String channelId = "FOR"; - private final FMLEventChannel channel; + public static final String channelId = "FOR"; + private final FMLEventChannel channel; - public PacketHandler() { - channel = NetworkRegistry.INSTANCE.newEventDrivenChannel(channelId); - channel.register(this); - } + public PacketHandler() { + channel = NetworkRegistry.INSTANCE.newEventDrivenChannel(channelId); + channel.register(this); + } - @SubscribeEvent - public void onPacket(ServerCustomPacketEvent event) { - DataInputStreamForestry data = getStream(event.packet); - EntityPlayerMP player = ((NetHandlerPlayServer) event.handler).playerEntity; + @SubscribeEvent + public void onPacket(ServerCustomPacketEvent event) { + DataInputStreamForestry data = getStream(event.packet); + EntityPlayerMP player = ((NetHandlerPlayServer) event.handler).playerEntity; - try { - byte packetIdOrdinal = data.readByte(); - PacketIdServer packetId = PacketIdServer.VALUES[packetIdOrdinal]; - IForestryPacketServer packetHandler = packetId.getPacketHandler(); - packetHandler.readData(data); - packetHandler.onPacketData(data, player); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + try { + byte packetIdOrdinal = data.readByte(); + PacketIdServer packetId = PacketIdServer.VALUES[packetIdOrdinal]; + IForestryPacketServer packetHandler = packetId.getPacketHandler(); + packetHandler.readData(data); + packetHandler.onPacketData(data, player); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - @SubscribeEvent - public void onPacket(ClientCustomPacketEvent event) { - DataInputStreamForestry data = getStream(event.packet); - EntityPlayer player = Proxies.common.getPlayer(); + @SubscribeEvent + public void onPacket(ClientCustomPacketEvent event) { + DataInputStreamForestry data = getStream(event.packet); + EntityPlayer player = Proxies.common.getPlayer(); - try { - byte packetIdOrdinal = data.readByte(); - PacketIdClient packetId = PacketIdClient.VALUES[packetIdOrdinal]; - IForestryPacketClient packetHandler = packetId.getPacketHandler(); - packetHandler.readData(data); - packetHandler.onPacketData(data, player); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + try { + byte packetIdOrdinal = data.readByte(); + PacketIdClient packetId = PacketIdClient.VALUES[packetIdOrdinal]; + IForestryPacketClient packetHandler = packetId.getPacketHandler(); + packetHandler.readData(data); + packetHandler.onPacketData(data, player); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - private static DataInputStreamForestry getStream(FMLProxyPacket fmlPacket) { - InputStream is = new ByteBufInputStream(fmlPacket.payload()); - return new DataInputStreamForestry(is); - } - - public void sendPacket(FMLProxyPacket packet, EntityPlayerMP player) { - channel.sendTo(packet, player); - } + private static DataInputStreamForestry getStream(FMLProxyPacket fmlPacket) { + InputStream is = new ByteBufInputStream(fmlPacket.payload()); + return new DataInputStreamForestry(is); + } + public void sendPacket(FMLProxyPacket packet, EntityPlayerMP player) { + channel.sendTo(packet, player); + } } diff --git a/src/main/java/forestry/core/network/PacketIdClient.java b/src/main/java/forestry/core/network/PacketIdClient.java index c60c97ef6..327193eaa 100644 --- a/src/main/java/forestry/core/network/PacketIdClient.java +++ b/src/main/java/forestry/core/network/PacketIdClient.java @@ -1,77 +1,76 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -import javax.annotation.Nonnull; - -import forestry.core.network.packets.PacketDummyClient; - -public enum PacketIdClient implements IPacketId { - INVALID, - - // Core Gui - ERROR_UPDATE, - ERROR_UPDATE_ENTITY, - GUI_UPDATE, - GUI_UPDATE_ENTITY, - GUI_LAYOUT_SELECT, - GUI_ENERGY, - SOCKET_UPDATE, - ACCESS_UPDATE, - ACCESS_UPDATE_ENTITY, - - // Core Tile Entities - TILE_FORESTRY_UPDATE, - ITEMSTACK_DISPLAY, - FX_SIGNAL, - TANK_LEVEL_UPDATE, - - // Core Genome - GENOME_TRACKER_UPDATE, - - // Factory - WORKTABLE_MEMORY_UPDATE, - WORKTABLE_CRAFTING_UPDATE, - - // Apiculture - TILE_FORESTRY_ACTIVE, - BEE_LOGIC_ACTIVE, - BEE_LOGIC_ACTIVE_ENTITY, - HABITAT_BIOME_POINTER, - CANDLE_UPDATE, - IMPRINT_SELECTION_RESPONSE, - - // Arboriculture - RIPENING_UPDATE, - - // Mail - TRADING_ADDRESS_RESPONSE, - LETTER_INFO_RESPONSE, - POBOX_INFO_RESPONSE; - - public static final PacketIdClient[] VALUES = values(); - - @Nonnull - private IForestryPacketClient packetHandler; - - PacketIdClient() { - this.packetHandler = PacketDummyClient.instance; - } - - public void setPacketHandler(@Nonnull IForestryPacketClient packetHandler) { - this.packetHandler = packetHandler; - } - - @Nonnull - public IForestryPacketClient getPacketHandler() { - return packetHandler; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network; + +import forestry.core.network.packets.PacketDummyClient; +import javax.annotation.Nonnull; + +public enum PacketIdClient implements IPacketId { + INVALID, + + // Core Gui + ERROR_UPDATE, + ERROR_UPDATE_ENTITY, + GUI_UPDATE, + GUI_UPDATE_ENTITY, + GUI_LAYOUT_SELECT, + GUI_ENERGY, + SOCKET_UPDATE, + ACCESS_UPDATE, + ACCESS_UPDATE_ENTITY, + + // Core Tile Entities + TILE_FORESTRY_UPDATE, + ITEMSTACK_DISPLAY, + FX_SIGNAL, + TANK_LEVEL_UPDATE, + + // Core Genome + GENOME_TRACKER_UPDATE, + + // Factory + WORKTABLE_MEMORY_UPDATE, + WORKTABLE_CRAFTING_UPDATE, + + // Apiculture + TILE_FORESTRY_ACTIVE, + BEE_LOGIC_ACTIVE, + BEE_LOGIC_ACTIVE_ENTITY, + HABITAT_BIOME_POINTER, + CANDLE_UPDATE, + IMPRINT_SELECTION_RESPONSE, + + // Arboriculture + RIPENING_UPDATE, + + // Mail + TRADING_ADDRESS_RESPONSE, + LETTER_INFO_RESPONSE, + POBOX_INFO_RESPONSE; + + public static final PacketIdClient[] VALUES = values(); + + @Nonnull + private IForestryPacketClient packetHandler; + + PacketIdClient() { + this.packetHandler = PacketDummyClient.instance; + } + + public void setPacketHandler(@Nonnull IForestryPacketClient packetHandler) { + this.packetHandler = packetHandler; + } + + @Nonnull + public IForestryPacketClient getPacketHandler() { + return packetHandler; + } +} diff --git a/src/main/java/forestry/core/network/PacketIdServer.java b/src/main/java/forestry/core/network/PacketIdServer.java index b970106ae..acfeb4f0e 100644 --- a/src/main/java/forestry/core/network/PacketIdServer.java +++ b/src/main/java/forestry/core/network/PacketIdServer.java @@ -1,57 +1,56 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -import javax.annotation.Nonnull; - -import forestry.core.network.packets.PacketDummyServer; - -public enum PacketIdServer implements IPacketId { - INVALID, - - // Core Gui - GUI_SELECTION_REQUEST, - PIPETTE_CLICK, - ACCESS_SWITCH, - ACCESS_SWITCH_ENTITY, - CHIPSET_CLICK, - SOLDERING_IRON_CLICK, - - // Apiculture - BEE_LOGIC_ACTIVE_ENTITY_REQUEST, - - // Factory - WORKTABLE_NEI_SELECT, - - // Mail - LETTER_INFO_REQUEST, - TRADING_ADDRESS_REQUEST, - POBOX_INFO_REQUEST, - LETTER_TEXT_SET; - - public static final PacketIdServer[] VALUES = values(); - - @Nonnull - private IForestryPacketServer packetHandler; - - PacketIdServer() { - this.packetHandler = PacketDummyServer.instance; - } - - public void setPacketHandler(@Nonnull IForestryPacketServer packetHandler) { - this.packetHandler = packetHandler; - } - - @Nonnull - public IForestryPacketServer getPacketHandler() { - return packetHandler; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network; + +import forestry.core.network.packets.PacketDummyServer; +import javax.annotation.Nonnull; + +public enum PacketIdServer implements IPacketId { + INVALID, + + // Core Gui + GUI_SELECTION_REQUEST, + PIPETTE_CLICK, + ACCESS_SWITCH, + ACCESS_SWITCH_ENTITY, + CHIPSET_CLICK, + SOLDERING_IRON_CLICK, + + // Apiculture + BEE_LOGIC_ACTIVE_ENTITY_REQUEST, + + // Factory + WORKTABLE_NEI_SELECT, + + // Mail + LETTER_INFO_REQUEST, + TRADING_ADDRESS_REQUEST, + POBOX_INFO_REQUEST, + LETTER_TEXT_SET; + + public static final PacketIdServer[] VALUES = values(); + + @Nonnull + private IForestryPacketServer packetHandler; + + PacketIdServer() { + this.packetHandler = PacketDummyServer.instance; + } + + public void setPacketHandler(@Nonnull IForestryPacketServer packetHandler) { + this.packetHandler = packetHandler; + } + + @Nonnull + public IForestryPacketServer getPacketHandler() { + return packetHandler; + } +} diff --git a/src/main/java/forestry/core/network/PacketRegistry.java b/src/main/java/forestry/core/network/PacketRegistry.java index 4a2c72e74..b87f90713 100644 --- a/src/main/java/forestry/core/network/PacketRegistry.java +++ b/src/main/java/forestry/core/network/PacketRegistry.java @@ -1,21 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -public abstract class PacketRegistry implements IPacketRegistry { - protected static void registerClientPacket(IForestryPacketClient packet) { - packet.getPacketId().setPacketHandler(packet); - } - - protected static void registerServerPacket(IForestryPacketServer packet) { - packet.getPacketId().setPacketHandler(packet); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network; + +public abstract class PacketRegistry implements IPacketRegistry { + protected static void registerClientPacket(IForestryPacketClient packet) { + packet.getPacketId().setPacketHandler(packet); + } + + protected static void registerServerPacket(IForestryPacketServer packet) { + packet.getPacketId().setPacketHandler(packet); + } +} diff --git a/src/main/java/forestry/core/network/PacketRegistryCore.java b/src/main/java/forestry/core/network/PacketRegistryCore.java index 3e0da76b1..848e105af 100644 --- a/src/main/java/forestry/core/network/PacketRegistryCore.java +++ b/src/main/java/forestry/core/network/PacketRegistryCore.java @@ -1,59 +1,59 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -import forestry.core.network.packets.PacketAccessSwitch; -import forestry.core.network.packets.PacketAccessSwitchEntity; -import forestry.core.network.packets.PacketAccessUpdate; -import forestry.core.network.packets.PacketAccessUpdateEntity; -import forestry.core.network.packets.PacketChipsetClick; -import forestry.core.network.packets.PacketErrorUpdate; -import forestry.core.network.packets.PacketErrorUpdateEntity; -import forestry.core.network.packets.PacketFXSignal; -import forestry.core.network.packets.PacketGenomeTrackerSync; -import forestry.core.network.packets.PacketGuiEnergy; -import forestry.core.network.packets.PacketGuiLayoutSelect; -import forestry.core.network.packets.PacketGuiSelectRequest; -import forestry.core.network.packets.PacketGuiUpdate; -import forestry.core.network.packets.PacketGuiUpdateEntity; -import forestry.core.network.packets.PacketItemStackDisplay; -import forestry.core.network.packets.PacketPipetteClick; -import forestry.core.network.packets.PacketSocketUpdate; -import forestry.core.network.packets.PacketSolderingIronClick; -import forestry.core.network.packets.PacketTankLevelUpdate; -import forestry.core.network.packets.PacketTileStream; - -public class PacketRegistryCore extends PacketRegistry { - @Override - public void registerPackets() { - registerClientPacket(new PacketErrorUpdate()); - registerClientPacket(new PacketErrorUpdateEntity()); - registerClientPacket(new PacketGuiUpdate()); - registerClientPacket(new PacketGuiUpdateEntity()); - registerClientPacket(new PacketGuiLayoutSelect()); - registerClientPacket(new PacketGuiEnergy()); - registerClientPacket(new PacketSocketUpdate()); - registerClientPacket(new PacketAccessUpdate()); - registerClientPacket(new PacketAccessUpdateEntity()); - registerClientPacket(new PacketTileStream()); - registerClientPacket(new PacketItemStackDisplay()); - registerClientPacket(new PacketFXSignal()); - registerClientPacket(new PacketTankLevelUpdate()); - registerClientPacket(new PacketGenomeTrackerSync()); - - registerServerPacket(new PacketGuiSelectRequest()); - registerServerPacket(new PacketPipetteClick()); - registerServerPacket(new PacketAccessSwitch()); - registerServerPacket(new PacketAccessSwitchEntity()); - registerServerPacket(new PacketChipsetClick()); - registerServerPacket(new PacketSolderingIronClick()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network; + +import forestry.core.network.packets.PacketAccessSwitch; +import forestry.core.network.packets.PacketAccessSwitchEntity; +import forestry.core.network.packets.PacketAccessUpdate; +import forestry.core.network.packets.PacketAccessUpdateEntity; +import forestry.core.network.packets.PacketChipsetClick; +import forestry.core.network.packets.PacketErrorUpdate; +import forestry.core.network.packets.PacketErrorUpdateEntity; +import forestry.core.network.packets.PacketFXSignal; +import forestry.core.network.packets.PacketGenomeTrackerSync; +import forestry.core.network.packets.PacketGuiEnergy; +import forestry.core.network.packets.PacketGuiLayoutSelect; +import forestry.core.network.packets.PacketGuiSelectRequest; +import forestry.core.network.packets.PacketGuiUpdate; +import forestry.core.network.packets.PacketGuiUpdateEntity; +import forestry.core.network.packets.PacketItemStackDisplay; +import forestry.core.network.packets.PacketPipetteClick; +import forestry.core.network.packets.PacketSocketUpdate; +import forestry.core.network.packets.PacketSolderingIronClick; +import forestry.core.network.packets.PacketTankLevelUpdate; +import forestry.core.network.packets.PacketTileStream; + +public class PacketRegistryCore extends PacketRegistry { + @Override + public void registerPackets() { + registerClientPacket(new PacketErrorUpdate()); + registerClientPacket(new PacketErrorUpdateEntity()); + registerClientPacket(new PacketGuiUpdate()); + registerClientPacket(new PacketGuiUpdateEntity()); + registerClientPacket(new PacketGuiLayoutSelect()); + registerClientPacket(new PacketGuiEnergy()); + registerClientPacket(new PacketSocketUpdate()); + registerClientPacket(new PacketAccessUpdate()); + registerClientPacket(new PacketAccessUpdateEntity()); + registerClientPacket(new PacketTileStream()); + registerClientPacket(new PacketItemStackDisplay()); + registerClientPacket(new PacketFXSignal()); + registerClientPacket(new PacketTankLevelUpdate()); + registerClientPacket(new PacketGenomeTrackerSync()); + + registerServerPacket(new PacketGuiSelectRequest()); + registerServerPacket(new PacketPipetteClick()); + registerServerPacket(new PacketAccessSwitch()); + registerServerPacket(new PacketAccessSwitchEntity()); + registerServerPacket(new PacketChipsetClick()); + registerServerPacket(new PacketSolderingIronClick()); + } +} diff --git a/src/main/java/forestry/core/network/PacketRegistryDummy.java b/src/main/java/forestry/core/network/PacketRegistryDummy.java index 3aadef49a..764b7b6b9 100644 --- a/src/main/java/forestry/core/network/PacketRegistryDummy.java +++ b/src/main/java/forestry/core/network/PacketRegistryDummy.java @@ -1,24 +1,20 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -public class PacketRegistryDummy implements IPacketRegistry { - public static final PacketRegistryDummy instance = new PacketRegistryDummy(); - - private PacketRegistryDummy() { - - } - - @Override - public void registerPackets() { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network; + +public class PacketRegistryDummy implements IPacketRegistry { + public static final PacketRegistryDummy instance = new PacketRegistryDummy(); + + private PacketRegistryDummy() {} + + @Override + public void registerPackets() {} +} diff --git a/src/main/java/forestry/core/network/packets/PacketAccessSwitch.java b/src/main/java/forestry/core/network/packets/PacketAccessSwitch.java index 2baac01c6..eb04bb83f 100644 --- a/src/main/java/forestry/core/network/packets/PacketAccessSwitch.java +++ b/src/main/java/forestry/core/network/packets/PacketAccessSwitch.java @@ -1,47 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.access.IRestrictedAccess; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; -import forestry.core.tiles.ILocatable; - -public class PacketAccessSwitch extends PacketCoordinates implements IForestryPacketServer { - - public PacketAccessSwitch() { - } - - public PacketAccessSwitch(ILocatable tile) { - super(tile.getCoordinates()); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - TileEntity tile = getTarget(player.worldObj); - - if (tile instanceof IRestrictedAccess) { - IRestrictedAccess restrictedAccessTile = (IRestrictedAccess) tile; - restrictedAccessTile.getAccessHandler().switchAccess(player); - } - } - - @Override - public PacketIdServer getPacketId() { - return PacketIdServer.ACCESS_SWITCH; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.access.IRestrictedAccess; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketIdServer; +import forestry.core.tiles.ILocatable; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.tileentity.TileEntity; + +public class PacketAccessSwitch extends PacketCoordinates implements IForestryPacketServer { + + public PacketAccessSwitch() {} + + public PacketAccessSwitch(ILocatable tile) { + super(tile.getCoordinates()); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { + TileEntity tile = getTarget(player.worldObj); + + if (tile instanceof IRestrictedAccess) { + IRestrictedAccess restrictedAccessTile = (IRestrictedAccess) tile; + restrictedAccessTile.getAccessHandler().switchAccess(player); + } + } + + @Override + public PacketIdServer getPacketId() { + return PacketIdServer.ACCESS_SWITCH; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketAccessSwitchEntity.java b/src/main/java/forestry/core/network/packets/PacketAccessSwitchEntity.java index 3e04e5906..a1ca6fd98 100644 --- a/src/main/java/forestry/core/network/packets/PacketAccessSwitchEntity.java +++ b/src/main/java/forestry/core/network/packets/PacketAccessSwitchEntity.java @@ -1,45 +1,42 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayerMP; - -import forestry.core.access.IRestrictedAccess; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; - -public class PacketAccessSwitchEntity extends PacketEntityUpdate implements IForestryPacketServer { - - public PacketAccessSwitchEntity() { - } - - public PacketAccessSwitchEntity(Entity entity) { - super(entity); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - Entity target = getTarget(player.worldObj); - if (target instanceof IRestrictedAccess) { - IRestrictedAccess restrictedAccessTile = (IRestrictedAccess) target; - restrictedAccessTile.getAccessHandler().switchAccess(player); - } - } - - @Override - public PacketIdServer getPacketId() { - return PacketIdServer.ACCESS_SWITCH_ENTITY; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.access.IRestrictedAccess; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketIdServer; +import java.io.IOException; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayerMP; + +public class PacketAccessSwitchEntity extends PacketEntityUpdate implements IForestryPacketServer { + + public PacketAccessSwitchEntity() {} + + public PacketAccessSwitchEntity(Entity entity) { + super(entity); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { + Entity target = getTarget(player.worldObj); + if (target instanceof IRestrictedAccess) { + IRestrictedAccess restrictedAccessTile = (IRestrictedAccess) target; + restrictedAccessTile.getAccessHandler().switchAccess(player); + } + } + + @Override + public PacketIdServer getPacketId() { + return PacketIdServer.ACCESS_SWITCH_ENTITY; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketAccessUpdate.java b/src/main/java/forestry/core/network/packets/PacketAccessUpdate.java index 49872c493..330d91f05 100644 --- a/src/main/java/forestry/core/network/packets/PacketAccessUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketAccessUpdate.java @@ -1,56 +1,53 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.access.IAccessHandler; -import forestry.core.access.IRestrictedAccess; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; - -public class PacketAccessUpdate extends PacketCoordinates implements IForestryPacketClient { - private IAccessHandler accessHandler; - - public PacketAccessUpdate() { - } - - public PacketAccessUpdate(IRestrictedAccess restrictedAccess, TileEntity tile) { - super(tile); - accessHandler = restrictedAccess.getAccessHandler(); - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - accessHandler.writeData(data); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(player.worldObj); - - if (tile instanceof IRestrictedAccess) { - IRestrictedAccess restrictedAccessTile = (IRestrictedAccess) tile; - restrictedAccessTile.getAccessHandler().readData(data); - } - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.ACCESS_UPDATE; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.access.IAccessHandler; +import forestry.core.access.IRestrictedAccess; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; + +public class PacketAccessUpdate extends PacketCoordinates implements IForestryPacketClient { + private IAccessHandler accessHandler; + + public PacketAccessUpdate() {} + + public PacketAccessUpdate(IRestrictedAccess restrictedAccess, TileEntity tile) { + super(tile); + accessHandler = restrictedAccess.getAccessHandler(); + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + accessHandler.writeData(data); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + TileEntity tile = getTarget(player.worldObj); + + if (tile instanceof IRestrictedAccess) { + IRestrictedAccess restrictedAccessTile = (IRestrictedAccess) tile; + restrictedAccessTile.getAccessHandler().readData(data); + } + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.ACCESS_UPDATE; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketAccessUpdateEntity.java b/src/main/java/forestry/core/network/packets/PacketAccessUpdateEntity.java index 4b458e0f3..dae6ea9f1 100644 --- a/src/main/java/forestry/core/network/packets/PacketAccessUpdateEntity.java +++ b/src/main/java/forestry/core/network/packets/PacketAccessUpdateEntity.java @@ -1,56 +1,53 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; - -import forestry.core.access.IAccessHandler; -import forestry.core.access.IRestrictedAccess; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; - -public class PacketAccessUpdateEntity extends PacketEntityUpdate implements IForestryPacketClient { - private IAccessHandler accessHandler; - - public PacketAccessUpdateEntity() { - } - - public PacketAccessUpdateEntity(IRestrictedAccess restrictedAccess, Entity entity) { - super(entity); - accessHandler = restrictedAccess.getAccessHandler(); - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - accessHandler.writeData(data); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Entity tile = getTarget(player.worldObj); - - if (tile instanceof IRestrictedAccess) { - IRestrictedAccess restrictedAccessTile = (IRestrictedAccess) tile; - restrictedAccessTile.getAccessHandler().readData(data); - } - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.ACCESS_UPDATE_ENTITY; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.access.IAccessHandler; +import forestry.core.access.IRestrictedAccess; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import java.io.IOException; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; + +public class PacketAccessUpdateEntity extends PacketEntityUpdate implements IForestryPacketClient { + private IAccessHandler accessHandler; + + public PacketAccessUpdateEntity() {} + + public PacketAccessUpdateEntity(IRestrictedAccess restrictedAccess, Entity entity) { + super(entity); + accessHandler = restrictedAccess.getAccessHandler(); + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + accessHandler.writeData(data); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + Entity tile = getTarget(player.worldObj); + + if (tile instanceof IRestrictedAccess) { + IRestrictedAccess restrictedAccessTile = (IRestrictedAccess) tile; + restrictedAccessTile.getAccessHandler().readData(data); + } + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.ACCESS_UPDATE_ENTITY; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketChipsetClick.java b/src/main/java/forestry/core/network/packets/PacketChipsetClick.java index 449d16082..c44de6864 100644 --- a/src/main/java/forestry/core/network/packets/PacketChipsetClick.java +++ b/src/main/java/forestry/core/network/packets/PacketChipsetClick.java @@ -1,51 +1,48 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.circuits.ItemCircuitBoard; -import forestry.core.gui.IContainerSocketed; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; - -public class PacketChipsetClick extends PacketSlotClick implements IForestryPacketServer { - - public PacketChipsetClick() { - } - - public PacketChipsetClick(TileEntity tile, int slot) { - super(tile, slot); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - if (!(player.openContainer instanceof IContainerSocketed)) { - return; - } - ItemStack itemstack = player.inventory.getItemStack(); - if (!(itemstack.getItem() instanceof ItemCircuitBoard)) { - return; - } - - ((IContainerSocketed) player.openContainer).handleChipsetClickServer(getSlot(), player, itemstack); - } - - @Override - public PacketIdServer getPacketId() { - return PacketIdServer.CHIPSET_CLICK; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.circuits.ItemCircuitBoard; +import forestry.core.gui.IContainerSocketed; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketIdServer; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; + +public class PacketChipsetClick extends PacketSlotClick implements IForestryPacketServer { + + public PacketChipsetClick() {} + + public PacketChipsetClick(TileEntity tile, int slot) { + super(tile, slot); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { + if (!(player.openContainer instanceof IContainerSocketed)) { + return; + } + ItemStack itemstack = player.inventory.getItemStack(); + if (!(itemstack.getItem() instanceof ItemCircuitBoard)) { + return; + } + + ((IContainerSocketed) player.openContainer).handleChipsetClickServer(getSlot(), player, itemstack); + } + + @Override + public PacketIdServer getPacketId() { + return PacketIdServer.CHIPSET_CLICK; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketCoordinates.java b/src/main/java/forestry/core/network/packets/PacketCoordinates.java index 3178628d5..3d0b3174e 100644 --- a/src/main/java/forestry/core/network/packets/PacketCoordinates.java +++ b/src/main/java/forestry/core/network/packets/PacketCoordinates.java @@ -10,74 +10,71 @@ ******************************************************************************/ package forestry.core.network.packets; -import java.io.IOException; - -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; - import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.ForestryPacket; import forestry.core.network.ILocatedPacket; +import java.io.IOException; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; public abstract class PacketCoordinates extends ForestryPacket implements ILocatedPacket { - private int posX; - private int posY; - private int posZ; + private int posX; + private int posY; + private int posZ; - public PacketCoordinates() { - } + public PacketCoordinates() {} - protected PacketCoordinates(TileEntity tileEntity) { - this(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); - } + protected PacketCoordinates(TileEntity tileEntity) { + this(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); + } - protected PacketCoordinates(ChunkCoordinates coordinates) { - this(coordinates.posX, coordinates.posY, coordinates.posZ); - } + protected PacketCoordinates(ChunkCoordinates coordinates) { + this(coordinates.posX, coordinates.posY, coordinates.posZ); + } - protected PacketCoordinates(int posX, int posY, int posZ) { - this.posX = posX; - this.posY = posY; - this.posZ = posZ; - } + protected PacketCoordinates(int posX, int posY, int posZ) { + this.posX = posX; + this.posY = posY; + this.posZ = posZ; + } - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - data.writeVarInt(posX); - data.writeVarInt(posY); - data.writeVarInt(posZ); - } + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + data.writeVarInt(posX); + data.writeVarInt(posY); + data.writeVarInt(posZ); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - posX = data.readVarInt(); - posY = data.readVarInt(); - posZ = data.readVarInt(); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + posX = data.readVarInt(); + posY = data.readVarInt(); + posZ = data.readVarInt(); + } - protected final ChunkCoordinates getCoordinates() { - return new ChunkCoordinates(posX, posY, posZ); - } + protected final ChunkCoordinates getCoordinates() { + return new ChunkCoordinates(posX, posY, posZ); + } - @Override - public final int getPosX() { - return posX; - } + @Override + public final int getPosX() { + return posX; + } - @Override - public final int getPosY() { - return posY; - } + @Override + public final int getPosY() { + return posY; + } - @Override - public final int getPosZ() { - return posZ; - } + @Override + public final int getPosZ() { + return posZ; + } - public final TileEntity getTarget(World world) { - return world.getTileEntity(posX, posY, posZ); - } + public final TileEntity getTarget(World world) { + return world.getTileEntity(posX, posY, posZ); + } } diff --git a/src/main/java/forestry/core/network/packets/PacketDummy.java b/src/main/java/forestry/core/network/packets/PacketDummy.java index 11af7fee1..ffe5e15dc 100644 --- a/src/main/java/forestry/core/network/packets/PacketDummy.java +++ b/src/main/java/forestry/core/network/packets/PacketDummy.java @@ -1,35 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import cpw.mods.fml.common.network.internal.FMLProxyPacket; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacket; - -public abstract class PacketDummy implements IForestryPacket { - protected PacketDummy() { - - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - - } - - @Override - public FMLProxyPacket getPacket() { - return null; - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import cpw.mods.fml.common.network.internal.FMLProxyPacket; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacket; +import java.io.IOException; + +public abstract class PacketDummy implements IForestryPacket { + protected PacketDummy() {} + + @Override + public void readData(DataInputStreamForestry data) throws IOException {} + + @Override + public FMLProxyPacket getPacket() { + return null; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketDummyClient.java b/src/main/java/forestry/core/network/packets/PacketDummyClient.java index 42ba5ef85..64790ba0a 100644 --- a/src/main/java/forestry/core/network/packets/PacketDummyClient.java +++ b/src/main/java/forestry/core/network/packets/PacketDummyClient.java @@ -1,37 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; - -public class PacketDummyClient extends PacketDummy implements IForestryPacketClient { - public static final PacketDummyClient instance = new PacketDummyClient(); - - private PacketDummyClient() { - - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.INVALID; - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; + +public class PacketDummyClient extends PacketDummy implements IForestryPacketClient { + public static final PacketDummyClient instance = new PacketDummyClient(); + + private PacketDummyClient() {} + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.INVALID; + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException {} +} diff --git a/src/main/java/forestry/core/network/packets/PacketDummyServer.java b/src/main/java/forestry/core/network/packets/PacketDummyServer.java index 4c4c86ed9..0952e88dd 100644 --- a/src/main/java/forestry/core/network/packets/PacketDummyServer.java +++ b/src/main/java/forestry/core/network/packets/PacketDummyServer.java @@ -1,37 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayerMP; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; - -public class PacketDummyServer extends PacketDummy implements IForestryPacketServer { - public static final PacketDummyServer instance = new PacketDummyServer(); - - private PacketDummyServer() { - - } - - @Override - public PacketIdServer getPacketId() { - return PacketIdServer.INVALID; - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketIdServer; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayerMP; + +public class PacketDummyServer extends PacketDummy implements IForestryPacketServer { + public static final PacketDummyServer instance = new PacketDummyServer(); + + private PacketDummyServer() {} + + @Override + public PacketIdServer getPacketId() { + return PacketIdServer.INVALID; + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException {} +} diff --git a/src/main/java/forestry/core/network/packets/PacketEntityUpdate.java b/src/main/java/forestry/core/network/packets/PacketEntityUpdate.java index 0f3e11c25..b6566f496 100644 --- a/src/main/java/forestry/core/network/packets/PacketEntityUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketEntityUpdate.java @@ -1,66 +1,63 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.Entity; -import net.minecraft.world.World; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.ForestryPacket; -import forestry.core.network.ILocatedPacket; - -public abstract class PacketEntityUpdate extends ForestryPacket implements ILocatedPacket { - // sending - private Entity entity; - // receiving - private int entityId; - - public PacketEntityUpdate() { - } - - public PacketEntityUpdate(Entity entity) { - this.entity = entity; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeVarInt(entity.getEntityId()); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - entityId = data.readVarInt(); - } - - public Entity getTarget(World world) { - return world.getEntityByID(entityId); - } - - @Override - public int getPosX() { - return (int) entity.posX; - } - - @Override - public int getPosY() { - return (int) entity.posY; - } - - @Override - public int getPosZ() { - return (int) entity.posZ; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; +import forestry.core.network.ILocatedPacket; +import java.io.IOException; +import net.minecraft.entity.Entity; +import net.minecraft.world.World; + +public abstract class PacketEntityUpdate extends ForestryPacket implements ILocatedPacket { + // sending + private Entity entity; + // receiving + private int entityId; + + public PacketEntityUpdate() {} + + public PacketEntityUpdate(Entity entity) { + this.entity = entity; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeVarInt(entity.getEntityId()); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + entityId = data.readVarInt(); + } + + public Entity getTarget(World world) { + return world.getEntityByID(entityId); + } + + @Override + public int getPosX() { + return (int) entity.posX; + } + + @Override + public int getPosY() { + return (int) entity.posY; + } + + @Override + public int getPosZ() { + return (int) entity.posZ; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketErrorUpdate.java b/src/main/java/forestry/core/network/packets/PacketErrorUpdate.java index cac3a74d3..f60501065 100644 --- a/src/main/java/forestry/core/network/packets/PacketErrorUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketErrorUpdate.java @@ -1,58 +1,55 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.api.core.IErrorLogic; -import forestry.api.core.IErrorLogicSource; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; - -public class PacketErrorUpdate extends PacketCoordinates implements IForestryPacketClient { - - private IErrorLogic errorLogic; - - public PacketErrorUpdate() { - } - - public PacketErrorUpdate(TileEntity tile, IErrorLogicSource errorLogicSource) { - super(tile); - this.errorLogic = errorLogicSource.getErrorLogic(); - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - errorLogic.writeData(data); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IErrorLogicSource) { - IErrorLogicSource errorSourceTile = (IErrorLogicSource) tile; - errorLogic = errorSourceTile.getErrorLogic(); - errorLogic.readData(data); - } - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.ERROR_UPDATE; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.api.core.IErrorLogic; +import forestry.api.core.IErrorLogicSource; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.proxy.Proxies; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; + +public class PacketErrorUpdate extends PacketCoordinates implements IForestryPacketClient { + + private IErrorLogic errorLogic; + + public PacketErrorUpdate() {} + + public PacketErrorUpdate(TileEntity tile, IErrorLogicSource errorLogicSource) { + super(tile); + this.errorLogic = errorLogicSource.getErrorLogic(); + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + errorLogic.writeData(data); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof IErrorLogicSource) { + IErrorLogicSource errorSourceTile = (IErrorLogicSource) tile; + errorLogic = errorSourceTile.getErrorLogic(); + errorLogic.readData(data); + } + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.ERROR_UPDATE; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketErrorUpdateEntity.java b/src/main/java/forestry/core/network/packets/PacketErrorUpdateEntity.java index 93399c9a1..ad9a1c74a 100644 --- a/src/main/java/forestry/core/network/packets/PacketErrorUpdateEntity.java +++ b/src/main/java/forestry/core/network/packets/PacketErrorUpdateEntity.java @@ -1,57 +1,54 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; - -import forestry.api.core.IErrorLogic; -import forestry.api.core.IErrorLogicSource; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; - -public class PacketErrorUpdateEntity extends PacketEntityUpdate implements IForestryPacketClient { - private IErrorLogic errorLogic; - - public PacketErrorUpdateEntity() { - } - - public PacketErrorUpdateEntity(Entity entity, IErrorLogicSource errorLogicSource) { - super(entity); - this.errorLogic = errorLogicSource.getErrorLogic(); - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - errorLogic.writeData(data); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Entity entity = getTarget(Proxies.common.getRenderWorld()); - if (entity instanceof IErrorLogicSource) { - IErrorLogicSource errorSourceTile = (IErrorLogicSource) entity; - errorLogic = errorSourceTile.getErrorLogic(); - errorLogic.readData(data); - } - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.ERROR_UPDATE_ENTITY; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.api.core.IErrorLogic; +import forestry.api.core.IErrorLogicSource; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.proxy.Proxies; +import java.io.IOException; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; + +public class PacketErrorUpdateEntity extends PacketEntityUpdate implements IForestryPacketClient { + private IErrorLogic errorLogic; + + public PacketErrorUpdateEntity() {} + + public PacketErrorUpdateEntity(Entity entity, IErrorLogicSource errorLogicSource) { + super(entity); + this.errorLogic = errorLogicSource.getErrorLogic(); + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + errorLogic.writeData(data); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + Entity entity = getTarget(Proxies.common.getRenderWorld()); + if (entity instanceof IErrorLogicSource) { + IErrorLogicSource errorSourceTile = (IErrorLogicSource) entity; + errorLogic = errorSourceTile.getErrorLogic(); + errorLogic.readData(data); + } + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.ERROR_UPDATE_ENTITY; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketFXSignal.java b/src/main/java/forestry/core/network/packets/PacketFXSignal.java index ca7da9f7a..1174c29fa 100644 --- a/src/main/java/forestry/core/network/packets/PacketFXSignal.java +++ b/src/main/java/forestry/core/network/packets/PacketFXSignal.java @@ -10,100 +10,114 @@ ******************************************************************************/ package forestry.core.network.packets; -import java.io.IOException; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; - import cpw.mods.fml.common.registry.GameData; - import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IForestryPacketClient; import forestry.core.network.PacketIdClient; import forestry.core.proxy.Proxies; +import java.io.IOException; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; public class PacketFXSignal extends PacketCoordinates implements IForestryPacketClient { - public enum VisualFXType { - NONE, BLOCK_DESTROY, SAPLING_PLACE - } + public enum VisualFXType { + NONE, + BLOCK_DESTROY, + SAPLING_PLACE + } - public enum SoundFXType { - NONE(""), BLOCK_DESTROY(""), BLOCK_PLACE(""), LEAF("step.grass"), LOG("dig.wood"), DIRT("dig.gravel"); + public enum SoundFXType { + NONE(""), + BLOCK_DESTROY(""), + BLOCK_PLACE(""), + LEAF("step.grass"), + LOG("dig.wood"), + DIRT("dig.gravel"); - public final String soundFile; - public final float volume; - public final float pitch; + public final String soundFile; + public final float volume; + public final float pitch; - SoundFXType(String soundFile) { - this.soundFile = soundFile; - this.volume = 1.0f; - this.pitch = 1.0f; - } - } + SoundFXType(String soundFile) { + this.soundFile = soundFile; + this.volume = 1.0f; + this.pitch = 1.0f; + } + } - private VisualFXType visualFX; - private SoundFXType soundFX; + private VisualFXType visualFX; + private SoundFXType soundFX; - private Block block; - private int meta; + private Block block; + private int meta; - public PacketFXSignal() { - } + public PacketFXSignal() {} - public PacketFXSignal(VisualFXType type, int xCoord, int yCoord, int zCoord, Block block, int meta) { - this(type, SoundFXType.NONE, xCoord, yCoord, zCoord, block, meta); - } + public PacketFXSignal(VisualFXType type, int xCoord, int yCoord, int zCoord, Block block, int meta) { + this(type, SoundFXType.NONE, xCoord, yCoord, zCoord, block, meta); + } - public PacketFXSignal(SoundFXType type, int xCoord, int yCoord, int zCoord, Block block, int meta) { - this(VisualFXType.NONE, type, xCoord, yCoord, zCoord, block, meta); - } + public PacketFXSignal(SoundFXType type, int xCoord, int yCoord, int zCoord, Block block, int meta) { + this(VisualFXType.NONE, type, xCoord, yCoord, zCoord, block, meta); + } - public PacketFXSignal(VisualFXType visualFX, SoundFXType soundFX, int xCoord, int yCoord, int zCoord, Block block, int meta) { - super(xCoord, yCoord, zCoord); - this.visualFX = visualFX; - this.soundFX = soundFX; - this.block = block; - this.meta = meta; - } + public PacketFXSignal( + VisualFXType visualFX, SoundFXType soundFX, int xCoord, int yCoord, int zCoord, Block block, int meta) { + super(xCoord, yCoord, zCoord); + this.visualFX = visualFX; + this.soundFX = soundFX; + this.block = block; + this.meta = meta; + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeShort(visualFX.ordinal()); - data.writeShort(soundFX.ordinal()); - data.writeUTF(GameData.getBlockRegistry().getNameForObject(block)); - data.writeInt(meta); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeShort(visualFX.ordinal()); + data.writeShort(soundFX.ordinal()); + data.writeUTF(GameData.getBlockRegistry().getNameForObject(block)); + data.writeInt(meta); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - this.visualFX = VisualFXType.values()[data.readShort()]; - this.soundFX = SoundFXType.values()[data.readShort()]; - this.block = GameData.getBlockRegistry().getRaw(data.readUTF()); - this.meta = data.readInt(); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + this.visualFX = VisualFXType.values()[data.readShort()]; + this.soundFX = SoundFXType.values()[data.readShort()]; + this.block = GameData.getBlockRegistry().getRaw(data.readUTF()); + this.meta = data.readInt(); + } - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - if (visualFX != VisualFXType.NONE) { - Proxies.common.addBlockDestroyEffects(Proxies.common.getRenderWorld(), getPosX(), getPosY(), getPosZ(), block, meta); - } - if (soundFX != SoundFXType.NONE) { - if (soundFX == SoundFXType.BLOCK_DESTROY) { - Proxies.common.playBlockBreakSoundFX(Proxies.common.getRenderWorld(), getPosX(), getPosY(), getPosZ(), block); - } else if (soundFX == SoundFXType.BLOCK_PLACE) { - Proxies.common.playBlockPlaceSoundFX(Proxies.common.getRenderWorld(), getPosX(), getPosY(), getPosZ(), block); - } else { - Proxies.common.playSoundFX(Proxies.common.getRenderWorld(), getPosX(), getPosY(), getPosZ(), soundFX.soundFile, soundFX.volume, soundFX.pitch); - } - } - } + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + if (visualFX != VisualFXType.NONE) { + Proxies.common.addBlockDestroyEffects( + Proxies.common.getRenderWorld(), getPosX(), getPosY(), getPosZ(), block, meta); + } + if (soundFX != SoundFXType.NONE) { + if (soundFX == SoundFXType.BLOCK_DESTROY) { + Proxies.common.playBlockBreakSoundFX( + Proxies.common.getRenderWorld(), getPosX(), getPosY(), getPosZ(), block); + } else if (soundFX == SoundFXType.BLOCK_PLACE) { + Proxies.common.playBlockPlaceSoundFX( + Proxies.common.getRenderWorld(), getPosX(), getPosY(), getPosZ(), block); + } else { + Proxies.common.playSoundFX( + Proxies.common.getRenderWorld(), + getPosX(), + getPosY(), + getPosZ(), + soundFX.soundFile, + soundFX.volume, + soundFX.pitch); + } + } + } - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.FX_SIGNAL; - } + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.FX_SIGNAL; + } } diff --git a/src/main/java/forestry/core/network/packets/PacketGenomeTrackerSync.java b/src/main/java/forestry/core/network/packets/PacketGenomeTrackerSync.java index 923a5eb30..0bfa07f3b 100644 --- a/src/main/java/forestry/core/network/packets/PacketGenomeTrackerSync.java +++ b/src/main/java/forestry/core/network/packets/PacketGenomeTrackerSync.java @@ -1,58 +1,54 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.MinecraftForge; - -import forestry.api.core.ForestryEvent; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IBreedingTracker; -import forestry.api.genetics.ISpeciesRoot; -import forestry.core.genetics.BreedingTracker; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; - -public class PacketGenomeTrackerSync extends PacketNBT implements IForestryPacketClient { - - public PacketGenomeTrackerSync() { - } - - public PacketGenomeTrackerSync(NBTTagCompound nbtTagCompound) { - super(nbtTagCompound); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - IBreedingTracker tracker = null; - String type = getTagCompound().getString(BreedingTracker.TYPE_KEY); - - ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(type); - if (root != null) { - tracker = root.getBreedingTracker(Proxies.common.getRenderWorld(), player.getGameProfile()); - } - if (tracker != null) { - tracker.decodeFromNBT(getTagCompound()); - MinecraftForge.EVENT_BUS.post(new ForestryEvent.SyncedBreedingTracker(tracker, player)); - } - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.GENOME_TRACKER_UPDATE; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.api.core.ForestryEvent; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IBreedingTracker; +import forestry.api.genetics.ISpeciesRoot; +import forestry.core.genetics.BreedingTracker; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.proxy.Proxies; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.MinecraftForge; + +public class PacketGenomeTrackerSync extends PacketNBT implements IForestryPacketClient { + + public PacketGenomeTrackerSync() {} + + public PacketGenomeTrackerSync(NBTTagCompound nbtTagCompound) { + super(nbtTagCompound); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + IBreedingTracker tracker = null; + String type = getTagCompound().getString(BreedingTracker.TYPE_KEY); + + ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(type); + if (root != null) { + tracker = root.getBreedingTracker(Proxies.common.getRenderWorld(), player.getGameProfile()); + } + if (tracker != null) { + tracker.decodeFromNBT(getTagCompound()); + MinecraftForge.EVENT_BUS.post(new ForestryEvent.SyncedBreedingTracker(tracker, player)); + } + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.GENOME_TRACKER_UPDATE; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketGuiEnergy.java b/src/main/java/forestry/core/network/packets/PacketGuiEnergy.java index ea3f37c42..c4bcfd4c3 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiEnergy.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiEnergy.java @@ -1,60 +1,57 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; - -import forestry.core.gui.ContainerTile; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.ForestryPacket; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; - -public class PacketGuiEnergy extends ForestryPacket implements IForestryPacketClient { - - private int windowId; - private int value; - - public PacketGuiEnergy() { - } - - public PacketGuiEnergy(int windowId, int value) { - this.windowId = windowId; - this.value = value; - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeVarInt(windowId); - data.writeVarInt(value); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - windowId = data.readVarInt(); - value = data.readVarInt(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - if (player.openContainer instanceof ContainerTile && player.openContainer.windowId == windowId) { - ((ContainerTile) player.openContainer).onGuiEnergy(value); - } - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.GUI_ENERGY; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.gui.ContainerTile; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; + +public class PacketGuiEnergy extends ForestryPacket implements IForestryPacketClient { + + private int windowId; + private int value; + + public PacketGuiEnergy() {} + + public PacketGuiEnergy(int windowId, int value) { + this.windowId = windowId; + this.value = value; + } + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeVarInt(windowId); + data.writeVarInt(value); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + windowId = data.readVarInt(); + value = data.readVarInt(); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + if (player.openContainer instanceof ContainerTile && player.openContainer.windowId == windowId) { + ((ContainerTile) player.openContainer).onGuiEnergy(value); + } + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.GUI_ENERGY; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketGuiLayoutSelect.java b/src/main/java/forestry/core/network/packets/PacketGuiLayoutSelect.java index d54205b90..41855168b 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiLayoutSelect.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiLayoutSelect.java @@ -1,46 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; - -import forestry.core.circuits.ContainerSolderingIron; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; - -public class PacketGuiLayoutSelect extends PacketString implements IForestryPacketClient { - - public PacketGuiLayoutSelect() { - } - - public PacketGuiLayoutSelect(String string) { - super(string); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Container container = player.openContainer; - if (!(container instanceof ContainerSolderingIron)) { - return; - } - - ((ContainerSolderingIron) container).setLayout(getString()); - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.GUI_LAYOUT_SELECT; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.circuits.ContainerSolderingIron; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; + +public class PacketGuiLayoutSelect extends PacketString implements IForestryPacketClient { + + public PacketGuiLayoutSelect() {} + + public PacketGuiLayoutSelect(String string) { + super(string); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + Container container = player.openContainer; + if (!(container instanceof ContainerSolderingIron)) { + return; + } + + ((ContainerSolderingIron) container).setLayout(getString()); + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.GUI_LAYOUT_SELECT; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketGuiSelect.java b/src/main/java/forestry/core/network/packets/PacketGuiSelect.java index ebff74529..df2f43402 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiSelect.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiSelect.java @@ -1,53 +1,50 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.ForestryPacket; - -public abstract class PacketGuiSelect extends ForestryPacket { - private int primaryIndex; - private int secondaryIndex; - - protected PacketGuiSelect() { - } - - protected PacketGuiSelect(int primaryIndex, int secondaryIndex) { - this.primaryIndex = primaryIndex; - this.secondaryIndex = secondaryIndex; - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeVarInt(primaryIndex); - data.writeVarInt(secondaryIndex); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - primaryIndex = data.readVarInt(); - secondaryIndex = data.readVarInt(); - } - - public int getPrimaryIndex() { - return primaryIndex; - } - - public int getSecondaryIndex() { - return secondaryIndex; - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; +import java.io.IOException; + +public abstract class PacketGuiSelect extends ForestryPacket { + private int primaryIndex; + private int secondaryIndex; + + protected PacketGuiSelect() {} + + protected PacketGuiSelect(int primaryIndex, int secondaryIndex) { + this.primaryIndex = primaryIndex; + this.secondaryIndex = secondaryIndex; + } + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeVarInt(primaryIndex); + data.writeVarInt(secondaryIndex); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + primaryIndex = data.readVarInt(); + secondaryIndex = data.readVarInt(); + } + + public int getPrimaryIndex() { + return primaryIndex; + } + + public int getSecondaryIndex() { + return secondaryIndex; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketGuiSelectRequest.java b/src/main/java/forestry/core/network/packets/PacketGuiSelectRequest.java index fb3d97f17..22617a3b9 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiSelectRequest.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiSelectRequest.java @@ -1,46 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.inventory.Container; - -import forestry.core.gui.IGuiSelectable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; - -public class PacketGuiSelectRequest extends PacketGuiSelect implements IForestryPacketServer { - - public PacketGuiSelectRequest() { - } - - public PacketGuiSelectRequest(int primaryIndex, int secondaryIndex) { - super(primaryIndex, secondaryIndex); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - Container container = player.openContainer; - if (!(container instanceof IGuiSelectable)) { - return; - } - - ((IGuiSelectable) container).handleSelectionRequest(player, this); - } - - @Override - public PacketIdServer getPacketId() { - return PacketIdServer.GUI_SELECTION_REQUEST; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.gui.IGuiSelectable; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketIdServer; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.Container; + +public class PacketGuiSelectRequest extends PacketGuiSelect implements IForestryPacketServer { + + public PacketGuiSelectRequest() {} + + public PacketGuiSelectRequest(int primaryIndex, int secondaryIndex) { + super(primaryIndex, secondaryIndex); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { + Container container = player.openContainer; + if (!(container instanceof IGuiSelectable)) { + return; + } + + ((IGuiSelectable) container).handleSelectionRequest(player, this); + } + + @Override + public PacketIdServer getPacketId() { + return PacketIdServer.GUI_SELECTION_REQUEST; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketGuiUpdate.java b/src/main/java/forestry/core/network/packets/PacketGuiUpdate.java index c959dbdd2..e7977ff05 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiUpdate.java @@ -1,56 +1,53 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.IStreamableGui; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.ILocatable; - -public class PacketGuiUpdate extends PacketCoordinates implements IForestryPacketClient { - - private IStreamableGui guiDataTile; - - public PacketGuiUpdate() { - } - - public PacketGuiUpdate(T guiDataTile) { - super(guiDataTile.getCoordinates()); - this.guiDataTile = guiDataTile; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - guiDataTile.writeGuiData(data); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IStreamableGui) { - ((IStreamableGui) tile).readGuiData(data); - } - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.GUI_UPDATE; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IStreamableGui; +import forestry.core.network.PacketIdClient; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.ILocatable; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; + +public class PacketGuiUpdate extends PacketCoordinates implements IForestryPacketClient { + + private IStreamableGui guiDataTile; + + public PacketGuiUpdate() {} + + public PacketGuiUpdate(T guiDataTile) { + super(guiDataTile.getCoordinates()); + this.guiDataTile = guiDataTile; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + guiDataTile.writeGuiData(data); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof IStreamableGui) { + ((IStreamableGui) tile).readGuiData(data); + } + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.GUI_UPDATE; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketGuiUpdateEntity.java b/src/main/java/forestry/core/network/packets/PacketGuiUpdateEntity.java index eb98948ee..f35cd069f 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiUpdateEntity.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiUpdateEntity.java @@ -1,54 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.IStreamableGui; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; - -public class PacketGuiUpdateEntity extends PacketEntityUpdate implements IForestryPacketClient { - private IStreamableGui streamableGui; - - public PacketGuiUpdateEntity() { - } - - public PacketGuiUpdateEntity(IStreamableGui streamableGui, Entity entity) { - super(entity); - this.streamableGui = streamableGui; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - streamableGui.writeGuiData(data); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Entity entity = getTarget(Proxies.common.getRenderWorld()); - if (entity instanceof IStreamableGui) { - ((IStreamableGui) entity).readGuiData(data); - } - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.GUI_UPDATE_ENTITY; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IStreamableGui; +import forestry.core.network.PacketIdClient; +import forestry.core.proxy.Proxies; +import java.io.IOException; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; + +public class PacketGuiUpdateEntity extends PacketEntityUpdate implements IForestryPacketClient { + private IStreamableGui streamableGui; + + public PacketGuiUpdateEntity() {} + + public PacketGuiUpdateEntity(IStreamableGui streamableGui, Entity entity) { + super(entity); + this.streamableGui = streamableGui; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + streamableGui.writeGuiData(data); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + Entity entity = getTarget(Proxies.common.getRenderWorld()); + if (entity instanceof IStreamableGui) { + ((IStreamableGui) entity).readGuiData(data); + } + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.GUI_UPDATE_ENTITY; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketItemStackDisplay.java b/src/main/java/forestry/core/network/packets/PacketItemStackDisplay.java index 51d81a0f0..6e2d9b1e7 100644 --- a/src/main/java/forestry/core/network/packets/PacketItemStackDisplay.java +++ b/src/main/java/forestry/core/network/packets/PacketItemStackDisplay.java @@ -1,63 +1,60 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.IItemStackDisplay; -import forestry.core.tiles.TileForestry; - -public class PacketItemStackDisplay extends PacketCoordinates implements IForestryPacketClient { - - private ItemStack itemStack; - - public PacketItemStackDisplay() { - } - - public PacketItemStackDisplay(T tile, ItemStack itemStack) { - super(tile); - this.itemStack = itemStack; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeItemStack(itemStack); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - itemStack = data.readItemStack(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IItemStackDisplay) { - ((IItemStackDisplay) tile).handleItemStackForDisplay(itemStack); - } - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.ITEMSTACK_DISPLAY; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.IItemStackDisplay; +import forestry.core.tiles.TileForestry; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; + +public class PacketItemStackDisplay extends PacketCoordinates implements IForestryPacketClient { + + private ItemStack itemStack; + + public PacketItemStackDisplay() {} + + public PacketItemStackDisplay(T tile, ItemStack itemStack) { + super(tile); + this.itemStack = itemStack; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeItemStack(itemStack); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + itemStack = data.readItemStack(); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof IItemStackDisplay) { + ((IItemStackDisplay) tile).handleItemStackForDisplay(itemStack); + } + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.ITEMSTACK_DISPLAY; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketNBT.java b/src/main/java/forestry/core/network/packets/PacketNBT.java index 6fd6652ff..be87f01af 100644 --- a/src/main/java/forestry/core/network/packets/PacketNBT.java +++ b/src/main/java/forestry/core/network/packets/PacketNBT.java @@ -10,36 +10,33 @@ ******************************************************************************/ package forestry.core.network.packets; -import java.io.IOException; - -import net.minecraft.nbt.NBTTagCompound; - import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.ForestryPacket; +import java.io.IOException; +import net.minecraft.nbt.NBTTagCompound; public abstract class PacketNBT extends ForestryPacket { - private NBTTagCompound nbttagcompound; + private NBTTagCompound nbttagcompound; - protected PacketNBT() { - } + protected PacketNBT() {} - protected PacketNBT(NBTTagCompound nbttagcompound) { - this.nbttagcompound = nbttagcompound; - } + protected PacketNBT(NBTTagCompound nbttagcompound) { + this.nbttagcompound = nbttagcompound; + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeNBTTagCompound(nbttagcompound); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeNBTTagCompound(nbttagcompound); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - this.nbttagcompound = data.readNBTTagCompound(); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + this.nbttagcompound = data.readNBTTagCompound(); + } - protected NBTTagCompound getTagCompound() { - return this.nbttagcompound; - } + protected NBTTagCompound getTagCompound() { + return this.nbttagcompound; + } } diff --git a/src/main/java/forestry/core/network/packets/PacketPipetteClick.java b/src/main/java/forestry/core/network/packets/PacketPipetteClick.java index 0337d39d1..f8dd21f4a 100644 --- a/src/main/java/forestry/core/network/packets/PacketPipetteClick.java +++ b/src/main/java/forestry/core/network/packets/PacketPipetteClick.java @@ -1,43 +1,40 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.gui.IContainerLiquidTanks; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; - -public class PacketPipetteClick extends PacketSlotClick implements IForestryPacketServer { - - public PacketPipetteClick() { - } - - public PacketPipetteClick(TileEntity tile, int slot) { - super(tile, slot); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - if ((player.openContainer instanceof IContainerLiquidTanks)) { - ((IContainerLiquidTanks) player.openContainer).handlePipetteClick(getSlot(), player); - } - } - - @Override - public PacketIdServer getPacketId() { - return PacketIdServer.PIPETTE_CLICK; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.gui.IContainerLiquidTanks; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketIdServer; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.tileentity.TileEntity; + +public class PacketPipetteClick extends PacketSlotClick implements IForestryPacketServer { + + public PacketPipetteClick() {} + + public PacketPipetteClick(TileEntity tile, int slot) { + super(tile, slot); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { + if ((player.openContainer instanceof IContainerLiquidTanks)) { + ((IContainerLiquidTanks) player.openContainer).handlePipetteClick(getSlot(), player); + } + } + + @Override + public PacketIdServer getPacketId() { + return PacketIdServer.PIPETTE_CLICK; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketSlotClick.java b/src/main/java/forestry/core/network/packets/PacketSlotClick.java index 31a189648..36f80565a 100644 --- a/src/main/java/forestry/core/network/packets/PacketSlotClick.java +++ b/src/main/java/forestry/core/network/packets/PacketSlotClick.java @@ -1,46 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.tileentity.TileEntity; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; - -public abstract class PacketSlotClick extends PacketCoordinates { - private int slot; - - protected PacketSlotClick() { - } - - protected PacketSlotClick(TileEntity tile, int slot) { - super(tile); - this.slot = slot; - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - this.slot = data.readVarInt(); - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeVarInt(slot); - } - - public int getSlot() { - return slot; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import java.io.IOException; +import net.minecraft.tileentity.TileEntity; + +public abstract class PacketSlotClick extends PacketCoordinates { + private int slot; + + protected PacketSlotClick() {} + + protected PacketSlotClick(TileEntity tile, int slot) { + super(tile); + this.slot = slot; + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + this.slot = data.readVarInt(); + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeVarInt(slot); + } + + public int getSlot() { + return slot; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketSocketUpdate.java b/src/main/java/forestry/core/network/packets/PacketSocketUpdate.java index 85f0c37b5..45535ba3d 100644 --- a/src/main/java/forestry/core/network/packets/PacketSocketUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketSocketUpdate.java @@ -10,62 +10,59 @@ ******************************************************************************/ package forestry.core.network.packets; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - import forestry.core.circuits.ISocketable; import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IForestryPacketClient; import forestry.core.network.PacketIdClient; import forestry.core.proxy.Proxies; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; public class PacketSocketUpdate extends PacketCoordinates implements IForestryPacketClient { - private ItemStack[] itemStacks; + private ItemStack[] itemStacks; - public PacketSocketUpdate() { - } + public PacketSocketUpdate() {} - public PacketSocketUpdate(T tile) { - super(tile); + public PacketSocketUpdate(T tile) { + super(tile); - itemStacks = new ItemStack[tile.getSocketCount()]; - for (int i = 0; i < tile.getSocketCount(); i++) { - itemStacks[i] = tile.getSocket(i); - } - } + itemStacks = new ItemStack[tile.getSocketCount()]; + for (int i = 0; i < tile.getSocketCount(); i++) { + itemStacks[i] = tile.getSocket(i); + } + } - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeItemStacks(itemStacks); - } + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeItemStacks(itemStacks); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - itemStacks = data.readItemStacks(); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + itemStacks = data.readItemStacks(); + } - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (!(tile instanceof ISocketable)) { - return; - } + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (!(tile instanceof ISocketable)) { + return; + } - ISocketable socketable = (ISocketable) tile; - for (int i = 0; i < itemStacks.length; i++) { - socketable.setSocket(i, itemStacks[i]); - } - } + ISocketable socketable = (ISocketable) tile; + for (int i = 0; i < itemStacks.length; i++) { + socketable.setSocket(i, itemStacks[i]); + } + } - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.SOCKET_UPDATE; - } + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.SOCKET_UPDATE; + } } diff --git a/src/main/java/forestry/core/network/packets/PacketSolderingIronClick.java b/src/main/java/forestry/core/network/packets/PacketSolderingIronClick.java index b8e50dcba..327813c41 100644 --- a/src/main/java/forestry/core/network/packets/PacketSolderingIronClick.java +++ b/src/main/java/forestry/core/network/packets/PacketSolderingIronClick.java @@ -1,47 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.gui.IContainerSocketed; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; - -public class PacketSolderingIronClick extends PacketSlotClick implements IForestryPacketServer { - - public PacketSolderingIronClick() { - } - - public PacketSolderingIronClick(TileEntity tile, int slot) { - super(tile, slot); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - if (!(player.openContainer instanceof IContainerSocketed)) { - return; - } - ItemStack itemstack = player.inventory.getItemStack(); - - ((IContainerSocketed) player.openContainer).handleSolderingIronClickServer(getSlot(), player, itemstack); - } - - @Override - public PacketIdServer getPacketId() { - return PacketIdServer.SOLDERING_IRON_CLICK; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.gui.IContainerSocketed; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketIdServer; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; + +public class PacketSolderingIronClick extends PacketSlotClick implements IForestryPacketServer { + + public PacketSolderingIronClick() {} + + public PacketSolderingIronClick(TileEntity tile, int slot) { + super(tile, slot); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { + if (!(player.openContainer instanceof IContainerSocketed)) { + return; + } + ItemStack itemstack = player.inventory.getItemStack(); + + ((IContainerSocketed) player.openContainer).handleSolderingIronClickServer(getSlot(), player, itemstack); + } + + @Override + public PacketIdServer getPacketId() { + return PacketIdServer.SOLDERING_IRON_CLICK; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketString.java b/src/main/java/forestry/core/network/packets/PacketString.java index c3a910d0f..59e3d115a 100644 --- a/src/main/java/forestry/core/network/packets/PacketString.java +++ b/src/main/java/forestry/core/network/packets/PacketString.java @@ -1,45 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.ForestryPacket; - -public abstract class PacketString extends ForestryPacket { - - private String string; - - protected PacketString() { - } - - protected PacketString(String string) { - this.string = string; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeUTF(string); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - string = data.readUTF(); - } - - public String getString() { - return string; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; +import java.io.IOException; + +public abstract class PacketString extends ForestryPacket { + + private String string; + + protected PacketString() {} + + protected PacketString(String string) { + this.string = string; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeUTF(string); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + string = data.readUTF(); + } + + public String getString() { + return string; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketTankLevelUpdate.java b/src/main/java/forestry/core/network/packets/PacketTankLevelUpdate.java index 2442e5b9c..8d03663d0 100644 --- a/src/main/java/forestry/core/network/packets/PacketTankLevelUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketTankLevelUpdate.java @@ -1,69 +1,65 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.core.fluids.ITankManager; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.ILiquidTankTile; - -public class PacketTankLevelUpdate extends PacketCoordinates implements IForestryPacketClient { - - private int tankIndex; - private FluidStack contents; - - public PacketTankLevelUpdate() { - } - - public PacketTankLevelUpdate(ILiquidTankTile tileEntity, int tankIndex, FluidStack contents) { - super(tileEntity.getCoordinates()); - this.tankIndex = tankIndex; - this.contents = contents; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeVarInt(tankIndex); - data.writeFluidStack(contents); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - tankIndex = data.readVarInt(); - contents = data.readFluidStack(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tileEntity = getTarget(Proxies.common.getRenderWorld()); - if (tileEntity instanceof ILiquidTankTile) { - ITankManager tankManager = ((ILiquidTankTile) tileEntity).getTankManager(); - tankManager.processTankUpdate(tankIndex, contents); - } - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.TANK_LEVEL_UPDATE; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.fluids.ITankManager; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.ILiquidTankTile; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.fluids.FluidStack; + +public class PacketTankLevelUpdate extends PacketCoordinates implements IForestryPacketClient { + + private int tankIndex; + private FluidStack contents; + + public PacketTankLevelUpdate() {} + + public PacketTankLevelUpdate(ILiquidTankTile tileEntity, int tankIndex, FluidStack contents) { + super(tileEntity.getCoordinates()); + this.tankIndex = tankIndex; + this.contents = contents; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeVarInt(tankIndex); + data.writeFluidStack(contents); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + tankIndex = data.readVarInt(); + contents = data.readFluidStack(); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + TileEntity tileEntity = getTarget(Proxies.common.getRenderWorld()); + if (tileEntity instanceof ILiquidTankTile) { + ITankManager tankManager = ((ILiquidTankTile) tileEntity).getTankManager(); + tankManager.processTankUpdate(tankIndex, contents); + } + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.TANK_LEVEL_UPDATE; + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketTileStream.java b/src/main/java/forestry/core/network/packets/PacketTileStream.java index 9d7a9c084..a0d4ba7e4 100644 --- a/src/main/java/forestry/core/network/packets/PacketTileStream.java +++ b/src/main/java/forestry/core/network/packets/PacketTileStream.java @@ -10,46 +10,43 @@ ******************************************************************************/ package forestry.core.network.packets; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IForestryPacketClient; import forestry.core.network.IStreamable; import forestry.core.network.PacketIdClient; import forestry.core.proxy.Proxies; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; public class PacketTileStream extends PacketCoordinates implements IForestryPacketClient { - private IStreamable streamable; + private IStreamable streamable; - public PacketTileStream() { - } + public PacketTileStream() {} - public PacketTileStream(T streamable) { - super(streamable); - this.streamable = streamable; - } + public PacketTileStream(T streamable) { + super(streamable); + this.streamable = streamable; + } - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - streamable.writeData(data); - } + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + streamable.writeData(data); + } - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IStreamable) { - ((IStreamable) tile).readData(data); - } - } + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof IStreamable) { + ((IStreamable) tile).readData(data); + } + } - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.TILE_FORESTRY_UPDATE; - } + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.TILE_FORESTRY_UPDATE; + } } diff --git a/src/main/java/forestry/core/proxy/Proxies.java b/src/main/java/forestry/core/proxy/Proxies.java index be643d819..47c1dac54 100755 --- a/src/main/java/forestry/core/proxy/Proxies.java +++ b/src/main/java/forestry/core/proxy/Proxies.java @@ -13,10 +13,12 @@ package forestry.core.proxy; import cpw.mods.fml.common.SidedProxy; public class Proxies { - @SidedProxy(clientSide = "forestry.core.proxy.ProxyCommonClient", serverSide = "forestry.core.proxy.ProxyCommon") - public static ProxyCommon common; - @SidedProxy(clientSide = "forestry.core.proxy.ProxyNetworkClient", serverSide = "forestry.core.proxy.ProxyNetwork") - public static ProxyNetwork net; - @SidedProxy(clientSide = "forestry.core.proxy.ProxyRenderClient", serverSide = "forestry.core.proxy.ProxyRender") - public static ProxyRender render; + @SidedProxy(clientSide = "forestry.core.proxy.ProxyCommonClient", serverSide = "forestry.core.proxy.ProxyCommon") + public static ProxyCommon common; + + @SidedProxy(clientSide = "forestry.core.proxy.ProxyNetworkClient", serverSide = "forestry.core.proxy.ProxyNetwork") + public static ProxyNetwork net; + + @SidedProxy(clientSide = "forestry.core.proxy.ProxyRenderClient", serverSide = "forestry.core.proxy.ProxyRender") + public static ProxyRender render; } diff --git a/src/main/java/forestry/core/proxy/ProxyCommon.java b/src/main/java/forestry/core/proxy/ProxyCommon.java index 8d3af60e7..9ff47e384 100755 --- a/src/main/java/forestry/core/proxy/ProxyCommon.java +++ b/src/main/java/forestry/core/proxy/ProxyCommon.java @@ -10,99 +10,115 @@ ******************************************************************************/ package forestry.core.proxy; +import cpw.mods.fml.client.FMLClientHandler; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.Loader; +import forestry.core.TickHandlerCoreServer; +import forestry.core.multiblock.MultiblockServerTickHandler; +import forestry.core.network.packets.PacketFXSignal; +import forestry.core.worldgen.WorldGenerator; import java.io.File; - import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; - import net.minecraftforge.common.MinecraftForge; -import cpw.mods.fml.client.FMLClientHandler; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.Loader; - -import forestry.core.TickHandlerCoreServer; -import forestry.core.multiblock.MultiblockServerTickHandler; -import forestry.core.network.packets.PacketFXSignal; -import forestry.core.worldgen.WorldGenerator; - public class ProxyCommon { - public String getMinecraftVersion() { - return Loader.instance().getMinecraftModContainer().getVersion(); - } + public String getMinecraftVersion() { + return Loader.instance().getMinecraftModContainer().getVersion(); + } - public void registerTickHandlers(WorldGenerator worldGenerator) { - TickHandlerCoreServer tickHandlerCoreServer = new TickHandlerCoreServer(worldGenerator); - FMLCommonHandler.instance().bus().register(tickHandlerCoreServer); - MinecraftForge.EVENT_BUS.register(tickHandlerCoreServer); + public void registerTickHandlers(WorldGenerator worldGenerator) { + TickHandlerCoreServer tickHandlerCoreServer = new TickHandlerCoreServer(worldGenerator); + FMLCommonHandler.instance().bus().register(tickHandlerCoreServer); + MinecraftForge.EVENT_BUS.register(tickHandlerCoreServer); - FMLCommonHandler.instance().bus().register(new MultiblockServerTickHandler()); - } + FMLCommonHandler.instance().bus().register(new MultiblockServerTickHandler()); + } - public String getDisplayName(ItemStack itemstack) { - return null; - } + public String getDisplayName(ItemStack itemstack) { + return null; + } - public File getForestryRoot() { - return new File("."); - } + public File getForestryRoot() { + return new File("."); + } - public boolean isOp(EntityPlayer player) { - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - return server.getConfigurationManager().func_152596_g(player.getGameProfile()); - } + public boolean isOp(EntityPlayer player) { + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + return server.getConfigurationManager().func_152596_g(player.getGameProfile()); + } - public double getBlockReachDistance(EntityPlayer entityplayer) { - return 4f; - } + public double getBlockReachDistance(EntityPlayer entityplayer) { + return 4f; + } - public boolean isShiftDown() { - return false; - } + public boolean isShiftDown() { + return false; + } - public void playSoundFX(World world, int x, int y, int z, Block block) { - Proxies.net.sendNetworkPacket(new PacketFXSignal(PacketFXSignal.SoundFXType.LEAF, x, y, z, block, 0), world); - } + public void playSoundFX(World world, int x, int y, int z, Block block) { + Proxies.net.sendNetworkPacket(new PacketFXSignal(PacketFXSignal.SoundFXType.LEAF, x, y, z, block, 0), world); + } - public void playSoundFX(World world, int x, int y, int z, String sound, float volume, float pitch) { - } + public void playSoundFX(World world, int x, int y, int z, String sound, float volume, float pitch) {} - public void addBlockDestroyEffects(World world, int xCoord, int yCoord, int zCoord, Block block, int i) { - sendFXSignal(PacketFXSignal.VisualFXType.BLOCK_DESTROY, PacketFXSignal.SoundFXType.BLOCK_DESTROY, world, xCoord, yCoord, zCoord, block, i); - } + public void addBlockDestroyEffects(World world, int xCoord, int yCoord, int zCoord, Block block, int i) { + sendFXSignal( + PacketFXSignal.VisualFXType.BLOCK_DESTROY, + PacketFXSignal.SoundFXType.BLOCK_DESTROY, + world, + xCoord, + yCoord, + zCoord, + block, + i); + } - public void addBlockPlaceEffects(World world, int xCoord, int yCoord, int zCoord, Block block, int i) { - sendFXSignal(PacketFXSignal.VisualFXType.NONE, PacketFXSignal.SoundFXType.BLOCK_PLACE, world, xCoord, yCoord, zCoord, block, i); - } + public void addBlockPlaceEffects(World world, int xCoord, int yCoord, int zCoord, Block block, int i) { + sendFXSignal( + PacketFXSignal.VisualFXType.NONE, + PacketFXSignal.SoundFXType.BLOCK_PLACE, + world, + xCoord, + yCoord, + zCoord, + block, + i); + } - public void playBlockBreakSoundFX(World world, int x, int y, int z, Block block) { - } + public void playBlockBreakSoundFX(World world, int x, int y, int z, Block block) {} - public void playBlockPlaceSoundFX(World world, int x, int y, int z, Block block) { - } + public void playBlockPlaceSoundFX(World world, int x, int y, int z, Block block) {} - public void sendFXSignal(PacketFXSignal.VisualFXType visualFX, PacketFXSignal.SoundFXType soundFX, World world, int xCoord, int yCoord, int zCoord, - Block block, int i) { - if (!world.isRemote) { - Proxies.net.sendNetworkPacket(new PacketFXSignal(visualFX, soundFX, xCoord, yCoord, zCoord, block, i), world); - } - } + public void sendFXSignal( + PacketFXSignal.VisualFXType visualFX, + PacketFXSignal.SoundFXType soundFX, + World world, + int xCoord, + int yCoord, + int zCoord, + Block block, + int i) { + if (!world.isRemote) { + Proxies.net.sendNetworkPacket( + new PacketFXSignal(visualFX, soundFX, xCoord, yCoord, zCoord, block, i), world); + } + } - public World getRenderWorld() { - return null; - } + public World getRenderWorld() { + return null; + } - public Minecraft getClientInstance() { - return FMLClientHandler.instance().getClient(); - } - - public EntityPlayer getPlayer() { - return null; - } + public Minecraft getClientInstance() { + return FMLClientHandler.instance().getClient(); + } + public EntityPlayer getPlayer() { + return null; + } } diff --git a/src/main/java/forestry/core/proxy/ProxyCommonClient.java b/src/main/java/forestry/core/proxy/ProxyCommonClient.java index 6bee8be2f..61ccef9cd 100644 --- a/src/main/java/forestry/core/proxy/ProxyCommonClient.java +++ b/src/main/java/forestry/core/proxy/ProxyCommonClient.java @@ -10,119 +10,143 @@ ******************************************************************************/ package forestry.core.proxy; +import cpw.mods.fml.common.FMLCommonHandler; +import forestry.core.TickHandlerCoreClient; +import forestry.core.multiblock.MultiblockClientTickHandler; +import forestry.core.worldgen.WorldGenerator; import java.io.File; - import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; - -import cpw.mods.fml.common.FMLCommonHandler; - import org.lwjgl.input.Keyboard; -import forestry.core.TickHandlerCoreClient; -import forestry.core.multiblock.MultiblockClientTickHandler; -import forestry.core.worldgen.WorldGenerator; - public class ProxyCommonClient extends ProxyCommon { - @Override - public void registerTickHandlers(WorldGenerator worldGenerator) { - super.registerTickHandlers(worldGenerator); + @Override + public void registerTickHandlers(WorldGenerator worldGenerator) { + super.registerTickHandlers(worldGenerator); - FMLCommonHandler.instance().bus().register(new TickHandlerCoreClient()); - FMLCommonHandler.instance().bus().register(new MultiblockClientTickHandler()); - } + FMLCommonHandler.instance().bus().register(new TickHandlerCoreClient()); + FMLCommonHandler.instance().bus().register(new MultiblockClientTickHandler()); + } - @Override - public File getForestryRoot() { - return Minecraft.getMinecraft().mcDataDir; - } + @Override + public File getForestryRoot() { + return Minecraft.getMinecraft().mcDataDir; + } - @Override - public World getRenderWorld() { - return getClientInstance().theWorld; - } + @Override + public World getRenderWorld() { + return getClientInstance().theWorld; + } - @Override - public boolean isOp(EntityPlayer player) { - return false; - } + @Override + public boolean isOp(EntityPlayer player) { + return false; + } - @Override - public double getBlockReachDistance(EntityPlayer entityplayer) { - if (entityplayer instanceof EntityPlayerSP) { - return getClientInstance().playerController.getBlockReachDistance(); - } else { - return 4f; - } - } + @Override + public double getBlockReachDistance(EntityPlayer entityplayer) { + if (entityplayer instanceof EntityPlayerSP) { + return getClientInstance().playerController.getBlockReachDistance(); + } else { + return 4f; + } + } - @Override - public boolean isShiftDown() { - return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); - } + @Override + public boolean isShiftDown() { + return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + } - @Override - public String getDisplayName(ItemStack itemstack) { - return itemstack.getItem().getItemStackDisplayName(itemstack); - } + @Override + public String getDisplayName(ItemStack itemstack) { + return itemstack.getItem().getItemStackDisplayName(itemstack); + } - @Override - public void playSoundFX(World world, int x, int y, int z, Block block) { - if (!world.isRemote) { - super.playSoundFX(world, x, y, z, block); - } else { - playSoundFX(world, x, y, z, block.stepSound.getStepResourcePath(), block.stepSound.getVolume(), block.stepSound.getPitch()); - } - } + @Override + public void playSoundFX(World world, int x, int y, int z, Block block) { + if (!world.isRemote) { + super.playSoundFX(world, x, y, z, block); + } else { + playSoundFX( + world, + x, + y, + z, + block.stepSound.getStepResourcePath(), + block.stepSound.getVolume(), + block.stepSound.getPitch()); + } + } - @Override - public void playBlockBreakSoundFX(World world, int x, int y, int z, Block block) { - if (!world.isRemote) { - super.playSoundFX(world, x, y, z, block); - } else { - playSoundFX(world, x, y, z, block.stepSound.getBreakSound(), block.stepSound.getVolume() / 4, block.stepSound.getPitch()); - } - } + @Override + public void playBlockBreakSoundFX(World world, int x, int y, int z, Block block) { + if (!world.isRemote) { + super.playSoundFX(world, x, y, z, block); + } else { + playSoundFX( + world, + x, + y, + z, + block.stepSound.getBreakSound(), + block.stepSound.getVolume() / 4, + block.stepSound.getPitch()); + } + } - @Override - public void playBlockPlaceSoundFX(World world, int x, int y, int z, Block block) { - if (!world.isRemote) { - super.playSoundFX(world, x, y, z, block); - } else { - playSoundFX(world, x, y, z, block.stepSound.getStepResourcePath(), block.stepSound.getVolume() / 4, block.stepSound.getPitch()); - } - } + @Override + public void playBlockPlaceSoundFX(World world, int x, int y, int z, Block block) { + if (!world.isRemote) { + super.playSoundFX(world, x, y, z, block); + } else { + playSoundFX( + world, + x, + y, + z, + block.stepSound.getStepResourcePath(), + block.stepSound.getVolume() / 4, + block.stepSound.getPitch()); + } + } - @Override - public void playSoundFX(World world, int x, int y, int z, String sound, float volume, float pitch) { - world.playSound(x + 0.5, y + 0.5, z + 0.5, sound, volume, (1.0f + (world.rand.nextFloat() - world.rand.nextFloat()) * 0.2f) * 0.7f, false); - } + @Override + public void playSoundFX(World world, int x, int y, int z, String sound, float volume, float pitch) { + world.playSound( + x + 0.5, + y + 0.5, + z + 0.5, + sound, + volume, + (1.0f + (world.rand.nextFloat() - world.rand.nextFloat()) * 0.2f) * 0.7f, + false); + } - @Override - public void addBlockDestroyEffects(World world, int xCoord, int yCoord, int zCoord, Block block, int i) { - if (world.isRemote) { - getClientInstance().effectRenderer.addBlockDestroyEffects(xCoord, yCoord, zCoord, block, i); - } else { - super.addBlockDestroyEffects(world, xCoord, yCoord, zCoord, block, i); - } - } + @Override + public void addBlockDestroyEffects(World world, int xCoord, int yCoord, int zCoord, Block block, int i) { + if (world.isRemote) { + getClientInstance().effectRenderer.addBlockDestroyEffects(xCoord, yCoord, zCoord, block, i); + } else { + super.addBlockDestroyEffects(world, xCoord, yCoord, zCoord, block, i); + } + } - @Override - public void addBlockPlaceEffects(World world, int xCoord, int yCoord, int zCoord, Block block, int i) { - if (world.isRemote) { - playBlockPlaceSoundFX(world, xCoord, yCoord, zCoord, block); - } else { - super.addBlockPlaceEffects(world, xCoord, yCoord, zCoord, block, i); - } - } + @Override + public void addBlockPlaceEffects(World world, int xCoord, int yCoord, int zCoord, Block block, int i) { + if (world.isRemote) { + playBlockPlaceSoundFX(world, xCoord, yCoord, zCoord, block); + } else { + super.addBlockPlaceEffects(world, xCoord, yCoord, zCoord, block, i); + } + } - @Override - public EntityPlayer getPlayer() { - return Minecraft.getMinecraft().thePlayer; - } + @Override + public EntityPlayer getPlayer() { + return Minecraft.getMinecraft().thePlayer; + } } diff --git a/src/main/java/forestry/core/proxy/ProxyNetwork.java b/src/main/java/forestry/core/proxy/ProxyNetwork.java index 483e0434a..dd6cf3ca2 100755 --- a/src/main/java/forestry/core/proxy/ProxyNetwork.java +++ b/src/main/java/forestry/core/proxy/ProxyNetwork.java @@ -10,58 +10,55 @@ ******************************************************************************/ package forestry.core.proxy; +import forestry.Forestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.ILocatedPacket; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.management.PlayerManager; import net.minecraft.world.World; import net.minecraft.world.WorldServer; - import net.minecraftforge.common.util.FakePlayer; -import forestry.Forestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.ILocatedPacket; - public class ProxyNetwork { - public

void sendNetworkPacket(P packet, World world) { - if (packet == null || !(world instanceof WorldServer)) { - return; - } + public

void sendNetworkPacket(P packet, World world) { + if (packet == null || !(world instanceof WorldServer)) { + return; + } - WorldServer worldServer = (WorldServer) world; - PlayerManager playerManager = worldServer.getPlayerManager(); + WorldServer worldServer = (WorldServer) world; + PlayerManager playerManager = worldServer.getPlayerManager(); - int chunkX = packet.getPosX() >> 4; - int chunkZ = packet.getPosZ() >> 4; + int chunkX = packet.getPosX() >> 4; + int chunkZ = packet.getPosZ() >> 4; - for (Object playerObj : world.playerEntities) { - if (playerObj instanceof EntityPlayerMP) { - EntityPlayerMP player = (EntityPlayerMP) playerObj; + for (Object playerObj : world.playerEntities) { + if (playerObj instanceof EntityPlayerMP) { + EntityPlayerMP player = (EntityPlayerMP) playerObj; - if (playerManager.isPlayerWatchingChunk(player, chunkX, chunkZ)) { - sendToPlayer(packet, player); - } - } - } - } + if (playerManager.isPlayerWatchingChunk(player, chunkX, chunkZ)) { + sendToPlayer(packet, player); + } + } + } + } - public void sendToPlayer(IForestryPacketClient packet, EntityPlayer entityplayer) { - if (!(entityplayer instanceof EntityPlayerMP) || (entityplayer instanceof FakePlayer)) { - return; - } + public void sendToPlayer(IForestryPacketClient packet, EntityPlayer entityplayer) { + if (!(entityplayer instanceof EntityPlayerMP) || (entityplayer instanceof FakePlayer)) { + return; + } - EntityPlayerMP player = (EntityPlayerMP) entityplayer; - Forestry.packetHandler.sendPacket(packet.getPacket(), player); - } + EntityPlayerMP player = (EntityPlayerMP) entityplayer; + Forestry.packetHandler.sendPacket(packet.getPacket(), player); + } - public void sendToServer(IForestryPacketServer packet) { - } + public void sendToServer(IForestryPacketServer packet) {} - public void inventoryChangeNotify(EntityPlayer player) { - if (player instanceof EntityPlayerMP) { - ((EntityPlayerMP) player).sendContainerToPlayer(player.inventoryContainer); - } - } + public void inventoryChangeNotify(EntityPlayer player) { + if (player instanceof EntityPlayerMP) { + ((EntityPlayerMP) player).sendContainerToPlayer(player.inventoryContainer); + } + } } diff --git a/src/main/java/forestry/core/proxy/ProxyNetworkClient.java b/src/main/java/forestry/core/proxy/ProxyNetworkClient.java index 34846f2dc..dba4b6dfc 100644 --- a/src/main/java/forestry/core/proxy/ProxyNetworkClient.java +++ b/src/main/java/forestry/core/proxy/ProxyNetworkClient.java @@ -10,17 +10,16 @@ ******************************************************************************/ package forestry.core.proxy; -import net.minecraft.client.network.NetHandlerPlayClient; - import forestry.core.network.IForestryPacketServer; +import net.minecraft.client.network.NetHandlerPlayClient; public class ProxyNetworkClient extends ProxyNetwork { - @Override - public void sendToServer(IForestryPacketServer packet) { - NetHandlerPlayClient netHandler = Proxies.common.getClientInstance().getNetHandler(); - if (netHandler != null) { - netHandler.addToSendQueue(packet.getPacket()); - } - } + @Override + public void sendToServer(IForestryPacketServer packet) { + NetHandlerPlayClient netHandler = Proxies.common.getClientInstance().getNetHandler(); + if (netHandler != null) { + netHandler.addToSendQueue(packet.getPacket()); + } + } } diff --git a/src/main/java/forestry/core/proxy/ProxyRender.java b/src/main/java/forestry/core/proxy/ProxyRender.java index 8b5e005c9..8c632d56d 100755 --- a/src/main/java/forestry/core/proxy/ProxyRender.java +++ b/src/main/java/forestry/core/proxy/ProxyRender.java @@ -10,93 +10,80 @@ ******************************************************************************/ package forestry.core.proxy; +import forestry.core.render.IBlockRenderer; +import forestry.core.render.SpriteSheet; +import forestry.core.tiles.MachineDefinition; import net.minecraft.client.resources.IResourceManager; import net.minecraft.entity.Entity; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; -import forestry.core.render.IBlockRenderer; -import forestry.core.render.SpriteSheet; -import forestry.core.tiles.MachineDefinition; - public class ProxyRender { - public void init() { - } + public void init() {} - public int getCandleRenderId() { - return 0; - } + public int getCandleRenderId() { + return 0; + } - public int getByBlockModelRenderId() { - return 0; - } + public int getByBlockModelRenderId() { + return 0; + } - public boolean fancyGraphicsEnabled() { - return false; - } + public boolean fancyGraphicsEnabled() { + return false; + } - public boolean hasRendering() { - return false; - } + public boolean hasRendering() { + return false; + } - public void registerTESR(MachineDefinition definition) { - } + public void registerTESR(MachineDefinition definition) {} - public IBlockRenderer getRenderDefaultMachine(String gfxBase) { - return null; - } + public IBlockRenderer getRenderDefaultMachine(String gfxBase) { + return null; + } - public IBlockRenderer getRenderMill(String gfxBase) { - return null; - } + public IBlockRenderer getRenderMill(String gfxBase) { + return null; + } - public IBlockRenderer getRenderMill(String gfxBase, byte charges) { - return null; - } + public IBlockRenderer getRenderMill(String gfxBase, byte charges) { + return null; + } - public IBlockRenderer getRenderEscritoire() { - return null; - } + public IBlockRenderer getRenderEscritoire() { + return null; + } - public IBlockRenderer getRenderChest(String textureName) { - return null; - } + public IBlockRenderer getRenderChest(String textureName) { + return null; + } - public void registerVillagerSkin(int villagerId, String texturePath) { - } + public void registerVillagerSkin(int villagerId, String texturePath) {} - public void setHabitatLocatorTexture(Entity player, ChunkCoordinates coordinates) { - } + public void setHabitatLocatorTexture(Entity player, ChunkCoordinates coordinates) {} - public IResourceManager getSelectedTexturePack() { - return null; - } + public IResourceManager getSelectedTexturePack() { + return null; + } - public void bindTexture(ResourceLocation location) { - } + public void bindTexture(ResourceLocation location) {} - public void bindTexture(SpriteSheet spriteSheet) { - } + public void bindTexture(SpriteSheet spriteSheet) {} - /* FX */ + /* FX */ - public void addBeeHiveFX(String texture, World world, double d1, double d2, double d3, int color) { - } + public void addBeeHiveFX(String texture, World world, double d1, double d2, double d3, int color) {} - public void addEntitySwarmFX(World world, double d1, double d2, double d3) { - } + public void addEntitySwarmFX(World world, double d1, double d2, double d3) {} - public void addEntityExplodeFX(World world, double d1, double d2, double d3) { - } + public void addEntityExplodeFX(World world, double d1, double d2, double d3) {} - public void addEntitySnowFX(World world, double d1, double d2, double d3) { - } + public void addEntitySnowFX(World world, double d1, double d2, double d3) {} - public void addEntityIgnitionFX(World world, double d1, double d2, double d3) { - } + public void addEntityIgnitionFX(World world, double d1, double d2, double d3) {} - public void addEntityPotionFX(World world, double d1, double d2, double d3, int color) { - } + public void addEntityPotionFX(World world, double d1, double d2, double d3, int color) {} } diff --git a/src/main/java/forestry/core/proxy/ProxyRenderClient.java b/src/main/java/forestry/core/proxy/ProxyRenderClient.java index 1a4028ae6..e7797104c 100644 --- a/src/main/java/forestry/core/proxy/ProxyRenderClient.java +++ b/src/main/java/forestry/core/proxy/ProxyRenderClient.java @@ -10,22 +10,10 @@ ******************************************************************************/ package forestry.core.proxy; -import net.minecraft.client.Minecraft; -import net.minecraft.client.particle.EntityExplodeFX; -import net.minecraft.client.particle.EntityFX; -import net.minecraft.client.particle.EntitySpellParticleFX; -import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; -import net.minecraft.client.resources.IResourceManager; -import net.minecraft.entity.Entity; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.ResourceLocation; -import net.minecraft.world.World; - import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.client.registry.RenderingRegistry; import cpw.mods.fml.common.registry.VillagerRegistry; - import forestry.apiculture.entities.EntityFXBee; import forestry.apiculture.render.ParticleRenderer; import forestry.apiculture.render.RenderCandleBlock; @@ -45,183 +33,198 @@ import forestry.core.render.SpriteSheet; import forestry.core.render.TextureManager; import forestry.core.render.TileRendererIndex; import forestry.core.tiles.MachineDefinition; +import net.minecraft.client.Minecraft; +import net.minecraft.client.particle.EntityExplodeFX; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.client.particle.EntitySpellParticleFX; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.minecraft.client.resources.IResourceManager; +import net.minecraft.entity.Entity; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.World; public class ProxyRenderClient extends ProxyRender { - private int byBlockModelId; - private int candleRenderId; + private int byBlockModelId; + private int candleRenderId; - @Override - public void init() { - byBlockModelId = RenderingRegistry.getNextAvailableRenderId(); - candleRenderId = RenderingRegistry.getNextAvailableRenderId(); + @Override + public void init() { + byBlockModelId = RenderingRegistry.getNextAvailableRenderId(); + candleRenderId = RenderingRegistry.getNextAvailableRenderId(); - RenderBlock renderHandler = new RenderBlock(); - RenderingRegistry.registerBlockHandler(byBlockModelId, renderHandler); - RenderingRegistry.registerBlockHandler(candleRenderId, new RenderCandleBlock()); - } + RenderBlock renderHandler = new RenderBlock(); + RenderingRegistry.registerBlockHandler(byBlockModelId, renderHandler); + RenderingRegistry.registerBlockHandler(candleRenderId, new RenderCandleBlock()); + } - @Override - public int getCandleRenderId() { - return candleRenderId; - } + @Override + public int getCandleRenderId() { + return candleRenderId; + } - @Override - public int getByBlockModelRenderId() { - return byBlockModelId; - } + @Override + public int getByBlockModelRenderId() { + return byBlockModelId; + } - @Override - public boolean fancyGraphicsEnabled() { - return Proxies.common.getClientInstance().gameSettings.fancyGraphics; - } + @Override + public boolean fancyGraphicsEnabled() { + return Proxies.common.getClientInstance().gameSettings.fancyGraphics; + } - @Override - public boolean hasRendering() { - return true; - } + @Override + public boolean hasRendering() { + return true; + } - @Override - public void registerTESR(MachineDefinition definition) { - RenderBlock.byBlockRenderer.put(new TileRendererIndex(definition.getBlock(), definition.getMeta()), definition.renderer); - ClientRegistry.bindTileEntitySpecialRenderer(definition.teClass, (TileEntitySpecialRenderer) definition.renderer); - } + @Override + public void registerTESR(MachineDefinition definition) { + RenderBlock.byBlockRenderer.put( + new TileRendererIndex(definition.getBlock(), definition.getMeta()), definition.renderer); + ClientRegistry.bindTileEntitySpecialRenderer( + definition.teClass, (TileEntitySpecialRenderer) definition.renderer); + } - @Override - public IBlockRenderer getRenderDefaultMachine(String gfxBase) { - if (gfxBase == null) { - return null; - } - return new RenderMachine(gfxBase); - } + @Override + public IBlockRenderer getRenderDefaultMachine(String gfxBase) { + if (gfxBase == null) { + return null; + } + return new RenderMachine(gfxBase); + } - @Override - public IBlockRenderer getRenderMill(String gfxBase) { - return new RenderMill(gfxBase); - } + @Override + public IBlockRenderer getRenderMill(String gfxBase) { + return new RenderMill(gfxBase); + } - @Override - public IBlockRenderer getRenderMill(String gfxBase, byte charges) { - return new RenderMill(gfxBase, charges); - } + @Override + public IBlockRenderer getRenderMill(String gfxBase, byte charges) { + return new RenderMill(gfxBase, charges); + } - @Override - public IBlockRenderer getRenderEscritoire() { - return new RenderEscritoire(); - } + @Override + public IBlockRenderer getRenderEscritoire() { + return new RenderEscritoire(); + } - @Override - public IBlockRenderer getRenderChest(String textureName) { - return new RenderNaturalistChest(textureName); - } + @Override + public IBlockRenderer getRenderChest(String textureName) { + return new RenderNaturalistChest(textureName); + } - @Override - public void registerVillagerSkin(int villagerId, String texturePath) { - VillagerRegistry.instance().registerVillagerSkin(villagerId, new ForestryResource(texturePath)); - } + @Override + public void registerVillagerSkin(int villagerId, String texturePath) { + VillagerRegistry.instance().registerVillagerSkin(villagerId, new ForestryResource(texturePath)); + } - @Override - public void setHabitatLocatorTexture(Entity player, ChunkCoordinates coordinates) { - TextureHabitatLocator.getInstance().setTargetCoordinates(coordinates); - } + @Override + public void setHabitatLocatorTexture(Entity player, ChunkCoordinates coordinates) { + TextureHabitatLocator.getInstance().setTargetCoordinates(coordinates); + } - @Override - public IResourceManager getSelectedTexturePack() { - return Proxies.common.getClientInstance().getResourceManager(); - } + @Override + public IResourceManager getSelectedTexturePack() { + return Proxies.common.getClientInstance().getResourceManager(); + } - @Override - public void bindTexture(ResourceLocation location) { - Proxies.common.getClientInstance().getTextureManager().bindTexture(location); - } + @Override + public void bindTexture(ResourceLocation location) { + Proxies.common.getClientInstance().getTextureManager().bindTexture(location); + } - @Override - public void bindTexture(SpriteSheet spriteSheet) { - bindTexture(spriteSheet.getLocation()); - } + @Override + public void bindTexture(SpriteSheet spriteSheet) { + bindTexture(spriteSheet.getLocation()); + } - public static boolean shouldSpawnParticle(World world) { - if (!Config.enableParticleFX) { - return false; - } + public static boolean shouldSpawnParticle(World world) { + if (!Config.enableParticleFX) { + return false; + } - Minecraft mc = FMLClientHandler.instance().getClient(); - int particleSetting = mc.gameSettings.particleSetting; + Minecraft mc = FMLClientHandler.instance().getClient(); + int particleSetting = mc.gameSettings.particleSetting; - // minimal - if (particleSetting == 2) { - return world.rand.nextInt(10) == 0; - } + // minimal + if (particleSetting == 2) { + return world.rand.nextInt(10) == 0; + } - // decreased - if (particleSetting == 1) { - return world.rand.nextInt(3) != 0; - } + // decreased + if (particleSetting == 1) { + return world.rand.nextInt(3) != 0; + } - // all - return true; - } + // all + return true; + } - @Override - public void addBeeHiveFX(String icon, World world, double d1, double d2, double d3, int color) { - if (!shouldSpawnParticle(world)) { - return; - } + @Override + public void addBeeHiveFX(String icon, World world, double d1, double d2, double d3, int color) { + if (!shouldSpawnParticle(world)) { + return; + } - EntityFX fx = new EntityFXBee(world, d1, d2, d3, color); - fx.setParticleIcon(TextureManager.getInstance().getDefault(icon)); - ParticleRenderer.getInstance().addEffect(fx); - } + EntityFX fx = new EntityFXBee(world, d1, d2, d3, color); + fx.setParticleIcon(TextureManager.getInstance().getDefault(icon)); + ParticleRenderer.getInstance().addEffect(fx); + } - @Override - public void addEntitySwarmFX(World world, double d1, double d2, double d3) { - if (!shouldSpawnParticle(world)) { - return; - } + @Override + public void addEntitySwarmFX(World world, double d1, double d2, double d3) { + if (!shouldSpawnParticle(world)) { + return; + } - Proxies.common.getClientInstance().effectRenderer.addEffect(new EntityFXHoneydust(world, d1, d2, d3, 0, 0, 0)); - } + Proxies.common.getClientInstance().effectRenderer.addEffect(new EntityFXHoneydust(world, d1, d2, d3, 0, 0, 0)); + } - @Override - public void addEntityExplodeFX(World world, double d1, double d2, double d3) { - if (!shouldSpawnParticle(world)) { - return; - } + @Override + public void addEntityExplodeFX(World world, double d1, double d2, double d3) { + if (!shouldSpawnParticle(world)) { + return; + } - Proxies.common.getClientInstance().effectRenderer.addEffect(new EntityExplodeFX(world, d1, d2, d3, 0, 0, 0)); - } + Proxies.common.getClientInstance().effectRenderer.addEffect(new EntityExplodeFX(world, d1, d2, d3, 0, 0, 0)); + } - @Override - public void addEntitySnowFX(World world, double d1, double d2, double d3) { - if (!shouldSpawnParticle(world)) { - return; - } + @Override + public void addEntitySnowFX(World world, double d1, double d2, double d3) { + if (!shouldSpawnParticle(world)) { + return; + } - Proxies.common.getClientInstance().effectRenderer.addEffect(new EntityFXSnow(world, d1 + world.rand.nextGaussian(), d2, d3 + world.rand.nextGaussian())); - } + Proxies.common + .getClientInstance() + .effectRenderer + .addEffect(new EntityFXSnow(world, d1 + world.rand.nextGaussian(), d2, d3 + world.rand.nextGaussian())); + } - @Override - public void addEntityIgnitionFX(World world, double d1, double d2, double d3) { - if (!shouldSpawnParticle(world)) { - return; - } + @Override + public void addEntityIgnitionFX(World world, double d1, double d2, double d3) { + if (!shouldSpawnParticle(world)) { + return; + } - Proxies.common.getClientInstance().effectRenderer.addEffect(new EntityFXIgnition(world, d1, d2, d3)); - } + Proxies.common.getClientInstance().effectRenderer.addEffect(new EntityFXIgnition(world, d1, d2, d3)); + } - @Override - public void addEntityPotionFX(World world, double d1, double d2, double d3, int color) { - if (!shouldSpawnParticle(world)) { - return; - } + @Override + public void addEntityPotionFX(World world, double d1, double d2, double d3, int color) { + if (!shouldSpawnParticle(world)) { + return; + } - float red = (color >> 16 & 255) / 255.0F; - float green = (color >> 8 & 255) / 255.0F; - float blue = (color & 255) / 255.0F; + float red = (color >> 16 & 255) / 255.0F; + float green = (color >> 8 & 255) / 255.0F; + float blue = (color & 255) / 255.0F; - EntityFX entityfx = new EntitySpellParticleFX(world, d1, d2, d3, 0, 0, 0); - entityfx.setRBGColorF(red, green, blue); + EntityFX entityfx = new EntitySpellParticleFX(world, d1, d2, d3, 0, 0, 0); + entityfx.setRBGColorF(red, green, blue); - Proxies.common.getClientInstance().effectRenderer.addEffect(entityfx); - } + Proxies.common.getClientInstance().effectRenderer.addEffect(entityfx); + } } diff --git a/src/main/java/forestry/core/recipes/RecipeUtil.java b/src/main/java/forestry/core/recipes/RecipeUtil.java index edd029665..8096f9be7 100644 --- a/src/main/java/forestry/core/recipes/RecipeUtil.java +++ b/src/main/java/forestry/core/recipes/RecipeUtil.java @@ -10,24 +10,7 @@ ******************************************************************************/ package forestry.core.recipes; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.CraftingManager; -import net.minecraft.item.crafting.IRecipe; -import net.minecraft.world.World; - -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.oredict.OreDictionary; -import net.minecraftforge.oredict.ShapelessOreRecipe; - import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.recipes.IDescriptiveRecipe; import forestry.api.recipes.RecipeManagers; import forestry.core.config.Config; @@ -35,368 +18,400 @@ import forestry.core.fluids.Fluids; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.Log; import forestry.factory.inventory.InventoryCraftingForestry; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.world.World; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.oredict.OreDictionary; +import net.minecraftforge.oredict.ShapelessOreRecipe; public abstract class RecipeUtil { static List cachedRecipes = new ArrayList(); - public static void addFermenterRecipes(ItemStack resource, int fermentationValue, Fluids output) { - if (RecipeManagers.fermenterManager == null) { - return; - } - RecipeManagers.fermenterManager.addRecipe(resource, fermentationValue, 1.0f, output.getFluid(1), Fluids.WATER.getFluid(1)); + public static void addFermenterRecipes(ItemStack resource, int fermentationValue, Fluids output) { + if (RecipeManagers.fermenterManager == null) { + return; + } - if (FluidRegistry.isFluidRegistered(Fluids.JUICE.getFluid())) { - RecipeManagers.fermenterManager.addRecipe(resource, fermentationValue, 1.5f, output.getFluid(1), Fluids.JUICE.getFluid(1)); - } + RecipeManagers.fermenterManager.addRecipe( + resource, fermentationValue, 1.0f, output.getFluid(1), Fluids.WATER.getFluid(1)); - if (FluidRegistry.isFluidRegistered(Fluids.HONEY.getFluid())) { - RecipeManagers.fermenterManager.addRecipe(resource, fermentationValue, 1.5f, output.getFluid(1), Fluids.HONEY.getFluid(1)); - } - } + if (FluidRegistry.isFluidRegistered(Fluids.JUICE.getFluid())) { + RecipeManagers.fermenterManager.addRecipe( + resource, fermentationValue, 1.5f, output.getFluid(1), Fluids.JUICE.getFluid(1)); + } - /** - * Returns a list of the ore dictionary names if they exist. - * Returns a list containing itemStack if there are no ore dictionary names. - * Used for creating recipes that should accept equivalent itemStacks, based on the ore dictionary. - */ - public static List getOreDictRecipeEquivalents(ItemStack itemStack) { - int[] oreDictIds = OreDictionary.getOreIDs(itemStack); - List oreDictNames = new ArrayList<>(oreDictIds.length); - for (int oreId : oreDictIds) { - String oreDictName = OreDictionary.getOreName(oreId); - oreDictNames.add(oreDictName); - } - if (oreDictNames.isEmpty()) { - return Collections.singletonList(itemStack); - } - return oreDictNames; - } + if (FluidRegistry.isFluidRegistered(Fluids.HONEY.getFluid())) { + RecipeManagers.fermenterManager.addRecipe( + resource, fermentationValue, 1.5f, output.getFluid(1), Fluids.HONEY.getFluid(1)); + } + } - public static Object[] getCraftingRecipeAsArray(IDescriptiveRecipe recipe) { + /** + * Returns a list of the ore dictionary names if they exist. + * Returns a list containing itemStack if there are no ore dictionary names. + * Used for creating recipes that should accept equivalent itemStacks, based on the ore dictionary. + */ + public static List getOreDictRecipeEquivalents(ItemStack itemStack) { + int[] oreDictIds = OreDictionary.getOreIDs(itemStack); + List oreDictNames = new ArrayList<>(oreDictIds.length); + for (int oreId : oreDictIds) { + String oreDictName = OreDictionary.getOreName(oreId); + oreDictNames.add(oreDictName); + } + if (oreDictNames.isEmpty()) { + return Collections.singletonList(itemStack); + } + return oreDictNames; + } - try { - return getShapedRecipeAsArray(recipe.getWidth(), recipe.getHeight(), recipe.getIngredients(), recipe.getRecipeOutput()); - } catch (Exception ex) { - Log.warning("Exception while trying to parse an ItemStack[10] from an IRecipe:"); - Log.warning(ex.getMessage()); - } + public static Object[] getCraftingRecipeAsArray(IDescriptiveRecipe recipe) { - return null; - } + try { + return getShapedRecipeAsArray( + recipe.getWidth(), recipe.getHeight(), recipe.getIngredients(), recipe.getRecipeOutput()); + } catch (Exception ex) { + Log.warning("Exception while trying to parse an ItemStack[10] from an IRecipe:"); + Log.warning(ex.getMessage()); + } - private static Object[] getShapedRecipeAsArray(int width, int height, Object[] ingredients, ItemStack output) { - Object[] result = new Object[10]; + return null; + } - for (int y = 0; y < height; y++) { - System.arraycopy(ingredients, y * width, result, y * 3, width); - } + private static Object[] getShapedRecipeAsArray(int width, int height, Object[] ingredients, ItemStack output) { + Object[] result = new Object[10]; - result[9] = output; - return result; - } + for (int y = 0; y < height; y++) { + System.arraycopy(ingredients, y * width, result, y * 3, width); + } - public static InventoryCraftingForestry getCraftRecipe(ItemStack[] recipeItems, ItemStack[] availableItems, World world, ItemStack recipeOutput) { - // Need at least one matched set - if (ItemStackUtil.containsSets(recipeItems, availableItems, true, true) == 0) { - return null; - } - // Check that it doesn't make a different recipe. - // For example: - // Wood Logs are all ore dictionary equivalent with each other, - // but an Oak Log shouldn't be able to make Ebony Wood Planks - // because it makes Oak Wood Planks using the same recipe. - // Strategy: - // Create a fake crafting inventory using items we have in availableItems - // in place of the ones in the saved crafting inventory. - // Check that the recipe it makes is the same as the currentRecipe. - InventoryCraftingForestry crafting = new InventoryCraftingForestry(); - final ItemStack[] ingregients = RecipeUtil.getCraftIngredients(recipeItems, availableItems); + result[9] = output; + return result; + } - for (int slot = 0; slot < ingregients.length; slot++) { - ItemStack recipeStack = ingregients[slot]; + public static InventoryCraftingForestry getCraftRecipe( + ItemStack[] recipeItems, ItemStack[] availableItems, World world, ItemStack recipeOutput) { + // Need at least one matched set + if (ItemStackUtil.containsSets(recipeItems, availableItems, true, true) == 0) { + return null; + } + // Check that it doesn't make a different recipe. + // For example: + // Wood Logs are all ore dictionary equivalent with each other, + // but an Oak Log shouldn't be able to make Ebony Wood Planks + // because it makes Oak Wood Planks using the same recipe. + // Strategy: + // Create a fake crafting inventory using items we have in availableItems + // in place of the ones in the saved crafting inventory. + // Check that the recipe it makes is the same as the currentRecipe. + InventoryCraftingForestry crafting = new InventoryCraftingForestry(); + final ItemStack[] ingregients = RecipeUtil.getCraftIngredients(recipeItems, availableItems); - if (recipeStack == null && recipeItems[slot] != null) { - return null; - } + for (int slot = 0; slot < ingregients.length; slot++) { + ItemStack recipeStack = ingregients[slot]; - if (recipeStack == null) { - continue; - } + if (recipeStack == null && recipeItems[slot] != null) { + return null; + } - crafting.setInventorySlotContents(slot, recipeStack); - } + if (recipeStack == null) { + continue; + } - List outputs = findMatchingRecipes(crafting, world); - if (!ItemStackUtil.containsItemStack(outputs, recipeOutput)) { - return null; - } - return crafting; - } + crafting.setInventorySlotContents(slot, recipeStack); + } - public static ItemStack[] getCraftIngredients(ItemStack[] recipeItems, ItemStack[] availableItems) - { - final ItemStack[] stockCopy = ItemStackUtil.condenseStacks(availableItems); - final ItemStack[] ingredients = new ItemStack[recipeItems.length]; + List outputs = findMatchingRecipes(crafting, world); + if (!ItemStackUtil.containsItemStack(outputs, recipeOutput)) { + return null; + } + return crafting; + } - for (int slot = 0; slot < recipeItems.length; slot++) { - ItemStack recipeStack = recipeItems[slot]; + public static ItemStack[] getCraftIngredients(ItemStack[] recipeItems, ItemStack[] availableItems) { + final ItemStack[] stockCopy = ItemStackUtil.condenseStacks(availableItems); + final ItemStack[] ingredients = new ItemStack[recipeItems.length]; - if (recipeStack == null) { - continue; - } + for (int slot = 0; slot < recipeItems.length; slot++) { + ItemStack recipeStack = recipeItems[slot]; - // Use crafting equivalent (not oredict) items first - for (ItemStack stockStack : stockCopy) { - if (stockStack.stackSize > 0 && ItemStackUtil.isCraftingEquivalent(recipeStack, stockStack, false, false)) { - ingredients[slot] = ItemStackUtil.createSplitStack(stockStack, 1); - stockStack.stackSize--; - break; - } - } + if (recipeStack == null) { + continue; + } - // Use oredict items if crafting equivalent items aren't available - if (ingredients[slot] == null) { - for (ItemStack stockStack : stockCopy) { - if (stockStack.stackSize > 0 && ItemStackUtil.isCraftingEquivalent(recipeStack, stockStack, true, true)) { - ingredients[slot] = ItemStackUtil.createSplitStack(stockStack, 1); - stockStack.stackSize--; - break; - } - } - } + // Use crafting equivalent (not oredict) items first + for (ItemStack stockStack : stockCopy) { + if (stockStack.stackSize > 0 + && ItemStackUtil.isCraftingEquivalent(recipeStack, stockStack, false, false)) { + ingredients[slot] = ItemStackUtil.createSplitStack(stockStack, 1); + stockStack.stackSize--; + break; + } + } - } + // Use oredict items if crafting equivalent items aren't available + if (ingredients[slot] == null) { + for (ItemStack stockStack : stockCopy) { + if (stockStack.stackSize > 0 + && ItemStackUtil.isCraftingEquivalent(recipeStack, stockStack, true, true)) { + ingredients[slot] = ItemStackUtil.createSplitStack(stockStack, 1); + stockStack.stackSize--; + break; + } + } + } + } - return ingredients; - } + return ingredients; + } - public static List findMatchingRecipes(InventoryCrafting inventory, World world) { - ItemStack repairRecipe = findRepairRecipe(inventory); - if (repairRecipe != null) { - return Collections.singletonList(repairRecipe); - } + public static List findMatchingRecipes(InventoryCrafting inventory, World world) { + ItemStack repairRecipe = findRepairRecipe(inventory); + if (repairRecipe != null) { + return Collections.singletonList(repairRecipe); + } - List matchingRecipes = new ArrayList<>(); - List matchingIndex=new ArrayList(); + List matchingRecipes = new ArrayList<>(); + List matchingIndex = new ArrayList(); List matchingRecipeMap = new ArrayList(); int index = 0; - if(Config.cacheWorktableRecipes) { + if (Config.cacheWorktableRecipes) { // Check across the whole cached recipe map // Add each recipe to the matchingRecipes list for (Object recipe : cachedRecipes) { - IRecipe irecipe = (IRecipe) recipe; + IRecipe irecipe = (IRecipe) recipe; - if (irecipe.matches(inventory, world)) { - ItemStack result = irecipe.getCraftingResult(inventory); - if (!ItemStackUtil.containsItemStack(matchingRecipes, result)) { - matchingRecipes.add(result); - } - } + if (irecipe.matches(inventory, world)) { + ItemStack result = irecipe.getCraftingResult(inventory); + if (!ItemStackUtil.containsItemStack(matchingRecipes, result)) { + matchingRecipes.add(result); + } + } } - if( matchingRecipes.size() > 0 ) { + if (matchingRecipes.size() > 0) { // If we found recipes here, we found all the potential recipes, so we can just return immediately. return matchingRecipes; } } // Only do this if there were no cached recipes hit - for (Object recipe : CraftingManager.getInstance().getRecipeList()) { - IRecipe irecipe = (IRecipe) recipe; + for (Object recipe : CraftingManager.getInstance().getRecipeList()) { + IRecipe irecipe = (IRecipe) recipe; - if (irecipe.matches(inventory, world)) { - ItemStack result = irecipe.getCraftingResult(inventory); - if (!ItemStackUtil.containsItemStack(matchingRecipes, result)) { - matchingRecipes.add(result); - if(Config.promoteWorktableRecipesToFrontOfGlobalRecipemap || Config.cacheWorktableRecipes) { + if (irecipe.matches(inventory, world)) { + ItemStack result = irecipe.getCraftingResult(inventory); + if (!ItemStackUtil.containsItemStack(matchingRecipes, result)) { + matchingRecipes.add(result); + if (Config.promoteWorktableRecipesToFrontOfGlobalRecipemap || Config.cacheWorktableRecipes) { // Add to the back of the list. That way when we cycle through the list // moving items to the front, the index locations for the following items doesn't change matchingRecipeMap.add(recipe); matchingIndex.add(new Integer(index)); } - } - } + } + } index++; - } - if (matchingRecipeMap.size() > 0 ) - { + } + if (matchingRecipeMap.size() > 0) { if (Config.promoteWorktableRecipesToFrontOfGlobalRecipemap) { // Only move the recipes if the last one was beyond 500 in the recipeMap (in GTNH about 57k recipes) - if (matchingIndex.get(matchingIndex.size()-1) > 500) { + if (matchingIndex.get(matchingIndex.size() - 1) > 500) { List recipeMap = CraftingManager.getInstance().getRecipeList(); - // System.out.println( "Highest recipe found at " + matchingIndex.get(matchingIndex.size()-1) + ", moving " + matchingIndex.size() + " to front" ); + // System.out.println( "Highest recipe found at " + matchingIndex.get(matchingIndex.size()-1) + ", + // moving " + matchingIndex.size() + " to front" ); // System.out.println( "Size of recipe map " + recipeMap.size() ); - for (index = 0; index < matchingIndex.size(); index++) { // index is reused here, it goes through the matching groups. + for (index = 0; + index < matchingIndex.size(); + index++) { // index is reused here, it goes through the matching groups. // Remove recipe and add back at the front int target = matchingIndex.get(index); // remove requires int // System.out.println("Removing recipe at " + target); recipeMap.remove(target); - recipeMap.add(0,matchingRecipeMap.get(index)); + recipeMap.add(0, matchingRecipeMap.get(index)); } } } - if(Config.cacheWorktableRecipes) { + if (Config.cacheWorktableRecipes) { // However, we should always add found recipes the cached recipe map // Location doesn't matter since we have to scan the whole cached recipe map anyways. cachedRecipes.addAll(matchingRecipeMap); } } - return matchingRecipes; - } + return matchingRecipes; + } - private static ItemStack findRepairRecipe(InventoryCrafting inventory) { - int craftIngredientCount = 0; - ItemStack itemstack0 = null; - ItemStack itemstack1 = null; + private static ItemStack findRepairRecipe(InventoryCrafting inventory) { + int craftIngredientCount = 0; + ItemStack itemstack0 = null; + ItemStack itemstack1 = null; - for (int j = 0; j < inventory.getSizeInventory(); j++) { - ItemStack itemstack = inventory.getStackInSlot(j); + for (int j = 0; j < inventory.getSizeInventory(); j++) { + ItemStack itemstack = inventory.getStackInSlot(j); - if (itemstack != null) { - if (craftIngredientCount == 0) { - itemstack0 = itemstack; - } + if (itemstack != null) { + if (craftIngredientCount == 0) { + itemstack0 = itemstack; + } - if (craftIngredientCount == 1) { - itemstack1 = itemstack; - } + if (craftIngredientCount == 1) { + itemstack1 = itemstack; + } - ++craftIngredientCount; - } - } + ++craftIngredientCount; + } + } - if (craftIngredientCount == 2 && itemstack0.getItem() == itemstack1.getItem() && itemstack0.stackSize == 1 && itemstack1.stackSize == 1 && itemstack0.getItem().isRepairable()) { - Item item = itemstack0.getItem(); - int damage0 = item.getMaxDamage() - itemstack0.getItemDamageForDisplay(); - int damage1 = item.getMaxDamage() - itemstack1.getItemDamageForDisplay(); - int repairAmount = damage0 + damage1 + item.getMaxDamage() * 5 / 100; - int repairedDamage = item.getMaxDamage() - repairAmount; + if (craftIngredientCount == 2 + && itemstack0.getItem() == itemstack1.getItem() + && itemstack0.stackSize == 1 + && itemstack1.stackSize == 1 + && itemstack0.getItem().isRepairable()) { + Item item = itemstack0.getItem(); + int damage0 = item.getMaxDamage() - itemstack0.getItemDamageForDisplay(); + int damage1 = item.getMaxDamage() - itemstack1.getItemDamageForDisplay(); + int repairAmount = damage0 + damage1 + item.getMaxDamage() * 5 / 100; + int repairedDamage = item.getMaxDamage() - repairAmount; - if (repairedDamage < 0) { - repairedDamage = 0; - } + if (repairedDamage < 0) { + repairedDamage = 0; + } - return new ItemStack(itemstack0.getItem(), 1, repairedDamage); - } + return new ItemStack(itemstack0.getItem(), 1, repairedDamage); + } - return null; - } + return null; + } - public static void addRecipe(Item item, Object... obj) { - addRecipe(new ItemStack(item), obj); - } + public static void addRecipe(Item item, Object... obj) { + addRecipe(new ItemStack(item), obj); + } - @SuppressWarnings("unchecked") - public static void addRecipe(ItemStack itemstack, Object... obj) { - CraftingManager.getInstance().getRecipeList().add(new ShapedRecipeCustom(itemstack, obj)); - } + @SuppressWarnings("unchecked") + public static void addRecipe(ItemStack itemstack, Object... obj) { + CraftingManager.getInstance().getRecipeList().add(new ShapedRecipeCustom(itemstack, obj)); + } - @SuppressWarnings("unchecked") - public static void addPriorityRecipe(ItemStack itemStack, Object... obj) { - CraftingManager.getInstance().getRecipeList().add(0, new ShapedRecipeCustom(itemStack, obj)); - } + @SuppressWarnings("unchecked") + public static void addPriorityRecipe(ItemStack itemStack, Object... obj) { + CraftingManager.getInstance().getRecipeList().add(0, new ShapedRecipeCustom(itemStack, obj)); + } - public static void addShapelessRecipe(Item item, Object... obj) { - addShapelessRecipe(new ItemStack(item), obj); - } + public static void addShapelessRecipe(Item item, Object... obj) { + addShapelessRecipe(new ItemStack(item), obj); + } - @SuppressWarnings("unchecked") - public static void addShapelessRecipe(ItemStack itemstack, Object... obj) { - CraftingManager.getInstance().getRecipeList().add(new ShapelessOreRecipe(itemstack, obj)); - } + @SuppressWarnings("unchecked") + public static void addShapelessRecipe(ItemStack itemstack, Object... obj) { + CraftingManager.getInstance().getRecipeList().add(new ShapelessOreRecipe(itemstack, obj)); + } - public static void addSmelting(ItemStack res, Item prod, float xp) { - addSmelting(res, new ItemStack(prod), xp); - } + public static void addSmelting(ItemStack res, Item prod, float xp) { + addSmelting(res, new ItemStack(prod), xp); + } - public static void addSmelting(ItemStack res, ItemStack prod, float xp) { - if (res == null || res.getItem() == null) { - throw new IllegalArgumentException("Tried to register smelting recipe with null input"); - } - if (prod == null || prod.getItem() == null) { - throw new IllegalArgumentException("Tried to register smelting recipe with null output"); - } - GameRegistry.addSmelting(res, prod, xp); - } + public static void addSmelting(ItemStack res, ItemStack prod, float xp) { + if (res == null || res.getItem() == null) { + throw new IllegalArgumentException("Tried to register smelting recipe with null input"); + } + if (prod == null || prod.getItem() == null) { + throw new IllegalArgumentException("Tried to register smelting recipe with null output"); + } + GameRegistry.addSmelting(res, prod, xp); + } - public static boolean matches(IDescriptiveRecipe recipe, IInventory inventoryCrafting) { - Object[] recipeIngredients = recipe.getIngredients(); - int width = recipe.getWidth(); - int height = recipe.getHeight(); - return matches(recipeIngredients, width, height, inventoryCrafting); - } + public static boolean matches(IDescriptiveRecipe recipe, IInventory inventoryCrafting) { + Object[] recipeIngredients = recipe.getIngredients(); + int width = recipe.getWidth(); + int height = recipe.getHeight(); + return matches(recipeIngredients, width, height, inventoryCrafting); + } - public static boolean matches(Object[] recipeIngredients, int width, int height, IInventory inventoryCrafting) { - ItemStack[][] resources = getResources(inventoryCrafting); - return matches(recipeIngredients, width, height, resources); - } + public static boolean matches(Object[] recipeIngredients, int width, int height, IInventory inventoryCrafting) { + ItemStack[][] resources = getResources(inventoryCrafting); + return matches(recipeIngredients, width, height, resources); + } - public static ItemStack[][] getResources(IInventory inventoryCrafting) { - ItemStack[][] resources = new ItemStack[3][3]; - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - int k = i + j * 3; - resources[i][j] = inventoryCrafting.getStackInSlot(k); - } - } - return resources; - } + public static ItemStack[][] getResources(IInventory inventoryCrafting) { + ItemStack[][] resources = new ItemStack[3][3]; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + int k = i + j * 3; + resources[i][j] = inventoryCrafting.getStackInSlot(k); + } + } + return resources; + } - public static boolean matches(Object[] recipeIngredients, int width, int height, ItemStack[][] resources) { - for (int i = 0; i <= 3 - width; i++) { - for (int j = 0; j <= 3 - height; j++) { - if (checkMatch(recipeIngredients, width, height, resources, i, j, true)) { - return true; - } + public static boolean matches(Object[] recipeIngredients, int width, int height, ItemStack[][] resources) { + for (int i = 0; i <= 3 - width; i++) { + for (int j = 0; j <= 3 - height; j++) { + if (checkMatch(recipeIngredients, width, height, resources, i, j, true)) { + return true; + } - if (checkMatch(recipeIngredients, width, height, resources, i, j, false)) { - return true; - } - } - } + if (checkMatch(recipeIngredients, width, height, resources, i, j, false)) { + return true; + } + } + } - return false; - } + return false; + } - private static boolean checkMatch(Object[] recipeIngredients, int width, int height, ItemStack[][] resources, int xInGrid, int yInGrid, boolean mirror) { - for (int k = 0; k < 3; k++) { - for (int l = 0; l < 3; l++) { - ItemStack resource = resources[k][l]; + private static boolean checkMatch( + Object[] recipeIngredients, + int width, + int height, + ItemStack[][] resources, + int xInGrid, + int yInGrid, + boolean mirror) { + for (int k = 0; k < 3; k++) { + for (int l = 0; l < 3; l++) { + ItemStack resource = resources[k][l]; - int widthIt = k - xInGrid; - int heightIt = l - yInGrid; - Object recipeIngredient = null; + int widthIt = k - xInGrid; + int heightIt = l - yInGrid; + Object recipeIngredient = null; - if (widthIt >= 0 && heightIt >= 0 && widthIt < width && heightIt < height) { - if (mirror) { - recipeIngredient = recipeIngredients[(width - widthIt - 1) + heightIt * width]; - } else { - recipeIngredient = recipeIngredients[widthIt + heightIt * width]; - } - } + if (widthIt >= 0 && heightIt >= 0 && widthIt < width && heightIt < height) { + if (mirror) { + recipeIngredient = recipeIngredients[(width - widthIt - 1) + heightIt * width]; + } else { + recipeIngredient = recipeIngredients[widthIt + heightIt * width]; + } + } - if (!checkIngredientMatch(recipeIngredient, resource)) { - return false; - } - } - } + if (!checkIngredientMatch(recipeIngredient, resource)) { + return false; + } + } + } - return true; - } + return true; + } - private static boolean checkIngredientMatch(Object recipeIngredient, ItemStack resource) { - if (recipeIngredient == null && resource == null) { - return true; - } else if (recipeIngredient instanceof ItemStack) { - return ItemStackUtil.isCraftingEquivalent((ItemStack) recipeIngredient, resource); - } else if (recipeIngredient instanceof Iterable) { - for (Object item : (Iterable) recipeIngredient) { - if (checkIngredientMatch(item, resource)) { - return true; - } - } - return false; - } else { - return false; - } - } + private static boolean checkIngredientMatch(Object recipeIngredient, ItemStack resource) { + if (recipeIngredient == null && resource == null) { + return true; + } else if (recipeIngredient instanceof ItemStack) { + return ItemStackUtil.isCraftingEquivalent((ItemStack) recipeIngredient, resource); + } else if (recipeIngredient instanceof Iterable) { + for (Object item : (Iterable) recipeIngredient) { + if (checkIngredientMatch(item, resource)) { + return true; + } + } + return false; + } else { + return false; + } + } } diff --git a/src/main/java/forestry/core/recipes/ShapedRecipeCustom.java b/src/main/java/forestry/core/recipes/ShapedRecipeCustom.java index 64caf1d43..9b6afb792 100644 --- a/src/main/java/forestry/core/recipes/ShapedRecipeCustom.java +++ b/src/main/java/forestry/core/recipes/ShapedRecipeCustom.java @@ -10,194 +10,191 @@ ******************************************************************************/ package forestry.core.recipes; +import forestry.api.recipes.IDescriptiveRecipe; +import forestry.core.utils.ItemStackUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; - import net.minecraft.block.Block; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; - import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; -import forestry.api.recipes.IDescriptiveRecipe; -import forestry.core.utils.ItemStackUtil; - public class ShapedRecipeCustom extends ShapedOreRecipe implements IDescriptiveRecipe { - //Added in for future ease of change, but hard coded for now. - private static final int MAX_CRAFT_GRID_WIDTH = 3; - private static final int MAX_CRAFT_GRID_HEIGHT = 3; + // Added in for future ease of change, but hard coded for now. + private static final int MAX_CRAFT_GRID_WIDTH = 3; + private static final int MAX_CRAFT_GRID_HEIGHT = 3; - private ItemStack output = null; - private Object[] input = null; - private int width; - private int height; - private boolean mirrored = true; + private ItemStack output = null; + private Object[] input = null; + private int width; + private int height; + private boolean mirrored = true; - public ShapedRecipeCustom(ItemStack result, Object... recipe) { - super(result, recipe); - output = result.copy(); + public ShapedRecipeCustom(ItemStack result, Object... recipe) { + super(result, recipe); + output = result.copy(); - String shape = ""; - int idx = 0; + String shape = ""; + int idx = 0; - if (recipe[idx] instanceof Boolean) { - mirrored = (Boolean) recipe[idx]; - if (recipe[idx + 1] instanceof Object[]) { - recipe = (Object[]) recipe[idx + 1]; - } else { - idx = 1; - } - } + if (recipe[idx] instanceof Boolean) { + mirrored = (Boolean) recipe[idx]; + if (recipe[idx + 1] instanceof Object[]) { + recipe = (Object[]) recipe[idx + 1]; + } else { + idx = 1; + } + } - if (recipe[idx] instanceof String[]) { - String[] parts = ((String[]) recipe[idx++]); + if (recipe[idx] instanceof String[]) { + String[] parts = ((String[]) recipe[idx++]); - for (String s : parts) { - width = s.length(); - shape += s; - } + for (String s : parts) { + width = s.length(); + shape += s; + } - height = parts.length; - } else { - while (recipe[idx] instanceof String) { - String s = (String) recipe[idx++]; - shape += s; - width = s.length(); - height++; - } - } + height = parts.length; + } else { + while (recipe[idx] instanceof String) { + String s = (String) recipe[idx++]; + shape += s; + width = s.length(); + height++; + } + } - if (width * height != shape.length()) { - String ret = "Invalid shaped ore recipe: "; - for (Object tmp : recipe) { - ret += tmp + ", "; - } - ret += output; - throw new RuntimeException(ret); - } + if (width * height != shape.length()) { + String ret = "Invalid shaped ore recipe: "; + for (Object tmp : recipe) { + ret += tmp + ", "; + } + ret += output; + throw new RuntimeException(ret); + } - HashMap itemMap = new HashMap(); + HashMap itemMap = new HashMap(); - for (; idx < recipe.length; idx += 2) { - Character chr = (Character) recipe[idx]; - Object in = recipe[idx + 1]; + for (; idx < recipe.length; idx += 2) { + Character chr = (Character) recipe[idx]; + Object in = recipe[idx + 1]; - if (in instanceof ItemStack) { - itemMap.put(chr, ((ItemStack) in).copy()); - } else if (in instanceof Item) { - itemMap.put(chr, new ItemStack((Item) in)); - } else if (in instanceof Block) { - itemMap.put(chr, new ItemStack((Block) in, 1, OreDictionary.WILDCARD_VALUE)); - } else if (in instanceof String) { - itemMap.put(chr, OreDictionary.getOres((String) in)); - } else { - String ret = "Invalid shaped ore recipe: "; - for (Object tmp : recipe) { - ret += tmp + ", "; - } - ret += output; - throw new RuntimeException(ret); - } - } + if (in instanceof ItemStack) { + itemMap.put(chr, ((ItemStack) in).copy()); + } else if (in instanceof Item) { + itemMap.put(chr, new ItemStack((Item) in)); + } else if (in instanceof Block) { + itemMap.put(chr, new ItemStack((Block) in, 1, OreDictionary.WILDCARD_VALUE)); + } else if (in instanceof String) { + itemMap.put(chr, OreDictionary.getOres((String) in)); + } else { + String ret = "Invalid shaped ore recipe: "; + for (Object tmp : recipe) { + ret += tmp + ", "; + } + ret += output; + throw new RuntimeException(ret); + } + } - input = new Object[width * height]; - int x = 0; - for (char chr : shape.toCharArray()) { - input[x++] = itemMap.get(chr); - } - } + input = new Object[width * height]; + int x = 0; + for (char chr : shape.toCharArray()) { + input[x++] = itemMap.get(chr); + } + } - @Override - public int getWidth() { - return width; - } + @Override + public int getWidth() { + return width; + } - @Override - public int getHeight() { - return height; - } + @Override + public int getHeight() { + return height; + } - @Override - public Object[] getIngredients() { - return getInput(); - } + @Override + public Object[] getIngredients() { + return getInput(); + } - @Override - public boolean preserveNBT() { - return false; - } + @Override + public boolean preserveNBT() { + return false; + } - @Override - @Deprecated - public boolean matches(IInventory inventoryCrafting, World world) { - return false; - } + @Override + @Deprecated + public boolean matches(IInventory inventoryCrafting, World world) { + return false; + } - @Override - public boolean matches(InventoryCrafting inv, World world) { - for (int x = 0; x <= MAX_CRAFT_GRID_WIDTH - width; x++) { - for (int y = 0; y <= MAX_CRAFT_GRID_HEIGHT - height; ++y) { - if (checkMatch(inv, x, y, false)) { - return true; - } + @Override + public boolean matches(InventoryCrafting inv, World world) { + for (int x = 0; x <= MAX_CRAFT_GRID_WIDTH - width; x++) { + for (int y = 0; y <= MAX_CRAFT_GRID_HEIGHT - height; ++y) { + if (checkMatch(inv, x, y, false)) { + return true; + } - if (mirrored && checkMatch(inv, x, y, true)) { - return true; - } - } - } + if (mirrored && checkMatch(inv, x, y, true)) { + return true; + } + } + } - return false; - } + return false; + } - @SuppressWarnings("unchecked") - private boolean checkMatch(InventoryCrafting inv, int startX, int startY, boolean mirror) { - for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++) { - for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++) { - int subX = x - startX; - int subY = y - startY; - Object target = null; + @SuppressWarnings("unchecked") + private boolean checkMatch(InventoryCrafting inv, int startX, int startY, boolean mirror) { + for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++) { + for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++) { + int subX = x - startX; + int subY = y - startY; + Object target = null; - if (subX >= 0 && subY >= 0 && subX < width && subY < height) { - if (mirror) { - target = input[width - subX - 1 + subY * width]; - } else { - target = input[subX + subY * width]; - } - } + if (subX >= 0 && subY >= 0 && subX < width && subY < height) { + if (mirror) { + target = input[width - subX - 1 + subY * width]; + } else { + target = input[subX + subY * width]; + } + } - ItemStack slot = inv.getStackInRowAndColumn(x, y); + ItemStack slot = inv.getStackInRowAndColumn(x, y); - if (target instanceof ItemStack) { - if (!ItemStackUtil.isCraftingEquivalent((ItemStack) target, slot)) { - return false; - } - } else if (target instanceof ArrayList) { - boolean matched = false; + if (target instanceof ItemStack) { + if (!ItemStackUtil.isCraftingEquivalent((ItemStack) target, slot)) { + return false; + } + } else if (target instanceof ArrayList) { + boolean matched = false; - Iterator itr = ((ArrayList) target).iterator(); - while (itr.hasNext() && !matched) { - matched = ItemStackUtil.isCraftingEquivalent(itr.next(), slot); - } + Iterator itr = ((ArrayList) target).iterator(); + while (itr.hasNext() && !matched) { + matched = ItemStackUtil.isCraftingEquivalent(itr.next(), slot); + } - if (!matched) { - return false; - } - } else if (target == null && slot != null) { - return false; - } - } - } + if (!matched) { + return false; + } + } else if (target == null && slot != null) { + return false; + } + } + } - return true; - } + return true; + } - public static ShapedRecipeCustom createShapedRecipe(ItemStack product, Object... materials) { - return new ShapedRecipeCustom(product, materials); - } + public static ShapedRecipeCustom createShapedRecipe(ItemStack product, Object... materials) { + return new ShapedRecipeCustom(product, materials); + } } diff --git a/src/main/java/forestry/core/recipes/craftguide/CraftGuideCustomRecipes.java b/src/main/java/forestry/core/recipes/craftguide/CraftGuideCustomRecipes.java index bf825d28f..5840bd06f 100644 --- a/src/main/java/forestry/core/recipes/craftguide/CraftGuideCustomRecipes.java +++ b/src/main/java/forestry/core/recipes/craftguide/CraftGuideCustomRecipes.java @@ -10,13 +10,11 @@ ******************************************************************************/ package forestry.core.recipes.craftguide; +import forestry.api.recipes.IDescriptiveRecipe; +import forestry.core.recipes.RecipeUtil; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; - -import forestry.api.recipes.IDescriptiveRecipe; -import forestry.core.recipes.RecipeUtil; - import uristqwerty.CraftGuide.api.ItemSlot; import uristqwerty.CraftGuide.api.RecipeGenerator; import uristqwerty.CraftGuide.api.RecipeProvider; @@ -25,38 +23,37 @@ import uristqwerty.CraftGuide.api.SlotType; public class CraftGuideCustomRecipes implements RecipeProvider { - private final ItemSlot[] slots = new ItemSlot[10]; + private final ItemSlot[] slots = new ItemSlot[10]; - public CraftGuideCustomRecipes() { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - slots[i + j * 3] = new ItemSlot(i * 18 + 3, j * 18 + 3, 16, 16); - } - } - slots[9] = new ItemSlot(59, 21, 16, 16, true).setSlotType(SlotType.OUTPUT_SLOT); - } + public CraftGuideCustomRecipes() { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + slots[i + j * 3] = new ItemSlot(i * 18 + 3, j * 18 + 3, 16, 16); + } + } + slots[9] = new ItemSlot(59, 21, 16, 16, true).setSlotType(SlotType.OUTPUT_SLOT); + } - @Override - public void generateRecipes(RecipeGenerator generator) { + @Override + public void generateRecipes(RecipeGenerator generator) { - ItemStack machine = new ItemStack(Blocks.crafting_table); - RecipeTemplate template = generator.createRecipeTemplate(slots, machine, "/gui/CraftGuideRecipe.png", 1, 1, 82, 1); + ItemStack machine = new ItemStack(Blocks.crafting_table); + RecipeTemplate template = + generator.createRecipeTemplate(slots, machine, "/gui/CraftGuideRecipe.png", 1, 1, 82, 1); - for (Object rec : CraftingManager.getInstance().getRecipeList()) { - if (!(rec instanceof IDescriptiveRecipe)) { - continue; - } + for (Object rec : CraftingManager.getInstance().getRecipeList()) { + if (!(rec instanceof IDescriptiveRecipe)) { + continue; + } - Object[] array = new Object[10]; - - Object[] flattened = RecipeUtil.getCraftingRecipeAsArray((IDescriptiveRecipe) rec); - if (flattened == null) { - continue; - } - System.arraycopy(flattened, 0, array, 0, flattened.length); - generator.addRecipe(template, array); - - } - } + Object[] array = new Object[10]; + Object[] flattened = RecipeUtil.getCraftingRecipeAsArray((IDescriptiveRecipe) rec); + if (flattened == null) { + continue; + } + System.arraycopy(flattened, 0, array, 0, flattened.length); + generator.addRecipe(template, array); + } + } } diff --git a/src/main/java/forestry/core/recipes/craftguide/CraftGuideIntegration.java b/src/main/java/forestry/core/recipes/craftguide/CraftGuideIntegration.java index db9339524..98defb3f9 100644 --- a/src/main/java/forestry/core/recipes/craftguide/CraftGuideIntegration.java +++ b/src/main/java/forestry/core/recipes/craftguide/CraftGuideIntegration.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.core.recipes.craftguide; -import java.lang.reflect.Method; - import forestry.core.utils.Log; import forestry.factory.recipes.craftguide.CraftGuideBottler; import forestry.factory.recipes.craftguide.CraftGuideCarpenter; @@ -20,39 +18,39 @@ import forestry.factory.recipes.craftguide.CraftGuideFabricator; import forestry.factory.recipes.craftguide.CraftGuideFermenter; import forestry.factory.recipes.craftguide.CraftGuideSqueezer; import forestry.factory.recipes.craftguide.CraftGuideStill; +import java.lang.reflect.Method; public class CraftGuideIntegration { - public static void register() { - registerRecipeProviders(); - } + public static void register() { + registerRecipeProviders(); + } - private static void registerRecipeProviders() { + private static void registerRecipeProviders() { - Log.info("Registering CraftGuide integration."); - try { - Class c = Class.forName("uristqwerty.CraftGuide.ReflectionAPI"); - Method m = c.getMethod("registerAPIObject", Object.class); - - Log.fine("Adding crafting handler custom recipes."); - m.invoke(null, new CraftGuideCustomRecipes()); - Log.fine("Adding crafting handler for the carpenter."); - m.invoke(null, new CraftGuideCarpenter()); - Log.fine("Adding crafting handler for the thermionic fabricator."); - m.invoke(null, new CraftGuideFabricator()); - Log.fine("Adding crafting handler for the centrifuge."); - m.invoke(null, new CraftGuideCentrifuge()); - Log.fine("Adding crafting handler for the squeezer."); - m.invoke(null, new CraftGuideSqueezer()); - Log.fine("Adding crafting handler for the fermenter."); - m.invoke(null, new CraftGuideFermenter()); - Log.fine("Adding crafting handler for the still."); - m.invoke(null, new CraftGuideStill()); - Log.fine("Adding crafting handler for the bottler."); - m.invoke(null, new CraftGuideBottler()); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + Log.info("Registering CraftGuide integration."); + try { + Class c = Class.forName("uristqwerty.CraftGuide.ReflectionAPI"); + Method m = c.getMethod("registerAPIObject", Object.class); + Log.fine("Adding crafting handler custom recipes."); + m.invoke(null, new CraftGuideCustomRecipes()); + Log.fine("Adding crafting handler for the carpenter."); + m.invoke(null, new CraftGuideCarpenter()); + Log.fine("Adding crafting handler for the thermionic fabricator."); + m.invoke(null, new CraftGuideFabricator()); + Log.fine("Adding crafting handler for the centrifuge."); + m.invoke(null, new CraftGuideCentrifuge()); + Log.fine("Adding crafting handler for the squeezer."); + m.invoke(null, new CraftGuideSqueezer()); + Log.fine("Adding crafting handler for the fermenter."); + m.invoke(null, new CraftGuideFermenter()); + Log.fine("Adding crafting handler for the still."); + m.invoke(null, new CraftGuideStill()); + Log.fine("Adding crafting handler for the bottler."); + m.invoke(null, new CraftGuideBottler()); + } catch (Exception ex) { + ex.printStackTrace(); + } + } } diff --git a/src/main/java/forestry/core/recipes/nei/CustomOverlayHandler.java b/src/main/java/forestry/core/recipes/nei/CustomOverlayHandler.java index ab3285e5b..b95307048 100644 --- a/src/main/java/forestry/core/recipes/nei/CustomOverlayHandler.java +++ b/src/main/java/forestry/core/recipes/nei/CustomOverlayHandler.java @@ -10,16 +10,6 @@ ******************************************************************************/ package forestry.core.recipes.nei; -import java.util.List; - -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; - -import forestry.core.proxy.Proxies; -import forestry.factory.network.packets.PacketWorktableNEISelect; - import codechicken.nei.LayoutManager; import codechicken.nei.OffsetPositioner; import codechicken.nei.PositionedStack; @@ -27,53 +17,60 @@ import codechicken.nei.api.DefaultOverlayRenderer; import codechicken.nei.api.IOverlayHandler; import codechicken.nei.api.IStackPositioner; import codechicken.nei.recipe.IRecipeHandler; +import forestry.core.proxy.Proxies; +import forestry.factory.network.packets.PacketWorktableNEISelect; +import java.util.List; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; /** * @author bdew */ public class CustomOverlayHandler implements IOverlayHandler { - private final int xOffs; - private final int yOffs; - private final boolean forceShift; + private final int xOffs; + private final int yOffs; + private final boolean forceShift; - public CustomOverlayHandler(int xOffs, int yOffs, boolean forceShift) { - this.xOffs = xOffs; - this.yOffs = yOffs; - this.forceShift = forceShift; - } + public CustomOverlayHandler(int xOffs, int yOffs, boolean forceShift) { + this.xOffs = xOffs; + this.yOffs = yOffs; + this.forceShift = forceShift; + } - @Override - public void overlayRecipe(GuiContainer cont, IRecipeHandler recipe, int recipeIndex, boolean shift) { - List ingr = recipe.getIngredientStacks(recipeIndex); + @Override + public void overlayRecipe(GuiContainer cont, IRecipeHandler recipe, int recipeIndex, boolean shift) { + List ingr = recipe.getIngredientStacks(recipeIndex); - if (shift || forceShift) { - NBTTagList stacksnbt = new NBTTagList(); + if (shift || forceShift) { + NBTTagList stacksnbt = new NBTTagList(); - for (PositionedStack pstack : ingr) { - if (pstack != null) { - // This is back-asswards but i don't see a better way :( - int x = (pstack.relx - 25) / 18; - int y = (pstack.rely - 6) / 18; + for (PositionedStack pstack : ingr) { + if (pstack != null) { + // This is back-asswards but i don't see a better way :( + int x = (pstack.relx - 25) / 18; + int y = (pstack.rely - 6) / 18; - ItemStack stack = pstack.item; - NBTTagCompound stacknbt = stack.writeToNBT(new NBTTagCompound()); - stacknbt.setInteger("slot", y * 3 + x); - stacksnbt.appendTag(stacknbt); - } + ItemStack stack = pstack.item; + NBTTagCompound stacknbt = stack.writeToNBT(new NBTTagCompound()); + stacknbt.setInteger("slot", y * 3 + x); + stacksnbt.appendTag(stacknbt); + } - ItemStack stack = recipe.getResultStack(recipeIndex).items[0]; - NBTTagCompound stacknbt = stack.writeToNBT(new NBTTagCompound()); - stacknbt.setInteger("slot", 9); - stacksnbt.appendTag(stacknbt); - } + ItemStack stack = recipe.getResultStack(recipeIndex).items[0]; + NBTTagCompound stacknbt = stack.writeToNBT(new NBTTagCompound()); + stacknbt.setInteger("slot", 9); + stacksnbt.appendTag(stacknbt); + } - NBTTagCompound data = new NBTTagCompound(); - data.setTag("stacks", stacksnbt); + NBTTagCompound data = new NBTTagCompound(); + data.setTag("stacks", stacksnbt); - Proxies.net.sendToServer(new PacketWorktableNEISelect(data)); - } else { - IStackPositioner positioner = new OffsetPositioner(xOffs, yOffs); - LayoutManager.overlayRenderer = new DefaultOverlayRenderer(ingr, positioner); - } - } + Proxies.net.sendToServer(new PacketWorktableNEISelect(data)); + } else { + IStackPositioner positioner = new OffsetPositioner(xOffs, yOffs); + LayoutManager.overlayRenderer = new DefaultOverlayRenderer(ingr, positioner); + } + } } diff --git a/src/main/java/forestry/core/recipes/nei/IRecipeHandlerBase.java b/src/main/java/forestry/core/recipes/nei/IRecipeHandlerBase.java index be645c0c3..0d4c0086a 100644 --- a/src/main/java/forestry/core/recipes/nei/IRecipeHandlerBase.java +++ b/src/main/java/forestry/core/recipes/nei/IRecipeHandlerBase.java @@ -14,5 +14,5 @@ import codechicken.nei.recipe.ICraftingHandler; import codechicken.nei.recipe.IUsageHandler; public interface IRecipeHandlerBase extends ICraftingHandler, IUsageHandler { - void prepare(); + void prepare(); } diff --git a/src/main/java/forestry/core/recipes/nei/ItemFilterForestry.java b/src/main/java/forestry/core/recipes/nei/ItemFilterForestry.java index 123eb0096..0ef7411e3 100644 --- a/src/main/java/forestry/core/recipes/nei/ItemFilterForestry.java +++ b/src/main/java/forestry/core/recipes/nei/ItemFilterForestry.java @@ -1,57 +1,55 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.recipes.nei; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; - -import forestry.core.config.Constants; - -import codechicken.nei.api.ItemFilter; - -/** - * @author bdew - */ -public class ItemFilterForestry implements ItemFilter { - private final boolean items; - - public ItemFilterForestry(Boolean items) { - this.items = items; - } - - @Override - public boolean matches(ItemStack item) { - if (item == null || item.getItem() == null) { - return false; - } - - if (item.getItem() instanceof ItemBlock && items) { - return false; - } - - if (!(item.getItem() instanceof ItemBlock) && !items) { - return false; - } - - String itemName = Item.itemRegistry.getNameForObject(item.getItem()); - if (itemName == null) { - return false; - } - - String[] s = itemName.split(":"); - if (s.length <= 1) { - return false; - } - - return s[0].equals(Constants.MOD); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.recipes.nei; + +import codechicken.nei.api.ItemFilter; +import forestry.core.config.Constants; +import net.minecraft.item.Item; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; + +/** + * @author bdew + */ +public class ItemFilterForestry implements ItemFilter { + private final boolean items; + + public ItemFilterForestry(Boolean items) { + this.items = items; + } + + @Override + public boolean matches(ItemStack item) { + if (item == null || item.getItem() == null) { + return false; + } + + if (item.getItem() instanceof ItemBlock && items) { + return false; + } + + if (!(item.getItem() instanceof ItemBlock) && !items) { + return false; + } + + String itemName = Item.itemRegistry.getNameForObject(item.getItem()); + if (itemName == null) { + return false; + } + + String[] s = itemName.split(":"); + if (s.length <= 1) { + return false; + } + + return s[0].equals(Constants.MOD); + } +} diff --git a/src/main/java/forestry/core/recipes/nei/ItemFilterGenetic.java b/src/main/java/forestry/core/recipes/nei/ItemFilterGenetic.java index 0d3610be2..ef3567732 100644 --- a/src/main/java/forestry/core/recipes/nei/ItemFilterGenetic.java +++ b/src/main/java/forestry/core/recipes/nei/ItemFilterGenetic.java @@ -10,45 +10,43 @@ ******************************************************************************/ package forestry.core.recipes.nei; -import net.minecraft.item.ItemStack; - +import codechicken.nei.api.ItemFilter; import forestry.api.genetics.IIndividual; import forestry.api.genetics.ISpeciesRoot; - -import codechicken.nei.api.ItemFilter; +import net.minecraft.item.ItemStack; /** * @author bdew */ public class ItemFilterGenetic implements ItemFilter { - private final ISpeciesRoot root; - private final int type; - private final boolean analyzedOnly; + private final ISpeciesRoot root; + private final int type; + private final boolean analyzedOnly; - public ItemFilterGenetic(ISpeciesRoot root, int type, boolean analyzedOnly) { - this.root = root; - this.type = type; - this.analyzedOnly = analyzedOnly; - } + public ItemFilterGenetic(ISpeciesRoot root, int type, boolean analyzedOnly) { + this.root = root; + this.type = type; + this.analyzedOnly = analyzedOnly; + } - private boolean isMember(ItemStack item) { - if (type >= 0) { - return root.isMember(item, type); - } else { - return root.isMember(item); - } - } + private boolean isMember(ItemStack item) { + if (type >= 0) { + return root.isMember(item, type); + } else { + return root.isMember(item); + } + } - @Override - public boolean matches(ItemStack item) { - if (analyzedOnly) { - if (!isMember(item)) { - return false; - } - IIndividual individual = root.getMember(item); - return individual.isAnalyzed() || !individual.isSecret(); - } else { - return isMember(item); - } - } + @Override + public boolean matches(ItemStack item) { + if (analyzedOnly) { + if (!isMember(item)) { + return false; + } + IIndividual individual = root.getMember(item); + return individual.isAnalyzed() || !individual.isSecret(); + } else { + return isMember(item); + } + } } diff --git a/src/main/java/forestry/core/recipes/nei/ItemFilterOther.java b/src/main/java/forestry/core/recipes/nei/ItemFilterOther.java index 6e93b261f..6d1645ab6 100644 --- a/src/main/java/forestry/core/recipes/nei/ItemFilterOther.java +++ b/src/main/java/forestry/core/recipes/nei/ItemFilterOther.java @@ -10,21 +10,20 @@ ******************************************************************************/ package forestry.core.recipes.nei; -import net.minecraft.item.ItemStack; - import forestry.api.genetics.AlleleManager; +import net.minecraft.item.ItemStack; /** * @author bdew */ public class ItemFilterOther extends ItemFilterForestry { - public ItemFilterOther(Boolean items) { - super(items); - } + public ItemFilterOther(Boolean items) { + super(items); + } - @Override - public boolean matches(ItemStack item) { - return super.matches(item) && !AlleleManager.alleleRegistry.isIndividual(item); - } + @Override + public boolean matches(ItemStack item) { + return super.matches(item) && !AlleleManager.alleleRegistry.isIndividual(item); + } } diff --git a/src/main/java/forestry/core/recipes/nei/NEIIntegrationConfig.java b/src/main/java/forestry/core/recipes/nei/NEIIntegrationConfig.java index 7d0bc0c03..096ad74e6 100644 --- a/src/main/java/forestry/core/recipes/nei/NEIIntegrationConfig.java +++ b/src/main/java/forestry/core/recipes/nei/NEIIntegrationConfig.java @@ -10,8 +10,8 @@ ******************************************************************************/ package forestry.core.recipes.nei; -import net.minecraftforge.oredict.OreDictionary; - +import codechicken.nei.api.API; +import codechicken.nei.api.IConfigureNEI; import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.arboriculture.EnumGermlingType; @@ -28,58 +28,69 @@ import forestry.factory.recipes.nei.NEIHandlerFermenter; import forestry.factory.recipes.nei.NEIHandlerMoistener; import forestry.factory.recipes.nei.NEIHandlerSqueezer; import forestry.factory.recipes.nei.NEIHandlerStill; - -import codechicken.nei.api.API; -import codechicken.nei.api.IConfigureNEI; +import net.minecraftforge.oredict.OreDictionary; public class NEIIntegrationConfig implements IConfigureNEI { - @Override - public void loadConfig() { - Log.info("Loading: " + getName()); + @Override + public void loadConfig() { + Log.info("Loading: " + getName()); - registerHandler(new NEIHandlerBottler()); - registerHandler(new NEIHandlerCarpenter()); - registerHandler(new NEIHandlerCentrifuge()); - registerHandler(new NEIHandlerFabricator()); - registerHandler(new NEIHandlerFermenter()); - registerHandler(new NEIHandlerMoistener()); - registerHandler(new NEIHandlerSqueezer()); - registerHandler(new NEIHandlerStill()); + registerHandler(new NEIHandlerBottler()); + registerHandler(new NEIHandlerCarpenter()); + registerHandler(new NEIHandlerCentrifuge()); + registerHandler(new NEIHandlerFabricator()); + registerHandler(new NEIHandlerFermenter()); + registerHandler(new NEIHandlerMoistener()); + registerHandler(new NEIHandlerSqueezer()); + registerHandler(new NEIHandlerStill()); - CustomOverlayHandler handler = new CustomOverlayHandler(-14, 14, true); - API.registerGuiOverlayHandler(GuiWorktable.class, handler, "crafting"); + CustomOverlayHandler handler = new CustomOverlayHandler(-14, 14, true); + API.registerGuiOverlayHandler(GuiWorktable.class, handler, "crafting"); - API.addSubset("Forestry.Bees.Princesses", new ItemFilterGenetic(BeeManager.beeRoot, EnumBeeType.PRINCESS.ordinal(), true)); - API.addSubset("Forestry.Bees.Drones", new ItemFilterGenetic(BeeManager.beeRoot, EnumBeeType.DRONE.ordinal(), true)); - API.addSubset("Forestry.Bees.Larvae", new ItemFilterGenetic(BeeManager.beeRoot, EnumBeeType.LARVAE.ordinal(), true)); + API.addSubset( + "Forestry.Bees.Princesses", + new ItemFilterGenetic(BeeManager.beeRoot, EnumBeeType.PRINCESS.ordinal(), true)); + API.addSubset( + "Forestry.Bees.Drones", new ItemFilterGenetic(BeeManager.beeRoot, EnumBeeType.DRONE.ordinal(), true)); + API.addSubset( + "Forestry.Bees.Larvae", new ItemFilterGenetic(BeeManager.beeRoot, EnumBeeType.LARVAE.ordinal(), true)); - API.addSubset("Forestry.Trees.Saplings", new ItemFilterGenetic(TreeManager.treeRoot, EnumGermlingType.SAPLING.ordinal(), true)); - API.addSubset("Forestry.Trees.Pollen", new ItemFilterGenetic(TreeManager.treeRoot, EnumGermlingType.POLLEN.ordinal(), true)); + API.addSubset( + "Forestry.Trees.Saplings", + new ItemFilterGenetic(TreeManager.treeRoot, EnumGermlingType.SAPLING.ordinal(), true)); + API.addSubset( + "Forestry.Trees.Pollen", + new ItemFilterGenetic(TreeManager.treeRoot, EnumGermlingType.POLLEN.ordinal(), true)); - API.addSubset("Forestry.Butterflies.Butterflies", new ItemFilterGenetic(ButterflyManager.butterflyRoot, EnumFlutterType.BUTTERFLY.ordinal(), true)); - API.addSubset("Forestry.Butterflies.Caterpillars", new ItemFilterGenetic(ButterflyManager.butterflyRoot, EnumFlutterType.CATERPILLAR.ordinal(), true)); - API.addSubset("Forestry.Butterflies.Serum", new ItemFilterGenetic(ButterflyManager.butterflyRoot, EnumFlutterType.SERUM.ordinal(), true)); + API.addSubset( + "Forestry.Butterflies.Butterflies", + new ItemFilterGenetic(ButterflyManager.butterflyRoot, EnumFlutterType.BUTTERFLY.ordinal(), true)); + API.addSubset( + "Forestry.Butterflies.Caterpillars", + new ItemFilterGenetic(ButterflyManager.butterflyRoot, EnumFlutterType.CATERPILLAR.ordinal(), true)); + API.addSubset( + "Forestry.Butterflies.Serum", + new ItemFilterGenetic(ButterflyManager.butterflyRoot, EnumFlutterType.SERUM.ordinal(), true)); - API.addSubset("Forestry.Bees.Combs", OreDictionary.getOres("beeComb")); - API.addSubset("Forestry.Blocks", new ItemFilterOther(false)); - API.addSubset("Forestry.Items", new ItemFilterOther(true)); - } + API.addSubset("Forestry.Bees.Combs", OreDictionary.getOres("beeComb")); + API.addSubset("Forestry.Blocks", new ItemFilterOther(false)); + API.addSubset("Forestry.Items", new ItemFilterOther(true)); + } - protected static void registerHandler(IRecipeHandlerBase handler) { - handler.prepare(); - API.registerRecipeHandler(handler); - API.registerUsageHandler(handler); - } + protected static void registerHandler(IRecipeHandlerBase handler) { + handler.prepare(); + API.registerRecipeHandler(handler); + API.registerUsageHandler(handler); + } - @Override - public String getName() { - return "Forestry NEI Integration"; - } - - @Override - public String getVersion() { - return "1.1.0"; - } + @Override + public String getName() { + return "Forestry NEI Integration"; + } + @Override + public String getVersion() { + return "1.1.0"; + } } diff --git a/src/main/java/forestry/core/recipes/nei/NEIUtils.java b/src/main/java/forestry/core/recipes/nei/NEIUtils.java index 881f81f09..3aaab251b 100644 --- a/src/main/java/forestry/core/recipes/nei/NEIUtils.java +++ b/src/main/java/forestry/core/recipes/nei/NEIUtils.java @@ -14,11 +14,9 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; - import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; - import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidStack; @@ -27,51 +25,51 @@ import net.minecraftforge.fluids.IFluidContainerItem; public class NEIUtils { - public static String translate(String unlocalized) { - return StatCollector.translateToLocal("neiintegration." + unlocalized); - } + public static String translate(String unlocalized) { + return StatCollector.translateToLocal("neiintegration." + unlocalized); + } - public static List getItemVariations(ItemStack base) { - List variations = new ArrayList<>(); - base.getItem().getSubItems(base.getItem(), null, variations); - Iterator itr = variations.iterator(); - ItemStack stack; - while (itr.hasNext()) { - stack = itr.next(); - if (!base.isItemEqual(stack) || !stack.hasTagCompound()) { - itr.remove(); - } - } - if (variations.isEmpty()) { - return Collections.singletonList(base); - } - return variations; - } + public static List getItemVariations(ItemStack base) { + List variations = new ArrayList<>(); + base.getItem().getSubItems(base.getItem(), null, variations); + Iterator itr = variations.iterator(); + ItemStack stack; + while (itr.hasNext()) { + stack = itr.next(); + if (!base.isItemEqual(stack) || !stack.hasTagCompound()) { + itr.remove(); + } + } + if (variations.isEmpty()) { + return Collections.singletonList(base); + } + return variations; + } - public static FluidStack getFluidStack(ItemStack stack) { - if (stack != null) { - FluidStack fluidStack = null; - if (stack.getItem() instanceof IFluidContainerItem) { - fluidStack = ((IFluidContainerItem) stack.getItem()).getFluid(stack); - } - if (fluidStack == null) { - fluidStack = FluidContainerRegistry.getFluidForFilledItem(stack); - } - if (fluidStack == null && Block.getBlockFromItem(stack.getItem()) instanceof IFluidBlock) { - Fluid fluid = ((IFluidBlock) Block.getBlockFromItem(stack.getItem())).getFluid(); - if (fluid != null) { - fluidStack = new FluidStack(fluid, 1000); - } - } - return fluidStack; - } - return null; - } + public static FluidStack getFluidStack(ItemStack stack) { + if (stack != null) { + FluidStack fluidStack = null; + if (stack.getItem() instanceof IFluidContainerItem) { + fluidStack = ((IFluidContainerItem) stack.getItem()).getFluid(stack); + } + if (fluidStack == null) { + fluidStack = FluidContainerRegistry.getFluidForFilledItem(stack); + } + if (fluidStack == null && Block.getBlockFromItem(stack.getItem()) instanceof IFluidBlock) { + Fluid fluid = ((IFluidBlock) Block.getBlockFromItem(stack.getItem())).getFluid(); + if (fluid != null) { + fluidStack = new FluidStack(fluid, 1000); + } + } + return fluidStack; + } + return null; + } - public static boolean areFluidsSameType(FluidStack fluidStack1, FluidStack fluidStack2) { - if (fluidStack1 == null || fluidStack2 == null) { - return false; - } - return fluidStack1.getFluid() == fluidStack2.getFluid(); - } + public static boolean areFluidsSameType(FluidStack fluidStack1, FluidStack fluidStack2) { + if (fluidStack1 == null || fluidStack2 == null) { + return false; + } + return fluidStack1.getFluid() == fluidStack2.getFluid(); + } } diff --git a/src/main/java/forestry/core/recipes/nei/PositionedFluidTank.java b/src/main/java/forestry/core/recipes/nei/PositionedFluidTank.java index 1abb52746..7616eeaac 100644 --- a/src/main/java/forestry/core/recipes/nei/PositionedFluidTank.java +++ b/src/main/java/forestry/core/recipes/nei/PositionedFluidTank.java @@ -10,148 +10,174 @@ ******************************************************************************/ package forestry.core.recipes.nei; +import codechicken.lib.gui.GuiDraw; +import codechicken.nei.recipe.GuiCraftingRecipe; +import codechicken.nei.recipe.GuiUsageRecipe; import java.awt.Point; import java.awt.Rectangle; import java.util.Collection; import java.util.Collections; import java.util.List; - import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IIcon; - import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; - import org.lwjgl.opengl.GL11; -import codechicken.lib.gui.GuiDraw; -import codechicken.nei.recipe.GuiCraftingRecipe; -import codechicken.nei.recipe.GuiUsageRecipe; - public class PositionedFluidTank { - public FluidTank[] tanks; - public FluidTank tank; - public Rectangle position; - public String overlayTexture; - public Point overlayTexturePos; - public boolean flowingTexture = false; - public boolean showAmount = true; - public boolean perTick = false; + public FluidTank[] tanks; + public FluidTank tank; + public Rectangle position; + public String overlayTexture; + public Point overlayTexturePos; + public boolean flowingTexture = false; + public boolean showAmount = true; + public boolean perTick = false; - public PositionedFluidTank(FluidTank[] tanks, Rectangle position, String overlayTexture, Point overlayTexturePos) { - this.position = position; - this.tanks = tanks; - this.tank = tanks[0]; - this.overlayTexture = overlayTexture; - this.overlayTexturePos = overlayTexturePos; - } + public PositionedFluidTank(FluidTank[] tanks, Rectangle position, String overlayTexture, Point overlayTexturePos) { + this.position = position; + this.tanks = tanks; + this.tank = tanks[0]; + this.overlayTexture = overlayTexture; + this.overlayTexturePos = overlayTexturePos; + } - public PositionedFluidTank(Collection fluids, int capacity, Rectangle position, String overlayTexture, Point overlayTexturePos) { - this(createFluidTanks(capacity, fluids), position, overlayTexture, overlayTexturePos); - } + public PositionedFluidTank( + Collection fluids, + int capacity, + Rectangle position, + String overlayTexture, + Point overlayTexturePos) { + this(createFluidTanks(capacity, fluids), position, overlayTexture, overlayTexturePos); + } - public PositionedFluidTank(FluidStack fluid, int capacity, Rectangle position, String overlayTexture, Point overlayTexturePos) { - this(createFluidTanks(capacity, Collections.singletonList(fluid)), position, overlayTexture, overlayTexturePos); - } + public PositionedFluidTank( + FluidStack fluid, int capacity, Rectangle position, String overlayTexture, Point overlayTexturePos) { + this(createFluidTanks(capacity, Collections.singletonList(fluid)), position, overlayTexture, overlayTexturePos); + } - public PositionedFluidTank(FluidStack fluid, int capacity, Rectangle position) { - this(fluid, capacity, position, null, null); - } + public PositionedFluidTank(FluidStack fluid, int capacity, Rectangle position) { + this(fluid, capacity, position, null, null); + } - private static FluidTank[] createFluidTanks(int capacity, Collection fluidStacks) { - FluidTank[] tanks = new FluidTank[fluidStacks.size()]; - int i = 0; - for (FluidStack fluidStack : fluidStacks) { - tanks[i++] = new FluidTank(fluidStacks != null ? fluidStack.copy() : null, capacity); - } - return tanks; - } + private static FluidTank[] createFluidTanks(int capacity, Collection fluidStacks) { + FluidTank[] tanks = new FluidTank[fluidStacks.size()]; + int i = 0; + for (FluidStack fluidStack : fluidStacks) { + tanks[i++] = new FluidTank(fluidStacks != null ? fluidStack.copy() : null, capacity); + } + return tanks; + } - public List handleTooltip(List currenttip) { - if (this.tank == null || this.tank.getFluid() == null || this.tank.getFluid().getFluid() == null || this.tank.getFluid().amount <= 0) { - return currenttip; - } - currenttip.add(this.tank.getFluid().getLocalizedName()); - if (this.showAmount) { - currenttip.add(EnumChatFormatting.GRAY.toString() + this.tank.getFluid().amount + (this.perTick ? " mB/t" : " mB")); - } - return currenttip; - } + public List handleTooltip(List currenttip) { + if (this.tank == null + || this.tank.getFluid() == null + || this.tank.getFluid().getFluid() == null + || this.tank.getFluid().amount <= 0) { + return currenttip; + } + currenttip.add(this.tank.getFluid().getLocalizedName()); + if (this.showAmount) { + currenttip.add(EnumChatFormatting.GRAY.toString() + + this.tank.getFluid().amount + + (this.perTick ? " mB/t" : " mB")); + } + return currenttip; + } - public boolean transfer(boolean usage) { - if (this.tank.getFluid() != null && this.tank.getFluid().amount > 0) { - if (usage) { - if (!GuiUsageRecipe.openRecipeGui("liquid", this.tank.getFluid())) { - return false; - } - } else { - if (!GuiCraftingRecipe.openRecipeGui("liquid", this.tank.getFluid())) { - return false; - } - } - return true; - } - return false; - } + public boolean transfer(boolean usage) { + if (this.tank.getFluid() != null && this.tank.getFluid().amount > 0) { + if (usage) { + if (!GuiUsageRecipe.openRecipeGui("liquid", this.tank.getFluid())) { + return false; + } + } else { + if (!GuiCraftingRecipe.openRecipeGui("liquid", this.tank.getFluid())) { + return false; + } + } + return true; + } + return false; + } - public void draw() { - if (this.tank == null || this.tank.getFluid() == null || this.tank.getFluid().getFluid() == null || this.tank.getFluid().amount <= 0) { - return; - } - final IIcon fluidIcon; - if (this.flowingTexture && this.tank.getFluid().getFluid().getFlowingIcon() != null) { - fluidIcon = this.tank.getFluid().getFluid().getFlowingIcon(); - } else if (this.tank.getFluid().getFluid().getStillIcon() != null) { - fluidIcon = this.tank.getFluid().getFluid().getStillIcon(); - } else { - return; - } + public void draw() { + if (this.tank == null + || this.tank.getFluid() == null + || this.tank.getFluid().getFluid() == null + || this.tank.getFluid().amount <= 0) { + return; + } + final IIcon fluidIcon; + if (this.flowingTexture && this.tank.getFluid().getFluid().getFlowingIcon() != null) { + fluidIcon = this.tank.getFluid().getFluid().getFlowingIcon(); + } else if (this.tank.getFluid().getFluid().getStillIcon() != null) { + fluidIcon = this.tank.getFluid().getFluid().getStillIcon(); + } else { + return; + } - GuiDraw.changeTexture(TextureMap.locationBlocksTexture); - int color = this.tank.getFluid().getFluid().getColor(this.tank.getFluid()); - GL11.glColor3ub((byte) (color >> 16 & 0xFF), (byte) (color >> 8 & 0xFF), (byte) (color & 0xFF)); + GuiDraw.changeTexture(TextureMap.locationBlocksTexture); + int color = this.tank.getFluid().getFluid().getColor(this.tank.getFluid()); + GL11.glColor3ub((byte) (color >> 16 & 0xFF), (byte) (color >> 8 & 0xFF), (byte) (color & 0xFF)); - int amount = Math.max(Math.min(this.position.height, this.tank.getFluid().amount * this.position.height / this.tank.getCapacity()), 1); - int posY = this.position.y + this.position.height - amount; + int amount = Math.max( + Math.min( + this.position.height, + this.tank.getFluid().amount * this.position.height / this.tank.getCapacity()), + 1); + int posY = this.position.y + this.position.height - amount; - for (int i = 0; i < this.position.width; i += 16) { - for (int j = 0; j < amount; j += 16) { - int drawWidth = Math.min(this.position.width - i, 16); - int drawHeight = Math.min(amount - j, 16); + for (int i = 0; i < this.position.width; i += 16) { + for (int j = 0; j < amount; j += 16) { + int drawWidth = Math.min(this.position.width - i, 16); + int drawHeight = Math.min(amount - j, 16); - int drawX = this.position.x + i; - int drawY = posY + j; + int drawX = this.position.x + i; + int drawY = posY + j; - double minU = fluidIcon.getMinU(); - double maxU = fluidIcon.getMaxU(); - double minV = fluidIcon.getMinV(); - double maxV = fluidIcon.getMaxV(); + double minU = fluidIcon.getMinU(); + double maxU = fluidIcon.getMaxU(); + double minV = fluidIcon.getMinV(); + double maxV = fluidIcon.getMaxV(); - Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); - tessellator.addVertexWithUV(drawX, drawY + drawHeight, 0, minU, minV + (maxV - minV) * drawHeight / 16F); - tessellator.addVertexWithUV(drawX + drawWidth, drawY + drawHeight, 0, minU + (maxU - minU) * drawWidth / 16F, minV + (maxV - minV) * drawHeight / 16F); - tessellator.addVertexWithUV(drawX + drawWidth, drawY, 0, minU + (maxU - minU) * drawWidth / 16F, minV); - tessellator.addVertexWithUV(drawX, drawY, 0, minU, minV); - tessellator.draw(); - } - } + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.addVertexWithUV( + drawX, drawY + drawHeight, 0, minU, minV + (maxV - minV) * drawHeight / 16F); + tessellator.addVertexWithUV( + drawX + drawWidth, + drawY + drawHeight, + 0, + minU + (maxU - minU) * drawWidth / 16F, + minV + (maxV - minV) * drawHeight / 16F); + tessellator.addVertexWithUV(drawX + drawWidth, drawY, 0, minU + (maxU - minU) * drawWidth / 16F, minV); + tessellator.addVertexWithUV(drawX, drawY, 0, minU, minV); + tessellator.draw(); + } + } - if (this.overlayTexture != null && this.overlayTexturePos != null) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GuiDraw.changeTexture(this.overlayTexture); - GuiDraw.drawTexturedModalRect(this.position.x, this.position.y, this.overlayTexturePos.x, this.overlayTexturePos.y, this.position.width, this.position.height); - } - } + if (this.overlayTexture != null && this.overlayTexturePos != null) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GuiDraw.changeTexture(this.overlayTexture); + GuiDraw.drawTexturedModalRect( + this.position.x, + this.position.y, + this.overlayTexturePos.x, + this.overlayTexturePos.y, + this.position.width, + this.position.height); + } + } - public void setPermutationToRender(int index) { - this.tank = this.tanks[index]; - } + public void setPermutationToRender(int index) { + this.tank = this.tanks[index]; + } - public int getPermutationCount() { - return this.tanks.length; - } + public int getPermutationCount() { + return this.tanks.length; + } } diff --git a/src/main/java/forestry/core/recipes/nei/PositionedStackAdv.java b/src/main/java/forestry/core/recipes/nei/PositionedStackAdv.java index 2bd81c910..7b1050169 100644 --- a/src/main/java/forestry/core/recipes/nei/PositionedStackAdv.java +++ b/src/main/java/forestry/core/recipes/nei/PositionedStackAdv.java @@ -10,65 +10,65 @@ ******************************************************************************/ package forestry.core.recipes.nei; +import codechicken.nei.PositionedStack; +import codechicken.nei.recipe.GuiRecipe; import java.awt.Rectangle; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; - import net.minecraft.util.EnumChatFormatting; -import codechicken.nei.PositionedStack; -import codechicken.nei.recipe.GuiRecipe; - public class PositionedStackAdv extends PositionedStack { - private final List tooltip = new ArrayList<>(); + private final List tooltip = new ArrayList<>(); - public PositionedStackAdv(Object object, int x, int y) { - super(object, x, y); - } + public PositionedStackAdv(Object object, int x, int y) { + super(object, x, y); + } - public PositionedStackAdv(Object object, int x, int y, List tooltip) { - super(object, x, y); - this.addToTooltip(tooltip); - } + public PositionedStackAdv(Object object, int x, int y, List tooltip) { + super(object, x, y); + this.addToTooltip(tooltip); + } - public Rectangle getRect() { - return new Rectangle(this.relx - 1, this.rely - 1, 18, 18); - } + public Rectangle getRect() { + return new Rectangle(this.relx - 1, this.rely - 1, 18, 18); + } - public List handleTooltip(GuiRecipe guiRecipe, List currenttip) { - if (!this.tooltip.isEmpty()) { - for (String tip : this.tooltip) { - currenttip.add(tip); - } - } - return currenttip; - } + public List handleTooltip(GuiRecipe guiRecipe, List currenttip) { + if (!this.tooltip.isEmpty()) { + for (String tip : this.tooltip) { + currenttip.add(tip); + } + } + return currenttip; + } - public PositionedStackAdv addToTooltip(List lines) { - for (String tip : lines) { - this.tooltip.add(tip); - } - return this; - } + public PositionedStackAdv addToTooltip(List lines) { + for (String tip : lines) { + this.tooltip.add(tip); + } + return this; + } - public PositionedStackAdv addToTooltip(String line) { - this.tooltip.add(line); - return this; - } - - public PositionedStackAdv setChance(float chance) { - if (chance <= 0.0F) { - this.tooltip.add(EnumChatFormatting.GRAY + String.format(NEIUtils.translate("chance"), NEIUtils.translate("chance.never"))); - } else if (chance < 0.01F) { - this.tooltip.add(EnumChatFormatting.GRAY + String.format(NEIUtils.translate("chance"), NEIUtils.translate("chance.lessThan1"))); - } else if (chance != 1.0F) { - NumberFormat percentFormat = NumberFormat.getPercentInstance(); - percentFormat.setMaximumFractionDigits(2); - this.tooltip.add(EnumChatFormatting.GRAY + String.format(NEIUtils.translate("chance"), String.valueOf(percentFormat.format(chance)))); - } - return this; - } + public PositionedStackAdv addToTooltip(String line) { + this.tooltip.add(line); + return this; + } + public PositionedStackAdv setChance(float chance) { + if (chance <= 0.0F) { + this.tooltip.add(EnumChatFormatting.GRAY + + String.format(NEIUtils.translate("chance"), NEIUtils.translate("chance.never"))); + } else if (chance < 0.01F) { + this.tooltip.add(EnumChatFormatting.GRAY + + String.format(NEIUtils.translate("chance"), NEIUtils.translate("chance.lessThan1"))); + } else if (chance != 1.0F) { + NumberFormat percentFormat = NumberFormat.getPercentInstance(); + percentFormat.setMaximumFractionDigits(2); + this.tooltip.add(EnumChatFormatting.GRAY + + String.format(NEIUtils.translate("chance"), String.valueOf(percentFormat.format(chance)))); + } + return this; + } } diff --git a/src/main/java/forestry/core/recipes/nei/RecipeHandlerBase.java b/src/main/java/forestry/core/recipes/nei/RecipeHandlerBase.java index fd550d651..1dbe8337f 100644 --- a/src/main/java/forestry/core/recipes/nei/RecipeHandlerBase.java +++ b/src/main/java/forestry/core/recipes/nei/RecipeHandlerBase.java @@ -10,225 +10,234 @@ ******************************************************************************/ package forestry.core.recipes.nei; -import java.awt.Point; -import java.awt.Rectangle; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - -import org.lwjgl.opengl.GL11; - import codechicken.lib.gui.GuiDraw; import codechicken.nei.NEIClientConfig; import codechicken.nei.PositionedStack; import codechicken.nei.guihook.GuiContainerManager; import codechicken.nei.recipe.GuiRecipe; import codechicken.nei.recipe.TemplateRecipeHandler; +import java.awt.Point; +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; +import org.lwjgl.opengl.GL11; public abstract class RecipeHandlerBase extends TemplateRecipeHandler implements IRecipeHandlerBase { - @Override - public void prepare() { - } + @Override + public void prepare() {} - public abstract class CachedBaseRecipe extends CachedRecipe { + public abstract class CachedBaseRecipe extends CachedRecipe { - public List getFluidTanks() { - List tanks = new ArrayList<>(); - PositionedFluidTank tank = this.getFluidTank(); - if (tank != null) { - tanks.add(tank); - } - return tanks; - } + public List getFluidTanks() { + List tanks = new ArrayList<>(); + PositionedFluidTank tank = this.getFluidTank(); + if (tank != null) { + tanks.add(tank); + } + return tanks; + } - public PositionedFluidTank getFluidTank() { - return null; - } + public PositionedFluidTank getFluidTank() { + return null; + } + } - } + public abstract String getRecipeID(); - public abstract String getRecipeID(); + public void changeToGuiTexture() { + GuiDraw.changeTexture(this.getGuiTexture()); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } - public void changeToGuiTexture() { - GuiDraw.changeTexture(this.getGuiTexture()); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - } + public void addTransferRect(int x, int y, int width, int height) { + this.transferRects.add(new RecipeTransferRect(new Rectangle(x, y, width, height), this.getRecipeID())); + } - public void addTransferRect(int x, int y, int width, int height) { - this.transferRects.add(new RecipeTransferRect(new Rectangle(x, y, width, height), this.getRecipeID())); - } + @Override + public void drawForeground(int recipe) { + super.drawForeground(recipe); + this.drawFluidTanks(recipe); + this.changeToGuiTexture(); + } - @Override - public void drawForeground(int recipe) { - super.drawForeground(recipe); - this.drawFluidTanks(recipe); - this.changeToGuiTexture(); - } + @Override + public void loadCraftingRecipes(String outputId, Object... results) { + if (outputId.equals("liquid") + && results[0] instanceof FluidStack + && ((FluidStack) results[0]).getFluid() != null) { + this.loadCraftingRecipes((FluidStack) results[0]); + } else if (outputId.equals(this.getRecipeID())) { + this.loadAllRecipes(); + } else { + super.loadCraftingRecipes(outputId, results); + } + } - @Override - public void loadCraftingRecipes(String outputId, Object... results) { - if (outputId.equals("liquid") && results[0] instanceof FluidStack && ((FluidStack) results[0]).getFluid() != null) { - this.loadCraftingRecipes((FluidStack) results[0]); - } else if (outputId.equals(this.getRecipeID())) { - this.loadAllRecipes(); - } else { - super.loadCraftingRecipes(outputId, results); - } - } + public void loadAllRecipes() {} - public void loadAllRecipes() { - } + @Override + public void loadCraftingRecipes(ItemStack result) { + FluidStack fluid = NEIUtils.getFluidStack(result); + if (fluid != null && fluid.getFluid() != null) { + this.loadCraftingRecipes(fluid); + } + } - @Override - public void loadCraftingRecipes(ItemStack result) { - FluidStack fluid = NEIUtils.getFluidStack(result); - if (fluid != null && fluid.getFluid() != null) { - this.loadCraftingRecipes(fluid); - } - } + public void loadCraftingRecipes(FluidStack result) {} - public void loadCraftingRecipes(FluidStack result) { - } + @Override + public void loadUsageRecipes(String inputId, Object... ingredients) { + if (inputId.equals("liquid") + && ingredients[0] instanceof FluidStack + && ((FluidStack) ingredients[0]).getFluid() != null) { + this.loadUsageRecipes((FluidStack) ingredients[0]); + } else { + super.loadUsageRecipes(inputId, ingredients); + } + } - @Override - public void loadUsageRecipes(String inputId, Object... ingredients) { - if (inputId.equals("liquid") && ingredients[0] instanceof FluidStack && ((FluidStack) ingredients[0]).getFluid() != null) { - this.loadUsageRecipes((FluidStack) ingredients[0]); - } else { - super.loadUsageRecipes(inputId, ingredients); - } - } + @Override + public void loadUsageRecipes(ItemStack ingred) { + FluidStack fluid = NEIUtils.getFluidStack(ingred); + if (fluid != null && fluid.getFluid() != null) { + this.loadUsageRecipes(fluid); + } + } - @Override - public void loadUsageRecipes(ItemStack ingred) { - FluidStack fluid = NEIUtils.getFluidStack(ingred); - if (fluid != null && fluid.getFluid() != null) { - this.loadUsageRecipes(fluid); - } - } + public void loadUsageRecipes(FluidStack ingredient) {} - public void loadUsageRecipes(FluidStack ingredient) { - } + @Override + public List handleTooltip(GuiRecipe guiRecipe, List currenttip, int recipe) { + super.handleTooltip(guiRecipe, currenttip, recipe); + CachedBaseRecipe crecipe = (CachedBaseRecipe) this.arecipes.get(recipe); + if (GuiContainerManager.shouldShowTooltip(guiRecipe)) { + Point mouse = GuiDraw.getMousePosition(); + Point offset = guiRecipe.getRecipePosition(recipe); + Point relMouse = new Point( + mouse.x - (guiRecipe.width - 176) / 2 - offset.x, + mouse.y - (guiRecipe.height - 166) / 2 - offset.y); - @Override - public List handleTooltip(GuiRecipe guiRecipe, List currenttip, int recipe) { - super.handleTooltip(guiRecipe, currenttip, recipe); - CachedBaseRecipe crecipe = (CachedBaseRecipe) this.arecipes.get(recipe); - if (GuiContainerManager.shouldShowTooltip(guiRecipe)) { - Point mouse = GuiDraw.getMousePosition(); - Point offset = guiRecipe.getRecipePosition(recipe); - Point relMouse = new Point(mouse.x - (guiRecipe.width - 176) / 2 - offset.x, mouse.y - (guiRecipe.height - 166) / 2 - offset.y); + currenttip = this.provideTooltip(guiRecipe, currenttip, crecipe, relMouse); + } + return currenttip; + } - currenttip = this.provideTooltip(guiRecipe, currenttip, crecipe, relMouse); - } - return currenttip; - } + @Override + public List handleItemTooltip( + GuiRecipe guiRecipe, ItemStack itemStack, List currenttip, int recipe) { + super.handleItemTooltip(guiRecipe, itemStack, currenttip, recipe); + CachedBaseRecipe crecipe = (CachedBaseRecipe) this.arecipes.get(recipe); + Point mouse = GuiDraw.getMousePosition(); + Point offset = guiRecipe.getRecipePosition(recipe); + Point relMouse = new Point( + mouse.x - (guiRecipe.width - 176) / 2 - offset.x, mouse.y - (guiRecipe.height - 166) / 2 - offset.y); - @Override - public List handleItemTooltip(GuiRecipe guiRecipe, ItemStack itemStack, List currenttip, int recipe) { - super.handleItemTooltip(guiRecipe, itemStack, currenttip, recipe); - CachedBaseRecipe crecipe = (CachedBaseRecipe) this.arecipes.get(recipe); - Point mouse = GuiDraw.getMousePosition(); - Point offset = guiRecipe.getRecipePosition(recipe); - Point relMouse = new Point(mouse.x - (guiRecipe.width - 176) / 2 - offset.x, mouse.y - (guiRecipe.height - 166) / 2 - offset.y); + currenttip = this.provideItemTooltip(guiRecipe, itemStack, currenttip, crecipe, relMouse); + return currenttip; + } - currenttip = this.provideItemTooltip(guiRecipe, itemStack, currenttip, crecipe, relMouse); - return currenttip; - } + public List provideTooltip( + GuiRecipe guiRecipe, List currenttip, CachedBaseRecipe crecipe, Point relMouse) { + if (crecipe.getFluidTanks() != null) { + for (PositionedFluidTank tank : crecipe.getFluidTanks()) { + if (tank.position.contains(relMouse)) { + tank.handleTooltip(currenttip); + } + } + } + return currenttip; + } - public List provideTooltip(GuiRecipe guiRecipe, List currenttip, CachedBaseRecipe crecipe, Point relMouse) { - if (crecipe.getFluidTanks() != null) { - for (PositionedFluidTank tank : crecipe.getFluidTanks()) { - if (tank.position.contains(relMouse)) { - tank.handleTooltip(currenttip); - } - } - } - return currenttip; - } + public List provideItemTooltip( + GuiRecipe guiRecipe, + ItemStack itemStack, + List currenttip, + CachedBaseRecipe crecipe, + Point relMouse) { + for (PositionedStack stack : crecipe.getIngredients()) { + if (stack instanceof PositionedStackAdv + && ((PositionedStackAdv) stack).getRect().contains(relMouse)) { + currenttip = ((PositionedStackAdv) stack).handleTooltip(guiRecipe, currenttip); + } + } + for (PositionedStack stack : crecipe.getOtherStacks()) { + if (stack instanceof PositionedStackAdv + && ((PositionedStackAdv) stack).getRect().contains(relMouse)) { + currenttip = ((PositionedStackAdv) stack).handleTooltip(guiRecipe, currenttip); + } + } + PositionedStack stack = crecipe.getResult(); + if (stack instanceof PositionedStackAdv + && ((PositionedStackAdv) stack).getRect().contains(relMouse)) { + currenttip = ((PositionedStackAdv) stack).handleTooltip(guiRecipe, currenttip); + } + return currenttip; + } - public List provideItemTooltip(GuiRecipe guiRecipe, ItemStack itemStack, List currenttip, CachedBaseRecipe crecipe, Point relMouse) { - for (PositionedStack stack : crecipe.getIngredients()) { - if (stack instanceof PositionedStackAdv && ((PositionedStackAdv) stack).getRect().contains(relMouse)) { - currenttip = ((PositionedStackAdv) stack).handleTooltip(guiRecipe, currenttip); - } - } - for (PositionedStack stack : crecipe.getOtherStacks()) { - if (stack instanceof PositionedStackAdv && ((PositionedStackAdv) stack).getRect().contains(relMouse)) { - currenttip = ((PositionedStackAdv) stack).handleTooltip(guiRecipe, currenttip); - } - } - PositionedStack stack = crecipe.getResult(); - if (stack instanceof PositionedStackAdv && ((PositionedStackAdv) stack).getRect().contains(relMouse)) { - currenttip = ((PositionedStackAdv) stack).handleTooltip(guiRecipe, currenttip); - } - return currenttip; - } + @Override + public boolean keyTyped(GuiRecipe gui, char keyChar, int keyCode, int recipe) { + if (keyCode == NEIClientConfig.getKeyBinding("gui.recipe")) { + if (this.transferFluidTank(gui, recipe, false)) { + return true; + } + } else if (keyCode == NEIClientConfig.getKeyBinding("gui.usage")) { + if (this.transferFluidTank(gui, recipe, true)) { + return true; + } + } + return super.keyTyped(gui, keyChar, keyCode, recipe); + } - @Override - public boolean keyTyped(GuiRecipe gui, char keyChar, int keyCode, int recipe) { - if (keyCode == NEIClientConfig.getKeyBinding("gui.recipe")) { - if (this.transferFluidTank(gui, recipe, false)) { - return true; - } - } else if (keyCode == NEIClientConfig.getKeyBinding("gui.usage")) { - if (this.transferFluidTank(gui, recipe, true)) { - return true; - } - } - return super.keyTyped(gui, keyChar, keyCode, recipe); - } + @Override + public boolean mouseClicked(GuiRecipe gui, int button, int recipe) { + if (button == 0) { + if (this.transferFluidTank(gui, recipe, false)) { + return true; + } + } else if (button == 1) { + if (this.transferFluidTank(gui, recipe, true)) { + return true; + } + } + return super.mouseClicked(gui, button, recipe); + } - @Override - public boolean mouseClicked(GuiRecipe gui, int button, int recipe) { - if (button == 0) { - if (this.transferFluidTank(gui, recipe, false)) { - return true; - } - } else if (button == 1) { - if (this.transferFluidTank(gui, recipe, true)) { - return true; - } - } - return super.mouseClicked(gui, button, recipe); - } + protected boolean transferFluidTank(GuiRecipe guiRecipe, int recipe, boolean usage) { + CachedBaseRecipe crecipe = (CachedBaseRecipe) this.arecipes.get(recipe); + Point mousepos = GuiDraw.getMousePosition(); + Point offset = guiRecipe.getRecipePosition(recipe); + Point relMouse = new Point( + mousepos.x - (guiRecipe.width - 176) / 2 - offset.x, + mousepos.y - (guiRecipe.height - 166) / 2 - offset.y); - protected boolean transferFluidTank(GuiRecipe guiRecipe, int recipe, boolean usage) { - CachedBaseRecipe crecipe = (CachedBaseRecipe) this.arecipes.get(recipe); - Point mousepos = GuiDraw.getMousePosition(); - Point offset = guiRecipe.getRecipePosition(recipe); - Point relMouse = new Point(mousepos.x - (guiRecipe.width - 176) / 2 - offset.x, mousepos.y - (guiRecipe.height - 166) / 2 - offset.y); + if (crecipe.getFluidTanks() != null) { + for (PositionedFluidTank tank : crecipe.getFluidTanks()) { + if (tank.position.contains(relMouse)) { + return tank.transfer(usage); + } + } + } - if (crecipe.getFluidTanks() != null) { - for (PositionedFluidTank tank : crecipe.getFluidTanks()) { - if (tank.position.contains(relMouse)) { - return tank.transfer(usage); - } - } - } + return false; + } - return false; - } - - public void drawFluidTanks(int recipe) { - CachedRecipe cachedRecipe = this.arecipes.get(recipe); - if (cachedRecipe instanceof CachedBaseRecipe) { - CachedBaseRecipe crecipe = (CachedBaseRecipe) cachedRecipe; - if (crecipe.getFluidTanks() != null) { - for (PositionedFluidTank fluidTank : crecipe.getFluidTanks()) { - fluidTank.draw(); - } - } - } - } - - @Override - public String getOverlayIdentifier() { - return this.getRecipeID(); - } + public void drawFluidTanks(int recipe) { + CachedRecipe cachedRecipe = this.arecipes.get(recipe); + if (cachedRecipe instanceof CachedBaseRecipe) { + CachedBaseRecipe crecipe = (CachedBaseRecipe) cachedRecipe; + if (crecipe.getFluidTanks() != null) { + for (PositionedFluidTank fluidTank : crecipe.getFluidTanks()) { + fluidTank.draw(); + } + } + } + } + @Override + public String getOverlayIdentifier() { + return this.getRecipeID(); + } } diff --git a/src/main/java/forestry/core/recipes/nei/SetRecipeCommandHandler.java b/src/main/java/forestry/core/recipes/nei/SetRecipeCommandHandler.java index f259f4e0b..0b4a2633f 100644 --- a/src/main/java/forestry/core/recipes/nei/SetRecipeCommandHandler.java +++ b/src/main/java/forestry/core/recipes/nei/SetRecipeCommandHandler.java @@ -12,7 +12,6 @@ package forestry.core.recipes.nei; import java.util.HashMap; import java.util.Map; - import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; @@ -24,37 +23,37 @@ import net.minecraft.nbt.NBTTagList; * @author bdew */ public class SetRecipeCommandHandler { - private final Class containerClass; - private final Class slotClass; + private final Class containerClass; + private final Class slotClass; - public SetRecipeCommandHandler(Class containerClass, Class slotClass) { - this.containerClass = containerClass; - this.slotClass = slotClass; - } + public SetRecipeCommandHandler(Class containerClass, Class slotClass) { + this.containerClass = containerClass; + this.slotClass = slotClass; + } - public void handle(NBTTagCompound data, EntityPlayerMP player) { - NBTTagList stacks = data.getTagList("stacks", 10); - Container cont = player.openContainer; - if (!containerClass.isInstance(cont)) { - return; - } + public void handle(NBTTagCompound data, EntityPlayerMP player) { + NBTTagList stacks = data.getTagList("stacks", 10); + Container cont = player.openContainer; + if (!containerClass.isInstance(cont)) { + return; + } - Map stmap = new HashMap<>(); - for (int i = 0; i < stacks.tagCount(); i++) { - NBTTagCompound itemdata = stacks.getCompoundTagAt(i); - stmap.put(itemdata.getInteger("slot"), ItemStack.loadItemStackFromNBT(itemdata)); - } - for (Object slotobj : cont.inventorySlots) { - if (!slotClass.isInstance(slotobj)) { - continue; - } + Map stmap = new HashMap<>(); + for (int i = 0; i < stacks.tagCount(); i++) { + NBTTagCompound itemdata = stacks.getCompoundTagAt(i); + stmap.put(itemdata.getInteger("slot"), ItemStack.loadItemStackFromNBT(itemdata)); + } + for (Object slotobj : cont.inventorySlots) { + if (!slotClass.isInstance(slotobj)) { + continue; + } - Slot slot = (Slot) slotobj; - if (stmap.containsKey(slot.getSlotIndex())) { - slot.putStack(stmap.get(slot.getSlotIndex())); - } else { - slot.putStack(null); - } - } - } + Slot slot = (Slot) slotobj; + if (stmap.containsKey(slot.getSlotIndex())) { + slot.putStack(stmap.get(slot.getSlotIndex())); + } else { + slot.putStack(null); + } + } + } } diff --git a/src/main/java/forestry/core/render/EnumTankLevel.java b/src/main/java/forestry/core/render/EnumTankLevel.java index e4b1fd3de..c98d8ae8b 100644 --- a/src/main/java/forestry/core/render/EnumTankLevel.java +++ b/src/main/java/forestry/core/render/EnumTankLevel.java @@ -13,39 +13,38 @@ package forestry.core.render; import net.minecraftforge.fluids.IFluidTank; public enum EnumTankLevel { + EMPTY(0), + LOW(25), + MEDIUM(50), + HIGH(75), + MAXIMUM(100); - EMPTY(0), - LOW(25), - MEDIUM(50), - HIGH(75), - MAXIMUM(100); + private final int level; - private final int level; + EnumTankLevel(int level) { + this.level = level; + } - EnumTankLevel(int level) { - this.level = level; - } + public int getLevelScaled(int scale) { + return level * scale / 100; + } - public int getLevelScaled(int scale) { - return level * scale / 100; - } + public static EnumTankLevel rateTankLevel(IFluidTank tank) { + return rateTankLevel(100 * tank.getFluidAmount() / tank.getCapacity()); + } - public static EnumTankLevel rateTankLevel(IFluidTank tank) { - return rateTankLevel(100 * tank.getFluidAmount() / tank.getCapacity()); - } + public static EnumTankLevel rateTankLevel(int scaled) { - public static EnumTankLevel rateTankLevel(int scaled) { - - if (scaled < 5) { - return EMPTY; - } else if (scaled < 30) { - return LOW; - } else if (scaled < 60) { - return MEDIUM; - } else if (scaled < 90) { - return HIGH; - } else { - return MAXIMUM; - } - } + if (scaled < 5) { + return EMPTY; + } else if (scaled < 30) { + return LOW; + } else if (scaled < 60) { + return MEDIUM; + } else if (scaled < 90) { + return HIGH; + } else { + return MAXIMUM; + } + } } diff --git a/src/main/java/forestry/core/render/FontColour.java b/src/main/java/forestry/core/render/FontColour.java index b9e75f0b4..353807cbd 100644 --- a/src/main/java/forestry/core/render/FontColour.java +++ b/src/main/java/forestry/core/render/FontColour.java @@ -12,39 +12,37 @@ package forestry.core.render; import java.io.InputStream; import java.util.Properties; - import net.minecraft.client.resources.IResourceManager; public class FontColour { - //private static final ResourceLocation colourDefinitions = new ForestryResource("/config/forestry/colour.properties"); + // private static final ResourceLocation colourDefinitions = new + // ForestryResource("/config/forestry/colour.properties"); - private final Properties defaultMappings = new Properties(); - private final Properties mappings = new Properties(); + private final Properties defaultMappings = new Properties(); + private final Properties mappings = new Properties(); - public FontColour(IResourceManager texturepack) { - load(texturepack); - } + public FontColour(IResourceManager texturepack) { + load(texturepack); + } - public synchronized int get(String key) { - return Integer.parseInt(mappings.getProperty(key, defaultMappings.getProperty(key, "d67fff")), 16); - } + public synchronized int get(String key) { + return Integer.parseInt(mappings.getProperty(key, defaultMappings.getProperty(key, "d67fff")), 16); + } - public void load(IResourceManager texturepack) { - try { - //InputStream fontStream = texturepack.func_110536_a(colourDefinitions).func_110527_b(); - InputStream defaultFontStream = FontColour.class.getResourceAsStream("/config/forestry/colour.properties"); - //mappings.load((fontStream == null) ? defaultFontStream : fontStream); - mappings.load(defaultFontStream); - defaultMappings.load(defaultFontStream); - - //if (fontStream != null) - // fontStream.close(); - defaultFontStream.close(); - } catch (Exception e) { - e.printStackTrace(); - } - - } + public void load(IResourceManager texturepack) { + try { + // InputStream fontStream = texturepack.func_110536_a(colourDefinitions).func_110527_b(); + InputStream defaultFontStream = FontColour.class.getResourceAsStream("/config/forestry/colour.properties"); + // mappings.load((fontStream == null) ? defaultFontStream : fontStream); + mappings.load(defaultFontStream); + defaultMappings.load(defaultFontStream); + // if (fontStream != null) + // fontStream.close(); + defaultFontStream.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/src/main/java/forestry/core/render/ForestryResource.java b/src/main/java/forestry/core/render/ForestryResource.java index 62b42af06..5db00459f 100644 --- a/src/main/java/forestry/core/render/ForestryResource.java +++ b/src/main/java/forestry/core/render/ForestryResource.java @@ -10,14 +10,12 @@ ******************************************************************************/ package forestry.core.render; -import net.minecraft.util.ResourceLocation; - import forestry.core.config.Constants; +import net.minecraft.util.ResourceLocation; public class ForestryResource extends ResourceLocation { - public ForestryResource(String path) { - super(Constants.ID, path); - } - + public ForestryResource(String path) { + super(Constants.ID, path); + } } diff --git a/src/main/java/forestry/core/render/IBlockRenderer.java b/src/main/java/forestry/core/render/IBlockRenderer.java index ea488f715..0b99f57af 100644 --- a/src/main/java/forestry/core/render/IBlockRenderer.java +++ b/src/main/java/forestry/core/render/IBlockRenderer.java @@ -11,5 +11,5 @@ package forestry.core.render; public interface IBlockRenderer { - void inventoryRender(double x, double y, double z); + void inventoryRender(double x, double y, double z); } diff --git a/src/main/java/forestry/core/render/ModelEscritoire.java b/src/main/java/forestry/core/render/ModelEscritoire.java index e02067781..cad691882 100755 --- a/src/main/java/forestry/core/render/ModelEscritoire.java +++ b/src/main/java/forestry/core/render/ModelEscritoire.java @@ -16,181 +16,180 @@ import net.minecraft.entity.Entity; public class ModelEscritoire extends ModelBase { - //fields - private final ModelRenderer desk; - private final ModelRenderer standRB; - private final ModelRenderer standRF; - private final ModelRenderer standLB; - private final ModelRenderer standLF; - private final ModelRenderer drawers; - private final ModelRenderer standLowLF; - private final ModelRenderer standLowRB; - private final ModelRenderer standLowRF; - private final ModelRenderer standLowLB; + // fields + private final ModelRenderer desk; + private final ModelRenderer standRB; + private final ModelRenderer standRF; + private final ModelRenderer standLB; + private final ModelRenderer standLF; + private final ModelRenderer drawers; + private final ModelRenderer standLowLF; + private final ModelRenderer standLowRB; + private final ModelRenderer standLowRF; + private final ModelRenderer standLowLB; - public ModelEscritoire() { - textureWidth = 64; - textureHeight = 32; + public ModelEscritoire() { + textureWidth = 64; + textureHeight = 32; - desk = new ModelRenderer(this, 0, 0); - desk.addBox(-8F, 3F, -7.8F, 16, 2, 15); - desk.setRotationPoint(0F, 0F, 0F); - desk.setTextureSize(64, 32); - desk.mirror = true; - setRotation(desk, 0.0872665f, 0f, 0f); - standRB = new ModelRenderer(this, 38, 18); - standRB.addBox(5F, 4F, 5F, 2, 6, 2); - standRB.setRotationPoint(0F, 0F, 0F); - standRB.setTextureSize(64, 32); - standRB.mirror = true; - setRotation(standRB, 0F, 0F, 0F); - standRF = new ModelRenderer(this, 38, 18); - standRF.addBox(5F, 4F, -7F, 2, 6, 2); - standRF.setRotationPoint(0F, 0F, 0F); - standRF.setTextureSize(64, 32); - standRF.mirror = true; - setRotation(standRF, 0F, 0F, 0F); - standLB = new ModelRenderer(this, 38, 18); - standLB.addBox(-7F, 4F, 5F, 2, 6, 2); - standLB.setRotationPoint(0F, 0F, 0F); - standLB.setTextureSize(64, 32); - standLB.mirror = true; - setRotation(standLB, 0F, 0F, 0F); - standLF = new ModelRenderer(this, 38, 18); - standLF.addBox(-7F, 4F, -7F, 2, 6, 2); - standLF.setRotationPoint(0F, 0F, 0F); - standLF.setTextureSize(64, 32); - standLF.mirror = true; - setRotation(standLF, 0F, 0F, 0F); - drawers = new ModelRenderer(this, 0, 18); - drawers.addBox(-7.5F, -2F, 4.5F, 15, 5, 3); - drawers.setRotationPoint(0F, 0F, 0F); - drawers.setTextureSize(64, 32); - drawers.mirror = true; - setRotation(drawers, 0F, 0F, 0F); - standLowLF = new ModelRenderer(this, 0, 26); - standLowLF.addBox(-6.5F, 10F, -6.5F, 1, 4, 1); - standLowLF.setRotationPoint(0F, 0F, 0F); - standLowLF.setTextureSize(64, 32); - standLowLF.mirror = true; - setRotation(standLowLF, 0F, 0F, 0F); - standLowRB = new ModelRenderer(this, 0, 26); - standLowRB.addBox(5.5F, 10F, 5.5F, 1, 4, 1); - standLowRB.setRotationPoint(0F, 0F, 0F); - standLowRB.setTextureSize(64, 32); - standLowRB.mirror = true; - setRotation(standLowRB, 0F, 0F, 0F); - standLowRF = new ModelRenderer(this, 0, 26); - standLowRF.addBox(5.5F, 10F, -6.5F, 1, 4, 1); - standLowRF.setRotationPoint(0F, 0F, 0F); - standLowRF.setTextureSize(64, 32); - standLowRF.mirror = true; - setRotation(standLowRF, 0F, 0F, 0F); - standLowLB = new ModelRenderer(this, 0, 26); - standLowLB.addBox(-6.5F, 10F, 5.5F, 1, 4, 1); - standLowLB.setRotationPoint(0F, 0F, 0F); - standLowLB.setTextureSize(64, 32); - standLowLB.mirror = true; - setRotation(standLowLB, 0F, 0F, 0F); - /* - desk = new ModelRenderer(this, 0, 0); - desk.addBox(0F, 0F, 0F, 16, 2, 15); - desk.setRotationPoint(-8F, 4F, -7.5F); - desk.setTextureSize(64, 32); - desk.mirror = true; - setRotation(desk, 0.0872665F, 0F, 0F); - standRB = new ModelRenderer(this, 38, 18); - standRB.addBox(0F, 0F, 0F, 2, 6, 2); - standRB.setRotationPoint(5F, 4F, 5F); - standRB.setTextureSize(64, 32); - standRB.mirror = true; - setRotation(standRB, 0F, 0F, 0F); - standRF = new ModelRenderer(this, 38, 18); - standRF.addBox(0F, 0F, 0F, 2, 6, 2); - standRF.setRotationPoint(5F, 4F, -7F); - standRF.setTextureSize(64, 32); - standRF.mirror = true; - setRotation(standRF, 0F, 0F, 0F); - standLB = new ModelRenderer(this, 38, 18); - standLB.addBox(0F, 0F, 0F, 2, 6, 2); - standLB.setRotationPoint(-7F, 4F, 5F); - standLB.setTextureSize(64, 32); - standLB.mirror = true; - setRotation(standLB, 0F, 0F, 0F); - standLF = new ModelRenderer(this, 38, 18); - standLF.addBox(0F, 0F, 0F, 2, 6, 2); - standLF.setRotationPoint(-7F, 4F, -7F); - standLF.setTextureSize(64, 32); - standLF.mirror = true; - setRotation(standLF, 0F, 0F, 0F); - drawers = new ModelRenderer(this, 0, 18); - drawers.addBox(0F, 0F, 0F, 16, 5, 3); - drawers.setRotationPoint(-8F, -2F, 4.5F); - drawers.setTextureSize(64, 32); - drawers.mirror = true; - setRotation(drawers, 0F, 0F, 0F); - standLowLF = new ModelRenderer(this, 0, 25); - standLowLF.addBox(0F, 0F, 0F, 1, 4, 1); - standLowLF.setRotationPoint(-6.5F, 10F, -6.5F); - standLowLF.setTextureSize(64, 32); - standLowLF.mirror = true; - setRotation(standLowLF, 0F, 0F, 0F); - standLowRB = new ModelRenderer(this, 0, 25); - standLowRB.addBox(0F, 0F, 0F, 1, 4, 1); - standLowRB.setRotationPoint(5.5F, 10F, 5.5F); - standLowRB.setTextureSize(64, 32); - standLowRB.mirror = true; - setRotation(standLowRB, 0F, 0F, 0F); - standLowRF = new ModelRenderer(this, 0, 25); - standLowRF.addBox(0F, 0F, 0F, 1, 4, 1); - standLowRF.setRotationPoint(5.5F, 10F, -6.5F); - standLowRF.setTextureSize(64, 32); - standLowRF.mirror = true; - setRotation(standLowRF, 0F, 0F, 0F); - standLowLB = new ModelRenderer(this, 0, 25); - standLowLB.addBox(0F, 0F, 0F, 1, 4, 1); - standLowLB.setRotationPoint(-6.5F, 10F, 5.5F); - standLowLB.setTextureSize(64, 32); - standLowLB.mirror = true; - setRotation(standLowLB, 0F, 0F, 0F); - */ - } + desk = new ModelRenderer(this, 0, 0); + desk.addBox(-8F, 3F, -7.8F, 16, 2, 15); + desk.setRotationPoint(0F, 0F, 0F); + desk.setTextureSize(64, 32); + desk.mirror = true; + setRotation(desk, 0.0872665f, 0f, 0f); + standRB = new ModelRenderer(this, 38, 18); + standRB.addBox(5F, 4F, 5F, 2, 6, 2); + standRB.setRotationPoint(0F, 0F, 0F); + standRB.setTextureSize(64, 32); + standRB.mirror = true; + setRotation(standRB, 0F, 0F, 0F); + standRF = new ModelRenderer(this, 38, 18); + standRF.addBox(5F, 4F, -7F, 2, 6, 2); + standRF.setRotationPoint(0F, 0F, 0F); + standRF.setTextureSize(64, 32); + standRF.mirror = true; + setRotation(standRF, 0F, 0F, 0F); + standLB = new ModelRenderer(this, 38, 18); + standLB.addBox(-7F, 4F, 5F, 2, 6, 2); + standLB.setRotationPoint(0F, 0F, 0F); + standLB.setTextureSize(64, 32); + standLB.mirror = true; + setRotation(standLB, 0F, 0F, 0F); + standLF = new ModelRenderer(this, 38, 18); + standLF.addBox(-7F, 4F, -7F, 2, 6, 2); + standLF.setRotationPoint(0F, 0F, 0F); + standLF.setTextureSize(64, 32); + standLF.mirror = true; + setRotation(standLF, 0F, 0F, 0F); + drawers = new ModelRenderer(this, 0, 18); + drawers.addBox(-7.5F, -2F, 4.5F, 15, 5, 3); + drawers.setRotationPoint(0F, 0F, 0F); + drawers.setTextureSize(64, 32); + drawers.mirror = true; + setRotation(drawers, 0F, 0F, 0F); + standLowLF = new ModelRenderer(this, 0, 26); + standLowLF.addBox(-6.5F, 10F, -6.5F, 1, 4, 1); + standLowLF.setRotationPoint(0F, 0F, 0F); + standLowLF.setTextureSize(64, 32); + standLowLF.mirror = true; + setRotation(standLowLF, 0F, 0F, 0F); + standLowRB = new ModelRenderer(this, 0, 26); + standLowRB.addBox(5.5F, 10F, 5.5F, 1, 4, 1); + standLowRB.setRotationPoint(0F, 0F, 0F); + standLowRB.setTextureSize(64, 32); + standLowRB.mirror = true; + setRotation(standLowRB, 0F, 0F, 0F); + standLowRF = new ModelRenderer(this, 0, 26); + standLowRF.addBox(5.5F, 10F, -6.5F, 1, 4, 1); + standLowRF.setRotationPoint(0F, 0F, 0F); + standLowRF.setTextureSize(64, 32); + standLowRF.mirror = true; + setRotation(standLowRF, 0F, 0F, 0F); + standLowLB = new ModelRenderer(this, 0, 26); + standLowLB.addBox(-6.5F, 10F, 5.5F, 1, 4, 1); + standLowLB.setRotationPoint(0F, 0F, 0F); + standLowLB.setTextureSize(64, 32); + standLowLB.mirror = true; + setRotation(standLowLB, 0F, 0F, 0F); + /* + desk = new ModelRenderer(this, 0, 0); + desk.addBox(0F, 0F, 0F, 16, 2, 15); + desk.setRotationPoint(-8F, 4F, -7.5F); + desk.setTextureSize(64, 32); + desk.mirror = true; + setRotation(desk, 0.0872665F, 0F, 0F); + standRB = new ModelRenderer(this, 38, 18); + standRB.addBox(0F, 0F, 0F, 2, 6, 2); + standRB.setRotationPoint(5F, 4F, 5F); + standRB.setTextureSize(64, 32); + standRB.mirror = true; + setRotation(standRB, 0F, 0F, 0F); + standRF = new ModelRenderer(this, 38, 18); + standRF.addBox(0F, 0F, 0F, 2, 6, 2); + standRF.setRotationPoint(5F, 4F, -7F); + standRF.setTextureSize(64, 32); + standRF.mirror = true; + setRotation(standRF, 0F, 0F, 0F); + standLB = new ModelRenderer(this, 38, 18); + standLB.addBox(0F, 0F, 0F, 2, 6, 2); + standLB.setRotationPoint(-7F, 4F, 5F); + standLB.setTextureSize(64, 32); + standLB.mirror = true; + setRotation(standLB, 0F, 0F, 0F); + standLF = new ModelRenderer(this, 38, 18); + standLF.addBox(0F, 0F, 0F, 2, 6, 2); + standLF.setRotationPoint(-7F, 4F, -7F); + standLF.setTextureSize(64, 32); + standLF.mirror = true; + setRotation(standLF, 0F, 0F, 0F); + drawers = new ModelRenderer(this, 0, 18); + drawers.addBox(0F, 0F, 0F, 16, 5, 3); + drawers.setRotationPoint(-8F, -2F, 4.5F); + drawers.setTextureSize(64, 32); + drawers.mirror = true; + setRotation(drawers, 0F, 0F, 0F); + standLowLF = new ModelRenderer(this, 0, 25); + standLowLF.addBox(0F, 0F, 0F, 1, 4, 1); + standLowLF.setRotationPoint(-6.5F, 10F, -6.5F); + standLowLF.setTextureSize(64, 32); + standLowLF.mirror = true; + setRotation(standLowLF, 0F, 0F, 0F); + standLowRB = new ModelRenderer(this, 0, 25); + standLowRB.addBox(0F, 0F, 0F, 1, 4, 1); + standLowRB.setRotationPoint(5.5F, 10F, 5.5F); + standLowRB.setTextureSize(64, 32); + standLowRB.mirror = true; + setRotation(standLowRB, 0F, 0F, 0F); + standLowRF = new ModelRenderer(this, 0, 25); + standLowRF.addBox(0F, 0F, 0F, 1, 4, 1); + standLowRF.setRotationPoint(5.5F, 10F, -6.5F); + standLowRF.setTextureSize(64, 32); + standLowRF.mirror = true; + setRotation(standLowRF, 0F, 0F, 0F); + standLowLB = new ModelRenderer(this, 0, 25); + standLowLB.addBox(0F, 0F, 0F, 1, 4, 1); + standLowLB.setRotationPoint(-6.5F, 10F, 5.5F); + standLowLB.setTextureSize(64, 32); + standLowLB.mirror = true; + setRotation(standLowLB, 0F, 0F, 0F); + */ + } - @Override - public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { - super.render(entity, f, f1, f2, f3, f4, f5); - setRotationAngles(f, f1, f2, f3, f4, f5, entity); - desk.render(f5); - standRB.render(f5); - standRF.render(f5); - standLB.render(f5); - standLF.render(f5); - drawers.render(f5); - standLowLF.render(f5); - standLowRB.render(f5); - standLowRF.render(f5); - standLowLB.render(f5); - } + @Override + public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { + super.render(entity, f, f1, f2, f3, f4, f5); + setRotationAngles(f, f1, f2, f3, f4, f5, entity); + desk.render(f5); + standRB.render(f5); + standRF.render(f5); + standLB.render(f5); + standLF.render(f5); + drawers.render(f5); + standLowLF.render(f5); + standLowRB.render(f5); + standLowRF.render(f5); + standLowLB.render(f5); + } - private static void setRotation(ModelRenderer model, float x, float y, float z) { - model.rotateAngleX = x; - model.rotateAngleY = y; - model.rotateAngleZ = z; - } - - @Override - public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { - setRotation(desk, f + 0.0872665f, f1, f2); - setRotation(standRB, f, f1, f2); - setRotation(standRF, f, f1, f2); - setRotation(standLB, f, f1, f2); - setRotation(standLF, f, f1, f2); - setRotation(drawers, f, f1, f2); - setRotation(standLowLF, f, f1, f2); - setRotation(standLowRB, f, f1, f2); - setRotation(standLowRF, f, f1, f2); - setRotation(standLowLB, f, f1, f2); - super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); - } + private static void setRotation(ModelRenderer model, float x, float y, float z) { + model.rotateAngleX = x; + model.rotateAngleY = y; + model.rotateAngleZ = z; + } + @Override + public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { + setRotation(desk, f + 0.0872665f, f1, f2); + setRotation(standRB, f, f1, f2); + setRotation(standRF, f, f1, f2); + setRotation(standLB, f, f1, f2); + setRotation(standLF, f, f1, f2); + setRotation(drawers, f, f1, f2); + setRotation(standLowLF, f, f1, f2); + setRotation(standLowRB, f, f1, f2); + setRotation(standLowRF, f, f1, f2); + setRotation(standLowLB, f, f1, f2); + super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); + } } diff --git a/src/main/java/forestry/core/render/ParticleHelper.java b/src/main/java/forestry/core/render/ParticleHelper.java index b9fe4dc73..4b6e5daaa 100644 --- a/src/main/java/forestry/core/render/ParticleHelper.java +++ b/src/main/java/forestry/core/render/ParticleHelper.java @@ -1,145 +1,156 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.render; - -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.client.particle.EffectRenderer; -import net.minecraft.client.particle.EntityDiggingFX; -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.world.World; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -/** - * @author CovertJaguar - */ -public class ParticleHelper { - - private static final Random rand = new Random(); - - @SideOnly(Side.CLIENT) - public static boolean addHitEffects(World world, Block block, MovingObjectPosition target, EffectRenderer effectRenderer, Callback callback) { - int x = target.blockX; - int y = target.blockY; - int z = target.blockZ; - - int sideHit = target.sideHit; - - if (block != world.getBlock(x, y, z)) { - return true; - } - - int meta = world.getBlockMetadata(x, y, z); - - float b = 0.1F; - double px = x + rand.nextDouble() * (block.getBlockBoundsMaxX() - block.getBlockBoundsMinX() - (b * 2.0F)) + b + block.getBlockBoundsMinX(); - double py = y + rand.nextDouble() * (block.getBlockBoundsMaxY() - block.getBlockBoundsMinY() - (b * 2.0F)) + b + block.getBlockBoundsMinY(); - double pz = z + rand.nextDouble() * (block.getBlockBoundsMaxZ() - block.getBlockBoundsMinZ() - (b * 2.0F)) + b + block.getBlockBoundsMinZ(); - - if (sideHit == 0) { - py = (double) y + block.getBlockBoundsMinY() - (double) b; - } else if (sideHit == 1) { - py = (double) y + block.getBlockBoundsMaxY() + (double) b; - } else if (sideHit == 2) { - pz = (double) z + block.getBlockBoundsMinZ() - (double) b; - } else if (sideHit == 3) { - pz = (double) z + block.getBlockBoundsMaxZ() + (double) b; - } else if (sideHit == 4) { - px = (double) x + block.getBlockBoundsMinX() - (double) b; - } else if (sideHit == 5) { - px = (double) x + block.getBlockBoundsMaxX() + (double) b; - } - - EntityDiggingFX fx = new EntityDiggingFX(world, px, py, pz, 0.0D, 0.0D, 0.0D, block, sideHit, meta); - callback.addHitEffects(fx, world, x, y, z, meta, sideHit); - effectRenderer.addEffect(fx.applyColourMultiplier(x, y, z).multiplyVelocity(0.2F).multipleParticleScaleBy(0.6F)); - - return true; - } - - /** - * Spawn particles for when the block is destroyed. Due to the nature of how - * this is invoked, the x/y/z locations are not always guaranteed to host - * your block. So be sure to do proper sanity checks before assuming that - * the location is this block. - * - * @param world The current world - * @param x X position to spawn the particle - * @param y Y position to spawn the particle - * @param z Z position to spawn the particle - * @param meta The metadata for the block before it was destroyed. - * @param effectRenderer A reference to the current effect renderer. - * @param callback - * @return True to prevent vanilla break particles from spawning. - */ - @SideOnly(Side.CLIENT) - public static boolean addDestroyEffects(World world, Block block, int x, int y, int z, int meta, EffectRenderer effectRenderer, Callback callback) { - if (block != world.getBlock(x, y, z)) { - return true; - } - - byte iterations = 4; - for (int i = 0; i < iterations; ++i) { - for (int j = 0; j < iterations; ++j) { - for (int k = 0; k < iterations; ++k) { - double px = x + (i + 0.5D) / (double) iterations; - double py = y + (j + 0.5D) / (double) iterations; - double pz = z + (k + 0.5D) / (double) iterations; - int random = rand.nextInt(6); - - EntityDiggingFX fx = new EntityDiggingFX(world, px, py, pz, px - x - 0.5D, py - y - 0.5D, pz - z - 0.5D, block, random, meta); - callback.addDestroyEffects(fx, world, x, y, z, meta); - effectRenderer.addEffect(fx.applyColourMultiplier(x, y, z)); - } - } - } - - return true; - } - - public interface Callback { - - @SideOnly(Side.CLIENT) - void addHitEffects(EntityDiggingFX fx, World world, int x, int y, int z, int meta, int side); - - @SideOnly(Side.CLIENT) - void addDestroyEffects(EntityDiggingFX fx, World world, int x, int y, int z, int meta); - } - - public static class DefaultCallback implements ParticleHelper.Callback { - - private final Block block; - - public DefaultCallback(Block block) { - this.block = block; - } - - @Override - @SideOnly(Side.CLIENT) - public void addHitEffects(EntityDiggingFX fx, World world, int x, int y, int z, int meta, int side) { - setTexture(fx, world, x, y, z, side); - } - - @Override - @SideOnly(Side.CLIENT) - public void addDestroyEffects(EntityDiggingFX fx, World world, int x, int y, int z, int meta) { - setTexture(fx, world, x, y, z, 0); - } - - @SideOnly(Side.CLIENT) - private void setTexture(EntityDiggingFX fx, World world, int x, int y, int z, int side) { - fx.setParticleIcon(block.getIcon(world, x, y, z, side)); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.render; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import java.util.Random; +import net.minecraft.block.Block; +import net.minecraft.client.particle.EffectRenderer; +import net.minecraft.client.particle.EntityDiggingFX; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.world.World; + +/** + * @author CovertJaguar + */ +public class ParticleHelper { + + private static final Random rand = new Random(); + + @SideOnly(Side.CLIENT) + public static boolean addHitEffects( + World world, Block block, MovingObjectPosition target, EffectRenderer effectRenderer, Callback callback) { + int x = target.blockX; + int y = target.blockY; + int z = target.blockZ; + + int sideHit = target.sideHit; + + if (block != world.getBlock(x, y, z)) { + return true; + } + + int meta = world.getBlockMetadata(x, y, z); + + float b = 0.1F; + double px = x + + rand.nextDouble() * (block.getBlockBoundsMaxX() - block.getBlockBoundsMinX() - (b * 2.0F)) + + b + + block.getBlockBoundsMinX(); + double py = y + + rand.nextDouble() * (block.getBlockBoundsMaxY() - block.getBlockBoundsMinY() - (b * 2.0F)) + + b + + block.getBlockBoundsMinY(); + double pz = z + + rand.nextDouble() * (block.getBlockBoundsMaxZ() - block.getBlockBoundsMinZ() - (b * 2.0F)) + + b + + block.getBlockBoundsMinZ(); + + if (sideHit == 0) { + py = (double) y + block.getBlockBoundsMinY() - (double) b; + } else if (sideHit == 1) { + py = (double) y + block.getBlockBoundsMaxY() + (double) b; + } else if (sideHit == 2) { + pz = (double) z + block.getBlockBoundsMinZ() - (double) b; + } else if (sideHit == 3) { + pz = (double) z + block.getBlockBoundsMaxZ() + (double) b; + } else if (sideHit == 4) { + px = (double) x + block.getBlockBoundsMinX() - (double) b; + } else if (sideHit == 5) { + px = (double) x + block.getBlockBoundsMaxX() + (double) b; + } + + EntityDiggingFX fx = new EntityDiggingFX(world, px, py, pz, 0.0D, 0.0D, 0.0D, block, sideHit, meta); + callback.addHitEffects(fx, world, x, y, z, meta, sideHit); + effectRenderer.addEffect( + fx.applyColourMultiplier(x, y, z).multiplyVelocity(0.2F).multipleParticleScaleBy(0.6F)); + + return true; + } + + /** + * Spawn particles for when the block is destroyed. Due to the nature of how + * this is invoked, the x/y/z locations are not always guaranteed to host + * your block. So be sure to do proper sanity checks before assuming that + * the location is this block. + * + * @param world The current world + * @param x X position to spawn the particle + * @param y Y position to spawn the particle + * @param z Z position to spawn the particle + * @param meta The metadata for the block before it was destroyed. + * @param effectRenderer A reference to the current effect renderer. + * @param callback + * @return True to prevent vanilla break particles from spawning. + */ + @SideOnly(Side.CLIENT) + public static boolean addDestroyEffects( + World world, Block block, int x, int y, int z, int meta, EffectRenderer effectRenderer, Callback callback) { + if (block != world.getBlock(x, y, z)) { + return true; + } + + byte iterations = 4; + for (int i = 0; i < iterations; ++i) { + for (int j = 0; j < iterations; ++j) { + for (int k = 0; k < iterations; ++k) { + double px = x + (i + 0.5D) / (double) iterations; + double py = y + (j + 0.5D) / (double) iterations; + double pz = z + (k + 0.5D) / (double) iterations; + int random = rand.nextInt(6); + + EntityDiggingFX fx = new EntityDiggingFX( + world, px, py, pz, px - x - 0.5D, py - y - 0.5D, pz - z - 0.5D, block, random, meta); + callback.addDestroyEffects(fx, world, x, y, z, meta); + effectRenderer.addEffect(fx.applyColourMultiplier(x, y, z)); + } + } + } + + return true; + } + + public interface Callback { + + @SideOnly(Side.CLIENT) + void addHitEffects(EntityDiggingFX fx, World world, int x, int y, int z, int meta, int side); + + @SideOnly(Side.CLIENT) + void addDestroyEffects(EntityDiggingFX fx, World world, int x, int y, int z, int meta); + } + + public static class DefaultCallback implements ParticleHelper.Callback { + + private final Block block; + + public DefaultCallback(Block block) { + this.block = block; + } + + @Override + @SideOnly(Side.CLIENT) + public void addHitEffects(EntityDiggingFX fx, World world, int x, int y, int z, int meta, int side) { + setTexture(fx, world, x, y, z, side); + } + + @Override + @SideOnly(Side.CLIENT) + public void addDestroyEffects(EntityDiggingFX fx, World world, int x, int y, int z, int meta) { + setTexture(fx, world, x, y, z, 0); + } + + @SideOnly(Side.CLIENT) + private void setTexture(EntityDiggingFX fx, World world, int x, int y, int z, int side) { + fx.setParticleIcon(block.getIcon(world, x, y, z, side)); + } + } +} diff --git a/src/main/java/forestry/core/render/RenderAnalyzer.java b/src/main/java/forestry/core/render/RenderAnalyzer.java index d7b707cad..e07e271af 100755 --- a/src/main/java/forestry/core/render/RenderAnalyzer.java +++ b/src/main/java/forestry/core/render/RenderAnalyzer.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.render; +import forestry.apiculture.render.ModelAnalyzer; +import forestry.core.tiles.TileAnalyzer; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; @@ -17,72 +19,65 @@ import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; - import net.minecraftforge.common.util.ForgeDirection; - import org.lwjgl.opengl.GL11; -import forestry.apiculture.render.ModelAnalyzer; -import forestry.core.tiles.TileAnalyzer; - public class RenderAnalyzer extends TileEntitySpecialRenderer implements IBlockRenderer { - private final ModelAnalyzer model; - private final EntityItem dummyEntityItem = new EntityItem(null); - private final RenderItem customRenderItem; - private long lastTick; + private final ModelAnalyzer model; + private final EntityItem dummyEntityItem = new EntityItem(null); + private final RenderItem customRenderItem; + private long lastTick; - public RenderAnalyzer(String baseTexture) { - customRenderItem = new RenderItem() { - @Override - public boolean shouldBob() { - return true; - } + public RenderAnalyzer(String baseTexture) { + customRenderItem = new RenderItem() { + @Override + public boolean shouldBob() { + return true; + } - @Override - public boolean shouldSpreadItems() { - return false; - } - }; - customRenderItem.setRenderManager(RenderManager.instance); - this.model = new ModelAnalyzer(baseTexture); - } + @Override + public boolean shouldSpreadItems() { + return false; + } + }; + customRenderItem.setRenderManager(RenderManager.instance); + this.model = new ModelAnalyzer(baseTexture); + } - @Override - public void inventoryRender(double x, double y, double z) { - render(null, null, ForgeDirection.WEST, x, y, z); - } + @Override + public void inventoryRender(double x, double y, double z) { + render(null, null, ForgeDirection.WEST, x, y, z); + } - @Override - public void renderTileEntityAt(TileEntity tile, double d, double d1, double d2, float f) { + @Override + public void renderTileEntityAt(TileEntity tile, double d, double d1, double d2, float f) { - TileAnalyzer analyzer = (TileAnalyzer) tile; - render(analyzer.getIndividualOnDisplay(), tile.getWorldObj(), analyzer.getOrientation(), d, d1, d2); - } + TileAnalyzer analyzer = (TileAnalyzer) tile; + render(analyzer.getIndividualOnDisplay(), tile.getWorldObj(), analyzer.getOrientation(), d, d1, d2); + } - private void render(ItemStack itemstack, World world, ForgeDirection orientation, double x, double y, double z) { + private void render(ItemStack itemstack, World world, ForgeDirection orientation, double x, double y, double z) { - dummyEntityItem.worldObj = world; + dummyEntityItem.worldObj = world; - model.render(orientation, (float) x, (float) y, (float) z); - if (itemstack == null) { - return; - } - float renderScale = 1.0f; + model.render(orientation, (float) x, (float) y, (float) z); + if (itemstack == null) { + return; + } + float renderScale = 1.0f; - GL11.glPushMatrix(); - GL11.glTranslatef((float) x, (float) y, (float) z); - GL11.glTranslatef(0.5f, 0.2f, 0.5f); - GL11.glScalef(renderScale, renderScale, renderScale); - dummyEntityItem.setEntityItemStack(itemstack); - - if (world.getTotalWorldTime() != lastTick) { - lastTick = world.getTotalWorldTime(); - dummyEntityItem.onUpdate(); - } - customRenderItem.doRender(dummyEntityItem, 0, 0, 0, 0, 0); - GL11.glPopMatrix(); - - } + GL11.glPushMatrix(); + GL11.glTranslatef((float) x, (float) y, (float) z); + GL11.glTranslatef(0.5f, 0.2f, 0.5f); + GL11.glScalef(renderScale, renderScale, renderScale); + dummyEntityItem.setEntityItemStack(itemstack); + if (world.getTotalWorldTime() != lastTick) { + lastTick = world.getTotalWorldTime(); + dummyEntityItem.onUpdate(); + } + customRenderItem.doRender(dummyEntityItem, 0, 0, 0, 0, 0); + GL11.glPopMatrix(); + } } diff --git a/src/main/java/forestry/core/render/RenderBlock.java b/src/main/java/forestry/core/render/RenderBlock.java index c2789e360..892b7a45c 100644 --- a/src/main/java/forestry/core/render/RenderBlock.java +++ b/src/main/java/forestry/core/render/RenderBlock.java @@ -10,45 +10,41 @@ ******************************************************************************/ package forestry.core.render; +import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; +import forestry.core.proxy.Proxies; import java.util.HashMap; - import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.world.IBlockAccess; -import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; - -import forestry.core.proxy.Proxies; - public class RenderBlock implements ISimpleBlockRenderingHandler { - public static final HashMap byBlockRenderer = new HashMap<>(); + public static final HashMap byBlockRenderer = new HashMap<>(); - @Override - public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { + @Override + public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { - if (block.getRenderType() == Proxies.render.getByBlockModelRenderId()) { - TileRendererIndex index = new TileRendererIndex(block, metadata); - if (byBlockRenderer.containsKey(index)) { - byBlockRenderer.get(index).inventoryRender(-0.5, -0.5, -0.5); - } - } + if (block.getRenderType() == Proxies.render.getByBlockModelRenderId()) { + TileRendererIndex index = new TileRendererIndex(block, metadata); + if (byBlockRenderer.containsKey(index)) { + byBlockRenderer.get(index).inventoryRender(-0.5, -0.5, -0.5); + } + } + } - } + @Override + public boolean renderWorldBlock( + IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { + return true; + } - @Override - public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { - return true; - } - - @Override - public boolean shouldRender3DInInventory(int modelId) { - return true; - } - - @Override - public int getRenderId() { - return Proxies.render.getByBlockModelRenderId(); - } + @Override + public boolean shouldRender3DInInventory(int modelId) { + return true; + } + @Override + public int getRenderId() { + return Proxies.render.getByBlockModelRenderId(); + } } diff --git a/src/main/java/forestry/core/render/RenderCrateItem.java b/src/main/java/forestry/core/render/RenderCrateItem.java index 617cd89c2..3eccb9d4e 100644 --- a/src/main/java/forestry/core/render/RenderCrateItem.java +++ b/src/main/java/forestry/core/render/RenderCrateItem.java @@ -1,350 +1,349 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.render; - -import java.util.Random; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.ItemRenderer; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.entity.RenderItem; -import net.minecraft.client.renderer.entity.RenderManager; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.item.Item; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.util.ResourceLocation; - -import net.minecraftforge.client.IItemRenderer; - -import org.lwjgl.opengl.GL11; - -import forestry.core.items.ItemCrated; - -/** - * Adapted from RenderTankCartItem by CovertJaguar - */ -public class RenderCrateItem implements IItemRenderer { - - private static final ResourceLocation BLOCK_TEXTURE = TextureMap.locationBlocksTexture; - private static final ResourceLocation ITEM_TEXTURE = TextureMap.locationItemsTexture; - private static final ResourceLocation GLINT_TEXTURE = new ResourceLocation("textures/misc/enchanted_item_glint.png"); - - private static final float PIXEL = 1.0f / 16.0f; - - private final RenderItem renderItem = new RenderItem(); - - @Override - public boolean handleRenderType(ItemStack stack, ItemRenderType type) { - switch (type) { - case INVENTORY: - case ENTITY: - case EQUIPPED: - case EQUIPPED_FIRST_PERSON: - return true; - default: - return false; - } - } - - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack stack, ItemRendererHelper helper) { - return helper == ItemRendererHelper.ENTITY_BOBBING; - } - - @Override - public void renderItem(ItemRenderType type, ItemStack stack, Object... data) { - if (type == ItemRenderType.INVENTORY) { - render(ItemRenderType.INVENTORY, stack); - } else if (type == ItemRenderType.ENTITY) { - if (RenderManager.instance.options.fancyGraphics) { - renderAsEntity(stack, (EntityItem) data[1]); - } else { - renderAsEntityFlat(stack); - } - } else if (type == ItemRenderType.EQUIPPED || type == ItemRenderType.EQUIPPED_FIRST_PERSON) { - GL11.glPushMatrix(); - renderEquipped(stack); - - ItemStack contained = getContainedFromCrate(stack); - - if (contained != null) { - float scale = 0.5f; - GL11.glScalef(scale, scale, 1.1f); - GL11.glTranslatef(10f * PIXEL, 8f * PIXEL, 0.001f); - if (contained.getItem() instanceof ItemBlock) { - renderIn3D(contained); - } else { - renderEquipped(contained); - } - } - GL11.glPopMatrix(); - } - } - - private void renderEquipped(ItemStack stack) { - GL11.glPushMatrix(); - Tessellator tessellator = Tessellator.instance; - - int meta = stack.getItemDamage(); - for (int pass = 0; pass < stack.getItem().getRenderPasses(meta); ++pass) { - IIcon icon = stack.getItem().getIconFromDamageForRenderPass(meta, pass); - if (icon == null) { - continue; - } - - if (renderItem.renderWithColor) { - int color = stack.getItem().getColorFromItemStack(stack, pass); - float c1 = (float) (color >> 16 & 255) / 255.0F; - float c2 = (float) (color >> 8 & 255) / 255.0F; - float c3 = (float) (color & 255) / 255.0F; - - GL11.glColor4f(c1, c2, c3, 1.0F); - } - - float uv1 = icon.getMinU(); - float uv2 = icon.getMaxU(); - float uv3 = icon.getMinV(); - float uv4 = icon.getMaxV(); - - ItemRenderer.renderItemIn2D(tessellator, uv2, uv3, uv1, uv4, icon.getIconWidth(), icon.getIconHeight(), PIXEL); - } - - GL11.glPopMatrix(); - } - - private void renderAsEntity(ItemStack stack, EntityItem entity) { - GL11.glPushMatrix(); - byte iterations = 1; - if (stack.stackSize > 1) { - iterations = 2; - } - if (stack.stackSize > 15) { - iterations = 3; - } - if (stack.stackSize > 31) { - iterations = 4; - } - - Random rand = new Random(187L); - - float offsetZ = PIXEL + 0.021875F; - - GL11.glRotatef((((float) entity.age + 1.0F) / 20.0F + entity.hoverStart) * (180F / (float) Math.PI), 0.0F, 1.0F, 0.0F); - GL11.glTranslatef(-0.5F, -0.25F, -(offsetZ * (float) iterations / 2.0F)); - - for (int count = 0; count < iterations; ++count) { - if (count > 0) { - float offsetX = (rand.nextFloat() * 2.0F - 1.0F) * 0.3F / 0.5F; - float offsetY = (rand.nextFloat() * 2.0F - 1.0F) * 0.3F / 0.5F; - GL11.glTranslatef(offsetX, offsetY, offsetZ); - } else { - GL11.glTranslatef(0f, 0f, offsetZ); - } - - renderIn3D(stack); - - ItemStack contained = getContainedFromCrate(stack); - - if (contained != null) { - GL11.glPushMatrix(); - float scale = 0.5f; - GL11.glScalef(scale, scale, 1.1F); - GL11.glTranslatef(10.0f * PIXEL, 8.0f * PIXEL, 0.003F); - renderIn3D(contained); - GL11.glPopMatrix(); - } - } - GL11.glPopMatrix(); - } - - private void renderIn3D(ItemStack stack) { - Tessellator tessellator = Tessellator.instance; - if (RenderManager.instance.renderEngine == null) { - return; - } - - int meta = stack.getItemDamage(); - for (int pass = 0; pass < stack.getItem().getRenderPasses(meta); ++pass) { - IIcon icon = stack.getItem().getIconFromDamageForRenderPass(meta, pass); - if (icon == null) { - continue; - } - - if (renderItem.renderWithColor) { - int color = stack.getItem().getColorFromItemStack(stack, pass); - float c1 = (float) (color >> 16 & 255) / 255.0F; - float c2 = (float) (color >> 8 & 255) / 255.0F; - float c3 = (float) (color & 255) / 255.0F; - - GL11.glColor4f(c1, c2, c3, 1.0F); - } - - float minU = icon.getMinU(); - float maxU = icon.getMaxU(); - float minV = icon.getMinV(); - float maxV = icon.getMaxV(); - - if (stack.getItemSpriteNumber() == 0) { - RenderManager.instance.renderEngine.bindTexture(BLOCK_TEXTURE); - } else { - RenderManager.instance.renderEngine.bindTexture(ITEM_TEXTURE); - } - - ItemRenderer.renderItemIn2D(tessellator, maxU, minV, minU, maxV, icon.getIconWidth(), icon.getIconHeight(), PIXEL); - - if (stack.hasEffect(pass)) { - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - { - GL11.glDepthFunc(GL11.GL_EQUAL); - GL11.glDisable(GL11.GL_LIGHTING); - RenderManager.instance.renderEngine.bindTexture(GLINT_TEXTURE); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE); - - float f13 = 0.76F; - float f14 = 0.125F; - float f15 = (float) (Minecraft.getSystemTime() % 3000L) / 3000.0F * 8.0F; - GL11.glColor4f(0.5F * f13, 0.25F * f13, 0.8F * f13, 1.0F); - - GL11.glMatrixMode(GL11.GL_TEXTURE); - - GL11.glPushMatrix(); - { - GL11.glScalef(f14, f14, f14); - GL11.glTranslatef(f15, 0.0F, 0.0F); - GL11.glRotatef(-50.0F, 0.0F, 0.0F, 1.0F); - ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 255, 255, PIXEL); - } - GL11.glPopMatrix(); - - GL11.glPushMatrix(); - { - GL11.glScalef(f14, f14, f14); - f15 = (float) (Minecraft.getSystemTime() % 4873L) / 4873.0F * 8.0F; - GL11.glTranslatef(-f15, 0.0F, 0.0F); - GL11.glRotatef(10.0F, 0.0F, 0.0F, 1.0F); - ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 255, 255, PIXEL); - } - GL11.glPopMatrix(); - - GL11.glMatrixMode(GL11.GL_MODELVIEW); - } - GL11.glPopAttrib(); - } - } - } - - private void renderAsEntityFlat(ItemStack stack) { - GL11.glPushMatrix(); - byte iterations = 1; - if (stack.stackSize > 1) { - iterations = 2; - } - if (stack.stackSize > 15) { - iterations = 3; - } - if (stack.stackSize > 31) { - iterations = 4; - } - - Random rand = new Random(187L); - - for (int ii = 0; ii < iterations; ++ii) { - GL11.glPushMatrix(); - GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F); - GL11.glRotatef(180 - RenderManager.instance.playerViewY, 0.0F, 1.0F, 0.0F); - - if (ii > 0) { - float var12 = (rand.nextFloat() * 2.0F - 1.0F) * 0.3F; - float var13 = (rand.nextFloat() * 2.0F - 1.0F) * 0.3F; - float var14 = (rand.nextFloat() * 2.0F - 1.0F) * 0.3F; - GL11.glTranslatef(var12, var13, var14); - } - - GL11.glTranslatef(0.5f, 0.8f, 0); - GL11.glRotatef(180.0F, 0.0F, 0.0F, 1.0F); - GL11.glScalef(1f / 16f, 1f / 16f, 1); - - render(ItemRenderType.ENTITY, stack); - GL11.glPopMatrix(); - } - GL11.glPopMatrix(); - } - - private void render(ItemRenderType type, ItemStack stack) { - GL11.glPushMatrix(); - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - - IIcon crateTexture = stack.getIconIndex(); - renderItem.renderIcon(0, 0, crateTexture, 16, 16); - - ItemStack contained = getContainedFromCrate(stack); - - if (contained != null) { - - int meta = contained.getItemDamage(); - - float scale = 0.5f; - GL11.glScalef(scale, scale, 1); - GL11.glTranslatef(6f, 8f, 0); - if (type == ItemRenderType.ENTITY) { - GL11.glTranslatef(0, 0, -0.1f); - } - - if (contained.getItem() instanceof ItemBlock) { - GL11.glScalef(16f, 16f, 1f); - GL11.glTranslatef(1f, 1f, 0.1f); - GL11.glRotatef(180.0F, 0.0F, 0.0F, 1.0F); - renderIn3D(contained); - } else { - for (int pass = 0; pass < contained.getItem().getRenderPasses(meta); ++pass) { - IIcon containedTexture = contained.getItem().getIconFromDamageForRenderPass(meta, pass); - if (containedTexture == null) { - continue; - } - - if (renderItem.renderWithColor) { - int color = contained.getItem().getColorFromItemStack(contained, pass); - float c1 = (float) (color >> 16 & 255) / 255.0F; - float c2 = (float) (color >> 8 & 255) / 255.0F; - float c3 = (float) (color & 255) / 255.0F; - - GL11.glColor4f(c1, c2, c3, 1.0F); - } - - renderItem.renderIcon(0, 0, containedTexture, 16, 16); - } - } - } - - GL11.glPopAttrib(); - GL11.glPopMatrix(); - } - - private static ItemStack getContainedFromCrate(ItemStack crate) { - if (crate == null) { - return null; - } - - Item crateItem = crate.getItem(); - if (crateItem instanceof ItemCrated) { - return ((ItemCrated) crateItem).getContained(); - } - return null; - } - -} \ No newline at end of file +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.render; + +import forestry.core.items.ItemCrated; +import java.util.Random; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.ItemRenderer; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.client.renderer.entity.RenderManager; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.item.Item; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.client.IItemRenderer; +import org.lwjgl.opengl.GL11; + +/** + * Adapted from RenderTankCartItem by CovertJaguar + */ +public class RenderCrateItem implements IItemRenderer { + + private static final ResourceLocation BLOCK_TEXTURE = TextureMap.locationBlocksTexture; + private static final ResourceLocation ITEM_TEXTURE = TextureMap.locationItemsTexture; + private static final ResourceLocation GLINT_TEXTURE = + new ResourceLocation("textures/misc/enchanted_item_glint.png"); + + private static final float PIXEL = 1.0f / 16.0f; + + private final RenderItem renderItem = new RenderItem(); + + @Override + public boolean handleRenderType(ItemStack stack, ItemRenderType type) { + switch (type) { + case INVENTORY: + case ENTITY: + case EQUIPPED: + case EQUIPPED_FIRST_PERSON: + return true; + default: + return false; + } + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack stack, ItemRendererHelper helper) { + return helper == ItemRendererHelper.ENTITY_BOBBING; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack stack, Object... data) { + if (type == ItemRenderType.INVENTORY) { + render(ItemRenderType.INVENTORY, stack); + } else if (type == ItemRenderType.ENTITY) { + if (RenderManager.instance.options.fancyGraphics) { + renderAsEntity(stack, (EntityItem) data[1]); + } else { + renderAsEntityFlat(stack); + } + } else if (type == ItemRenderType.EQUIPPED || type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + GL11.glPushMatrix(); + renderEquipped(stack); + + ItemStack contained = getContainedFromCrate(stack); + + if (contained != null) { + float scale = 0.5f; + GL11.glScalef(scale, scale, 1.1f); + GL11.glTranslatef(10f * PIXEL, 8f * PIXEL, 0.001f); + if (contained.getItem() instanceof ItemBlock) { + renderIn3D(contained); + } else { + renderEquipped(contained); + } + } + GL11.glPopMatrix(); + } + } + + private void renderEquipped(ItemStack stack) { + GL11.glPushMatrix(); + Tessellator tessellator = Tessellator.instance; + + int meta = stack.getItemDamage(); + for (int pass = 0; pass < stack.getItem().getRenderPasses(meta); ++pass) { + IIcon icon = stack.getItem().getIconFromDamageForRenderPass(meta, pass); + if (icon == null) { + continue; + } + + if (renderItem.renderWithColor) { + int color = stack.getItem().getColorFromItemStack(stack, pass); + float c1 = (float) (color >> 16 & 255) / 255.0F; + float c2 = (float) (color >> 8 & 255) / 255.0F; + float c3 = (float) (color & 255) / 255.0F; + + GL11.glColor4f(c1, c2, c3, 1.0F); + } + + float uv1 = icon.getMinU(); + float uv2 = icon.getMaxU(); + float uv3 = icon.getMinV(); + float uv4 = icon.getMaxV(); + + ItemRenderer.renderItemIn2D( + tessellator, uv2, uv3, uv1, uv4, icon.getIconWidth(), icon.getIconHeight(), PIXEL); + } + + GL11.glPopMatrix(); + } + + private void renderAsEntity(ItemStack stack, EntityItem entity) { + GL11.glPushMatrix(); + byte iterations = 1; + if (stack.stackSize > 1) { + iterations = 2; + } + if (stack.stackSize > 15) { + iterations = 3; + } + if (stack.stackSize > 31) { + iterations = 4; + } + + Random rand = new Random(187L); + + float offsetZ = PIXEL + 0.021875F; + + GL11.glRotatef( + (((float) entity.age + 1.0F) / 20.0F + entity.hoverStart) * (180F / (float) Math.PI), 0.0F, 1.0F, 0.0F); + GL11.glTranslatef(-0.5F, -0.25F, -(offsetZ * (float) iterations / 2.0F)); + + for (int count = 0; count < iterations; ++count) { + if (count > 0) { + float offsetX = (rand.nextFloat() * 2.0F - 1.0F) * 0.3F / 0.5F; + float offsetY = (rand.nextFloat() * 2.0F - 1.0F) * 0.3F / 0.5F; + GL11.glTranslatef(offsetX, offsetY, offsetZ); + } else { + GL11.glTranslatef(0f, 0f, offsetZ); + } + + renderIn3D(stack); + + ItemStack contained = getContainedFromCrate(stack); + + if (contained != null) { + GL11.glPushMatrix(); + float scale = 0.5f; + GL11.glScalef(scale, scale, 1.1F); + GL11.glTranslatef(10.0f * PIXEL, 8.0f * PIXEL, 0.003F); + renderIn3D(contained); + GL11.glPopMatrix(); + } + } + GL11.glPopMatrix(); + } + + private void renderIn3D(ItemStack stack) { + Tessellator tessellator = Tessellator.instance; + if (RenderManager.instance.renderEngine == null) { + return; + } + + int meta = stack.getItemDamage(); + for (int pass = 0; pass < stack.getItem().getRenderPasses(meta); ++pass) { + IIcon icon = stack.getItem().getIconFromDamageForRenderPass(meta, pass); + if (icon == null) { + continue; + } + + if (renderItem.renderWithColor) { + int color = stack.getItem().getColorFromItemStack(stack, pass); + float c1 = (float) (color >> 16 & 255) / 255.0F; + float c2 = (float) (color >> 8 & 255) / 255.0F; + float c3 = (float) (color & 255) / 255.0F; + + GL11.glColor4f(c1, c2, c3, 1.0F); + } + + float minU = icon.getMinU(); + float maxU = icon.getMaxU(); + float minV = icon.getMinV(); + float maxV = icon.getMaxV(); + + if (stack.getItemSpriteNumber() == 0) { + RenderManager.instance.renderEngine.bindTexture(BLOCK_TEXTURE); + } else { + RenderManager.instance.renderEngine.bindTexture(ITEM_TEXTURE); + } + + ItemRenderer.renderItemIn2D( + tessellator, maxU, minV, minU, maxV, icon.getIconWidth(), icon.getIconHeight(), PIXEL); + + if (stack.hasEffect(pass)) { + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + { + GL11.glDepthFunc(GL11.GL_EQUAL); + GL11.glDisable(GL11.GL_LIGHTING); + RenderManager.instance.renderEngine.bindTexture(GLINT_TEXTURE); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE); + + float f13 = 0.76F; + float f14 = 0.125F; + float f15 = (float) (Minecraft.getSystemTime() % 3000L) / 3000.0F * 8.0F; + GL11.glColor4f(0.5F * f13, 0.25F * f13, 0.8F * f13, 1.0F); + + GL11.glMatrixMode(GL11.GL_TEXTURE); + + GL11.glPushMatrix(); + { + GL11.glScalef(f14, f14, f14); + GL11.glTranslatef(f15, 0.0F, 0.0F); + GL11.glRotatef(-50.0F, 0.0F, 0.0F, 1.0F); + ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 255, 255, PIXEL); + } + GL11.glPopMatrix(); + + GL11.glPushMatrix(); + { + GL11.glScalef(f14, f14, f14); + f15 = (float) (Minecraft.getSystemTime() % 4873L) / 4873.0F * 8.0F; + GL11.glTranslatef(-f15, 0.0F, 0.0F); + GL11.glRotatef(10.0F, 0.0F, 0.0F, 1.0F); + ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 255, 255, PIXEL); + } + GL11.glPopMatrix(); + + GL11.glMatrixMode(GL11.GL_MODELVIEW); + } + GL11.glPopAttrib(); + } + } + } + + private void renderAsEntityFlat(ItemStack stack) { + GL11.glPushMatrix(); + byte iterations = 1; + if (stack.stackSize > 1) { + iterations = 2; + } + if (stack.stackSize > 15) { + iterations = 3; + } + if (stack.stackSize > 31) { + iterations = 4; + } + + Random rand = new Random(187L); + + for (int ii = 0; ii < iterations; ++ii) { + GL11.glPushMatrix(); + GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F); + GL11.glRotatef(180 - RenderManager.instance.playerViewY, 0.0F, 1.0F, 0.0F); + + if (ii > 0) { + float var12 = (rand.nextFloat() * 2.0F - 1.0F) * 0.3F; + float var13 = (rand.nextFloat() * 2.0F - 1.0F) * 0.3F; + float var14 = (rand.nextFloat() * 2.0F - 1.0F) * 0.3F; + GL11.glTranslatef(var12, var13, var14); + } + + GL11.glTranslatef(0.5f, 0.8f, 0); + GL11.glRotatef(180.0F, 0.0F, 0.0F, 1.0F); + GL11.glScalef(1f / 16f, 1f / 16f, 1); + + render(ItemRenderType.ENTITY, stack); + GL11.glPopMatrix(); + } + GL11.glPopMatrix(); + } + + private void render(ItemRenderType type, ItemStack stack) { + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + IIcon crateTexture = stack.getIconIndex(); + renderItem.renderIcon(0, 0, crateTexture, 16, 16); + + ItemStack contained = getContainedFromCrate(stack); + + if (contained != null) { + + int meta = contained.getItemDamage(); + + float scale = 0.5f; + GL11.glScalef(scale, scale, 1); + GL11.glTranslatef(6f, 8f, 0); + if (type == ItemRenderType.ENTITY) { + GL11.glTranslatef(0, 0, -0.1f); + } + + if (contained.getItem() instanceof ItemBlock) { + GL11.glScalef(16f, 16f, 1f); + GL11.glTranslatef(1f, 1f, 0.1f); + GL11.glRotatef(180.0F, 0.0F, 0.0F, 1.0F); + renderIn3D(contained); + } else { + for (int pass = 0; pass < contained.getItem().getRenderPasses(meta); ++pass) { + IIcon containedTexture = contained.getItem().getIconFromDamageForRenderPass(meta, pass); + if (containedTexture == null) { + continue; + } + + if (renderItem.renderWithColor) { + int color = contained.getItem().getColorFromItemStack(contained, pass); + float c1 = (float) (color >> 16 & 255) / 255.0F; + float c2 = (float) (color >> 8 & 255) / 255.0F; + float c3 = (float) (color & 255) / 255.0F; + + GL11.glColor4f(c1, c2, c3, 1.0F); + } + + renderItem.renderIcon(0, 0, containedTexture, 16, 16); + } + } + } + + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } + + private static ItemStack getContainedFromCrate(ItemStack crate) { + if (crate == null) { + return null; + } + + Item crateItem = crate.getItem(); + if (crateItem instanceof ItemCrated) { + return ((ItemCrated) crateItem).getContained(); + } + return null; + } +} diff --git a/src/main/java/forestry/core/render/RenderEscritoire.java b/src/main/java/forestry/core/render/RenderEscritoire.java index d78825b92..89ae848c7 100755 --- a/src/main/java/forestry/core/render/RenderEscritoire.java +++ b/src/main/java/forestry/core/render/RenderEscritoire.java @@ -10,104 +10,101 @@ ******************************************************************************/ package forestry.core.render; +import forestry.core.config.Constants; +import forestry.core.inventory.InventoryEscritoire; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.TileEscritoire; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; - import net.minecraftforge.common.util.ForgeDirection; - import org.lwjgl.opengl.GL11; -import forestry.core.config.Constants; -import forestry.core.inventory.InventoryEscritoire; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.TileEscritoire; - public class RenderEscritoire extends TileEntitySpecialRenderer implements IBlockRenderer { - private static final ResourceLocation texture = new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/escritoire.png"); - private final ModelEscritoire modelEscritoire; + private static final ResourceLocation texture = + new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/escritoire.png"); + private final ModelEscritoire modelEscritoire; - public RenderEscritoire() { - modelEscritoire = new ModelEscritoire(); + public RenderEscritoire() { + modelEscritoire = new ModelEscritoire(); - RenderItem customRenderItem = new RenderItem() { - @Override - public boolean shouldBob() { - return false; - } + RenderItem customRenderItem = new RenderItem() { + @Override + public boolean shouldBob() { + return false; + } - @Override - public boolean shouldSpreadItems() { - return false; - } - }; - customRenderItem.setRenderManager(RenderManager.instance); + @Override + public boolean shouldSpreadItems() { + return false; + } + }; + customRenderItem.setRenderManager(RenderManager.instance); + } - } + @Override + public void inventoryRender(double x, double y, double z) { + render(null, ForgeDirection.EAST, x, y, z); + } - @Override - public void inventoryRender(double x, double y, double z) { - render(null, ForgeDirection.EAST, x, y, z); - } + @Override + public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float f) { + TileEscritoire tile = (TileEscritoire) tileentity; + render(tile.getStackInSlot(InventoryEscritoire.SLOT_ANALYZE), tile.getOrientation(), x, y, z); + } - @Override - public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float f) { - TileEscritoire tile = (TileEscritoire) tileentity; - render(tile.getStackInSlot(InventoryEscritoire.SLOT_ANALYZE), tile.getOrientation(), x, y, z); - } + private void render(ItemStack itemstack, ForgeDirection orientation, double x, double y, double z) { + float factor = (float) (1.0 / 16.0); - private void render(ItemStack itemstack, ForgeDirection orientation, double x, double y, double z) { - float factor = (float) (1.0 / 16.0); + GL11.glPushMatrix(); + GL11.glTranslatef((float) x + 0.5f, (float) y + 0.875f, (float) z + 0.5f); - GL11.glPushMatrix(); - GL11.glTranslatef((float) x + 0.5f, (float) y + 0.875f, (float) z + 0.5f); + float[] angle = {(float) Math.PI, 0, 0}; - float[] angle = {(float) Math.PI, 0, 0}; + if (orientation == null) { + orientation = ForgeDirection.WEST; + } + switch (orientation) { + case EAST: + angle[1] = (float) Math.PI / 2; + break; + case SOUTH: + break; + case NORTH: + angle[1] = (float) Math.PI; + break; + case WEST: + default: + angle[1] = -(float) Math.PI / 2; + break; + } - if (orientation == null) { - orientation = ForgeDirection.WEST; - } - switch (orientation) { - case EAST: - angle[1] = (float) Math.PI / 2; - break; - case SOUTH: - break; - case NORTH: - angle[1] = (float) Math.PI; - break; - case WEST: - default: - angle[1] = -(float) Math.PI / 2; - break; - } + Proxies.render.bindTexture(texture); + modelEscritoire.render(null, angle[0], angle[1], angle[2], 0f, 0f, factor); - Proxies.render.bindTexture(texture); - modelEscritoire.render(null, angle[0], angle[1], angle[2], 0f, 0f, factor); + GL11.glPopMatrix(); - GL11.glPopMatrix(); + /* + if(itemstack != null) { + float renderScale = 1.0f; - /* - if(itemstack != null) { - float renderScale = 1.0f; + GL11.glPushMatrix(); + GL11.glTranslatef((float) x, (float) y, (float) z); + GL11.glTranslatef(0.6f, 0.8f, 0.5f); + GL11.glRotatef(90.0f, 1.0F, 0.0F, 0.0F); + GL11.glScalef(renderScale, renderScale, renderScale); - GL11.glPushMatrix(); - GL11.glTranslatef((float) x, (float) y, (float) z); - GL11.glTranslatef(0.6f, 0.8f, 0.5f); - GL11.glRotatef(90.0f, 1.0F, 0.0F, 0.0F); - GL11.glScalef(renderScale, renderScale, renderScale); + RenderItem.renderInFrame = true; + dummyEntityItem.setEntityItemStack(itemstack); + customRenderItem.doRenderItem(dummyEntityItem, 0, 0, 0, 0, 0); + RenderItem.renderInFrame = false; + GL11.glPopMatrix(); + } + */ - RenderItem.renderInFrame = true; - dummyEntityItem.setEntityItemStack(itemstack); - customRenderItem.doRenderItem(dummyEntityItem, 0, 0, 0, 0, 0); - RenderItem.renderInFrame = false; - GL11.glPopMatrix(); - } - */ - - } + } } diff --git a/src/main/java/forestry/core/render/RenderMachine.java b/src/main/java/forestry/core/render/RenderMachine.java index 62731c718..1eea051c7 100755 --- a/src/main/java/forestry/core/render/RenderMachine.java +++ b/src/main/java/forestry/core/render/RenderMachine.java @@ -10,172 +10,175 @@ ******************************************************************************/ package forestry.core.render; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.IRenderableTile; import java.awt.Color; import java.util.EnumMap; import java.util.Locale; - import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; - import net.minecraftforge.common.util.ForgeDirection; - import org.lwjgl.opengl.GL11; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.IRenderableTile; - public class RenderMachine extends TileEntitySpecialRenderer implements IBlockRenderer { - private final ModelRenderer basefront; - private final ModelRenderer baseback; - private final ModelRenderer resourceTank; - private final ModelRenderer productTank; + private final ModelRenderer basefront; + private final ModelRenderer baseback; + private final ModelRenderer resourceTank; + private final ModelRenderer productTank; - private ResourceLocation textureBase; - private ResourceLocation textureResourceTank; - private ResourceLocation textureProductTank; + private ResourceLocation textureBase; + private ResourceLocation textureResourceTank; + private ResourceLocation textureProductTank; - private final EnumMap texturesTankLevels = new EnumMap<>(EnumTankLevel.class); + private final EnumMap texturesTankLevels = new EnumMap<>(EnumTankLevel.class); - private RenderMachine() { - ModelBase model = new RenderModelBase(); + private RenderMachine() { + ModelBase model = new RenderModelBase(); - basefront = new ModelRenderer(model, 0, 0); - basefront.addBox(-8F, -8F, -8F, 16, 4, 16); - basefront.rotationPointX = 8; - basefront.rotationPointY = 8; - basefront.rotationPointZ = 8; + basefront = new ModelRenderer(model, 0, 0); + basefront.addBox(-8F, -8F, -8F, 16, 4, 16); + basefront.rotationPointX = 8; + basefront.rotationPointY = 8; + basefront.rotationPointZ = 8; - baseback = new ModelRenderer(model, 0, 0); - baseback.addBox(-8F, 4F, -8F, 16, 4, 16); - baseback.rotationPointX = 8; - baseback.rotationPointY = 8; - baseback.rotationPointZ = 8; + baseback = new ModelRenderer(model, 0, 0); + baseback.addBox(-8F, 4F, -8F, 16, 4, 16); + baseback.rotationPointX = 8; + baseback.rotationPointY = 8; + baseback.rotationPointZ = 8; - resourceTank = new ModelRenderer(model, 0, 0); - resourceTank.addBox(-6F, -8F, -6F, 12, 16, 6); - resourceTank.rotationPointX = 8; - resourceTank.rotationPointY = 8; - resourceTank.rotationPointZ = 8; + resourceTank = new ModelRenderer(model, 0, 0); + resourceTank.addBox(-6F, -8F, -6F, 12, 16, 6); + resourceTank.rotationPointX = 8; + resourceTank.rotationPointY = 8; + resourceTank.rotationPointZ = 8; - productTank = new ModelRenderer(model, 0, 0); - productTank.addBox(-6F, -8F, 0F, 12, 16, 6); - productTank.rotationPointX = 8; - productTank.rotationPointY = 8; - productTank.rotationPointZ = 8; - } + productTank = new ModelRenderer(model, 0, 0); + productTank.addBox(-6F, -8F, 0F, 12, 16, 6); + productTank.rotationPointX = 8; + productTank.rotationPointY = 8; + productTank.rotationPointZ = 8; + } - public RenderMachine(String baseTexture) { - this(); + public RenderMachine(String baseTexture) { + this(); - textureBase = new ForestryResource(baseTexture + "base.png"); - textureProductTank = new ForestryResource(baseTexture + "tank_product_empty.png"); - textureResourceTank = new ForestryResource(baseTexture + "tank_resource_empty.png"); + textureBase = new ForestryResource(baseTexture + "base.png"); + textureProductTank = new ForestryResource(baseTexture + "tank_product_empty.png"); + textureResourceTank = new ForestryResource(baseTexture + "tank_resource_empty.png"); - for (EnumTankLevel tankLevel : EnumTankLevel.values()) { - if (tankLevel == EnumTankLevel.EMPTY) { - continue; - } - String tankLevelString = tankLevel.toString().toLowerCase(Locale.ENGLISH); - texturesTankLevels.put(tankLevel, new ForestryResource("textures/blocks/machine_tank_" + tankLevelString + ".png")); - } - } + for (EnumTankLevel tankLevel : EnumTankLevel.values()) { + if (tankLevel == EnumTankLevel.EMPTY) { + continue; + } + String tankLevelString = tankLevel.toString().toLowerCase(Locale.ENGLISH); + texturesTankLevels.put( + tankLevel, new ForestryResource("textures/blocks/machine_tank_" + tankLevelString + ".png")); + } + } - @Override - public void inventoryRender(double x, double y, double z) { - render(TankRenderInfo.EMPTY, TankRenderInfo.EMPTY, ForgeDirection.SOUTH, x, y, z); - } + @Override + public void inventoryRender(double x, double y, double z) { + render(TankRenderInfo.EMPTY, TankRenderInfo.EMPTY, ForgeDirection.SOUTH, x, y, z); + } - @Override - public void renderTileEntityAt(TileEntity tileentity, double d, double d1, double d2, float f) { - IRenderableTile generator = (IRenderableTile) tileentity; - render(generator.getResourceTankInfo(), generator.getProductTankInfo(), generator.getOrientation(), d, d1, d2); - } + @Override + public void renderTileEntityAt(TileEntity tileentity, double d, double d1, double d2, float f) { + IRenderableTile generator = (IRenderableTile) tileentity; + render(generator.getResourceTankInfo(), generator.getProductTankInfo(), generator.getOrientation(), d, d1, d2); + } - private void render(TankRenderInfo resourceTankInfo, TankRenderInfo productTankInfo, ForgeDirection orientation, double x, double y, double z) { - GL11.glPushMatrix(); - GL11.glTranslatef((float) x, (float) y, (float) z); + private void render( + TankRenderInfo resourceTankInfo, + TankRenderInfo productTankInfo, + ForgeDirection orientation, + double x, + double y, + double z) { + GL11.glPushMatrix(); + GL11.glTranslatef((float) x, (float) y, (float) z); - float[] angle = {0, 0, 0}; + float[] angle = {0, 0, 0}; - if (orientation == null) { - orientation = ForgeDirection.WEST; - } - switch (orientation) { - case EAST: - angle[1] = (float) Math.PI; - angle[2] = (float) -Math.PI / 2; - break; - case WEST: - angle[2] = (float) Math.PI / 2; - break; - case UP: - break; - case DOWN: - angle[2] = (float) Math.PI; - break; - case SOUTH: - angle[0] = (float) Math.PI / 2; - angle[2] = (float) Math.PI / 2; - break; - case NORTH: - default: - angle[0] = (float) -Math.PI / 2; - angle[2] = (float) Math.PI / 2; - break; - } + if (orientation == null) { + orientation = ForgeDirection.WEST; + } + switch (orientation) { + case EAST: + angle[1] = (float) Math.PI; + angle[2] = (float) -Math.PI / 2; + break; + case WEST: + angle[2] = (float) Math.PI / 2; + break; + case UP: + break; + case DOWN: + angle[2] = (float) Math.PI; + break; + case SOUTH: + angle[0] = (float) Math.PI / 2; + angle[2] = (float) Math.PI / 2; + break; + case NORTH: + default: + angle[0] = (float) -Math.PI / 2; + angle[2] = (float) Math.PI / 2; + break; + } - basefront.rotateAngleX = angle[0]; - basefront.rotateAngleY = angle[1]; - basefront.rotateAngleZ = angle[2]; + basefront.rotateAngleX = angle[0]; + basefront.rotateAngleY = angle[1]; + basefront.rotateAngleZ = angle[2]; - baseback.rotateAngleX = angle[0]; - baseback.rotateAngleY = angle[1]; - baseback.rotateAngleZ = angle[2]; + baseback.rotateAngleX = angle[0]; + baseback.rotateAngleY = angle[1]; + baseback.rotateAngleZ = angle[2]; - resourceTank.rotateAngleX = angle[0]; - resourceTank.rotateAngleY = angle[1]; - resourceTank.rotateAngleZ = angle[2]; + resourceTank.rotateAngleX = angle[0]; + resourceTank.rotateAngleY = angle[1]; + resourceTank.rotateAngleZ = angle[2]; - productTank.rotateAngleX = angle[0]; - productTank.rotateAngleY = angle[1]; - productTank.rotateAngleZ = angle[2]; + productTank.rotateAngleX = angle[0]; + productTank.rotateAngleY = angle[1]; + productTank.rotateAngleZ = angle[2]; - float factor = (float) (1.0 / 16.0); + float factor = (float) (1.0 / 16.0); - Proxies.render.bindTexture(textureBase); - basefront.render(factor); - baseback.render(factor); + Proxies.render.bindTexture(textureBase); + basefront.render(factor); + baseback.render(factor); - renderTank(resourceTank, textureResourceTank, resourceTankInfo, factor); - renderTank(productTank, textureProductTank, productTankInfo, factor); + renderTank(resourceTank, textureResourceTank, resourceTankInfo, factor); + renderTank(productTank, textureProductTank, productTankInfo, factor); - GL11.glPopMatrix(); - } + GL11.glPopMatrix(); + } - private void renderTank(ModelRenderer tankModel, ResourceLocation textureBase, TankRenderInfo renderInfo, float factor) { - Proxies.render.bindTexture(textureBase); - tankModel.render(factor); + private void renderTank( + ModelRenderer tankModel, ResourceLocation textureBase, TankRenderInfo renderInfo, float factor) { + Proxies.render.bindTexture(textureBase); + tankModel.render(factor); - ResourceLocation textureResourceTankLevel = texturesTankLevels.get(renderInfo.getLevel()); - if (textureResourceTankLevel == null) { - return; - } + ResourceLocation textureResourceTankLevel = texturesTankLevels.get(renderInfo.getLevel()); + if (textureResourceTankLevel == null) { + return; + } - Color primaryTankColor = renderInfo.getFluidColor(); - float[] colors = new float[3]; - primaryTankColor.getRGBColorComponents(colors); - GL11.glColor4f(colors[0], colors[1], colors[2], 1.0f); + Color primaryTankColor = renderInfo.getFluidColor(); + float[] colors = new float[3]; + primaryTankColor.getRGBColorComponents(colors); + GL11.glColor4f(colors[0], colors[1], colors[2], 1.0f); - Proxies.render.bindTexture(textureResourceTankLevel); - tankModel.render(factor); + Proxies.render.bindTexture(textureResourceTankLevel); + tankModel.render(factor); - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - } + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } - private static class RenderModelBase extends ModelBase { - } + private static class RenderModelBase extends ModelBase {} } diff --git a/src/main/java/forestry/core/render/RenderMill.java b/src/main/java/forestry/core/render/RenderMill.java index 2018f7d31..6887f992c 100755 --- a/src/main/java/forestry/core/render/RenderMill.java +++ b/src/main/java/forestry/core/render/RenderMill.java @@ -10,191 +10,190 @@ ******************************************************************************/ package forestry.core.render; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.TileMill; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; - import net.minecraftforge.common.util.ForgeDirection; - import org.lwjgl.opengl.GL11; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.TileMill; - public class RenderMill extends TileEntitySpecialRenderer implements IBlockRenderer { - private final ModelBase model = new ModelBase() { - }; + private final ModelBase model = new ModelBase() {}; - private enum Textures {PEDESTAL, EXTENSION, BLADE_1, BLADE_2, CHARGE} + private enum Textures { + PEDESTAL, + EXTENSION, + BLADE_1, + BLADE_2, + CHARGE + } - private ResourceLocation[] textures; + private ResourceLocation[] textures; - private final ModelRenderer pedestal; - private final ModelRenderer column; - private final ModelRenderer extension; - private final ModelRenderer blade1; - private final ModelRenderer blade2; + private final ModelRenderer pedestal; + private final ModelRenderer column; + private final ModelRenderer extension; + private final ModelRenderer blade1; + private final ModelRenderer blade2; - public RenderMill() { - pedestal = new ModelRenderer(model, 0, 0); - pedestal.addBox(-8F, -8F, -8F, 16, 1, 16); - pedestal.rotationPointX = 8; - pedestal.rotationPointY = 8; - pedestal.rotationPointZ = 8; + public RenderMill() { + pedestal = new ModelRenderer(model, 0, 0); + pedestal.addBox(-8F, -8F, -8F, 16, 1, 16); + pedestal.rotationPointX = 8; + pedestal.rotationPointY = 8; + pedestal.rotationPointZ = 8; - column = new ModelRenderer(model, 0, 0); - column.addBox(-2, -7F, -2, 4, 15, 4); - column.rotationPointX = 8; - column.rotationPointY = 8; - column.rotationPointZ = 8; + column = new ModelRenderer(model, 0, 0); + column.addBox(-2, -7F, -2, 4, 15, 4); + column.rotationPointX = 8; + column.rotationPointY = 8; + column.rotationPointZ = 8; - extension = new ModelRenderer(model, 0, 0); - extension.addBox(1F, 8F, 7F, 14, 2, 2); - extension.rotationPointX = 0; - extension.rotationPointY = 0; - extension.rotationPointZ = 0; + extension = new ModelRenderer(model, 0, 0); + extension.addBox(1F, 8F, 7F, 14, 2, 2); + extension.rotationPointX = 0; + extension.rotationPointY = 0; + extension.rotationPointZ = 0; - blade1 = new ModelRenderer(model, 0, 0); - blade1.addBox(-4F, -5F, -3F, 8, 12, 1); - blade1.rotationPointX = 8; - blade1.rotationPointY = 8; - blade1.rotationPointZ = 8; + blade1 = new ModelRenderer(model, 0, 0); + blade1.addBox(-4F, -5F, -3F, 8, 12, 1); + blade1.rotationPointX = 8; + blade1.rotationPointY = 8; + blade1.rotationPointZ = 8; - blade2 = new ModelRenderer(model, 0, 0); - blade2.addBox(-4F, -5F, 2F, 8, 12, 1); - blade2.rotationPointX = 8; - blade2.rotationPointY = 8; - blade2.rotationPointZ = 8; + blade2 = new ModelRenderer(model, 0, 0); + blade2.addBox(-4F, -5F, 2F, 8, 12, 1); + blade2.rotationPointX = 8; + blade2.rotationPointY = 8; + blade2.rotationPointZ = 8; + } - } + public RenderMill(String baseTexture) { + this(); - public RenderMill(String baseTexture) { - this(); + textures = new ResourceLocation[12]; - textures = new ResourceLocation[12]; + textures[Textures.PEDESTAL.ordinal()] = new ForestryResource(baseTexture + "pedestal.png"); + textures[Textures.EXTENSION.ordinal()] = new ForestryResource(baseTexture + "extension.png"); + textures[Textures.BLADE_1.ordinal()] = new ForestryResource(baseTexture + "blade1.png"); + textures[Textures.BLADE_2.ordinal()] = new ForestryResource(baseTexture + "blade2.png"); - textures[Textures.PEDESTAL.ordinal()] = new ForestryResource(baseTexture + "pedestal.png"); - textures[Textures.EXTENSION.ordinal()] = new ForestryResource(baseTexture + "extension.png"); - textures[Textures.BLADE_1.ordinal()] = new ForestryResource(baseTexture + "blade1.png"); - textures[Textures.BLADE_2.ordinal()] = new ForestryResource(baseTexture + "blade2.png"); + for (int i = 0; i < 8; i++) { + textures[Textures.CHARGE.ordinal() + i] = new ForestryResource(baseTexture + "column_" + i + ".png"); + } + } - for (int i = 0; i < 8; i++) { - textures[Textures.CHARGE.ordinal() + i] = new ForestryResource(baseTexture + "column_" + i + ".png"); - } - } + public RenderMill(String baseTexture, byte charges) { + this(baseTexture); + } - public RenderMill(String baseTexture, byte charges) { - this(baseTexture); - } + @Override + public void inventoryRender(double x, double y, double z) { + byte charge = 0; + render(0.0f, charge, ForgeDirection.WEST, x, y, z); + } - @Override - public void inventoryRender(double x, double y, double z) { - byte charge = 0; - render(0.0f, charge, ForgeDirection.WEST, x, y, z); - } + @Override + public void renderTileEntityAt(TileEntity tileentity, double d, double d1, double d2, float f) { + TileMill tile = (TileMill) tileentity; + render(tile.progress, tile.charge, ForgeDirection.WEST, d, d1, d2); + } - @Override - public void renderTileEntityAt(TileEntity tileentity, double d, double d1, double d2, float f) { - TileMill tile = (TileMill) tileentity; - render(tile.progress, tile.charge, ForgeDirection.WEST, d, d1, d2); - } + private void render(float progress, int charge, ForgeDirection orientation, double x, double y, double z) { - private void render(float progress, int charge, ForgeDirection orientation, double x, double y, double z) { + GL11.glPushMatrix(); - GL11.glPushMatrix(); + GL11.glTranslatef((float) x, (float) y, (float) z); - GL11.glTranslatef((float) x, (float) y, (float) z); + float step; - float step; + if (progress > 0.5) { + step = 3.99F - (progress - 0.5F) * 2F * 3.99F; + } else { + step = progress * 2F * 3.99F; + } - if (progress > 0.5) { - step = 3.99F - (progress - 0.5F) * 2F * 3.99F; - } else { - step = progress * 2F * 3.99F; - } + float[] angle = {0, 0, 0}; + float[] translate = {0, 0, 0}; + float tfactor = step / 16; - float[] angle = {0, 0, 0}; - float[] translate = {0, 0, 0}; - float tfactor = step / 16; + if (orientation == null) { + orientation = ForgeDirection.WEST; + } + switch (orientation) { + case EAST: + // angle [2] = (float) Math.PI / 2; + angle[1] = (float) Math.PI; + angle[2] = (float) -Math.PI / 2; + translate[0] = 1; + break; + case WEST: + // 2, -PI/2 + angle[2] = (float) Math.PI / 2; + translate[0] = -1; + break; + case UP: + translate[1] = 1; + break; + case DOWN: + angle[2] = (float) Math.PI; + translate[1] = -1; + break; + case SOUTH: + angle[0] = (float) Math.PI / 2; + angle[2] = (float) Math.PI / 2; + translate[2] = 1; + break; + case NORTH: + default: + angle[0] = (float) -Math.PI / 2; + angle[2] = (float) Math.PI / 2; + translate[2] = -1; + break; + } - if (orientation == null) { - orientation = ForgeDirection.WEST; - } - switch (orientation) { - case EAST: - // angle [2] = (float) Math.PI / 2; - angle[1] = (float) Math.PI; - angle[2] = (float) -Math.PI / 2; - translate[0] = 1; - break; - case WEST: - // 2, -PI/2 - angle[2] = (float) Math.PI / 2; - translate[0] = -1; - break; - case UP: - translate[1] = 1; - break; - case DOWN: - angle[2] = (float) Math.PI; - translate[1] = -1; - break; - case SOUTH: - angle[0] = (float) Math.PI / 2; - angle[2] = (float) Math.PI / 2; - translate[2] = 1; - break; - case NORTH: - default: - angle[0] = (float) -Math.PI / 2; - angle[2] = (float) Math.PI / 2; - translate[2] = -1; - break; - } + pedestal.rotateAngleX = angle[0]; + pedestal.rotateAngleY = angle[2]; + pedestal.rotateAngleZ = angle[1]; - pedestal.rotateAngleX = angle[0]; - pedestal.rotateAngleY = angle[2]; - pedestal.rotateAngleZ = angle[1]; + column.rotateAngleX = angle[0]; + column.rotateAngleY = angle[2]; + column.rotateAngleZ = angle[1]; - column.rotateAngleX = angle[0]; - column.rotateAngleY = angle[2]; - column.rotateAngleZ = angle[1]; + blade1.rotateAngleX = angle[0]; + blade1.rotateAngleY = angle[2]; + blade1.rotateAngleZ = angle[1]; - blade1.rotateAngleX = angle[0]; - blade1.rotateAngleY = angle[2]; - blade1.rotateAngleZ = angle[1]; + blade2.rotateAngleX = angle[0]; + blade2.rotateAngleY = angle[2]; + blade2.rotateAngleZ = angle[1]; - blade2.rotateAngleX = angle[0]; - blade2.rotateAngleY = angle[2]; - blade2.rotateAngleZ = angle[1]; + float factor = (float) (1.0 / 16.0); - float factor = (float) (1.0 / 16.0); + Proxies.render.bindTexture(textures[Textures.PEDESTAL.ordinal()]); + pedestal.render(factor); - Proxies.render.bindTexture(textures[Textures.PEDESTAL.ordinal()]); - pedestal.render(factor); + Proxies.render.bindTexture(textures[Textures.CHARGE.ordinal() + charge]); + column.render(factor); - Proxies.render.bindTexture(textures[Textures.CHARGE.ordinal() + charge]); - column.render(factor); + Proxies.render.bindTexture(textures[Textures.EXTENSION.ordinal()]); + extension.render(factor); - Proxies.render.bindTexture(textures[Textures.EXTENSION.ordinal()]); - extension.render(factor); + Proxies.render.bindTexture(textures[Textures.BLADE_1.ordinal()]); + GL11.glTranslatef(translate[0] * tfactor, translate[1] * tfactor, translate[2] * tfactor); + blade1.render(factor); - Proxies.render.bindTexture(textures[Textures.BLADE_1.ordinal()]); - GL11.glTranslatef(translate[0] * tfactor, translate[1] * tfactor, translate[2] * tfactor); - blade1.render(factor); + // Reset + GL11.glTranslatef(-translate[0] * tfactor, -translate[1] * tfactor, -translate[2] * tfactor); - // Reset - GL11.glTranslatef(-translate[0] * tfactor, -translate[1] * tfactor, -translate[2] * tfactor); - - Proxies.render.bindTexture(textures[Textures.BLADE_2.ordinal()]); - GL11.glTranslatef(-translate[0] * tfactor, translate[1] * tfactor, -translate[2] * tfactor); - blade2.render(factor); - - GL11.glPopMatrix(); - - } + Proxies.render.bindTexture(textures[Textures.BLADE_2.ordinal()]); + GL11.glTranslatef(-translate[0] * tfactor, translate[1] * tfactor, -translate[2] * tfactor); + blade2.render(factor); + GL11.glPopMatrix(); + } } diff --git a/src/main/java/forestry/core/render/RenderNaturalistChest.java b/src/main/java/forestry/core/render/RenderNaturalistChest.java index 4f5d0b399..80b31ae20 100644 --- a/src/main/java/forestry/core/render/RenderNaturalistChest.java +++ b/src/main/java/forestry/core/render/RenderNaturalistChest.java @@ -10,72 +10,76 @@ ******************************************************************************/ package forestry.core.render; +import forestry.core.config.Constants; +import forestry.core.tiles.TileNaturalistChest; import net.minecraft.client.model.ModelChest; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; - import net.minecraftforge.common.util.ForgeDirection; - import org.lwjgl.opengl.GL11; -import forestry.core.config.Constants; -import forestry.core.tiles.TileNaturalistChest; - public class RenderNaturalistChest extends TileEntitySpecialRenderer implements IBlockRenderer { - private final ModelChest chestModel = new ModelChest(); - private final ResourceLocation texture; + private final ModelChest chestModel = new ModelChest(); + private final ResourceLocation texture; - public RenderNaturalistChest(String textureName) { - texture = new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/" + textureName + ".png"); - } + public RenderNaturalistChest(String textureName) { + texture = new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/" + textureName + ".png"); + } - @Override - public void inventoryRender(double x, double y, double z) { - render(ForgeDirection.EAST, 0, 0, x, y, z, 0); - } + @Override + public void inventoryRender(double x, double y, double z) { + render(ForgeDirection.EAST, 0, 0, x, y, z, 0); + } - @Override - public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float partialTick) { - TileNaturalistChest chest = (TileNaturalistChest) tileentity; - render(chest.getOrientation(), chest.prevLidAngle, chest.lidAngle, x, y, z, partialTick); - } + @Override + public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float partialTick) { + TileNaturalistChest chest = (TileNaturalistChest) tileentity; + render(chest.getOrientation(), chest.prevLidAngle, chest.lidAngle, x, y, z, partialTick); + } - public void render(ForgeDirection orientation, float prevLidAngle, float lidAngle, double x, double y, double z, float partialTick) { - GL11.glPushMatrix(); - bindTexture(texture); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glTranslatef((float) x, (float) y + 1.0F, (float) z + 1.0F); - GL11.glScalef(1.0F, -1.0F, -1.0F); - GL11.glTranslatef(0.5F, 0.5F, 0.5F); + public void render( + ForgeDirection orientation, + float prevLidAngle, + float lidAngle, + double x, + double y, + double z, + float partialTick) { + GL11.glPushMatrix(); + bindTexture(texture); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glTranslatef((float) x, (float) y + 1.0F, (float) z + 1.0F); + GL11.glScalef(1.0F, -1.0F, -1.0F); + GL11.glTranslatef(0.5F, 0.5F, 0.5F); - int rotation; - switch (orientation) { - case EAST: - rotation = -90; - break; - case NORTH: - rotation = 180; - break; - case WEST: - rotation = 90; - break; - default: - case SOUTH: - rotation = 0; - break; - } + int rotation; + switch (orientation) { + case EAST: + rotation = -90; + break; + case NORTH: + rotation = 180; + break; + case WEST: + rotation = 90; + break; + default: + case SOUTH: + rotation = 0; + break; + } - GL11.glRotatef(rotation, 0.0F, 1.0F, 0.0F); - GL11.glTranslatef(-0.5F, -0.5F, -0.5F); + GL11.glRotatef(rotation, 0.0F, 1.0F, 0.0F); + GL11.glTranslatef(-0.5F, -0.5F, -0.5F); - float angle = prevLidAngle + (lidAngle - prevLidAngle) * partialTick; - angle = 1.0F - angle; - angle = 1.0F - angle * angle * angle; - chestModel.chestLid.rotateAngleX = -(angle * (float) Math.PI / 2.0F); - chestModel.renderAll(); + float angle = prevLidAngle + (lidAngle - prevLidAngle) * partialTick; + angle = 1.0F - angle; + angle = 1.0F - angle * angle * angle; + chestModel.chestLid.rotateAngleX = -(angle * (float) Math.PI / 2.0F); + chestModel.renderAll(); - GL11.glPopMatrix(); - } + GL11.glPopMatrix(); + } } diff --git a/src/main/java/forestry/core/render/RenderOverlayBlock.java b/src/main/java/forestry/core/render/RenderOverlayBlock.java index 85fc20c76..a18bf1add 100644 --- a/src/main/java/forestry/core/render/RenderOverlayBlock.java +++ b/src/main/java/forestry/core/render/RenderOverlayBlock.java @@ -10,110 +10,163 @@ ******************************************************************************/ package forestry.core.render; +import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; -import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; - public abstract class RenderOverlayBlock implements ISimpleBlockRenderingHandler { - protected static final double OVERLAY_SHIFT = 0.001; + protected static final double OVERLAY_SHIFT = 0.001; - private static int determineMixedBrightness(IBlockAccess world, Block block, int x, int y, int z, RenderBlocks renderer, int mixedBrightness) { - return renderer.renderMinY > 0.0D ? mixedBrightness : block.getMixedBrightnessForBlock(world, x, y, z); - } + private static int determineMixedBrightness( + IBlockAccess world, Block block, int x, int y, int z, RenderBlocks renderer, int mixedBrightness) { + return renderer.renderMinY > 0.0D ? mixedBrightness : block.getMixedBrightnessForBlock(world, x, y, z); + } - protected static void renderBottomFace(IBlockAccess world, Block block, int x, int y, int z, RenderBlocks renderer, IIcon textureIndex, int mixedBrightness, - float r, float g, float b) { + protected static void renderBottomFace( + IBlockAccess world, + Block block, + int x, + int y, + int z, + RenderBlocks renderer, + IIcon textureIndex, + int mixedBrightness, + float r, + float g, + float b) { - if (!renderer.renderAllFaces && !block.shouldSideBeRendered(world, x, y - 1, z, 0)) { - return; - } + if (!renderer.renderAllFaces && !block.shouldSideBeRendered(world, x, y - 1, z, 0)) { + return; + } - Tessellator tesselator = Tessellator.instance; + Tessellator tesselator = Tessellator.instance; - tesselator.setBrightness(determineMixedBrightness(world, block, x, y - 1, z, renderer, mixedBrightness)); - tesselator.setColorOpaque_F(r, g, b); - renderer.renderFaceYNeg(block, x, y - OVERLAY_SHIFT, z, textureIndex); + tesselator.setBrightness(determineMixedBrightness(world, block, x, y - 1, z, renderer, mixedBrightness)); + tesselator.setColorOpaque_F(r, g, b); + renderer.renderFaceYNeg(block, x, y - OVERLAY_SHIFT, z, textureIndex); + } - } + protected static void renderTopFace( + IBlockAccess world, + Block block, + int x, + int y, + int z, + RenderBlocks renderer, + IIcon textureIndex, + int mixedBrightness, + float r, + float g, + float b) { - protected static void renderTopFace(IBlockAccess world, Block block, int x, int y, int z, RenderBlocks renderer, IIcon textureIndex, int mixedBrightness, float r, - float g, float b) { + if (!renderer.renderAllFaces && !block.shouldSideBeRendered(world, x, y + 1, z, 1)) { + return; + } - if (!renderer.renderAllFaces && !block.shouldSideBeRendered(world, x, y + 1, z, 1)) { - return; - } + Tessellator tesselator = Tessellator.instance; - Tessellator tesselator = Tessellator.instance; + tesselator.setBrightness(determineMixedBrightness(world, block, x, y + 1, z, renderer, mixedBrightness)); + tesselator.setColorOpaque_F(r, g, b); + renderer.renderFaceYPos(block, x, y + OVERLAY_SHIFT, z, textureIndex); + } - tesselator.setBrightness(determineMixedBrightness(world, block, x, y + 1, z, renderer, mixedBrightness)); - tesselator.setColorOpaque_F(r, g, b); - renderer.renderFaceYPos(block, x, y + OVERLAY_SHIFT, z, textureIndex); + protected static void renderEastFace( + IBlockAccess world, + Block block, + int x, + int y, + int z, + RenderBlocks renderer, + IIcon textureIndex, + int mixedBrightness, + float r, + float g, + float b) { - } + if (!renderer.renderAllFaces && !block.shouldSideBeRendered(world, x, y, z - 1, 2)) { + return; + } - protected static void renderEastFace(IBlockAccess world, Block block, int x, int y, int z, RenderBlocks renderer, IIcon textureIndex, int mixedBrightness, float r, - float g, float b) { + Tessellator tesselator = Tessellator.instance; - if (!renderer.renderAllFaces && !block.shouldSideBeRendered(world, x, y, z - 1, 2)) { - return; - } + tesselator.setBrightness(determineMixedBrightness(world, block, x, y, z - 1, renderer, mixedBrightness)); + tesselator.setColorOpaque_F(r, g, b); + renderer.renderFaceZNeg(block, x, y, z - OVERLAY_SHIFT, textureIndex); + } - Tessellator tesselator = Tessellator.instance; + protected static void renderWestFace( + IBlockAccess world, + Block block, + int x, + int y, + int z, + RenderBlocks renderer, + IIcon textureIndex, + int mixedBrightness, + float r, + float g, + float b) { - tesselator.setBrightness(determineMixedBrightness(world, block, x, y, z - 1, renderer, mixedBrightness)); - tesselator.setColorOpaque_F(r, g, b); - renderer.renderFaceZNeg(block, x, y, z - OVERLAY_SHIFT, textureIndex); + if (!renderer.renderAllFaces && !block.shouldSideBeRendered(world, x, y, z + 1, 3)) { + return; + } - } + Tessellator tesselator = Tessellator.instance; - protected static void renderWestFace(IBlockAccess world, Block block, int x, int y, int z, RenderBlocks renderer, IIcon textureIndex, int mixedBrightness, float r, - float g, float b) { + tesselator.setBrightness(determineMixedBrightness(world, block, x, y, z + 1, renderer, mixedBrightness)); + tesselator.setColorOpaque_F(r, g, b); + renderer.renderFaceZPos(block, x, y, z + OVERLAY_SHIFT, textureIndex); + } - if (!renderer.renderAllFaces && !block.shouldSideBeRendered(world, x, y, z + 1, 3)) { - return; - } + protected static void renderNorthFace( + IBlockAccess world, + Block block, + int x, + int y, + int z, + RenderBlocks renderer, + IIcon textureIndex, + int mixedBrightness, + float r, + float g, + float b) { - Tessellator tesselator = Tessellator.instance; + if (!renderer.renderAllFaces && !block.shouldSideBeRendered(world, x - 1, y, z, 4)) { + return; + } - tesselator.setBrightness(determineMixedBrightness(world, block, x, y, z + 1, renderer, mixedBrightness)); - tesselator.setColorOpaque_F(r, g, b); - renderer.renderFaceZPos(block, x, y, z + OVERLAY_SHIFT, textureIndex); + Tessellator tesselator = Tessellator.instance; - } + tesselator.setBrightness(determineMixedBrightness(world, block, x - 1, y, z, renderer, mixedBrightness)); + tesselator.setColorOpaque_F(r, g, b); + renderer.renderFaceXNeg(block, x - OVERLAY_SHIFT, y, z, textureIndex); + } - protected static void renderNorthFace(IBlockAccess world, Block block, int x, int y, int z, RenderBlocks renderer, IIcon textureIndex, int mixedBrightness, - float r, float g, float b) { + protected static void renderSouthFace( + IBlockAccess world, + Block block, + int x, + int y, + int z, + RenderBlocks renderer, + IIcon textureIndex, + int mixedBrightness, + float r, + float g, + float b) { - if (!renderer.renderAllFaces && !block.shouldSideBeRendered(world, x - 1, y, z, 4)) { - return; - } + if (!renderer.renderAllFaces && !block.shouldSideBeRendered(world, x + 1, y, z, 5)) { + return; + } - Tessellator tesselator = Tessellator.instance; - - tesselator.setBrightness(determineMixedBrightness(world, block, x - 1, y, z, renderer, mixedBrightness)); - tesselator.setColorOpaque_F(r, g, b); - renderer.renderFaceXNeg(block, x - OVERLAY_SHIFT, y, z, textureIndex); - - } - - protected static void renderSouthFace(IBlockAccess world, Block block, int x, int y, int z, RenderBlocks renderer, IIcon textureIndex, int mixedBrightness, - float r, float g, float b) { - - if (!renderer.renderAllFaces && !block.shouldSideBeRendered(world, x + 1, y, z, 5)) { - return; - } - - Tessellator tesselator = Tessellator.instance; - - tesselator.setBrightness(determineMixedBrightness(world, block, x + 1, y, z, renderer, mixedBrightness)); - tesselator.setColorOpaque_F(r, g, b); - renderer.renderFaceXPos(block, x + OVERLAY_SHIFT, y, z, textureIndex); - - } + Tessellator tesselator = Tessellator.instance; + tesselator.setBrightness(determineMixedBrightness(world, block, x + 1, y, z, renderer, mixedBrightness)); + tesselator.setColorOpaque_F(r, g, b); + renderer.renderFaceXPos(block, x + OVERLAY_SHIFT, y, z, textureIndex); + } } diff --git a/src/main/java/forestry/core/render/SpriteSheet.java b/src/main/java/forestry/core/render/SpriteSheet.java index 633535897..7520b902d 100755 --- a/src/main/java/forestry/core/render/SpriteSheet.java +++ b/src/main/java/forestry/core/render/SpriteSheet.java @@ -14,14 +14,14 @@ import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.ResourceLocation; public enum SpriteSheet { - BLOCKS, - ITEMS; + BLOCKS, + ITEMS; - public ResourceLocation getLocation() { - return ordinal() == 0 ? TextureMap.locationBlocksTexture : TextureMap.locationItemsTexture; - } - - public int getSheetOrdinal() { - return ordinal(); - } + public ResourceLocation getLocation() { + return ordinal() == 0 ? TextureMap.locationBlocksTexture : TextureMap.locationItemsTexture; + } + + public int getSheetOrdinal() { + return ordinal(); + } } diff --git a/src/main/java/forestry/core/render/TankRenderInfo.java b/src/main/java/forestry/core/render/TankRenderInfo.java index 23164344e..5f254eef1 100644 --- a/src/main/java/forestry/core/render/TankRenderInfo.java +++ b/src/main/java/forestry/core/render/TankRenderInfo.java @@ -1,46 +1,45 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.render; - -import javax.annotation.Nonnull; -import java.awt.Color; - -import net.minecraftforge.fluids.IFluidTank; - -import forestry.core.fluids.Fluids; - -public class TankRenderInfo { - public static final TankRenderInfo EMPTY = new TankRenderInfo(Fluids.WATER.getColor(), EnumTankLevel.EMPTY); - - @Nonnull - private final Color fluidColor; - @Nonnull - private final EnumTankLevel level; - - public TankRenderInfo(@Nonnull IFluidTank fluidTank) { - this(Fluids.getFluidColor(fluidTank.getFluid()), EnumTankLevel.rateTankLevel(fluidTank)); - } - - public TankRenderInfo(@Nonnull Color fluidColor, @Nonnull EnumTankLevel level) { - this.fluidColor = fluidColor; - this.level = level; - } - - @Nonnull - public Color getFluidColor() { - return fluidColor; - } - - @Nonnull - public EnumTankLevel getLevel() { - return level; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.render; + +import forestry.core.fluids.Fluids; +import java.awt.Color; +import javax.annotation.Nonnull; +import net.minecraftforge.fluids.IFluidTank; + +public class TankRenderInfo { + public static final TankRenderInfo EMPTY = new TankRenderInfo(Fluids.WATER.getColor(), EnumTankLevel.EMPTY); + + @Nonnull + private final Color fluidColor; + + @Nonnull + private final EnumTankLevel level; + + public TankRenderInfo(@Nonnull IFluidTank fluidTank) { + this(Fluids.getFluidColor(fluidTank.getFluid()), EnumTankLevel.rateTankLevel(fluidTank)); + } + + public TankRenderInfo(@Nonnull Color fluidColor, @Nonnull EnumTankLevel level) { + this.fluidColor = fluidColor; + this.level = level; + } + + @Nonnull + public Color getFluidColor() { + return fluidColor; + } + + @Nonnull + public EnumTankLevel getLevel() { + return level; + } +} diff --git a/src/main/java/forestry/core/render/TextureManager.java b/src/main/java/forestry/core/render/TextureManager.java index d407485a1..4c5c6f93d 100755 --- a/src/main/java/forestry/core/render/TextureManager.java +++ b/src/main/java/forestry/core/render/TextureManager.java @@ -10,109 +10,137 @@ ******************************************************************************/ package forestry.core.render; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.core.ForestryAPI; +import forestry.api.core.IIconProvider; +import forestry.api.core.ITextureManager; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.core.ForestryAPI; -import forestry.api.core.IIconProvider; -import forestry.api.core.ITextureManager; - @SideOnly(Side.CLIENT) public class TextureManager implements ITextureManager { - private static final TextureManager instance = new TextureManager(); + private static final TextureManager instance = new TextureManager(); - private static final Map defaultIcons = new HashMap<>(); - private static final DefaultIconProvider defaultIconProvider = new DefaultIconProvider(); - private static final List iconProviders = new ArrayList<>(); + private static final Map defaultIcons = new HashMap<>(); + private static final DefaultIconProvider defaultIconProvider = new DefaultIconProvider(); + private static final List iconProviders = new ArrayList<>(); - static { - ForestryAPI.textureManager = instance; - instance.registerIconProvider(defaultIconProvider); - } + static { + ForestryAPI.textureManager = instance; + instance.registerIconProvider(defaultIconProvider); + } - public static TextureManager getInstance() { - return instance; - } + public static TextureManager getInstance() { + return instance; + } - private TextureManager() { - } + private TextureManager() {} - public static void initDefaultIcons(IIconRegister register) { - String[] defaultIconNames = new String[]{"habitats/desert", "habitats/end", "habitats/forest", "habitats/hills", "habitats/jungle", "habitats/mushroom", - "habitats/nether", "habitats/ocean", "habitats/plains", "habitats/snow", "habitats/swamp", "habitats/taiga", "misc/access.private", - "misc/access.viewable", "misc/access.shared", "misc/energy", "misc/hint", - "analyzer/anything", "analyzer/bee", "analyzer/cave", "analyzer/closed", "analyzer/drone", "analyzer/flyer", - "analyzer/item", "analyzer/nocturnal", "analyzer/princess", "analyzer/pure_breed", "analyzer/pure_cave", - "analyzer/pure_flyer", "analyzer/pure_nocturnal", "analyzer/queen", - "particles/swarm_bee", "errors/errored", "errors/unknown", - "slots/blocked", "slots/blocked_2", "slots/liquid", "slots/container", "slots/locked", - "mail/carrier.player", "mail/carrier.trader"}; - for (String str : defaultIconNames) { - IIcon icon = registerTex(register, str); - defaultIcons.put(str, icon); - } - } + public static void initDefaultIcons(IIconRegister register) { + String[] defaultIconNames = new String[] { + "habitats/desert", + "habitats/end", + "habitats/forest", + "habitats/hills", + "habitats/jungle", + "habitats/mushroom", + "habitats/nether", + "habitats/ocean", + "habitats/plains", + "habitats/snow", + "habitats/swamp", + "habitats/taiga", + "misc/access.private", + "misc/access.viewable", + "misc/access.shared", + "misc/energy", + "misc/hint", + "analyzer/anything", + "analyzer/bee", + "analyzer/cave", + "analyzer/closed", + "analyzer/drone", + "analyzer/flyer", + "analyzer/item", + "analyzer/nocturnal", + "analyzer/princess", + "analyzer/pure_breed", + "analyzer/pure_cave", + "analyzer/pure_flyer", + "analyzer/pure_nocturnal", + "analyzer/queen", + "particles/swarm_bee", + "errors/errored", + "errors/unknown", + "slots/blocked", + "slots/blocked_2", + "slots/liquid", + "slots/container", + "slots/locked", + "mail/carrier.player", + "mail/carrier.trader" + }; + for (String str : defaultIconNames) { + IIcon icon = registerTex(register, str); + defaultIcons.put(str, icon); + } + } - public static IIcon registerTex(IIconRegister register, String identifier) { - return register.registerIcon("forestry:" + identifier); - } + public static IIcon registerTex(IIconRegister register, String identifier) { + return register.registerIcon("forestry:" + identifier); + } - public static IIcon registerTexUID(IIconRegister register, short uid, String identifier) { - IIcon texture = registerTex(register, identifier); - defaultIconProvider.addTexture(uid, texture); - return texture; - } + public static IIcon registerTexUID(IIconRegister register, short uid, String identifier) { + IIcon texture = registerTex(register, identifier); + defaultIconProvider.addTexture(uid, texture); + return texture; + } - @Override - public IIcon getDefault(String ident) { - return defaultIcons.get(ident); - } + @Override + public IIcon getDefault(String ident) { + return defaultIcons.get(ident); + } - @Override - public void registerIconProvider(IIconProvider provider) { - iconProviders.add(provider); - } + @Override + public void registerIconProvider(IIconProvider provider) { + iconProviders.add(provider); + } - @Override - public IIcon getIcon(short texUID) { - if (texUID < 0) { - return null; - } + @Override + public IIcon getIcon(short texUID) { + if (texUID < 0) { + return null; + } - for (IIconProvider provider : iconProviders) { - IIcon icon = provider.getIcon(texUID); - if (icon != null) { - return icon; - } - } + for (IIconProvider provider : iconProviders) { + IIcon icon = provider.getIcon(texUID); + if (icon != null) { + return icon; + } + } - return null; - } + return null; + } - private static class DefaultIconProvider implements IIconProvider { - private final Map textures = new HashMap<>(); + private static class DefaultIconProvider implements IIconProvider { + private final Map textures = new HashMap<>(); - public void addTexture(short texUID, IIcon texture) { - textures.put(texUID, texture); - } + public void addTexture(short texUID, IIcon texture) { + textures.put(texUID, texture); + } - @Override - public IIcon getIcon(short texUID) { - return textures.get(texUID); - } + @Override + public IIcon getIcon(short texUID) { + return textures.get(texUID); + } - @Override - public void registerIcons(IIconRegister register) { - - } - } + @Override + public void registerIcons(IIconRegister register) {} + } } diff --git a/src/main/java/forestry/core/render/TileRendererIndex.java b/src/main/java/forestry/core/render/TileRendererIndex.java index 747e0a00d..5f71b53b5 100755 --- a/src/main/java/forestry/core/render/TileRendererIndex.java +++ b/src/main/java/forestry/core/render/TileRendererIndex.java @@ -13,25 +13,25 @@ package forestry.core.render; import net.minecraft.block.Block; public class TileRendererIndex { - private final Block block; - private final int meta; + private final Block block; + private final int meta; - public TileRendererIndex(Block block, int meta) { - this.block = block; - this.meta = meta; - } + public TileRendererIndex(Block block, int meta) { + this.block = block; + this.meta = meta; + } - public int hashCode() { - return block.hashCode() + meta; - } + public int hashCode() { + return block.hashCode() + meta; + } - public boolean equals(Object obj) { - if (!(obj instanceof TileRendererIndex)) { - return false; - } + public boolean equals(Object obj) { + if (!(obj instanceof TileRendererIndex)) { + return false; + } - TileRendererIndex index = (TileRendererIndex) obj; + TileRendererIndex index = (TileRendererIndex) obj; - return index.block == block && index.meta == meta; - } + return index.block == block && index.meta == meta; + } } diff --git a/src/main/java/forestry/core/tiles/AdjacentTileCache.java b/src/main/java/forestry/core/tiles/AdjacentTileCache.java index 1cc14edb3..ef432a169 100644 --- a/src/main/java/forestry/core/tiles/AdjacentTileCache.java +++ b/src/main/java/forestry/core/tiles/AdjacentTileCache.java @@ -13,11 +13,9 @@ package forestry.core.tiles; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; - import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; - import net.minecraftforge.common.util.ForgeDirection; /** @@ -25,134 +23,134 @@ import net.minecraftforge.common.util.ForgeDirection; */ public final class AdjacentTileCache { - private static final int DELAY_MIN = 20; - private static final int DELAY_MAX = 2400; - private static final int DELAY_STEP = 2; - private final Timer[] timer = new Timer[6]; - private final TileEntity[] cache = new TileEntity[6]; - private final int[] delay = new int[6]; - private final TileEntity source; - private final Set listeners = new LinkedHashSet<>(); + private static final int DELAY_MIN = 20; + private static final int DELAY_MAX = 2400; + private static final int DELAY_STEP = 2; + private final Timer[] timer = new Timer[6]; + private final TileEntity[] cache = new TileEntity[6]; + private final int[] delay = new int[6]; + private final TileEntity source; + private final Set listeners = new LinkedHashSet<>(); - public interface ICacheListener { + public interface ICacheListener { - void changed(); + void changed(); - void purge(); + void purge(); + } - } + public AdjacentTileCache(TileEntity tile) { + this.source = tile; + Arrays.fill(delay, DELAY_MIN); + for (int i = 0; i < timer.length; i++) { + timer[i] = new Timer(); + } + } - public AdjacentTileCache(TileEntity tile) { - this.source = tile; - Arrays.fill(delay, DELAY_MIN); - for (int i = 0; i < timer.length; i++) { - timer[i] = new Timer(); - } - } + public void addListener(ICacheListener listener) { + listeners.add(listener); + } - public void addListener(ICacheListener listener) { - listeners.add(listener); - } + private TileEntity searchSide(ForgeDirection side) { + World world = source.getWorldObj(); + int sx = source.xCoord + side.offsetX; + int sy = source.yCoord + side.offsetY; + int sz = source.zCoord + side.offsetZ; + if (world.blockExists(sx, sy, sz) && world.getBlock(sx, sy, sz) != Blocks.air) { + return world.getTileEntity(sx, sy, sz); + } + return null; + } - private TileEntity searchSide(ForgeDirection side) { - World world = source.getWorldObj(); - int sx = source.xCoord + side.offsetX; - int sy = source.yCoord + side.offsetY; - int sz = source.zCoord + side.offsetZ; - if (world.blockExists(sx, sy, sz) && world.getBlock(sx, sy, sz) != Blocks.air) { - return world.getTileEntity(sx, sy, sz); - } - return null; - } + public void refresh() { + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + getTileOnSide(side); + } + } - public void refresh() { - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { - getTileOnSide(side); - } - } + public void purge() { + Arrays.fill(cache, null); + Arrays.fill(delay, DELAY_MIN); + for (Timer t : timer) { + t.reset(); + } + changed(); + for (ICacheListener listener : listeners) { + listener.purge(); + } + } - public void purge() { - Arrays.fill(cache, null); - Arrays.fill(delay, DELAY_MIN); - for (Timer t : timer) { - t.reset(); - } - changed(); - for (ICacheListener listener : listeners) { - listener.purge(); - } - } + public void onNeighborChange() { + Arrays.fill(delay, DELAY_MIN); + } - public void onNeighborChange() { - Arrays.fill(delay, DELAY_MIN); - } + protected void setTile(int side, TileEntity tile) { + if (cache[side] != tile) { + cache[side] = tile; + changed(); + } + } - protected void setTile(int side, TileEntity tile) { - if (cache[side] != tile) { - cache[side] = tile; - changed(); - } - } + private void changed() { + for (ICacheListener listener : listeners) { + listener.changed(); + } + } - private void changed() { - for (ICacheListener listener : listeners) { - listener.changed(); - } - } + private boolean areCoordinatesOnSide(ForgeDirection side, TileEntity target) { + return source.xCoord + side.offsetX == target.xCoord + && source.yCoord + side.offsetY == target.yCoord + && source.zCoord + side.offsetZ == target.zCoord; + } - private boolean areCoordinatesOnSide(ForgeDirection side, TileEntity target) { - return source.xCoord + side.offsetX == target.xCoord && source.yCoord + side.offsetY == target.yCoord && source.zCoord + side.offsetZ == target.zCoord; - } + public TileEntity getTileOnSide(ForgeDirection side) { + int s = side.ordinal(); + if (cache[s] != null) { + if (cache[s].isInvalid() || !areCoordinatesOnSide(side, cache[s])) { + setTile(s, null); + } else { + return cache[s]; + } + } - public TileEntity getTileOnSide(ForgeDirection side) { - int s = side.ordinal(); - if (cache[s] != null) { - if (cache[s].isInvalid() || !areCoordinatesOnSide(side, cache[s])) { - setTile(s, null); - } else { - return cache[s]; - } - } + if (timer[s].hasTriggered(source.getWorldObj(), delay[s])) { + setTile(s, searchSide(side)); + if (cache[s] == null) { + incrementDelay(s); + } else { + delay[s] = DELAY_MIN; + } + } - if (timer[s].hasTriggered(source.getWorldObj(), delay[s])) { - setTile(s, searchSide(side)); - if (cache[s] == null) { - incrementDelay(s); - } else { - delay[s] = DELAY_MIN; - } - } + return cache[s]; + } - return cache[s]; - } + private void incrementDelay(int side) { + delay[side] += DELAY_STEP; + if (delay[side] > DELAY_MAX) { + delay[side] = DELAY_MAX; + } + } - private void incrementDelay(int side) { - delay[side] += DELAY_STEP; - if (delay[side] > DELAY_MAX) { - delay[side] = DELAY_MAX; - } - } + public TileEntity getSource() { + return source; + } - public TileEntity getSource() { - return source; - } + private static class Timer { - private static class Timer { + private long startTime = Long.MIN_VALUE; - private long startTime = Long.MIN_VALUE; + public boolean hasTriggered(World world, int ticks) { + long currentTime = world.getTotalWorldTime(); + if (currentTime >= (ticks + startTime) || startTime > currentTime) { + startTime = currentTime; + return true; + } + return false; + } - public boolean hasTriggered(World world, int ticks) { - long currentTime = world.getTotalWorldTime(); - if (currentTime >= (ticks + startTime) || startTime > currentTime) { - startTime = currentTime; - return true; - } - return false; - } - - public void reset() { - startTime = Long.MIN_VALUE; - } - - } + public void reset() { + startTime = Long.MIN_VALUE; + } + } } diff --git a/src/main/java/forestry/core/tiles/EscritoireGame.java b/src/main/java/forestry/core/tiles/EscritoireGame.java index b8c97780d..92aef0fa1 100644 --- a/src/main/java/forestry/core/tiles/EscritoireGame.java +++ b/src/main/java/forestry/core/tiles/EscritoireGame.java @@ -10,13 +10,6 @@ ******************************************************************************/ package forestry.core.tiles; -import java.io.IOException; -import java.util.Random; - -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import forestry.api.core.INBTTagable; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAlleleSpecies; @@ -24,145 +17,153 @@ import forestry.api.genetics.IIndividual; import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import java.io.IOException; +import java.util.Random; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; public class EscritoireGame implements INBTTagable, IStreamable { - private static final Random rand = new Random(); - public static final int BOUNTY_MAX = 16; + private static final Random rand = new Random(); + public static final int BOUNTY_MAX = 16; - public enum Status { - EMPTY, PLAYING, FAILURE, SUCCESS; - public static final Status[] VALUES = values(); - } + public enum Status { + EMPTY, + PLAYING, + FAILURE, + SUCCESS; + public static final Status[] VALUES = values(); + } - private final EscritoireGameBoard gameBoard = new EscritoireGameBoard(); - private long lastUpdate; - private int bountyLevel; - private Status status = Status.EMPTY; + private final EscritoireGameBoard gameBoard = new EscritoireGameBoard(); + private long lastUpdate; + private int bountyLevel; + private Status status = Status.EMPTY; - public EscritoireGameToken getToken(int index) { - return gameBoard.getToken(index); - } + public EscritoireGameToken getToken(int index) { + return gameBoard.getToken(index); + } - public Status getStatus() { - return status; - } + public Status getStatus() { + return status; + } - public long getLastUpdate() { - return lastUpdate; - } + public long getLastUpdate() { + return lastUpdate; + } - /* SAVING & LOADING */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setInteger("bountyLevel", bountyLevel); - nbttagcompound.setLong("lastUpdate", lastUpdate); - gameBoard.writeToNBT(nbttagcompound); + /* SAVING & LOADING */ + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setInteger("bountyLevel", bountyLevel); + nbttagcompound.setLong("lastUpdate", lastUpdate); + gameBoard.writeToNBT(nbttagcompound); - nbttagcompound.setInteger("Status", status.ordinal()); - } + nbttagcompound.setInteger("Status", status.ordinal()); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - bountyLevel = nbttagcompound.getInteger("bountyLevel"); - lastUpdate = nbttagcompound.getLong("lastUpdate"); - gameBoard.readFromNBT(nbttagcompound); + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + bountyLevel = nbttagcompound.getInteger("bountyLevel"); + lastUpdate = nbttagcompound.getLong("lastUpdate"); + gameBoard.readFromNBT(nbttagcompound); - if (nbttagcompound.hasKey("Status")) { - int statusOrdinal = nbttagcompound.getInteger("Status"); - status = Status.values()[statusOrdinal]; - } + if (nbttagcompound.hasKey("Status")) { + int statusOrdinal = nbttagcompound.getInteger("Status"); + status = Status.values()[statusOrdinal]; + } - lastUpdate = System.currentTimeMillis(); - } + lastUpdate = System.currentTimeMillis(); + } - /* NETWORK */ - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeInt(bountyLevel); - gameBoard.writeData(data); - data.writeEnum(status, Status.VALUES); - } + /* NETWORK */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeInt(bountyLevel); + gameBoard.writeData(data); + data.writeEnum(status, Status.VALUES); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - bountyLevel = data.readInt(); - gameBoard.readData(data); - status = data.readEnum(Status.VALUES); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + bountyLevel = data.readInt(); + gameBoard.readData(data); + status = data.readEnum(Status.VALUES); + } - /* INTERACTION */ - public void initialize(ItemStack specimen) { - if (gameBoard.initialize(specimen)) { - status = Status.PLAYING; - bountyLevel = BOUNTY_MAX; - lastUpdate = System.currentTimeMillis(); - } - } + /* INTERACTION */ + public void initialize(ItemStack specimen) { + if (gameBoard.initialize(specimen)) { + status = Status.PLAYING; + bountyLevel = BOUNTY_MAX; + lastUpdate = System.currentTimeMillis(); + } + } - public void probe(ItemStack specimen, IInventory inventory, int startSlot, int slotCount) { - if (status != Status.PLAYING) { - return; - } + public void probe(ItemStack specimen, IInventory inventory, int startSlot, int slotCount) { + if (status != Status.PLAYING) { + return; + } - IIndividual individual = AlleleManager.alleleRegistry.getIndividual(specimen); - if (individual == null) { - return; - } + IIndividual individual = AlleleManager.alleleRegistry.getIndividual(specimen); + if (individual == null) { + return; + } - if (bountyLevel > 1) { - bountyLevel--; - } + if (bountyLevel > 1) { + bountyLevel--; + } - IAlleleSpecies species = individual.getGenome().getPrimary(); - gameBoard.hideProbedTokens(); + IAlleleSpecies species = individual.getGenome().getPrimary(); + gameBoard.hideProbedTokens(); - int revealCount = getSampleSize(slotCount); - for (int i = 0; i < revealCount; i++) { - ItemStack sample = inventory.decrStackSize(startSlot + i, 1); - if (sample == null || sample.stackSize <= 0) { - continue; - } + int revealCount = getSampleSize(slotCount); + for (int i = 0; i < revealCount; i++) { + ItemStack sample = inventory.decrStackSize(startSlot + i, 1); + if (sample == null || sample.stackSize <= 0) { + continue; + } - if (rand.nextFloat() < species.getResearchSuitability(sample)) { - gameBoard.probe(); - } - } + if (rand.nextFloat() < species.getResearchSuitability(sample)) { + gameBoard.probe(); + } + } - lastUpdate = System.currentTimeMillis(); - } + lastUpdate = System.currentTimeMillis(); + } - public void reset() { - bountyLevel = BOUNTY_MAX; - gameBoard.reset(); - status = Status.EMPTY; + public void reset() { + bountyLevel = BOUNTY_MAX; + gameBoard.reset(); + status = Status.EMPTY; - lastUpdate = System.currentTimeMillis(); - } + lastUpdate = System.currentTimeMillis(); + } - public void choose(int tokenIndex) { - if (getStatus() != Status.PLAYING) { - return; - } + public void choose(int tokenIndex) { + if (getStatus() != Status.PLAYING) { + return; + } - EscritoireGameToken token = gameBoard.getToken(tokenIndex); - if (token != null) { - status = gameBoard.choose(token); - lastUpdate = System.currentTimeMillis(); - } - } + EscritoireGameToken token = gameBoard.getToken(tokenIndex); + if (token != null) { + status = gameBoard.choose(token); + lastUpdate = System.currentTimeMillis(); + } + } - public int getBountyLevel() { - return bountyLevel; - } + public int getBountyLevel() { + return bountyLevel; + } - /* RETRIEVAL */ - public int getSampleSize(int slotCount) { - if (status == Status.EMPTY) { - return 0; - } + /* RETRIEVAL */ + public int getSampleSize(int slotCount) { + if (status == Status.EMPTY) { + return 0; + } - int samples = gameBoard.getTokenCount() / 4; - samples = Math.max(samples, 2); - return Math.min(samples, slotCount); - } + int samples = gameBoard.getTokenCount() / 4; + samples = Math.max(samples, 2); + return Math.min(samples, slotCount); + } } diff --git a/src/main/java/forestry/core/tiles/EscritoireGameBoard.java b/src/main/java/forestry/core/tiles/EscritoireGameBoard.java index 178ae9280..87b8444c5 100644 --- a/src/main/java/forestry/core/tiles/EscritoireGameBoard.java +++ b/src/main/java/forestry/core/tiles/EscritoireGameBoard.java @@ -1,227 +1,224 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.tiles; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; - -import forestry.api.core.INBTTagable; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAlleleSpecies; -import forestry.api.genetics.IGenome; -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.ISpeciesRoot; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamable; - -public class EscritoireGameBoard implements INBTTagable, IStreamable { - private static final Random rand = new Random(); - private static final int TOKEN_COUNT_MAX = 22; - private static final int TOKEN_COUNT_MIN = 6; - - private final List gameTokens = new ArrayList<>(TOKEN_COUNT_MAX); - private int tokenCount; - - - public boolean initialize(ItemStack specimen) { - IIndividual individual = AlleleManager.alleleRegistry.getIndividual(specimen); - if (individual == null) { - return false; - } - - IGenome genome = individual.getGenome(); - ISpeciesRoot root = genome.getPrimary().getRoot(); - - tokenCount = getTokenCount(genome); - - for (int i = 0; i < tokenCount / 2; i++) { - IIndividual token = root.templateAsIndividual(root.getRandomTemplate(rand)); - ItemStack pair = root.getMemberStack(token, 0); - gameTokens.add(new EscritoireGameToken(pair)); - gameTokens.add(new EscritoireGameToken(pair)); - } - Collections.shuffle(gameTokens); - return true; - } - - public EscritoireGameToken getToken(int index) { - if (index >= tokenCount) { - return null; - } - return gameTokens.get(index); - } - - public int getTokenCount() { - return tokenCount; - } - - public void hideProbedTokens() { - for (EscritoireGameToken token : gameTokens) { - if (token.isProbed()) { - token.setProbed(false); - } - } - } - - private List getUnrevealedTokens() { - List unrevealed = new ArrayList<>(); - for (EscritoireGameToken token : gameTokens) { - if (!token.isVisible()) { - unrevealed.add(token); - } - } - - return unrevealed; - } - - private EscritoireGameToken getSelected() { - for (EscritoireGameToken token : gameTokens) { - if (token.isSelected()) { - return token; - } - } - - return null; - } - - private boolean isBoardCleared() { - for (EscritoireGameToken token : gameTokens) { - if (!token.isMatched()) { - return false; - } - } - - return true; - } - - public void probe() { - List tokens = getUnrevealedTokens(); - int index = rand.nextInt(tokens.size()); - - EscritoireGameToken token = tokens.get(index); - token.setProbed(true); - } - - public EscritoireGame.Status choose(EscritoireGameToken token) { - EscritoireGame.Status status = EscritoireGame.Status.PLAYING; - if (token.isMatched() || token.isSelected()) { - return status; - } - - EscritoireGameToken selected = getSelected(); - if (selected == null) { - token.setSelected(); - hideProbedTokens(); - } else if (token.matches(selected)) { - selected.setMatched(); - token.setMatched(); - if (isBoardCleared()) { - status = EscritoireGame.Status.SUCCESS; - } - hideProbedTokens(); - } else { - token.setFailed(); - selected.setFailed(); - status = EscritoireGame.Status.FAILURE; - } - - return status; - } - - public void reset() { - gameTokens.clear(); - tokenCount = 0; - } - - private static int getTokenCount(IGenome genome) { - IAlleleSpecies species1 = genome.getPrimary(); - IAlleleSpecies species2 = genome.getSecondary(); - - int tokenCount = species1.getComplexity() + species2.getComplexity(); - - if (tokenCount % 2 != 0) { - tokenCount = Math.round((float) tokenCount / 2) * 2; - } - - if (tokenCount > TOKEN_COUNT_MAX) { - tokenCount = TOKEN_COUNT_MAX; - } else if (tokenCount < TOKEN_COUNT_MIN) { - tokenCount = TOKEN_COUNT_MIN; - } - - return tokenCount; - } - - /* INBTTagable */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - tokenCount = nbttagcompound.getInteger("TokenCount"); - gameTokens.clear(); - - if (tokenCount > 0) { - EscritoireGameToken[] tokens = new EscritoireGameToken[tokenCount]; - NBTTagList nbttaglist = nbttagcompound.getTagList("GameTokens", 10); - - for (int j = 0; j < nbttaglist.tagCount(); ++j) { - NBTTagCompound nbttagcompound2 = nbttaglist.getCompoundTagAt(j); - int index = nbttagcompound2.getByte("Slot"); - tokens[index] = new EscritoireGameToken(nbttagcompound2); - } - - Collections.addAll(gameTokens, tokens); - } - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - if (tokenCount > 0) { - nbttagcompound.setInteger("TokenCount", tokenCount); - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < tokenCount; i++) { - EscritoireGameToken token = gameTokens.get(i); - if (token == null) { - continue; - } - - NBTTagCompound nbttagcompound2 = new NBTTagCompound(); - nbttagcompound2.setByte("Slot", (byte) i); - token.writeToNBT(nbttagcompound2); - nbttaglist.appendTag(nbttagcompound2); - } - - nbttagcompound.setTag("GameTokens", nbttaglist); - } else { - nbttagcompound.setInteger("TokenCount", 0); - } - } - - /* IStreamable */ - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeVarInt(tokenCount); - data.writeStreamables(gameTokens); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - tokenCount = data.readVarInt(); - data.readStreamables(gameTokens, EscritoireGameToken.class); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.tiles; + +import forestry.api.core.INBTTagable; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAlleleSpecies; +import forestry.api.genetics.IGenome; +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.ISpeciesRoot; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + +public class EscritoireGameBoard implements INBTTagable, IStreamable { + private static final Random rand = new Random(); + private static final int TOKEN_COUNT_MAX = 22; + private static final int TOKEN_COUNT_MIN = 6; + + private final List gameTokens = new ArrayList<>(TOKEN_COUNT_MAX); + private int tokenCount; + + public boolean initialize(ItemStack specimen) { + IIndividual individual = AlleleManager.alleleRegistry.getIndividual(specimen); + if (individual == null) { + return false; + } + + IGenome genome = individual.getGenome(); + ISpeciesRoot root = genome.getPrimary().getRoot(); + + tokenCount = getTokenCount(genome); + + for (int i = 0; i < tokenCount / 2; i++) { + IIndividual token = root.templateAsIndividual(root.getRandomTemplate(rand)); + ItemStack pair = root.getMemberStack(token, 0); + gameTokens.add(new EscritoireGameToken(pair)); + gameTokens.add(new EscritoireGameToken(pair)); + } + Collections.shuffle(gameTokens); + return true; + } + + public EscritoireGameToken getToken(int index) { + if (index >= tokenCount) { + return null; + } + return gameTokens.get(index); + } + + public int getTokenCount() { + return tokenCount; + } + + public void hideProbedTokens() { + for (EscritoireGameToken token : gameTokens) { + if (token.isProbed()) { + token.setProbed(false); + } + } + } + + private List getUnrevealedTokens() { + List unrevealed = new ArrayList<>(); + for (EscritoireGameToken token : gameTokens) { + if (!token.isVisible()) { + unrevealed.add(token); + } + } + + return unrevealed; + } + + private EscritoireGameToken getSelected() { + for (EscritoireGameToken token : gameTokens) { + if (token.isSelected()) { + return token; + } + } + + return null; + } + + private boolean isBoardCleared() { + for (EscritoireGameToken token : gameTokens) { + if (!token.isMatched()) { + return false; + } + } + + return true; + } + + public void probe() { + List tokens = getUnrevealedTokens(); + int index = rand.nextInt(tokens.size()); + + EscritoireGameToken token = tokens.get(index); + token.setProbed(true); + } + + public EscritoireGame.Status choose(EscritoireGameToken token) { + EscritoireGame.Status status = EscritoireGame.Status.PLAYING; + if (token.isMatched() || token.isSelected()) { + return status; + } + + EscritoireGameToken selected = getSelected(); + if (selected == null) { + token.setSelected(); + hideProbedTokens(); + } else if (token.matches(selected)) { + selected.setMatched(); + token.setMatched(); + if (isBoardCleared()) { + status = EscritoireGame.Status.SUCCESS; + } + hideProbedTokens(); + } else { + token.setFailed(); + selected.setFailed(); + status = EscritoireGame.Status.FAILURE; + } + + return status; + } + + public void reset() { + gameTokens.clear(); + tokenCount = 0; + } + + private static int getTokenCount(IGenome genome) { + IAlleleSpecies species1 = genome.getPrimary(); + IAlleleSpecies species2 = genome.getSecondary(); + + int tokenCount = species1.getComplexity() + species2.getComplexity(); + + if (tokenCount % 2 != 0) { + tokenCount = Math.round((float) tokenCount / 2) * 2; + } + + if (tokenCount > TOKEN_COUNT_MAX) { + tokenCount = TOKEN_COUNT_MAX; + } else if (tokenCount < TOKEN_COUNT_MIN) { + tokenCount = TOKEN_COUNT_MIN; + } + + return tokenCount; + } + + /* INBTTagable */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + tokenCount = nbttagcompound.getInteger("TokenCount"); + gameTokens.clear(); + + if (tokenCount > 0) { + EscritoireGameToken[] tokens = new EscritoireGameToken[tokenCount]; + NBTTagList nbttaglist = nbttagcompound.getTagList("GameTokens", 10); + + for (int j = 0; j < nbttaglist.tagCount(); ++j) { + NBTTagCompound nbttagcompound2 = nbttaglist.getCompoundTagAt(j); + int index = nbttagcompound2.getByte("Slot"); + tokens[index] = new EscritoireGameToken(nbttagcompound2); + } + + Collections.addAll(gameTokens, tokens); + } + } + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + if (tokenCount > 0) { + nbttagcompound.setInteger("TokenCount", tokenCount); + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < tokenCount; i++) { + EscritoireGameToken token = gameTokens.get(i); + if (token == null) { + continue; + } + + NBTTagCompound nbttagcompound2 = new NBTTagCompound(); + nbttagcompound2.setByte("Slot", (byte) i); + token.writeToNBT(nbttagcompound2); + nbttaglist.appendTag(nbttagcompound2); + } + + nbttagcompound.setTag("GameTokens", nbttaglist); + } else { + nbttagcompound.setInteger("TokenCount", 0); + } + } + + /* IStreamable */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeVarInt(tokenCount); + data.writeStreamables(gameTokens); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + tokenCount = data.readVarInt(); + data.readStreamables(gameTokens, EscritoireGameToken.class); + } +} diff --git a/src/main/java/forestry/core/tiles/EscritoireGameToken.java b/src/main/java/forestry/core/tiles/EscritoireGameToken.java index 4aac42827..fa0a1299c 100644 --- a/src/main/java/forestry/core/tiles/EscritoireGameToken.java +++ b/src/main/java/forestry/core/tiles/EscritoireGameToken.java @@ -1,168 +1,166 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.tiles; - -import java.io.IOException; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import forestry.api.core.INBTTagable; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IIndividual; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamable; -import forestry.core.utils.ColourUtil; -import forestry.core.utils.StringUtil; - -public class EscritoireGameToken implements INBTTagable, IStreamable { - - private enum State { - UNREVEALED,// face down - PROBED, // shown by escritoire probe action - SELECTED, // selected by the user as the first half of a match - MATCHED, // successfully matched - FAILED; // failed to match - public static final State[] VALUES = values(); - } - - private static final String[] OVERLAY_NONE = new String[0]; - private static final String[] OVERLAY_FAILED = new String[]{"errors/errored"}; - private static final String[] OVERLAY_SELECTED = new String[]{"errors/unknown"}; - - private ItemStack tokenStack; - private State state = State.UNREVEALED; - - @SuppressWarnings("unused") - public EscritoireGameToken() { - // required for IStreamable serialization - } - - public EscritoireGameToken(ItemStack tokenStack) { - this.tokenStack = tokenStack; - } - - public EscritoireGameToken(NBTTagCompound nbttagcompound) { - readFromNBT(nbttagcompound); - } - - public ItemStack getTokenStack() { - return tokenStack; - } - - public boolean isVisible() { - return state != State.UNREVEALED; - } - - public boolean isProbed() { - return state == State.PROBED; - } - - public boolean isMatched() { - return state == State.MATCHED; - } - - public boolean isSelected() { - return state == State.SELECTED; - } - - public void setFailed() { - state = State.FAILED; - } - - public void setProbed(boolean probed) { - if (probed) { - state = State.PROBED; - } else { - state = State.UNREVEALED; - } - } - - public void setSelected() { - state = State.SELECTED; - } - - public void setMatched() { - state = State.MATCHED; - } - - public int getTokenColour() { - if (tokenStack == null || !isVisible()) { - return 0xffffff; - } - - IIndividual individual = AlleleManager.alleleRegistry.getIndividual(tokenStack); - int iconColor = individual.getGenome().getPrimary().getIconColour(0); - - if (state == State.MATCHED) { - return ColourUtil.multiplyRGBComponents(iconColor, 0.7f); - } else { - return iconColor; - } - } - - public String getTooltip() { - return tokenStack != null ? tokenStack.getDisplayName() : StringUtil.localize("gui.unknown"); - } - - public String[] getOverlayIcons() { - switch (state) { - case FAILED: - return OVERLAY_FAILED; - case SELECTED: - return OVERLAY_SELECTED; - default: - return OVERLAY_NONE; - } - } - - public boolean matches(EscritoireGameToken other) { - return ItemStack.areItemStacksEqual(tokenStack, other.getTokenStack()); - } - - /* INBTTagable */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - if (nbttagcompound.hasKey("state")) { - int stateOrdinal = nbttagcompound.getInteger("state"); - state = State.values()[stateOrdinal]; - } - - if (nbttagcompound.hasKey("tokenStack")) { - tokenStack = ItemStack.loadItemStackFromNBT(nbttagcompound.getCompoundTag("tokenStack")); - } - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setInteger("state", state.ordinal()); - - if (tokenStack != null) { - NBTTagCompound stackcompound = new NBTTagCompound(); - tokenStack.writeToNBT(stackcompound); - nbttagcompound.setTag("tokenStack", stackcompound); - } - } - - /* IStreamable */ - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeEnum(state, State.VALUES); - data.writeItemStack(tokenStack); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - state = data.readEnum(State.VALUES); - tokenStack = data.readItemStack(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.tiles; + +import forestry.api.core.INBTTagable; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IIndividual; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; +import forestry.core.utils.ColourUtil; +import forestry.core.utils.StringUtil; +import java.io.IOException; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +public class EscritoireGameToken implements INBTTagable, IStreamable { + + private enum State { + UNREVEALED, // face down + PROBED, // shown by escritoire probe action + SELECTED, // selected by the user as the first half of a match + MATCHED, // successfully matched + FAILED; // failed to match + public static final State[] VALUES = values(); + } + + private static final String[] OVERLAY_NONE = new String[0]; + private static final String[] OVERLAY_FAILED = new String[] {"errors/errored"}; + private static final String[] OVERLAY_SELECTED = new String[] {"errors/unknown"}; + + private ItemStack tokenStack; + private State state = State.UNREVEALED; + + @SuppressWarnings("unused") + public EscritoireGameToken() { + // required for IStreamable serialization + } + + public EscritoireGameToken(ItemStack tokenStack) { + this.tokenStack = tokenStack; + } + + public EscritoireGameToken(NBTTagCompound nbttagcompound) { + readFromNBT(nbttagcompound); + } + + public ItemStack getTokenStack() { + return tokenStack; + } + + public boolean isVisible() { + return state != State.UNREVEALED; + } + + public boolean isProbed() { + return state == State.PROBED; + } + + public boolean isMatched() { + return state == State.MATCHED; + } + + public boolean isSelected() { + return state == State.SELECTED; + } + + public void setFailed() { + state = State.FAILED; + } + + public void setProbed(boolean probed) { + if (probed) { + state = State.PROBED; + } else { + state = State.UNREVEALED; + } + } + + public void setSelected() { + state = State.SELECTED; + } + + public void setMatched() { + state = State.MATCHED; + } + + public int getTokenColour() { + if (tokenStack == null || !isVisible()) { + return 0xffffff; + } + + IIndividual individual = AlleleManager.alleleRegistry.getIndividual(tokenStack); + int iconColor = individual.getGenome().getPrimary().getIconColour(0); + + if (state == State.MATCHED) { + return ColourUtil.multiplyRGBComponents(iconColor, 0.7f); + } else { + return iconColor; + } + } + + public String getTooltip() { + return tokenStack != null ? tokenStack.getDisplayName() : StringUtil.localize("gui.unknown"); + } + + public String[] getOverlayIcons() { + switch (state) { + case FAILED: + return OVERLAY_FAILED; + case SELECTED: + return OVERLAY_SELECTED; + default: + return OVERLAY_NONE; + } + } + + public boolean matches(EscritoireGameToken other) { + return ItemStack.areItemStacksEqual(tokenStack, other.getTokenStack()); + } + + /* INBTTagable */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + if (nbttagcompound.hasKey("state")) { + int stateOrdinal = nbttagcompound.getInteger("state"); + state = State.values()[stateOrdinal]; + } + + if (nbttagcompound.hasKey("tokenStack")) { + tokenStack = ItemStack.loadItemStackFromNBT(nbttagcompound.getCompoundTag("tokenStack")); + } + } + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setInteger("state", state.ordinal()); + + if (tokenStack != null) { + NBTTagCompound stackcompound = new NBTTagCompound(); + tokenStack.writeToNBT(stackcompound); + nbttagcompound.setTag("tokenStack", stackcompound); + } + } + + /* IStreamable */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeEnum(state, State.VALUES); + data.writeItemStack(tokenStack); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + state = data.readEnum(State.VALUES); + tokenStack = data.readItemStack(); + } +} diff --git a/src/main/java/forestry/core/tiles/EscritoireTextSource.java b/src/main/java/forestry/core/tiles/EscritoireTextSource.java index a34aede82..f87842044 100644 --- a/src/main/java/forestry/core/tiles/EscritoireTextSource.java +++ b/src/main/java/forestry/core/tiles/EscritoireTextSource.java @@ -1,87 +1,92 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.tiles; - -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.ListMultimap; - -import java.util.EnumSet; -import java.util.List; -import java.util.Random; - -import forestry.core.utils.StringUtil; - -public class EscritoireTextSource { - - private enum Notes { - level1, level2, level3, level4, success, failure, empty - } - - private static final ListMultimap researchNotes; - private static final Random random = new Random(); - - static { - researchNotes = ArrayListMultimap.create(); - EnumSet multipleTranslationNoteLevels = EnumSet.of(Notes.level1, Notes.level2, Notes.level3, Notes.level4, Notes.success, Notes.failure); - for (Notes notesLevel : multipleTranslationNoteLevels) { - int levelCount = Integer.valueOf(StringUtil.localize("gui.escritoire.notes." + notesLevel + ".count")); - for (int i = 1; i <= levelCount; i++) { - String note = StringUtil.localize("gui.escritoire.notes." + notesLevel + '.' + i); - researchNotes.put(notesLevel, note); - } - } - researchNotes.put(Notes.empty, StringUtil.localize("gui.escritoire.instructions")); - } - - private String researchNote; - private Notes lastNoteLevel; - - public String getText(EscritoireGame escritoireGame) { - Notes noteLevel = getNoteLevel(escritoireGame); - if (lastNoteLevel != noteLevel) { - researchNote = getRandomNote(noteLevel); - lastNoteLevel = noteLevel; - } - - return researchNote; - } - - private static String getRandomNote(Notes level) { - List candidates = researchNotes.get(level); - int index = random.nextInt(candidates.size()); - return candidates.get(index); - } - - public static Notes getNoteLevel(EscritoireGame game) { - EscritoireGame.Status status = game.getStatus(); - switch (status) { - case PLAYING: { - int bounty = game.getBountyLevel(); - if (bounty >= EscritoireGame.BOUNTY_MAX) { - return Notes.level1; - } else if (bounty > EscritoireGame.BOUNTY_MAX / 2) { - return Notes.level2; - } else if (bounty > EscritoireGame.BOUNTY_MAX / 4) { - return Notes.level3; - } else { - return Notes.level4; - } - } - case FAILURE: - return Notes.failure; - case SUCCESS: - return Notes.success; - case EMPTY: - return Notes.empty; - } - return null; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.tiles; + +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.ListMultimap; +import forestry.core.utils.StringUtil; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; + +public class EscritoireTextSource { + + private enum Notes { + level1, + level2, + level3, + level4, + success, + failure, + empty + } + + private static final ListMultimap researchNotes; + private static final Random random = new Random(); + + static { + researchNotes = ArrayListMultimap.create(); + EnumSet multipleTranslationNoteLevels = + EnumSet.of(Notes.level1, Notes.level2, Notes.level3, Notes.level4, Notes.success, Notes.failure); + for (Notes notesLevel : multipleTranslationNoteLevels) { + int levelCount = Integer.valueOf(StringUtil.localize("gui.escritoire.notes." + notesLevel + ".count")); + for (int i = 1; i <= levelCount; i++) { + String note = StringUtil.localize("gui.escritoire.notes." + notesLevel + '.' + i); + researchNotes.put(notesLevel, note); + } + } + researchNotes.put(Notes.empty, StringUtil.localize("gui.escritoire.instructions")); + } + + private String researchNote; + private Notes lastNoteLevel; + + public String getText(EscritoireGame escritoireGame) { + Notes noteLevel = getNoteLevel(escritoireGame); + if (lastNoteLevel != noteLevel) { + researchNote = getRandomNote(noteLevel); + lastNoteLevel = noteLevel; + } + + return researchNote; + } + + private static String getRandomNote(Notes level) { + List candidates = researchNotes.get(level); + int index = random.nextInt(candidates.size()); + return candidates.get(index); + } + + public static Notes getNoteLevel(EscritoireGame game) { + EscritoireGame.Status status = game.getStatus(); + switch (status) { + case PLAYING: { + int bounty = game.getBountyLevel(); + if (bounty >= EscritoireGame.BOUNTY_MAX) { + return Notes.level1; + } else if (bounty > EscritoireGame.BOUNTY_MAX / 2) { + return Notes.level2; + } else if (bounty > EscritoireGame.BOUNTY_MAX / 4) { + return Notes.level3; + } else { + return Notes.level4; + } + } + case FAILURE: + return Notes.failure; + case SUCCESS: + return Notes.success; + case EMPTY: + return Notes.empty; + } + return null; + } +} diff --git a/src/main/java/forestry/core/tiles/IActivatable.java b/src/main/java/forestry/core/tiles/IActivatable.java index b4a7e4630..aef36532d 100644 --- a/src/main/java/forestry/core/tiles/IActivatable.java +++ b/src/main/java/forestry/core/tiles/IActivatable.java @@ -1,23 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.tiles; - -import net.minecraft.util.ChunkCoordinates; - -/* Networked tile entities that have a client side "active" flag */ -public interface IActivatable { - - ChunkCoordinates getCoordinates(); - - boolean isActive(); - - void setActive(boolean active); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.tiles; + +import net.minecraft.util.ChunkCoordinates; + +/* Networked tile entities that have a client side "active" flag */ +public interface IActivatable { + + ChunkCoordinates getCoordinates(); + + boolean isActive(); + + void setActive(boolean active); +} diff --git a/src/main/java/forestry/core/tiles/IClimatised.java b/src/main/java/forestry/core/tiles/IClimatised.java index 3200b617e..5e032a56c 100644 --- a/src/main/java/forestry/core/tiles/IClimatised.java +++ b/src/main/java/forestry/core/tiles/IClimatised.java @@ -15,11 +15,11 @@ import forestry.api.core.EnumTemperature; public interface IClimatised { - EnumTemperature getTemperature(); + EnumTemperature getTemperature(); - EnumHumidity getHumidity(); + EnumHumidity getHumidity(); - float getExactTemperature(); + float getExactTemperature(); - float getExactHumidity(); + float getExactHumidity(); } diff --git a/src/main/java/forestry/core/tiles/IFilterSlotDelegate.java b/src/main/java/forestry/core/tiles/IFilterSlotDelegate.java index 98bb16796..16491eaa9 100644 --- a/src/main/java/forestry/core/tiles/IFilterSlotDelegate.java +++ b/src/main/java/forestry/core/tiles/IFilterSlotDelegate.java @@ -1,31 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.tiles; - -import net.minecraft.item.ItemStack; - -public interface IFilterSlotDelegate { - - /** - * Non-automation version of IInventory's isItemValidForSlot. - * Used to determine if a player can place a stack in a slot. - * - * Combine this with Forestry's access permissions to implement isItemValidForSlot. - */ - boolean canSlotAccept(int slotIndex, ItemStack itemStack); - - /** - * Used to lock slots under special conditions. - * Locked slots will have an X over them. - */ - boolean isLocked(int slotIndex); - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.tiles; + +import net.minecraft.item.ItemStack; + +public interface IFilterSlotDelegate { + + /** + * Non-automation version of IInventory's isItemValidForSlot. + * Used to determine if a player can place a stack in a slot. + * + * Combine this with Forestry's access permissions to implement isItemValidForSlot. + */ + boolean canSlotAccept(int slotIndex, ItemStack itemStack); + + /** + * Used to lock slots under special conditions. + * Locked slots will have an X over them. + */ + boolean isLocked(int slotIndex); +} diff --git a/src/main/java/forestry/core/tiles/IItemStackDisplay.java b/src/main/java/forestry/core/tiles/IItemStackDisplay.java index a4f515d42..d46caf5e6 100644 --- a/src/main/java/forestry/core/tiles/IItemStackDisplay.java +++ b/src/main/java/forestry/core/tiles/IItemStackDisplay.java @@ -1,17 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.tiles; - -import net.minecraft.item.ItemStack; - -public interface IItemStackDisplay { - void handleItemStackForDisplay(ItemStack itemStack); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.tiles; + +import net.minecraft.item.ItemStack; + +public interface IItemStackDisplay { + void handleItemStackForDisplay(ItemStack itemStack); +} diff --git a/src/main/java/forestry/core/tiles/ILiquidTankTile.java b/src/main/java/forestry/core/tiles/ILiquidTankTile.java index abe9370a3..6bc195f3b 100644 --- a/src/main/java/forestry/core/tiles/ILiquidTankTile.java +++ b/src/main/java/forestry/core/tiles/ILiquidTankTile.java @@ -14,6 +14,5 @@ import forestry.core.fluids.ITankManager; public interface ILiquidTankTile extends ILocatable { - ITankManager getTankManager(); - + ITankManager getTankManager(); } diff --git a/src/main/java/forestry/core/tiles/ILocatable.java b/src/main/java/forestry/core/tiles/ILocatable.java index fdcc6aaad..0bf52c6c1 100644 --- a/src/main/java/forestry/core/tiles/ILocatable.java +++ b/src/main/java/forestry/core/tiles/ILocatable.java @@ -1,20 +1,20 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.tiles; - -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; - -public interface ILocatable { - ChunkCoordinates getCoordinates(); - - World getWorld(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.tiles; + +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; + +public interface ILocatable { + ChunkCoordinates getCoordinates(); + + World getWorld(); +} diff --git a/src/main/java/forestry/core/tiles/IPowerHandler.java b/src/main/java/forestry/core/tiles/IPowerHandler.java index 7bbf7ef83..3f967e301 100644 --- a/src/main/java/forestry/core/tiles/IPowerHandler.java +++ b/src/main/java/forestry/core/tiles/IPowerHandler.java @@ -10,10 +10,9 @@ ******************************************************************************/ package forestry.core.tiles; +import cofh.api.energy.IEnergyHandler; import forestry.energy.EnergyManager; -import cofh.api.energy.IEnergyHandler; - public interface IPowerHandler extends IEnergyHandler { - EnergyManager getEnergyManager(); + EnergyManager getEnergyManager(); } diff --git a/src/main/java/forestry/core/tiles/IRenderableTile.java b/src/main/java/forestry/core/tiles/IRenderableTile.java index 93eb7b7e5..3c35d4bef 100644 --- a/src/main/java/forestry/core/tiles/IRenderableTile.java +++ b/src/main/java/forestry/core/tiles/IRenderableTile.java @@ -10,15 +10,14 @@ ******************************************************************************/ package forestry.core.tiles; -import net.minecraftforge.common.util.ForgeDirection; - import forestry.core.render.TankRenderInfo; +import net.minecraftforge.common.util.ForgeDirection; public interface IRenderableTile { - ForgeDirection getOrientation(); + ForgeDirection getOrientation(); - TankRenderInfo getResourceTankInfo(); + TankRenderInfo getResourceTankInfo(); - TankRenderInfo getProductTankInfo(); + TankRenderInfo getProductTankInfo(); } diff --git a/src/main/java/forestry/core/tiles/ITitled.java b/src/main/java/forestry/core/tiles/ITitled.java index 6518a4d16..9c86f0ce6 100644 --- a/src/main/java/forestry/core/tiles/ITitled.java +++ b/src/main/java/forestry/core/tiles/ITitled.java @@ -1,5 +1,5 @@ -package forestry.core.tiles; - -public interface ITitled { - String getUnlocalizedTitle(); -} +package forestry.core.tiles; + +public interface ITitled { + String getUnlocalizedTitle(); +} diff --git a/src/main/java/forestry/core/tiles/MachineDefinition.java b/src/main/java/forestry/core/tiles/MachineDefinition.java index 3a7023369..039a90102 100644 --- a/src/main/java/forestry/core/tiles/MachineDefinition.java +++ b/src/main/java/forestry/core/tiles/MachineDefinition.java @@ -10,9 +10,17 @@ ******************************************************************************/ package forestry.core.tiles; +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.blocks.IMachineProperties; +import forestry.core.blocks.IMachinePropertiesTESR; +import forestry.core.proxy.Proxies; +import forestry.core.render.IBlockRenderer; +import forestry.core.render.TextureManager; +import forestry.core.utils.BlockUtil; import java.util.List; import java.util.Locale; - import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; @@ -25,203 +33,192 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.common.util.ForgeDirection; -import cpw.mods.fml.common.registry.GameRegistry; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.blocks.IMachineProperties; -import forestry.core.blocks.IMachinePropertiesTESR; -import forestry.core.proxy.Proxies; -import forestry.core.render.IBlockRenderer; -import forestry.core.render.TextureManager; -import forestry.core.utils.BlockUtil; - public class MachineDefinition { - public final Class teClass; + public final Class teClass; - private final String teIdent; - private Block block; - private final int meta; - private boolean legacy; + private final String teIdent; + private Block block; + private final int meta; + private boolean legacy; - public final IBlockRenderer renderer; - - private float minX, minY, minZ, maxX, maxY, maxZ; + public final IBlockRenderer renderer; - public MachineDefinition(IMachineProperties properties) { - this(properties.getMeta(), properties.getTeIdent(), properties.getTeClass(), null); - } + private float minX, minY, minZ, maxX, maxY, maxZ; - public MachineDefinition(IMachinePropertiesTESR properties) { - this(properties.getMeta(), properties.getTeIdent(), properties.getTeClass(), properties.getRenderer()); - } + public MachineDefinition(IMachineProperties properties) { + this(properties.getMeta(), properties.getTeIdent(), properties.getTeClass(), null); + } - public MachineDefinition(int meta, String teIdent, Class teClass, IBlockRenderer renderer) { - this.meta = meta; - this.teIdent = teIdent; - this.teClass = teClass; - this.renderer = renderer; + public MachineDefinition(IMachinePropertiesTESR properties) { + this(properties.getMeta(), properties.getTeIdent(), properties.getTeClass(), properties.getRenderer()); + } - this.faceMap = new int[8]; - for (int i = 0; i < 8; i++) { - faceMap[i] = 0; - } + public MachineDefinition(int meta, String teIdent, Class teClass, IBlockRenderer renderer) { + this.meta = meta; + this.teIdent = teIdent; + this.teClass = teClass; + this.renderer = renderer; - minX = 0; - minY = 0; - minZ = 0; - maxX = 1; - maxY = 1; - maxZ = 1; - } + this.faceMap = new int[8]; + for (int i = 0; i < 8; i++) { + faceMap[i] = 0; + } - public Block getBlock() { - return block; - } + minX = 0; + minY = 0; + minZ = 0; + maxX = 1; + maxY = 1; + maxZ = 1; + } - public int getMeta() { - return meta; - } + public Block getBlock() { + return block; + } - public void setBlock(Block block) { - this.block = block; - } + public int getMeta() { + return meta; + } - public MachineDefinition setLegacy() { - legacy = true; - return this; - } - - public MachineDefinition setBoundingBox(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { - this.minX = minX; - this.minY = minY; - this.minZ = minZ; - this.maxX = maxX; - this.maxY = maxY; - this.maxZ = maxZ; - return this; - } + public void setBlock(Block block) { + this.block = block; + } - public void register() { - registerTileEntity(); - if (renderer != null) { - Proxies.render.registerTESR(this); - } - } - - public AxisAlignedBB getBoundingBox(int x, int y, int z) { - return AxisAlignedBB.getBoundingBox(x + minX, y + minY, z + minZ, x + maxX, y + maxY, z + maxZ); - } + public MachineDefinition setLegacy() { + legacy = true; + return this; + } - public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 startVec, Vec3 endVec) { - return BlockUtil.collisionRayTrace(world, x, y, z, startVec, endVec, minX, minY, minZ, maxX, maxY, maxZ); - } + public MachineDefinition setBoundingBox(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { + this.minX = minX; + this.minY = minY; + this.minZ = minZ; + this.maxX = maxX; + this.maxY = maxY; + this.maxZ = maxZ; + return this; + } - /** - * Registers the tile entity with MC. - */ - private void registerTileEntity() { - GameRegistry.registerTileEntity(teClass, teIdent); - } + public void register() { + registerTileEntity(); + if (renderer != null) { + Proxies.render.registerTESR(this); + } + } - public TileEntity createMachine() { - try { - return teClass.getConstructor().newInstance(); - } catch (Exception ex) { - throw new RuntimeException("Failed to instantiate tile entity of class " + teClass.getName()); - } - } + public AxisAlignedBB getBoundingBox(int x, int y, int z) { + return AxisAlignedBB.getBoundingBox(x + minX, y + minY, z + minZ, x + maxX, y + maxY, z + maxZ); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - public void getSubBlocks(Item item, CreativeTabs tab, List list) { - if (legacy) { - return; - } - list.add(new ItemStack(item, 1, meta)); - } + public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 startVec, Vec3 endVec) { + return BlockUtil.collisionRayTrace(world, x, y, z, startVec, endVec, minX, minY, minZ, maxX, maxY, maxZ); + } - /* INTERACTION */ - public boolean isSolidOnSide(IBlockAccess world, int x, int y, int z, int side) { - return true; - } + /** + * Registers the tile entity with MC. + */ + private void registerTileEntity() { + GameRegistry.registerTileEntity(teClass, teIdent); + } - public boolean rotateBlock(World world, int x, int y, int z, ForgeDirection axis) { - TileForestry tile = TileUtil.getTile(world, x, y, z, teClass); - if (tile == null) { - return false; - } + public TileEntity createMachine() { + try { + return teClass.getConstructor().newInstance(); + } catch (Exception ex) { + throw new RuntimeException("Failed to instantiate tile entity of class " + teClass.getName()); + } + } - return tile.rotate(axis); - } + @SuppressWarnings({"rawtypes", "unchecked"}) + public void getSubBlocks(Item item, CreativeTabs tab, List list) { + if (legacy) { + return; + } + list.add(new ItemStack(item, 1, meta)); + } - /* TEXTURES */ - private final int[] faceMap; + /* INTERACTION */ + public boolean isSolidOnSide(IBlockAccess world, int x, int y, int z, int side) { + return true; + } - public MachineDefinition setFaces(int... faces) { + public boolean rotateBlock(World world, int x, int y, int z, ForgeDirection axis) { + TileForestry tile = TileUtil.getTile(world, x, y, z, teClass); + if (tile == null) { + return false; + } - if (faces.length > 6) { - System.arraycopy(faces, 0, faceMap, 0, faces.length); - } else { - System.arraycopy(faces, 0, faceMap, 0, 6); - faceMap[6] = faces[0]; - faceMap[7] = faces[1]; - } + return tile.rotate(axis); + } - return this; - } + /* TEXTURES */ + private final int[] faceMap; - @SideOnly(Side.CLIENT) - private IIcon[] icons; + public MachineDefinition setFaces(int... faces) { - @SideOnly(Side.CLIENT) - public void registerIcons(IIconRegister register) { - icons = new IIcon[8]; + if (faces.length > 6) { + System.arraycopy(faces, 0, faceMap, 0, faces.length); + } else { + System.arraycopy(faces, 0, faceMap, 0, 6); + faceMap[6] = faces[0]; + faceMap[7] = faces[1]; + } - if (legacy) { - return; - } + return this; + } - for (int i = 0; i < 8; i++) { - icons[i] = TextureManager.registerTex(register, teIdent.replace("forestry.", "").toLowerCase(Locale.ENGLISH) + "." + faceMap[i]); - } - } + @SideOnly(Side.CLIENT) + private IIcon[] icons; - @SideOnly(Side.CLIENT) - public IIcon getBlockTextureForSide(int side) { - return icons[side]; - } + @SideOnly(Side.CLIENT) + public void registerIcons(IIconRegister register) { + icons = new IIcon[8]; - /** - * 0 - Bottom 1 - Top 2 - Back 3 - Front 4,5 - Sides, 7 - Reversed ?, 8 - Reversed ? - */ - @SideOnly(Side.CLIENT) - public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { + if (legacy) { + return; + } - TileEntity tile = world.getTileEntity(x, y, z); - if (!(tile instanceof TileForestry)) { - return getBlockTextureForSide(side); - } + for (int i = 0; i < 8; i++) { + icons[i] = TextureManager.registerTex( + register, teIdent.replace("forestry.", "").toLowerCase(Locale.ENGLISH) + "." + faceMap[i]); + } + } - ForgeDirection dir = ((TileForestry) tile).getOrientation(); - switch (dir) { - case WEST: - side = side == 2 ? 4 : side == 3 ? 5 : side == 4 ? 3 : side == 5 ? 2 : side == 0 ? 6 : 7; - break; - case EAST: - side = side == 2 ? 5 : side == 3 ? 4 : side == 4 ? 2 : side == 5 ? 3 : side == 0 ? 6 : 7; - break; - case SOUTH: - break; - case NORTH: - side = side == 2 ? 3 : side == 3 ? 2 : side == 4 ? 5 : side == 5 ? 4 : side; - break; - default: - } + @SideOnly(Side.CLIENT) + public IIcon getBlockTextureForSide(int side) { + return icons[side]; + } - return getBlockTextureForSide(side); - } + /** + * 0 - Bottom 1 - Top 2 - Back 3 - Front 4,5 - Sides, 7 - Reversed ?, 8 - Reversed ? + */ + @SideOnly(Side.CLIENT) + public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { + + TileEntity tile = world.getTileEntity(x, y, z); + if (!(tile instanceof TileForestry)) { + return getBlockTextureForSide(side); + } + + ForgeDirection dir = ((TileForestry) tile).getOrientation(); + switch (dir) { + case WEST: + side = side == 2 ? 4 : side == 3 ? 5 : side == 4 ? 3 : side == 5 ? 2 : side == 0 ? 6 : 7; + break; + case EAST: + side = side == 2 ? 5 : side == 3 ? 4 : side == 4 ? 2 : side == 5 ? 3 : side == 0 ? 6 : 7; + break; + case SOUTH: + break; + case NORTH: + side = side == 2 ? 3 : side == 3 ? 2 : side == 4 ? 5 : side == 5 ? 4 : side; + break; + default: + } + + return getBlockTextureForSide(side); + } } diff --git a/src/main/java/forestry/core/tiles/TemperatureState.java b/src/main/java/forestry/core/tiles/TemperatureState.java index f06968ad1..5969ee549 100644 --- a/src/main/java/forestry/core/tiles/TemperatureState.java +++ b/src/main/java/forestry/core/tiles/TemperatureState.java @@ -11,31 +11,29 @@ package forestry.core.tiles; public enum TemperatureState { + UNKNOWN, + COOL, + WARMED_UP, + OPERATING_TEMPERATURE, + RUNNING_HOT, + OVERHEATING, + MELTING; - UNKNOWN, - COOL, - WARMED_UP, - OPERATING_TEMPERATURE, - RUNNING_HOT, - OVERHEATING, - MELTING; - - public static TemperatureState getState(double heat, double maxHeat) { - final double scaledHeat = heat / maxHeat; - - if (scaledHeat < 0.20) { - return TemperatureState.COOL; - } else if (scaledHeat < 0.45) { - return TemperatureState.WARMED_UP; - } else if (scaledHeat < 0.65) { - return TemperatureState.OPERATING_TEMPERATURE; - } else if (scaledHeat < 0.85) { - return TemperatureState.RUNNING_HOT; - } else if (scaledHeat < 1.0) { - return TemperatureState.OVERHEATING; - } else { - return TemperatureState.MELTING; - } - } + public static TemperatureState getState(double heat, double maxHeat) { + final double scaledHeat = heat / maxHeat; + if (scaledHeat < 0.20) { + return TemperatureState.COOL; + } else if (scaledHeat < 0.45) { + return TemperatureState.WARMED_UP; + } else if (scaledHeat < 0.65) { + return TemperatureState.OPERATING_TEMPERATURE; + } else if (scaledHeat < 0.85) { + return TemperatureState.RUNNING_HOT; + } else if (scaledHeat < 1.0) { + return TemperatureState.OVERHEATING; + } else { + return TemperatureState.MELTING; + } + } } diff --git a/src/main/java/forestry/core/tiles/TileAnalyzer.java b/src/main/java/forestry/core/tiles/TileAnalyzer.java index 05a2b7d01..470988652 100644 --- a/src/main/java/forestry/core/tiles/TileAnalyzer.java +++ b/src/main/java/forestry/core/tiles/TileAnalyzer.java @@ -10,20 +10,6 @@ ******************************************************************************/ package forestry.core.tiles; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; - import forestry.api.arboriculture.TreeManager; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IIndividual; @@ -46,244 +32,258 @@ import forestry.core.proxy.Proxies; import forestry.core.utils.GeneticsUtil; import forestry.core.utils.InventoryUtil; import forestry.plugins.PluginManager; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; -public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiquidTankTile, IFluidHandler, IItemStackDisplay { - private static final int TIME_TO_ANALYZE = 125; - private static final int HONEY_REQUIRED = 100; - private static final int ENERGY_PER_WORK_CYCLE = 20320; +public class TileAnalyzer extends TilePowered + implements ISidedInventory, ILiquidTankTile, IFluidHandler, IItemStackDisplay { + private static final int TIME_TO_ANALYZE = 125; + private static final int HONEY_REQUIRED = 100; + private static final int ENERGY_PER_WORK_CYCLE = 20320; - private final FilteredTank resourceTank; - private final TankManager tankManager; - private final IInventory invInput; - private final IInventory invOutput; + private final FilteredTank resourceTank; + private final TankManager tankManager; + private final IInventory invInput; + private final IInventory invOutput; - private IIndividual specimenToAnalyze; - private ItemStack individualOnDisplayClient; + private IIndividual specimenToAnalyze; + private ItemStack individualOnDisplayClient; - /* CONSTRUCTOR */ - public TileAnalyzer() { - super("analyzer", 800, Constants.MACHINE_MAX_ENERGY); - setInternalInventory(new InventoryAnalyzer(this)); - resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, Fluids.HONEY.getFluid()); - tankManager = new TankManager(this, resourceTank); - invInput = new InventoryMapper(getInternalInventory(), InventoryAnalyzer.SLOT_INPUT_1, InventoryAnalyzer.SLOT_INPUT_COUNT); - invOutput = new InventoryMapper(getInternalInventory(), InventoryAnalyzer.SLOT_OUTPUT_1, InventoryAnalyzer.SLOT_OUTPUT_COUNT); - } + /* CONSTRUCTOR */ + public TileAnalyzer() { + super("analyzer", 800, Constants.MACHINE_MAX_ENERGY); + setInternalInventory(new InventoryAnalyzer(this)); + resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, Fluids.HONEY.getFluid()); + tankManager = new TankManager(this, resourceTank); + invInput = new InventoryMapper( + getInternalInventory(), InventoryAnalyzer.SLOT_INPUT_1, InventoryAnalyzer.SLOT_INPUT_COUNT); + invOutput = new InventoryMapper( + getInternalInventory(), InventoryAnalyzer.SLOT_OUTPUT_1, InventoryAnalyzer.SLOT_OUTPUT_COUNT); + } - /* SAVING & LOADING */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - tankManager.writeToNBT(nbttagcompound); - } + /* SAVING & LOADING */ + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + tankManager.writeToNBT(nbttagcompound); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - tankManager.readFromNBT(nbttagcompound); + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + tankManager.readFromNBT(nbttagcompound); - ItemStack stackToAnalyze = getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE); - if (stackToAnalyze != null) { - specimenToAnalyze = AlleleManager.alleleRegistry.getIndividual(stackToAnalyze); - } - } + ItemStack stackToAnalyze = getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE); + if (stackToAnalyze != null) { + specimenToAnalyze = AlleleManager.alleleRegistry.getIndividual(stackToAnalyze); + } + } - @Override - protected void updateServerSide() { - super.updateServerSide(); + @Override + protected void updateServerSide() { + super.updateServerSide(); - if (updateOnInterval(20)) { - // Check if we have suitable items waiting in the can slot - FluidHelper.drainContainers(tankManager, this, InventoryAnalyzer.SLOT_CAN); - } - } + if (updateOnInterval(20)) { + // Check if we have suitable items waiting in the can slot + FluidHelper.drainContainers(tankManager, this, InventoryAnalyzer.SLOT_CAN); + } + } - /* WORKING */ - @Override - public boolean workCycle() { - ItemStack stackToAnalyze = getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE); - if (stackToAnalyze == null) { - return false; - } + /* WORKING */ + @Override + public boolean workCycle() { + ItemStack stackToAnalyze = getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE); + if (stackToAnalyze == null) { + return false; + } - if (!specimenToAnalyze.isAnalyzed()) { - if (!resourceTank.canDrain(HONEY_REQUIRED)) { - return false; - } - resourceTank.drain(HONEY_REQUIRED, true); + if (!specimenToAnalyze.isAnalyzed()) { + if (!resourceTank.canDrain(HONEY_REQUIRED)) { + return false; + } + resourceTank.drain(HONEY_REQUIRED, true); - specimenToAnalyze.analyze(); + specimenToAnalyze.analyze(); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - specimenToAnalyze.writeToNBT(nbttagcompound); - stackToAnalyze.setTagCompound(nbttagcompound); - } + NBTTagCompound nbttagcompound = new NBTTagCompound(); + specimenToAnalyze.writeToNBT(nbttagcompound); + stackToAnalyze.setTagCompound(nbttagcompound); + } - boolean added = InventoryUtil.tryAddStack(invOutput, stackToAnalyze, true); - if (!added) { - return false; - } + boolean added = InventoryUtil.tryAddStack(invOutput, stackToAnalyze, true); + if (!added) { + return false; + } - setInventorySlotContents(InventoryAnalyzer.SLOT_ANALYZE, null); - PacketItemStackDisplay packet = new PacketItemStackDisplay(this, getIndividualOnDisplay()); - Proxies.net.sendNetworkPacket(packet, worldObj); + setInventorySlotContents(InventoryAnalyzer.SLOT_ANALYZE, null); + PacketItemStackDisplay packet = new PacketItemStackDisplay(this, getIndividualOnDisplay()); + Proxies.net.sendNetworkPacket(packet, worldObj); - return true; - } + return true; + } - private IInvSlot getInputSlot() { - for (IInvSlot slot : InventoryIterator.getIterable(invInput)) { - ItemStack inputStack = slot.getStackInSlot(); - if (AlleleManager.alleleRegistry.isIndividual(inputStack)) { - return slot; - } - } - return null; - } + private IInvSlot getInputSlot() { + for (IInvSlot slot : InventoryIterator.getIterable(invInput)) { + ItemStack inputStack = slot.getStackInSlot(); + if (AlleleManager.alleleRegistry.isIndividual(inputStack)) { + return slot; + } + } + return null; + } - /* Network */ - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - ItemStack displayStack = getIndividualOnDisplay(); - data.writeItemStack(displayStack); - tankManager.writeData(data); - } + /* Network */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + ItemStack displayStack = getIndividualOnDisplay(); + data.writeItemStack(displayStack); + tankManager.writeData(data); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - individualOnDisplayClient = data.readItemStack(); - tankManager.readData(data); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + individualOnDisplayClient = data.readItemStack(); + tankManager.readData(data); + } - @Override - public void handleItemStackForDisplay(ItemStack itemStack) { - if (!ItemStack.areItemStacksEqual(itemStack, individualOnDisplayClient)) { - individualOnDisplayClient = itemStack; - worldObj.func_147479_m(xCoord, yCoord, zCoord); - } - } + @Override + public void handleItemStackForDisplay(ItemStack itemStack) { + if (!ItemStack.areItemStacksEqual(itemStack, individualOnDisplayClient)) { + individualOnDisplayClient = itemStack; + worldObj.func_147479_m(xCoord, yCoord, zCoord); + } + } - /* STATE INFORMATION */ - @Override - public boolean hasWork() { - moveSpecimenToAnalyzeSlot(); + /* STATE INFORMATION */ + @Override + public boolean hasWork() { + moveSpecimenToAnalyzeSlot(); - ItemStack specimen = getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE); + ItemStack specimen = getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE); - boolean hasSpecimen = (specimen != null); - boolean hasResource = true; - boolean hasSpace = true; + boolean hasSpecimen = (specimen != null); + boolean hasResource = true; + boolean hasSpace = true; - if (hasSpecimen) { - hasSpace = InventoryUtil.tryAddStack(invOutput, specimen, true, false); + if (hasSpecimen) { + hasSpace = InventoryUtil.tryAddStack(invOutput, specimen, true, false); - if (!specimenToAnalyze.isAnalyzed()) { - hasResource = resourceTank.canDrain(HONEY_REQUIRED); - } - } + if (!specimenToAnalyze.isAnalyzed()) { + hasResource = resourceTank.canDrain(HONEY_REQUIRED); + } + } - getErrorLogic().setCondition(!hasSpecimen, EnumErrorCode.NO_SPECIMEN); - getErrorLogic().setCondition(!hasResource, EnumErrorCode.NO_RESOURCE_LIQUID); - getErrorLogic().setCondition(!hasSpace, EnumErrorCode.NO_SPACE_INVENTORY); + getErrorLogic().setCondition(!hasSpecimen, EnumErrorCode.NO_SPECIMEN); + getErrorLogic().setCondition(!hasResource, EnumErrorCode.NO_RESOURCE_LIQUID); + getErrorLogic().setCondition(!hasSpace, EnumErrorCode.NO_SPACE_INVENTORY); - return hasSpecimen && hasResource && hasSpace; - } + return hasSpecimen && hasResource && hasSpace; + } - private void moveSpecimenToAnalyzeSlot() { - if (getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE) != null) { - return; - } + private void moveSpecimenToAnalyzeSlot() { + if (getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE) != null) { + return; + } - IInvSlot slot = getInputSlot(); - if (slot == null) { - return; - } + IInvSlot slot = getInputSlot(); + if (slot == null) { + return; + } - ItemStack inputStack = slot.getStackInSlot(); - if (inputStack == null) { - return; - } + ItemStack inputStack = slot.getStackInSlot(); + if (inputStack == null) { + return; + } - if (PluginManager.Module.ARBORICULTURE.isEnabled() && !TreeManager.treeRoot.isMember(inputStack)) { - ItemStack ersatz = GeneticsUtil.convertSaplingToGeneticEquivalent(inputStack); - if (ersatz != null) { - inputStack = ersatz; - } - } + if (PluginManager.Module.ARBORICULTURE.isEnabled() && !TreeManager.treeRoot.isMember(inputStack)) { + ItemStack ersatz = GeneticsUtil.convertSaplingToGeneticEquivalent(inputStack); + if (ersatz != null) { + inputStack = ersatz; + } + } - specimenToAnalyze = AlleleManager.alleleRegistry.getIndividual(inputStack); - if (specimenToAnalyze == null) { - return; - } + specimenToAnalyze = AlleleManager.alleleRegistry.getIndividual(inputStack); + if (specimenToAnalyze == null) { + return; + } - setInventorySlotContents(InventoryAnalyzer.SLOT_ANALYZE, inputStack); - slot.setStackInSlot(null); + setInventorySlotContents(InventoryAnalyzer.SLOT_ANALYZE, inputStack); + slot.setStackInSlot(null); - if (specimenToAnalyze.isAnalyzed()) { - setTicksPerWorkCycle(1); - setEnergyPerWorkCycle(0); - } else { - setTicksPerWorkCycle(TIME_TO_ANALYZE); - setEnergyPerWorkCycle(ENERGY_PER_WORK_CYCLE); - } + if (specimenToAnalyze.isAnalyzed()) { + setTicksPerWorkCycle(1); + setEnergyPerWorkCycle(0); + } else { + setTicksPerWorkCycle(TIME_TO_ANALYZE); + setEnergyPerWorkCycle(ENERGY_PER_WORK_CYCLE); + } - PacketItemStackDisplay packet = new PacketItemStackDisplay(this, getIndividualOnDisplay()); - Proxies.net.sendNetworkPacket(packet, worldObj); - } + PacketItemStackDisplay packet = new PacketItemStackDisplay(this, getIndividualOnDisplay()); + Proxies.net.sendNetworkPacket(packet, worldObj); + } - public ItemStack getIndividualOnDisplay() { - if (worldObj.isRemote) { - return individualOnDisplayClient; - } - return getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE); - } + public ItemStack getIndividualOnDisplay() { + if (worldObj.isRemote) { + return individualOnDisplayClient; + } + return getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE); + } - /* ILiquidTankTile */ - @Override - public TankManager getTankManager() { - return tankManager; - } + /* ILiquidTankTile */ + @Override + public TankManager getTankManager() { + return tankManager; + } - /* IFluidHandler */ - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return tankManager.fill(from, resource, doFill); - } + /* IFluidHandler */ + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return tankManager.drain(from, resource, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return tankManager.drain(from, maxDrain, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return tankManager.canFill(from, fluid); - } + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return tankManager.canDrain(from, fluid); - } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return tankManager.getTankInfo(from); - } + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiAnalyzer(player.inventory, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiAnalyzer(player.inventory, this); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerAnalyzer(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerAnalyzer(player.inventory, this); + } } diff --git a/src/main/java/forestry/core/tiles/TileBase.java b/src/main/java/forestry/core/tiles/TileBase.java index 2aa38ad39..0f3b2a44b 100644 --- a/src/main/java/forestry/core/tiles/TileBase.java +++ b/src/main/java/forestry/core/tiles/TileBase.java @@ -10,33 +10,31 @@ ******************************************************************************/ package forestry.core.tiles; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; - import forestry.core.config.Config; import forestry.core.gui.GuiHandler; import forestry.core.gui.IHintSource; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; public abstract class TileBase extends TileForestry implements IHintSource { - protected final List hints; + protected final List hints; - protected TileBase(String hintKey) { - this.hints = new ArrayList<>(Config.hints.get(hintKey)); - } + protected TileBase(String hintKey) { + this.hints = new ArrayList<>(Config.hints.get(hintKey)); + } - public void openGui(EntityPlayer player) { - GuiHandler.openGui(player, this); - } + public void openGui(EntityPlayer player) { + GuiHandler.openGui(player, this); + } - public boolean canDrainWithBucket() { - return false; - } + public boolean canDrainWithBucket() { + return false; + } - /* IHintSource */ - @Override - public final List getHints() { - return hints; - } + /* IHintSource */ + @Override + public final List getHints() { + return hints; + } } diff --git a/src/main/java/forestry/core/tiles/TileEngine.java b/src/main/java/forestry/core/tiles/TileEngine.java index 944f707f9..496341315 100644 --- a/src/main/java/forestry/core/tiles/TileEngine.java +++ b/src/main/java/forestry/core/tiles/TileEngine.java @@ -10,16 +10,7 @@ ******************************************************************************/ package forestry.core.tiles; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.ICrafting; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import cofh.api.energy.IEnergyConnection; import forestry.api.core.IErrorLogic; import forestry.apiculture.network.packets.PacketActiveUpdate; import forestry.core.config.Config; @@ -30,294 +21,304 @@ import forestry.core.network.DataOutputStreamForestry; import forestry.core.proxy.Proxies; import forestry.core.utils.BlockUtil; import forestry.energy.EnergyManager; - -import cofh.api.energy.IEnergyConnection; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public abstract class TileEngine extends TileBase implements IEnergyConnection, IActivatable { - private static final int CANT_SEND_ENERGY_TIME = 20; + private static final int CANT_SEND_ENERGY_TIME = 20; - private boolean active = false; // Used for smp. - private int cantSendEnergyCountdown = CANT_SEND_ENERGY_TIME; - /** - * Indicates whether the piston is receding from or approaching the - * combustion chamber - */ - private int stagePiston = 0; - /** - * Piston speed as supplied by the server - */ - private float pistonSpeedServer = 0; + private boolean active = false; // Used for smp. + private int cantSendEnergyCountdown = CANT_SEND_ENERGY_TIME; + /** + * Indicates whether the piston is receding from or approaching the + * combustion chamber + */ + private int stagePiston = 0; + /** + * Piston speed as supplied by the server + */ + private float pistonSpeedServer = 0; - protected int currentOutput = 0; - protected int heat; - protected final int maxHeat; - protected boolean forceCooldown = false; - public float progress; - protected final EnergyManager energyManager; + protected int currentOutput = 0; + protected int heat; + protected final int maxHeat; + protected boolean forceCooldown = false; + public float progress; + protected final EnergyManager energyManager; - protected TileEngine(String hintKey, int maxHeat, int maxEnergy) { - super(hintKey); - this.maxHeat = maxHeat; - energyManager = new EnergyManager(2000, maxEnergy); + protected TileEngine(String hintKey, int maxHeat, int maxEnergy) { + super(hintKey); + this.maxHeat = maxHeat; + energyManager = new EnergyManager(2000, maxEnergy); - // allow engines to chain, but not have energy sucked out of them - energyManager.setReceiveOnly(); + // allow engines to chain, but not have energy sucked out of them + energyManager.setReceiveOnly(); - hints.addAll(Config.hints.get("engine")); - } + hints.addAll(Config.hints.get("engine")); + } - @Override - public void rotateAfterPlacement(EntityPlayer player, int side) { - ForgeDirection orientation = ForgeDirection.getOrientation(side).getOpposite(); - if (isOrientedAtEnergyReciever(orientation)) { - setOrientation(orientation); - } else { - super.rotateAfterPlacement(player, side); - rotate(); - } - } + @Override + public void rotateAfterPlacement(EntityPlayer player, int side) { + ForgeDirection orientation = ForgeDirection.getOrientation(side).getOpposite(); + if (isOrientedAtEnergyReciever(orientation)) { + setOrientation(orientation); + } else { + super.rotateAfterPlacement(player, side); + rotate(); + } + } - protected void addHeat(int i) { - heat += i; + protected void addHeat(int i) { + heat += i; - if (heat > maxHeat) { - heat = maxHeat; - } - } + if (heat > maxHeat) { + heat = maxHeat; + } + } - protected abstract int dissipateHeat(); + protected abstract int dissipateHeat(); - protected abstract int generateHeat(); + protected abstract int generateHeat(); - protected boolean mayBurn() { - return !forceCooldown; - } + protected boolean mayBurn() { + return !forceCooldown; + } - protected abstract void burn(); + protected abstract void burn(); - @Override - public void updateClientSide() { - if (stagePiston != 0) { - progress += pistonSpeedServer; + @Override + public void updateClientSide() { + if (stagePiston != 0) { + progress += pistonSpeedServer; - if (progress > 1) { - stagePiston = 0; - progress = 0; - } - } else if (this.active) { - stagePiston = 1; - } - } + if (progress > 1) { + stagePiston = 0; + progress = 0; + } + } else if (this.active) { + stagePiston = 1; + } + } - @Override - protected void updateServerSide() { - TemperatureState energyState = getTemperatureState(); - if (energyState == TemperatureState.MELTING && heat > 0) { - forceCooldown = true; - } else if (forceCooldown && heat <= 0) { - forceCooldown = false; - } + @Override + protected void updateServerSide() { + TemperatureState energyState = getTemperatureState(); + if (energyState == TemperatureState.MELTING && heat > 0) { + forceCooldown = true; + } else if (forceCooldown && heat <= 0) { + forceCooldown = false; + } - IErrorLogic errorLogic = getErrorLogic(); - errorLogic.setCondition(forceCooldown, EnumErrorCode.FORCED_COOLDOWN); + IErrorLogic errorLogic = getErrorLogic(); + errorLogic.setCondition(forceCooldown, EnumErrorCode.FORCED_COOLDOWN); - boolean enabledRedstone = isRedstoneActivated(); - errorLogic.setCondition(!enabledRedstone, EnumErrorCode.NO_REDSTONE); + boolean enabledRedstone = isRedstoneActivated(); + errorLogic.setCondition(!enabledRedstone, EnumErrorCode.NO_REDSTONE); - // Determine targeted tile - TileEntity tile = worldObj.getTileEntity(xCoord + getOrientation().offsetX, yCoord + getOrientation().offsetY, zCoord + getOrientation().offsetZ); + // Determine targeted tile + TileEntity tile = worldObj.getTileEntity( + xCoord + getOrientation().offsetX, + yCoord + getOrientation().offsetY, + zCoord + getOrientation().offsetZ); - float newPistonSpeed = getPistonSpeed(); - if (newPistonSpeed != pistonSpeedServer) { - pistonSpeedServer = newPistonSpeed; - setNeedsNetworkUpdate(); - } + float newPistonSpeed = getPistonSpeed(); + if (newPistonSpeed != pistonSpeedServer) { + pistonSpeedServer = newPistonSpeed; + setNeedsNetworkUpdate(); + } - if (stagePiston != 0) { + if (stagePiston != 0) { - progress += pistonSpeedServer; + progress += pistonSpeedServer; - energyManager.sendEnergy(getOrientation(), tile); + energyManager.sendEnergy(getOrientation(), tile); - if (progress > 0.25 && stagePiston == 1) { - stagePiston = 2; - } else if (progress >= 0.5) { - progress = 0; - stagePiston = 0; - } - } else if (enabledRedstone && BlockUtil.isEnergyReceiverOrEngine(getOrientation().getOpposite(), tile)) { - if (energyManager.canSendEnergy(getOrientation(), tile)) { - stagePiston = 1; // If we can transfer energy, start running - setActive(true); - cantSendEnergyCountdown = CANT_SEND_ENERGY_TIME; - } else { - if (isActive()) { - cantSendEnergyCountdown--; - if (cantSendEnergyCountdown <= 0) { - setActive(false); - } - } - } - } else { - setActive(false); - } + if (progress > 0.25 && stagePiston == 1) { + stagePiston = 2; + } else if (progress >= 0.5) { + progress = 0; + stagePiston = 0; + } + } else if (enabledRedstone + && BlockUtil.isEnergyReceiverOrEngine(getOrientation().getOpposite(), tile)) { + if (energyManager.canSendEnergy(getOrientation(), tile)) { + stagePiston = 1; // If we can transfer energy, start running + setActive(true); + cantSendEnergyCountdown = CANT_SEND_ENERGY_TIME; + } else { + if (isActive()) { + cantSendEnergyCountdown--; + if (cantSendEnergyCountdown <= 0) { + setActive(false); + } + } + } + } else { + setActive(false); + } - dissipateHeat(); - generateHeat(); - // Now let's fire up the engine: - if (mayBurn()) { - burn(); - } else { - energyManager.drainEnergy(20); - } - } + dissipateHeat(); + generateHeat(); + // Now let's fire up the engine: + if (mayBurn()) { + burn(); + } else { + energyManager.drainEnergy(20); + } + } - @Override - public boolean isActive() { - return active; - } + @Override + public boolean isActive() { + return active; + } - @Override - public void setActive(boolean active) { - if (this.active == active) { - return; - } - this.active = active; + @Override + public void setActive(boolean active) { + if (this.active == active) { + return; + } + this.active = active; - if (!worldObj.isRemote) { - Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), worldObj); - } - } + if (!worldObj.isRemote) { + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), worldObj); + } + } - /* INTERACTION */ - @Override - public boolean rotate(ForgeDirection axis) { - rotate(); + /* INTERACTION */ + @Override + public boolean rotate(ForgeDirection axis) { + rotate(); - // it would be irritating if the wrench opened the engine gui when it failed to rotate, so always return true - return true; - } + // it would be irritating if the wrench opened the engine gui when it failed to rotate, so always return true + return true; + } - private void rotate() { - for (int i = getOrientation().ordinal() + 1; i <= getOrientation().ordinal() + 6; ++i) { - ForgeDirection orientation = ForgeDirection.values()[i % 6]; - if (isOrientedAtEnergyReciever(orientation)) { - setOrientation(orientation); - return; - } - } - } + private void rotate() { + for (int i = getOrientation().ordinal() + 1; i <= getOrientation().ordinal() + 6; ++i) { + ForgeDirection orientation = ForgeDirection.values()[i % 6]; + if (isOrientedAtEnergyReciever(orientation)) { + setOrientation(orientation); + return; + } + } + } - private boolean isOrientedAtEnergyReciever(ForgeDirection orientation) { - TileEntity tile = worldObj.getTileEntity(xCoord + orientation.offsetX, yCoord + orientation.offsetY, zCoord + orientation.offsetZ); - return BlockUtil.isEnergyReceiverOrEngine(getOrientation().getOpposite(), tile); - } + private boolean isOrientedAtEnergyReciever(ForgeDirection orientation) { + TileEntity tile = worldObj.getTileEntity( + xCoord + orientation.offsetX, yCoord + orientation.offsetY, zCoord + orientation.offsetZ); + return BlockUtil.isEnergyReceiverOrEngine(getOrientation().getOpposite(), tile); + } - // STATE INFORMATION - protected double getHeatLevel() { - return (double) heat / (double) maxHeat; - } + // STATE INFORMATION + protected double getHeatLevel() { + return (double) heat / (double) maxHeat; + } - protected abstract boolean isBurning(); + protected abstract boolean isBurning(); - public int getBurnTimeRemainingScaled(int i) { - return 0; - } + public int getBurnTimeRemainingScaled(int i) { + return 0; + } - public boolean hasFuelMin(float percentage) { - return false; - } + public boolean hasFuelMin(float percentage) { + return false; + } - public int getCurrentOutput() { - if (isBurning() && isRedstoneActivated()) { - return currentOutput; - } else { - return 0; - } - } + public int getCurrentOutput() { + if (isBurning() && isRedstoneActivated()) { + return currentOutput; + } else { + return 0; + } + } - public int getHeat() { - return heat; - } + public int getHeat() { + return heat; + } - /** - * Returns the current energy state of the engine - */ - public TemperatureState getTemperatureState() { - return TemperatureState.getState(heat, maxHeat); - } + /** + * Returns the current energy state of the engine + */ + public TemperatureState getTemperatureState() { + return TemperatureState.getState(heat, maxHeat); + } - protected float getPistonSpeed() { - switch (getTemperatureState()) { - case COOL: - return 0.03f; - case WARMED_UP: - return 0.04f; - case OPERATING_TEMPERATURE: - return 0.05f; - case RUNNING_HOT: - return 0.06f; - case OVERHEATING: - return 0.07f; - case MELTING: - return Constants.ENGINE_PISTON_SPEED_MAX; - default: - return 0; - } - } + protected float getPistonSpeed() { + switch (getTemperatureState()) { + case COOL: + return 0.03f; + case WARMED_UP: + return 0.04f; + case OPERATING_TEMPERATURE: + return 0.05f; + case RUNNING_HOT: + return 0.06f; + case OVERHEATING: + return 0.07f; + case MELTING: + return Constants.ENGINE_PISTON_SPEED_MAX; + default: + return 0; + } + } - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbt) { - super.readFromNBT(nbt); - energyManager.readFromNBT(nbt); + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbt) { + super.readFromNBT(nbt); + energyManager.readFromNBT(nbt); - heat = nbt.getInteger("EngineHeat"); + heat = nbt.getInteger("EngineHeat"); - progress = nbt.getFloat("EngineProgress"); - forceCooldown = nbt.getBoolean("ForceCooldown"); - } + progress = nbt.getFloat("EngineProgress"); + forceCooldown = nbt.getBoolean("ForceCooldown"); + } - @Override - public void writeToNBT(NBTTagCompound nbt) { - super.writeToNBT(nbt); - energyManager.writeToNBT(nbt); + @Override + public void writeToNBT(NBTTagCompound nbt) { + super.writeToNBT(nbt); + energyManager.writeToNBT(nbt); - nbt.setInteger("EngineHeat", heat); - nbt.setFloat("EngineProgress", progress); - nbt.setBoolean("ForceCooldown", forceCooldown); - } + nbt.setInteger("EngineHeat", heat); + nbt.setFloat("EngineProgress", progress); + nbt.setBoolean("ForceCooldown", forceCooldown); + } - /* NETWORK */ - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeBoolean(active); - data.writeInt(heat); - data.writeFloat(pistonSpeedServer); - energyManager.writeData(data); - } + /* NETWORK */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeBoolean(active); + data.writeInt(heat); + data.writeFloat(pistonSpeedServer); + energyManager.writeData(data); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - active = data.readBoolean(); - heat = data.readInt(); - pistonSpeedServer = data.readFloat(); - energyManager.readData(data); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + active = data.readBoolean(); + heat = data.readInt(); + pistonSpeedServer = data.readFloat(); + energyManager.readData(data); + } - /* SMP GUI */ - public abstract void getGUINetworkData(int i, int j); + /* SMP GUI */ + public abstract void getGUINetworkData(int i, int j); - public abstract void sendGUINetworkData(Container containerEngine, ICrafting iCrafting); + public abstract void sendGUINetworkData(Container containerEngine, ICrafting iCrafting); - @Override - public boolean canConnectEnergy(ForgeDirection from) { - return energyManager.canConnectEnergy(from); - } + @Override + public boolean canConnectEnergy(ForgeDirection from) { + return energyManager.canConnectEnergy(from); + } - public EnergyManager getEnergyManager() { - return energyManager; - } + public EnergyManager getEnergyManager() { + return energyManager; + } } diff --git a/src/main/java/forestry/core/tiles/TileEscritoire.java b/src/main/java/forestry/core/tiles/TileEscritoire.java index b59644708..314cd5504 100644 --- a/src/main/java/forestry/core/tiles/TileEscritoire.java +++ b/src/main/java/forestry/core/tiles/TileEscritoire.java @@ -10,15 +10,7 @@ ******************************************************************************/ package forestry.core.tiles; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import com.mojang.authlib.GameProfile; - import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IIndividual; @@ -30,105 +22,117 @@ import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamableGui; import forestry.core.utils.InventoryUtil; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; public class TileEscritoire extends TileBase implements ISidedInventory, ISlotPickupWatcher, IStreamableGui { - private final EscritoireGame game = new EscritoireGame(); + private final EscritoireGame game = new EscritoireGame(); - public TileEscritoire() { - super("escritoire"); - setInternalInventory(new InventoryEscritoire(this)); - } + public TileEscritoire() { + super("escritoire"); + setInternalInventory(new InventoryEscritoire(this)); + } - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - game.readFromNBT(nbttagcompound); - } + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + game.readFromNBT(nbttagcompound); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - game.writeToNBT(nbttagcompound); - } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + game.writeToNBT(nbttagcompound); + } - /* GAME */ - public EscritoireGame getGame() { - return game; - } + /* GAME */ + public EscritoireGame getGame() { + return game; + } - public void choose(GameProfile gameProfile, int index) { - game.choose(index); - processTurnResult(gameProfile); - } + public void choose(GameProfile gameProfile, int index) { + game.choose(index); + processTurnResult(gameProfile); + } - private void processTurnResult(GameProfile gameProfile) { - if (getGame().getStatus() != EscritoireGame.Status.SUCCESS) { - return; - } + private void processTurnResult(GameProfile gameProfile) { + if (getGame().getStatus() != EscritoireGame.Status.SUCCESS) { + return; + } - IIndividual individual = AlleleManager.alleleRegistry.getIndividual(getStackInSlot(InventoryEscritoire.SLOT_ANALYZE)); - if (individual == null) { - return; - } + IIndividual individual = + AlleleManager.alleleRegistry.getIndividual(getStackInSlot(InventoryEscritoire.SLOT_ANALYZE)); + if (individual == null) { + return; + } - IAlleleSpecies species = individual.getGenome().getPrimary(); - for (ItemStack itemstack : species.getResearchBounty(worldObj, gameProfile, individual, game.getBountyLevel())) { - InventoryUtil.addStack(getInternalInventory(), itemstack, InventoryEscritoire.SLOT_RESULTS_1, InventoryEscritoire.SLOTS_RESULTS_COUNT, true); - } - } + IAlleleSpecies species = individual.getGenome().getPrimary(); + for (ItemStack itemstack : + species.getResearchBounty(worldObj, gameProfile, individual, game.getBountyLevel())) { + InventoryUtil.addStack( + getInternalInventory(), + itemstack, + InventoryEscritoire.SLOT_RESULTS_1, + InventoryEscritoire.SLOTS_RESULTS_COUNT, + true); + } + } - private boolean areProbeSlotsFilled() { - int filledSlots = 0; - int required = game.getSampleSize(InventoryEscritoire.SLOTS_INPUT_COUNT); - for (int i = InventoryEscritoire.SLOT_INPUT_1; i < InventoryEscritoire.SLOT_INPUT_1 + required; i++) { - if (getStackInSlot(i) != null) { - filledSlots++; - } - } + private boolean areProbeSlotsFilled() { + int filledSlots = 0; + int required = game.getSampleSize(InventoryEscritoire.SLOTS_INPUT_COUNT); + for (int i = InventoryEscritoire.SLOT_INPUT_1; i < InventoryEscritoire.SLOT_INPUT_1 + required; i++) { + if (getStackInSlot(i) != null) { + filledSlots++; + } + } - return filledSlots >= required; - } + return filledSlots >= required; + } - public void probe() { - if (worldObj.isRemote) { - return; - } + public void probe() { + if (worldObj.isRemote) { + return; + } - ItemStack analyze = getStackInSlot(InventoryEscritoire.SLOT_ANALYZE); + ItemStack analyze = getStackInSlot(InventoryEscritoire.SLOT_ANALYZE); - if (analyze != null && areProbeSlotsFilled()) { - game.probe(analyze, this, InventoryEscritoire.SLOT_INPUT_1, InventoryEscritoire.SLOTS_INPUT_COUNT); - } - } + if (analyze != null && areProbeSlotsFilled()) { + game.probe(analyze, this, InventoryEscritoire.SLOT_INPUT_1, InventoryEscritoire.SLOTS_INPUT_COUNT); + } + } - /* NETWORK */ - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - game.writeData(data); - } + /* NETWORK */ + @Override + public void writeGuiData(DataOutputStreamForestry data) throws IOException { + game.writeData(data); + } - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - game.readData(data); - } + @Override + public void readGuiData(DataInputStreamForestry data) throws IOException { + game.readData(data); + } - /* ISlotPickupWatcher */ - @Override - public void onPickupFromSlot(int slotIndex, EntityPlayer player) { - if (slotIndex == InventoryEscritoire.SLOT_ANALYZE) { - game.reset(); - } - } + /* ISlotPickupWatcher */ + @Override + public void onPickupFromSlot(int slotIndex, EntityPlayer player) { + if (slotIndex == InventoryEscritoire.SLOT_ANALYZE) { + game.reset(); + } + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiEscritoire(player, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiEscritoire(player, this); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerEscritoire(player, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerEscritoire(player, this); + } } diff --git a/src/main/java/forestry/core/tiles/TileForestry.java b/src/main/java/forestry/core/tiles/TileForestry.java index d06c3264f..4dc6d0b05 100644 --- a/src/main/java/forestry/core/tiles/TileForestry.java +++ b/src/main/java/forestry/core/tiles/TileForestry.java @@ -10,25 +10,11 @@ ******************************************************************************/ package forestry.core.tiles; -import java.io.IOException; -import java.util.Collection; -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.Packet; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.MathHelper; -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.statements.IStatementContainer; +import buildcraft.api.statements.ITriggerExternal; +import buildcraft.api.statements.ITriggerInternal; +import buildcraft.api.statements.ITriggerProvider; import cpw.mods.fml.common.Optional; - import forestry.api.core.IErrorLogic; import forestry.api.core.IErrorLogicSource; import forestry.core.access.AccessHandler; @@ -44,320 +30,335 @@ import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; import forestry.core.network.packets.PacketTileStream; import forestry.core.proxy.Proxies; - -import buildcraft.api.statements.IStatementContainer; -import buildcraft.api.statements.ITriggerExternal; -import buildcraft.api.statements.ITriggerInternal; -import buildcraft.api.statements.ITriggerProvider; +import java.io.IOException; +import java.util.Collection; +import java.util.Random; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.Packet; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.MathHelper; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; @Optional.Interface(iface = "buildcraft.api.statements.ITriggerProvider", modid = "BuildCraftAPI|statements") -public abstract class TileForestry extends TileEntity implements IStreamable, IErrorLogicSource, ITriggerProvider, ISidedInventory, IFilterSlotDelegate, IRestrictedAccess, ITitled, ILocatable, IGuiHandlerTile { - private static final ForgeDirection[] forgeDirections = ForgeDirection.values(); - private static final Random rand = new Random(); +public abstract class TileForestry extends TileEntity + implements IStreamable, + IErrorLogicSource, + ITriggerProvider, + ISidedInventory, + IFilterSlotDelegate, + IRestrictedAccess, + ITitled, + ILocatable, + IGuiHandlerTile { + private static final ForgeDirection[] forgeDirections = ForgeDirection.values(); + private static final Random rand = new Random(); - private final AccessHandler accessHandler = new AccessHandler(this); - private final ErrorLogic errorHandler = new ErrorLogic(); - private final AdjacentTileCache tileCache = new AdjacentTileCache(this); - private IInventoryAdapter inventory = FakeInventoryAdapter.instance(); + private final AccessHandler accessHandler = new AccessHandler(this); + private final ErrorLogic errorHandler = new ErrorLogic(); + private final AdjacentTileCache tileCache = new AdjacentTileCache(this); + private IInventoryAdapter inventory = FakeInventoryAdapter.instance(); - private int tickCount = rand.nextInt(256); - private boolean needsNetworkUpdate = false; - private ForgeDirection orientation = ForgeDirection.WEST; + private int tickCount = rand.nextInt(256); + private boolean needsNetworkUpdate = false; + private ForgeDirection orientation = ForgeDirection.WEST; - protected AdjacentTileCache getTileCache() { - return tileCache; - } + protected AdjacentTileCache getTileCache() { + return tileCache; + } - public void onNeighborBlockChange(Block id) { - tileCache.onNeighborChange(); - } + public void onNeighborBlockChange(Block id) { + tileCache.onNeighborChange(); + } - @Override - public void invalidate() { - tileCache.purge(); - super.invalidate(); - } + @Override + public void invalidate() { + tileCache.purge(); + super.invalidate(); + } - @Override - public void validate() { - tileCache.purge(); - super.validate(); - } + @Override + public void validate() { + tileCache.purge(); + super.validate(); + } - public void rotateAfterPlacement(EntityPlayer player, int side) { - int l = MathHelper.floor_double(((player.rotationYaw * 4F) / 360F) + 0.5D) & 3; - if (l == 0) { - setOrientation(ForgeDirection.NORTH); - } - if (l == 1) { - setOrientation(ForgeDirection.EAST); - } - if (l == 2) { - setOrientation(ForgeDirection.SOUTH); - } - if (l == 3) { - setOrientation(ForgeDirection.WEST); - } - } + public void rotateAfterPlacement(EntityPlayer player, int side) { + int l = MathHelper.floor_double(((player.rotationYaw * 4F) / 360F) + 0.5D) & 3; + if (l == 0) { + setOrientation(ForgeDirection.NORTH); + } + if (l == 1) { + setOrientation(ForgeDirection.EAST); + } + if (l == 2) { + setOrientation(ForgeDirection.SOUTH); + } + if (l == 3) { + setOrientation(ForgeDirection.WEST); + } + } - public boolean rotate(ForgeDirection axis) { - if (axis == ForgeDirection.DOWN || axis == ForgeDirection.UP) { - ForgeDirection orientation = getOrientation().getRotation(axis); - setOrientation(orientation); - return true; - } - return false; - } + public boolean rotate(ForgeDirection axis) { + if (axis == ForgeDirection.DOWN || axis == ForgeDirection.UP) { + ForgeDirection orientation = getOrientation().getRotation(axis); + setOrientation(orientation); + return true; + } + return false; + } - // / UPDATING - @Override - public final void updateEntity() { - tickCount++; + // / UPDATING + @Override + public final void updateEntity() { + tickCount++; - if (!worldObj.isRemote) { - updateServerSide(); - } else { - updateClientSide(); - } + if (!worldObj.isRemote) { + updateServerSide(); + } else { + updateClientSide(); + } - if (needsNetworkUpdate) { - needsNetworkUpdate = false; - sendNetworkUpdate(); - } - } + if (needsNetworkUpdate) { + needsNetworkUpdate = false; + sendNetworkUpdate(); + } + } - protected void updateClientSide() { - } + protected void updateClientSide() {} - protected void updateServerSide() { - } + protected void updateServerSide() {} - protected final boolean updateOnInterval(int tickInterval) { - return tickCount % tickInterval == 0; - } + protected final boolean updateOnInterval(int tickInterval) { + return tickCount % tickInterval == 0; + } - // / SAVING & LOADING - @Override - public void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); + // / SAVING & LOADING + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); - inventory.readFromNBT(data); - accessHandler.readFromNBT(data); + inventory.readFromNBT(data); + accessHandler.readFromNBT(data); - if (data.hasKey("Orientation")) { - orientation = ForgeDirection.values()[data.getInteger("Orientation")]; - } else { - orientation = ForgeDirection.WEST; - } - } + if (data.hasKey("Orientation")) { + orientation = ForgeDirection.values()[data.getInteger("Orientation")]; + } else { + orientation = ForgeDirection.WEST; + } + } - @Override - public void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - inventory.writeToNBT(data); - accessHandler.writeToNBT(data); - data.setInteger("Orientation", orientation.ordinal()); - } + @Override + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + inventory.writeToNBT(data); + accessHandler.writeToNBT(data); + data.setInteger("Orientation", orientation.ordinal()); + } - @Override - public Packet getDescriptionPacket() { - PacketTileStream packet = new PacketTileStream(this); - return packet.getPacket(); - } + @Override + public Packet getDescriptionPacket() { + PacketTileStream packet = new PacketTileStream(this); + return packet.getPacket(); + } - /* INetworkedEntity */ - protected final void sendNetworkUpdate() { - PacketTileStream packet = new PacketTileStream(this); - Proxies.net.sendNetworkPacket(packet, worldObj); - } + /* INetworkedEntity */ + protected final void sendNetworkUpdate() { + PacketTileStream packet = new PacketTileStream(this); + Proxies.net.sendNetworkPacket(packet, worldObj); + } - /* IStreamable */ - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeEnum(orientation, forgeDirections); - } + /* IStreamable */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeEnum(orientation, forgeDirections); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - orientation = data.readEnum(forgeDirections); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + orientation = data.readEnum(forgeDirections); + } - public void onRemoval() { - } + public void onRemoval() {} - public World getWorld() { - return worldObj; - } + public World getWorld() { + return worldObj; + } - /* ITriggerProvider */ - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getInternalTriggers(IStatementContainer container) { - return null; - } + /* ITriggerProvider */ + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getInternalTriggers(IStatementContainer container) { + return null; + } - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { - return null; - } + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { + return null; + } - // / REDSTONE INFO - protected boolean isRedstoneActivated() { - return worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord); - } + // / REDSTONE INFO + protected boolean isRedstoneActivated() { + return worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord); + } - // / ORIENTATION - public ForgeDirection getOrientation() { - return this.orientation; - } + // / ORIENTATION + public ForgeDirection getOrientation() { + return this.orientation; + } - public void setOrientation(ForgeDirection orientation) { - if (orientation == null) { - throw new NullPointerException("Orientation cannot be null"); - } - if (this.orientation == orientation) { - return; - } - this.orientation = orientation; - this.setNeedsNetworkUpdate(); - worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, worldObj.getBlock(xCoord, yCoord, zCoord)); - worldObj.func_147479_m(xCoord, yCoord, zCoord); - } + public void setOrientation(ForgeDirection orientation) { + if (orientation == null) { + throw new NullPointerException("Orientation cannot be null"); + } + if (this.orientation == orientation) { + return; + } + this.orientation = orientation; + this.setNeedsNetworkUpdate(); + worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, worldObj.getBlock(xCoord, yCoord, zCoord)); + worldObj.func_147479_m(xCoord, yCoord, zCoord); + } - protected final void setNeedsNetworkUpdate() { - needsNetworkUpdate = true; - } + protected final void setNeedsNetworkUpdate() { + needsNetworkUpdate = true; + } - @Override - public final IErrorLogic getErrorLogic() { - return errorHandler; - } + @Override + public final IErrorLogic getErrorLogic() { + return errorHandler; + } - @Override - public final IAccessHandler getAccessHandler() { - return accessHandler; - } + @Override + public final IAccessHandler getAccessHandler() { + return accessHandler; + } - @Override - public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { - if (oldAccess == EnumAccess.SHARED || newAccess == EnumAccess.SHARED) { - // pipes connected to this need to update - worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, blockType); - markDirty(); - } - } + @Override + public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { + if (oldAccess == EnumAccess.SHARED || newAccess == EnumAccess.SHARED) { + // pipes connected to this need to update + worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, blockType); + markDirty(); + } + } - /* NAME */ + /* NAME */ - /** - * Gets the tile's unlocalized name, based on the block at the location of this entity (client-only). - */ - @Override - public String getUnlocalizedTitle() { - String blockUnlocalizedName = getBlockType().getUnlocalizedName(); - return blockUnlocalizedName + '.' + getBlockMetadata() + ".name"; - } + /** + * Gets the tile's unlocalized name, based on the block at the location of this entity (client-only). + */ + @Override + public String getUnlocalizedTitle() { + String blockUnlocalizedName = getBlockType().getUnlocalizedName(); + return blockUnlocalizedName + '.' + getBlockMetadata() + ".name"; + } - /* INVENTORY BASICS */ - public IInventoryAdapter getInternalInventory() { - return inventory; - } + /* INVENTORY BASICS */ + public IInventoryAdapter getInternalInventory() { + return inventory; + } - protected final void setInternalInventory(IInventoryAdapter inv) { - if (inv == null) { - throw new NullPointerException("Inventory cannot be null"); - } - this.inventory = inv; - } + protected final void setInternalInventory(IInventoryAdapter inv) { + if (inv == null) { + throw new NullPointerException("Inventory cannot be null"); + } + this.inventory = inv; + } - /* ISidedInventory */ - @Override - public final int getSizeInventory() { - return getInternalInventory().getSizeInventory(); - } + /* ISidedInventory */ + @Override + public final int getSizeInventory() { + return getInternalInventory().getSizeInventory(); + } - @Override - public final ItemStack getStackInSlot(int slotIndex) { - return getInternalInventory().getStackInSlot(slotIndex); - } + @Override + public final ItemStack getStackInSlot(int slotIndex) { + return getInternalInventory().getStackInSlot(slotIndex); + } - @Override - public ItemStack decrStackSize(int slotIndex, int amount) { - return getInternalInventory().decrStackSize(slotIndex, amount); - } + @Override + public ItemStack decrStackSize(int slotIndex, int amount) { + return getInternalInventory().decrStackSize(slotIndex, amount); + } - @Override - public final ItemStack getStackInSlotOnClosing(int slotIndex) { - return getInternalInventory().getStackInSlotOnClosing(slotIndex); - } + @Override + public final ItemStack getStackInSlotOnClosing(int slotIndex) { + return getInternalInventory().getStackInSlotOnClosing(slotIndex); + } - @Override - public void setInventorySlotContents(int slotIndex, ItemStack itemstack) { - getInternalInventory().setInventorySlotContents(slotIndex, itemstack); - } + @Override + public void setInventorySlotContents(int slotIndex, ItemStack itemstack) { + getInternalInventory().setInventorySlotContents(slotIndex, itemstack); + } - @Override - public final int getInventoryStackLimit() { - return getInternalInventory().getInventoryStackLimit(); - } + @Override + public final int getInventoryStackLimit() { + return getInternalInventory().getInventoryStackLimit(); + } - @Override - public final void openInventory() { - getInternalInventory().openInventory(); - } + @Override + public final void openInventory() { + getInternalInventory().openInventory(); + } - @Override - public final void closeInventory() { - getInternalInventory().closeInventory(); - } + @Override + public final void closeInventory() { + getInternalInventory().closeInventory(); + } - @Override - public final String getInventoryName() { - return getUnlocalizedTitle(); - } + @Override + public final String getInventoryName() { + return getUnlocalizedTitle(); + } - @Override - public final boolean isUseableByPlayer(EntityPlayer player) { - return getInternalInventory().isUseableByPlayer(player); - } + @Override + public final boolean isUseableByPlayer(EntityPlayer player) { + return getInternalInventory().isUseableByPlayer(player); + } - @Override - public final boolean hasCustomInventoryName() { - return getInternalInventory().hasCustomInventoryName(); - } + @Override + public final boolean hasCustomInventoryName() { + return getInternalInventory().hasCustomInventoryName(); + } - @Override - public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { - return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); - } + @Override + public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { + return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); + } - @Override - public final boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return getInternalInventory().canSlotAccept(slotIndex, itemStack); - } + @Override + public final boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return getInternalInventory().canSlotAccept(slotIndex, itemStack); + } - @Override - public boolean isLocked(int slotIndex) { - return getInternalInventory().isLocked(slotIndex); - } + @Override + public boolean isLocked(int slotIndex) { + return getInternalInventory().isLocked(slotIndex); + } - @Override - public final int[] getAccessibleSlotsFromSide(int side) { - return getInternalInventory().getAccessibleSlotsFromSide(side); - } + @Override + public final int[] getAccessibleSlotsFromSide(int side) { + return getInternalInventory().getAccessibleSlotsFromSide(side); + } - @Override - public final boolean canInsertItem(int slotIndex, ItemStack itemStack, int side) { - return getInternalInventory().canInsertItem(slotIndex, itemStack, side); - } + @Override + public final boolean canInsertItem(int slotIndex, ItemStack itemStack, int side) { + return getInternalInventory().canInsertItem(slotIndex, itemStack, side); + } - @Override - public final boolean canExtractItem(int slotIndex, ItemStack itemStack, int side) { - return getInternalInventory().canExtractItem(slotIndex, itemStack, side); - } + @Override + public final boolean canExtractItem(int slotIndex, ItemStack itemStack, int side) { + return getInternalInventory().canExtractItem(slotIndex, itemStack, side); + } - public final ChunkCoordinates getCoordinates() { - return new ChunkCoordinates(xCoord, yCoord, zCoord); - } + public final ChunkCoordinates getCoordinates() { + return new ChunkCoordinates(xCoord, yCoord, zCoord); + } } diff --git a/src/main/java/forestry/core/tiles/TileMill.java b/src/main/java/forestry/core/tiles/TileMill.java index 7804885e2..1f914e949 100644 --- a/src/main/java/forestry/core/tiles/TileMill.java +++ b/src/main/java/forestry/core/tiles/TileMill.java @@ -10,90 +10,88 @@ ******************************************************************************/ package forestry.core.tiles; -import java.io.IOException; - import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; +import java.io.IOException; public abstract class TileMill extends TileBase { - protected float speed; - protected int stage = 0; - public int charge = 0; - public float progress; + protected float speed; + protected int stage = 0; + public int charge = 0; + public float progress; - protected TileMill(String hintKey) { - super(hintKey); - speed = 0.01F; - } + protected TileMill(String hintKey) { + super(hintKey); + speed = 0.01F; + } - @Override - public void updateClientSide() { - update(false); - } + @Override + public void updateClientSide() { + update(false); + } - @Override - public void updateServerSide() { - update(true); - } + @Override + public void updateServerSide() { + update(true); + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeInt(charge); - data.writeFloat(speed); - data.writeInt(stage); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeInt(charge); + data.writeFloat(speed); + data.writeInt(stage); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - charge = data.readInt(); - speed = data.readFloat(); - stage = data.readInt(); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + charge = data.readInt(); + speed = data.readFloat(); + stage = data.readInt(); + } - private void update(boolean isSimulating) { + private void update(boolean isSimulating) { - // Stop gracefully if discharged. - if (charge <= 0) { - if (stage > 0) { - progress += speed; - } - if (progress > 0.5) { - stage = 2; - } - if (progress > 1) { - progress = 0; - stage = 0; - } - return; - } + // Stop gracefully if discharged. + if (charge <= 0) { + if (stage > 0) { + progress += speed; + } + if (progress > 0.5) { + stage = 2; + } + if (progress > 1) { + progress = 0; + stage = 0; + } + return; + } - // Update blades - progress += speed; - if (stage <= 0) { - stage = 1; - } + // Update blades + progress += speed; + if (stage <= 0) { + stage = 1; + } - if (progress > 0.5 && stage == 1) { - stage = 2; - if (charge < 7 && isSimulating) { - charge++; - setNeedsNetworkUpdate(); - } - } - if (progress > 1) { - progress = 0; - stage = 0; + if (progress > 0.5 && stage == 1) { + stage = 2; + if (charge < 7 && isSimulating) { + charge++; + setNeedsNetworkUpdate(); + } + } + if (progress > 1) { + progress = 0; + stage = 0; - // Fully charged! Do something! - if (charge >= 7) { - activate(); - } - } + // Fully charged! Do something! + if (charge >= 7) { + activate(); + } + } + } - } - - protected abstract void activate(); + protected abstract void activate(); } diff --git a/src/main/java/forestry/core/tiles/TileNaturalistChest.java b/src/main/java/forestry/core/tiles/TileNaturalistChest.java index af0cca5e6..70f42859e 100644 --- a/src/main/java/forestry/core/tiles/TileNaturalistChest.java +++ b/src/main/java/forestry/core/tiles/TileNaturalistChest.java @@ -10,10 +10,6 @@ ******************************************************************************/ package forestry.core.tiles; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; - import forestry.api.genetics.ISpeciesRoot; import forestry.core.gui.ContainerNaturalistInventory; import forestry.core.gui.GuiHandler; @@ -22,98 +18,101 @@ import forestry.core.gui.IPagedInventory; import forestry.core.inventory.InventoryNaturalistChest; import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; public abstract class TileNaturalistChest extends TileBase implements IPagedInventory { - private static final float lidAngleVariationPerTick = 0.1F; + private static final float lidAngleVariationPerTick = 0.1F; - private final ISpeciesRoot speciesRoot; - public float lidAngle; - public float prevLidAngle; - private int numPlayersUsing; + private final ISpeciesRoot speciesRoot; + public float lidAngle; + public float prevLidAngle; + private int numPlayersUsing; - public TileNaturalistChest(ISpeciesRoot speciesRoot) { - super("naturalist.chest"); - this.speciesRoot = speciesRoot; - setInternalInventory(new InventoryNaturalistChest(this, speciesRoot)); - } + public TileNaturalistChest(ISpeciesRoot speciesRoot) { + super("naturalist.chest"); + this.speciesRoot = speciesRoot; + setInternalInventory(new InventoryNaturalistChest(this, speciesRoot)); + } - public void increaseNumPlayersUsing() { - numPlayersUsing++; - setNeedsNetworkUpdate(); - } + public void increaseNumPlayersUsing() { + numPlayersUsing++; + setNeedsNetworkUpdate(); + } - public void decreaseNumPlayersUsing() { - numPlayersUsing--; - if (numPlayersUsing < 0) { - numPlayersUsing = 0; - } - setNeedsNetworkUpdate(); - } + public void decreaseNumPlayersUsing() { + numPlayersUsing--; + if (numPlayersUsing < 0) { + numPlayersUsing = 0; + } + setNeedsNetworkUpdate(); + } - @Override - protected void updateClientSide() { - update(); - } - - @Override - protected void updateServerSide() { - update(); - } + @Override + protected void updateClientSide() { + update(); + } - private void update() { - prevLidAngle = lidAngle; + @Override + protected void updateServerSide() { + update(); + } - if (numPlayersUsing > 0 && lidAngle == 0.0F) { - playLidSound("random.chestopen"); - } + private void update() { + prevLidAngle = lidAngle; - if (numPlayersUsing == 0 && lidAngle > 0.0F || numPlayersUsing > 0 && lidAngle < 1.0F) { - float oldAngle = lidAngle; + if (numPlayersUsing > 0 && lidAngle == 0.0F) { + playLidSound("random.chestopen"); + } - if (numPlayersUsing > 0) { - lidAngle += lidAngleVariationPerTick; - } else { - lidAngle -= lidAngleVariationPerTick; - } + if (numPlayersUsing == 0 && lidAngle > 0.0F || numPlayersUsing > 0 && lidAngle < 1.0F) { + float oldAngle = lidAngle; - lidAngle = Math.max(Math.min(lidAngle, 1), 0); + if (numPlayersUsing > 0) { + lidAngle += lidAngleVariationPerTick; + } else { + lidAngle -= lidAngleVariationPerTick; + } - if (lidAngle < 0.5F && oldAngle >= 0.5F) { - playLidSound("random.chestclosed"); - } - } - } + lidAngle = Math.max(Math.min(lidAngle, 1), 0); - private void playLidSound(String sound) { - worldObj.playSoundEffect(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5, sound, 0.5F, worldObj.rand.nextFloat() * 0.1F + 0.9F); - } + if (lidAngle < 0.5F && oldAngle >= 0.5F) { + playLidSound("random.chestclosed"); + } + } + } - @Override - public void flipPage(EntityPlayer player, short page) { - GuiHandler.openGui(player, this, page); - } + private void playLidSound(String sound) { + worldObj.playSoundEffect( + xCoord + 0.5, yCoord + 0.5, zCoord + 0.5, sound, 0.5F, worldObj.rand.nextFloat() * 0.1F + 0.9F); + } - /* IStreamable */ - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeInt(numPlayersUsing); - } + @Override + public void flipPage(EntityPlayer player, short page) { + GuiHandler.openGui(player, this, page); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - numPlayersUsing = data.readInt(); - } + /* IStreamable */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeInt(numPlayersUsing); + } - @Override - public Object getGui(EntityPlayer player, int page) { - ContainerNaturalistInventory container = new ContainerNaturalistInventory(player.inventory, this, page); - return new GuiNaturalistInventory(speciesRoot, player, container, this, page, 5); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + numPlayersUsing = data.readInt(); + } - @Override - public Object getContainer(EntityPlayer player, int page) { - return new ContainerNaturalistInventory(player.inventory, this, page); - } + @Override + public Object getGui(EntityPlayer player, int page) { + ContainerNaturalistInventory container = new ContainerNaturalistInventory(player.inventory, this, page); + return new GuiNaturalistInventory(speciesRoot, player, container, this, page, 5); + } + + @Override + public Object getContainer(EntityPlayer player, int page) { + return new ContainerNaturalistInventory(player.inventory, this, page); + } } diff --git a/src/main/java/forestry/core/tiles/TilePowered.java b/src/main/java/forestry/core/tiles/TilePowered.java index 9d48bb4b0..eb8a7e8a9 100644 --- a/src/main/java/forestry/core/tiles/TilePowered.java +++ b/src/main/java/forestry/core/tiles/TilePowered.java @@ -10,14 +10,8 @@ ******************************************************************************/ package forestry.core.tiles; -import java.io.IOException; - -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.tiles.IHasWork; import cpw.mods.fml.common.Optional; - import forestry.api.core.IErrorLogic; import forestry.core.circuits.ISpeedUpgradable; import forestry.core.config.Config; @@ -27,198 +21,201 @@ import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamableGui; import forestry.core.render.TankRenderInfo; import forestry.energy.EnergyManager; - -import buildcraft.api.tiles.IHasWork; +import java.io.IOException; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; @Optional.Interface(iface = "buildcraft.api.tiles.IHasWork", modid = "BuildCraftAPI|tiles") -public abstract class TilePowered extends TileBase implements IRenderableTile, IPowerHandler, IHasWork, ISpeedUpgradable, IStreamableGui { - private static final int WORK_TICK_INTERVAL = 5; // one Forestry work tick happens every WORK_TICK_INTERVAL game ticks +public abstract class TilePowered extends TileBase + implements IRenderableTile, IPowerHandler, IHasWork, ISpeedUpgradable, IStreamableGui { + private static final int WORK_TICK_INTERVAL = + 5; // one Forestry work tick happens every WORK_TICK_INTERVAL game ticks - private final EnergyManager energyManager; + private final EnergyManager energyManager; - private int workCounter; - private int ticksPerWorkCycle; - private int energyPerWorkCycle; + private int workCounter; + private int ticksPerWorkCycle; + private int energyPerWorkCycle; - protected float speedMultiplier = 1.0f; - protected float powerMultiplier = 1.0f; + protected float speedMultiplier = 1.0f; + protected float powerMultiplier = 1.0f; - // the number of work ticks that this tile has had no power - private int noPowerTime = 0; + // the number of work ticks that this tile has had no power + private int noPowerTime = 0; - protected TilePowered(String hintKey, int maxTransfer, int capacity) { - super(hintKey); - this.energyManager = new EnergyManager(maxTransfer, capacity); - this.energyManager.setReceiveOnly(); + protected TilePowered(String hintKey, int maxTransfer, int capacity) { + super(hintKey); + this.energyManager = new EnergyManager(maxTransfer, capacity); + this.energyManager.setReceiveOnly(); - this.ticksPerWorkCycle = 4; + this.ticksPerWorkCycle = 4; - hints.addAll(Config.hints.get("powered.machine")); - } + hints.addAll(Config.hints.get("powered.machine")); + } - public int getWorkCounter() { - return workCounter; - } + public int getWorkCounter() { + return workCounter; + } - public void setTicksPerWorkCycle(int ticksPerWorkCycle) { - this.ticksPerWorkCycle = ticksPerWorkCycle; - this.workCounter = 0; - } + public void setTicksPerWorkCycle(int ticksPerWorkCycle) { + this.ticksPerWorkCycle = ticksPerWorkCycle; + this.workCounter = 0; + } - public int getTicksPerWorkCycle() { - if (worldObj.isRemote) { - return ticksPerWorkCycle; - } - return Math.round(ticksPerWorkCycle / speedMultiplier); - } + public int getTicksPerWorkCycle() { + if (worldObj.isRemote) { + return ticksPerWorkCycle; + } + return Math.round(ticksPerWorkCycle / speedMultiplier); + } - public void setEnergyPerWorkCycle(int energyPerWorkCycle) { - this.energyPerWorkCycle = EnergyManager.scaleForDifficulty(energyPerWorkCycle); - } + public void setEnergyPerWorkCycle(int energyPerWorkCycle) { + this.energyPerWorkCycle = EnergyManager.scaleForDifficulty(energyPerWorkCycle); + } - public int getEnergyPerWorkCycle() { - return Math.round(energyPerWorkCycle * powerMultiplier); - } + public int getEnergyPerWorkCycle() { + return Math.round(energyPerWorkCycle * powerMultiplier); + } - /* STATE INFORMATION */ - public boolean hasResourcesMin(float percentage) { - return false; - } + /* STATE INFORMATION */ + public boolean hasResourcesMin(float percentage) { + return false; + } - public boolean hasFuelMin(float percentage) { - return false; - } + public boolean hasFuelMin(float percentage) { + return false; + } - public abstract boolean hasWork(); + public abstract boolean hasWork(); - @Override - protected void updateServerSide() { - super.updateServerSide(); + @Override + protected void updateServerSide() { + super.updateServerSide(); - if (!updateOnInterval(WORK_TICK_INTERVAL)) { - return; - } + if (!updateOnInterval(WORK_TICK_INTERVAL)) { + return; + } - IErrorLogic errorLogic = getErrorLogic(); + IErrorLogic errorLogic = getErrorLogic(); - boolean disabled = isRedstoneActivated(); - errorLogic.setCondition(disabled, EnumErrorCode.DISABLED_BY_REDSTONE); - if (disabled) { - return; - } + boolean disabled = isRedstoneActivated(); + errorLogic.setCondition(disabled, EnumErrorCode.DISABLED_BY_REDSTONE); + if (disabled) { + return; + } - if (!hasWork()) { - return; - } + if (!hasWork()) { + return; + } - int ticksPerWorkCycle = getTicksPerWorkCycle(); + int ticksPerWorkCycle = getTicksPerWorkCycle(); - if (workCounter < ticksPerWorkCycle) { - int energyPerWorkCycle = getEnergyPerWorkCycle(); - boolean consumedEnergy = energyManager.consumeEnergyToDoWork(ticksPerWorkCycle, energyPerWorkCycle); - if (consumedEnergy) { - errorLogic.setCondition(false, EnumErrorCode.NO_POWER); - workCounter++; - noPowerTime = 0; - } else { - noPowerTime++; - if (noPowerTime > 4) { - errorLogic.setCondition(true, EnumErrorCode.NO_POWER); - } - } - } + if (workCounter < ticksPerWorkCycle) { + int energyPerWorkCycle = getEnergyPerWorkCycle(); + boolean consumedEnergy = energyManager.consumeEnergyToDoWork(ticksPerWorkCycle, energyPerWorkCycle); + if (consumedEnergy) { + errorLogic.setCondition(false, EnumErrorCode.NO_POWER); + workCounter++; + noPowerTime = 0; + } else { + noPowerTime++; + if (noPowerTime > 4) { + errorLogic.setCondition(true, EnumErrorCode.NO_POWER); + } + } + } - if (workCounter >= ticksPerWorkCycle) { - if (workCycle()) { - workCounter = 0; - } - } - } + if (workCounter >= ticksPerWorkCycle) { + if (workCycle()) { + workCounter = 0; + } + } + } - protected abstract boolean workCycle(); + protected abstract boolean workCycle(); - public int getProgressScaled(int i) { - int ticksPerWorkCycle = getTicksPerWorkCycle(); - if (ticksPerWorkCycle == 0) { - return 0; - } + public int getProgressScaled(int i) { + int ticksPerWorkCycle = getTicksPerWorkCycle(); + if (ticksPerWorkCycle == 0) { + return 0; + } - return (workCounter * i) / ticksPerWorkCycle; - } + return (workCounter * i) / ticksPerWorkCycle; + } - @Override - public void writeToNBT(NBTTagCompound nbt) { - super.writeToNBT(nbt); - energyManager.writeToNBT(nbt); - } + @Override + public void writeToNBT(NBTTagCompound nbt) { + super.writeToNBT(nbt); + energyManager.writeToNBT(nbt); + } - @Override - public void readFromNBT(NBTTagCompound nbt) { - super.readFromNBT(nbt); - energyManager.readFromNBT(nbt); - } + @Override + public void readFromNBT(NBTTagCompound nbt) { + super.readFromNBT(nbt); + energyManager.readFromNBT(nbt); + } - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - energyManager.writeData(data); - data.writeVarInt(workCounter); - data.writeVarInt(getTicksPerWorkCycle()); - } + @Override + public void writeGuiData(DataOutputStreamForestry data) throws IOException { + energyManager.writeData(data); + data.writeVarInt(workCounter); + data.writeVarInt(getTicksPerWorkCycle()); + } - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - energyManager.readData(data); - workCounter = data.readVarInt(); - ticksPerWorkCycle = data.readVarInt(); - } + @Override + public void readGuiData(DataInputStreamForestry data) throws IOException { + energyManager.readData(data); + workCounter = data.readVarInt(); + ticksPerWorkCycle = data.readVarInt(); + } - /* ISpeedUpgradable */ - @Override - public void applySpeedUpgrade(double speedChange, double powerChange) { - speedMultiplier += speedChange; - powerMultiplier += powerChange; - workCounter = 0; - } + /* ISpeedUpgradable */ + @Override + public void applySpeedUpgrade(double speedChange, double powerChange) { + speedMultiplier += speedChange; + powerMultiplier += powerChange; + workCounter = 0; + } - /* IRenderableTile */ - @Override - public TankRenderInfo getResourceTankInfo() { - return TankRenderInfo.EMPTY; - } + /* IRenderableTile */ + @Override + public TankRenderInfo getResourceTankInfo() { + return TankRenderInfo.EMPTY; + } - @Override - public TankRenderInfo getProductTankInfo() { - return TankRenderInfo.EMPTY; - } + @Override + public TankRenderInfo getProductTankInfo() { + return TankRenderInfo.EMPTY; + } - /* IPowerHandler */ - @Override - public EnergyManager getEnergyManager() { - return energyManager; - } + /* IPowerHandler */ + @Override + public EnergyManager getEnergyManager() { + return energyManager; + } - @Override - public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { - return energyManager.receiveEnergy(from, maxReceive, simulate); - } + @Override + public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + return energyManager.receiveEnergy(from, maxReceive, simulate); + } - @Override - public int extractEnergy(ForgeDirection from, int maxReceive, boolean simulate) { - return energyManager.extractEnergy(from, maxReceive, simulate); - } + @Override + public int extractEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + return energyManager.extractEnergy(from, maxReceive, simulate); + } - @Override - public int getEnergyStored(ForgeDirection from) { - return energyManager.getEnergyStored(from); - } + @Override + public int getEnergyStored(ForgeDirection from) { + return energyManager.getEnergyStored(from); + } - @Override - public int getMaxEnergyStored(ForgeDirection from) { - return energyManager.getMaxEnergyStored(from); - } + @Override + public int getMaxEnergyStored(ForgeDirection from) { + return energyManager.getMaxEnergyStored(from); + } - @Override - public boolean canConnectEnergy(ForgeDirection from) { - return energyManager.canConnectEnergy(from); - } + @Override + public boolean canConnectEnergy(ForgeDirection from) { + return energyManager.canConnectEnergy(from); + } } diff --git a/src/main/java/forestry/core/tiles/TileUtil.java b/src/main/java/forestry/core/tiles/TileUtil.java index feb9469bf..e031c948a 100644 --- a/src/main/java/forestry/core/tiles/TileUtil.java +++ b/src/main/java/forestry/core/tiles/TileUtil.java @@ -10,59 +10,56 @@ ******************************************************************************/ package forestry.core.tiles; +import forestry.core.inventory.wrappers.ChestWrapper; +import forestry.core.utils.InventoryUtil; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.common.util.ForgeDirection; -import forestry.core.inventory.wrappers.ChestWrapper; -import forestry.core.utils.InventoryUtil; - public abstract class TileUtil { - public static boolean isUsableByPlayer(EntityPlayer player, TileEntity tile) { - if (tile == null) { - return false; - } - int x = tile.xCoord; - int y = tile.yCoord; - int z = tile.zCoord; - World world = tile.getWorldObj(); - - if (tile.isInvalid()) { - return false; - } - - if (world.getTileEntity(x, y, z) != tile) { - return false; - } + public static boolean isUsableByPlayer(EntityPlayer player, TileEntity tile) { + if (tile == null) { + return false; + } + int x = tile.xCoord; + int y = tile.yCoord; + int z = tile.zCoord; + World world = tile.getWorldObj(); - return player.getDistanceSq(x + 0.5D, y + 0.5D, z + 0.5D) <= 64.0D; + if (tile.isInvalid()) { + return false; + } - } + if (world.getTileEntity(x, y, z) != tile) { + return false; + } - public static T getTile(IBlockAccess world, int x, int y, int z, Class tileClass) { - TileEntity tileEntity = world.getTileEntity(x, y, z); - if (tileClass.isInstance(tileEntity)) { - return tileClass.cast(tileEntity); - } else { - return null; - } - } + return player.getDistanceSq(x + 0.5D, y + 0.5D, z + 0.5D) <= 64.0D; + } - public static IInventory getInventoryFromTile(TileEntity tile, ForgeDirection side) { - if (!(tile instanceof IInventory)) { - return null; - } + public static T getTile(IBlockAccess world, int x, int y, int z, Class tileClass) { + TileEntity tileEntity = world.getTileEntity(x, y, z); + if (tileClass.isInstance(tileEntity)) { + return tileClass.cast(tileEntity); + } else { + return null; + } + } - if (tile instanceof TileEntityChest) { - TileEntityChest chest = (TileEntityChest) tile; - return new ChestWrapper(chest); - } - return InventoryUtil.getInventory((IInventory) tile, side); - } + public static IInventory getInventoryFromTile(TileEntity tile, ForgeDirection side) { + if (!(tile instanceof IInventory)) { + return null; + } + + if (tile instanceof TileEntityChest) { + TileEntityChest chest = (TileEntityChest) tile; + return new ChestWrapper(chest); + } + return InventoryUtil.getInventory((IInventory) tile, side); + } } diff --git a/src/main/java/forestry/core/triggers/Trigger.java b/src/main/java/forestry/core/triggers/Trigger.java index 0f559496c..4894464df 100755 --- a/src/main/java/forestry/core/triggers/Trigger.java +++ b/src/main/java/forestry/core/triggers/Trigger.java @@ -10,77 +10,74 @@ ******************************************************************************/ package forestry.core.triggers; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.util.IIcon; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.render.TextureManager; -import forestry.core.utils.StringUtil; - import buildcraft.api.statements.IStatement; import buildcraft.api.statements.IStatementParameter; import buildcraft.api.statements.ITriggerExternal; import buildcraft.api.statements.StatementManager; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.render.TextureManager; +import forestry.core.utils.StringUtil; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.util.IIcon; public abstract class Trigger implements ITriggerExternal { - private final String uid; - private final String unlocalized; + private final String uid; + private final String unlocalized; - protected Trigger(String uid) { - this(uid, uid); - } + protected Trigger(String uid) { + this(uid, uid); + } - protected Trigger(String uid, String localization) { - this.uid = "forestry:" + uid; - unlocalized = "trigger." + localization; - StatementManager.registerStatement(this); - } + protected Trigger(String uid, String localization) { + this.uid = "forestry:" + uid; + unlocalized = "trigger." + localization; + StatementManager.registerStatement(this); + } - @Override - public String getUniqueTag() { - return uid; - } + @Override + public String getUniqueTag() { + return uid; + } - @Override - public String getDescription() { - return StringUtil.localize(unlocalized); - } + @Override + public String getDescription() { + return StringUtil.localize(unlocalized); + } - @Override - public IStatementParameter createParameter(int index) { - return null; - } + @Override + public IStatementParameter createParameter(int index) { + return null; + } - @Override - public int maxParameters() { - return 0; - } + @Override + public int maxParameters() { + return 0; + } - @Override - public int minParameters() { - return 0; - } + @Override + public int minParameters() { + return 0; + } - @SideOnly(Side.CLIENT) - private IIcon icon; + @SideOnly(Side.CLIENT) + private IIcon icon; - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return icon; - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return icon; + } - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IIconRegister register) { - icon = TextureManager.registerTex(register, "triggers/" + unlocalized.replace("trigger.", "")); - } + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IIconRegister register) { + icon = TextureManager.registerTex(register, "triggers/" + unlocalized.replace("trigger.", "")); + } - @Override - public IStatement rotateLeft() { - return this; - } + @Override + public IStatement rotateLeft() { + return this; + } } diff --git a/src/main/java/forestry/core/utils/BlockUtil.java b/src/main/java/forestry/core/utils/BlockUtil.java index 932baa184..909a0e611 100644 --- a/src/main/java/forestry/core/utils/BlockUtil.java +++ b/src/main/java/forestry/core/utils/BlockUtil.java @@ -16,6 +16,8 @@ import cpw.mods.fml.common.Loader; import forestry.core.config.Constants; import forestry.core.tiles.TileEngine; import forestry.core.utils.vect.Vect; +import java.util.ArrayList; +import java.util.function.Predicate; import net.minecraft.block.Block; import net.minecraft.block.BlockCocoa; import net.minecraft.block.BlockLog; @@ -29,235 +31,249 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.oredict.OreDictionary; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.function.Predicate; - public abstract class BlockUtil { - private static final int slabWoodId = OreDictionary.getOreID("slabWood"); + private static final int slabWoodId = OreDictionary.getOreID("slabWood"); - public static ArrayList getBlockDrops(World world, Vect posBlock) { - Block block = world.getBlock(posBlock.x, posBlock.y, posBlock.z); - int meta = world.getBlockMetadata(posBlock.x, posBlock.y, posBlock.z); + public static ArrayList getBlockDrops(World world, Vect posBlock) { + Block block = world.getBlock(posBlock.x, posBlock.y, posBlock.z); + int meta = world.getBlockMetadata(posBlock.x, posBlock.y, posBlock.z); - return block.getDrops(world, posBlock.x, posBlock.y, posBlock.z, meta, 0); + return block.getDrops(world, posBlock.x, posBlock.y, posBlock.z, meta, 0); + } - } + public static boolean isEnergyReceiverOrEngine(ForgeDirection side, TileEntity tile) { + if (!(tile instanceof IEnergyReceiver) && !(tile instanceof TileEngine)) { + return false; + } - public static boolean isEnergyReceiverOrEngine(ForgeDirection side, TileEntity tile) { - if (!(tile instanceof IEnergyReceiver) && !(tile instanceof TileEngine)) { - return false; - } + IEnergyConnection receptor = (IEnergyConnection) tile; + return receptor.canConnectEnergy(side); + } - IEnergyConnection receptor = (IEnergyConnection) tile; - return receptor.canConnectEnergy(side); - } + public static boolean tryPlantPot(World world, int x, int y, int z, Block block) { - public static boolean tryPlantPot(World world, int x, int y, int z, Block block) { + int direction = getDirectionalMetadata(world, x, y, z); + if (direction < 0) { + return false; + } - int direction = getDirectionalMetadata(world, x, y, z); - if (direction < 0) { - return false; - } + world.setBlock(x, y, z, block, direction, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); + return true; + } - world.setBlock(x, y, z, block, direction, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); - return true; - } + public static int getDirectionalMetadata(World world, int x, int y, int z) { + for (int i = 0; i < 4; i++) { + if (!isValidPot(world, x, y, z, i)) { + continue; + } + return i; + } + return -1; + } - public static int getDirectionalMetadata(World world, int x, int y, int z) { - for (int i = 0; i < 4; i++) { - if (!isValidPot(world, x, y, z, i)) { - continue; - } - return i; - } - return -1; - } + public static boolean isValidPot(World world, int x, int y, int z, int notchDirection) { + x += Direction.offsetX[notchDirection]; + z += Direction.offsetZ[notchDirection]; + Block block = world.getBlock(x, y, z); + if (block == Blocks.log) { + return BlockLog.func_150165_c(world.getBlockMetadata(x, y, z)) == 3; + } else { + return block.isWood(world, x, y, z); + } + } - public static boolean isValidPot(World world, int x, int y, int z, int notchDirection) { - x += Direction.offsetX[notchDirection]; - z += Direction.offsetZ[notchDirection]; - Block block = world.getBlock(x, y, z); - if (block == Blocks.log) { - return BlockLog.func_150165_c(world.getBlockMetadata(x, y, z)) == 3; - } else { - return block.isWood(world, x, y, z); - } - } + public static int getMaturityPod(int metadata) { + return BlockCocoa.func_149987_c(metadata); + } - public static int getMaturityPod(int metadata) { - return BlockCocoa.func_149987_c(metadata); - } + public static boolean isWoodSlabBlock(Block block) { + int[] oreIds = OreDictionary.getOreIDs(new ItemStack(block)); + for (int oreId : oreIds) { + if (oreId == slabWoodId) { + return true; + } + } - public static boolean isWoodSlabBlock(Block block) { - int[] oreIds = OreDictionary.getOreIDs(new ItemStack(block)); - for (int oreId : oreIds) { - if (oreId == slabWoodId) { - return true; - } - } + return false; + } - return false; - } + public static boolean isReplaceableBlock(World world, int x, int y, int z) { + Block block = world.getBlock(x, y, z); - public static boolean isReplaceableBlock(World world, int x, int y, int z) { - Block block = world.getBlock(x, y, z); + return isReplaceableBlock(block); + } - return isReplaceableBlock(block); - } + public static boolean isReplaceableBlock(Block block) { + return block == Blocks.vine + || block == Blocks.tallgrass + || block == Blocks.deadbush + || block == Blocks.snow_layer + || block.getMaterial().isReplaceable(); + } - public static boolean isReplaceableBlock(Block block) { - return block == Blocks.vine || block == Blocks.tallgrass || block == Blocks.deadbush || block == Blocks.snow_layer - || block.getMaterial().isReplaceable(); - } + /** + * Ray traces through the blocks collision from start vector to end vector returning a ray trace hit. + */ + public static MovingObjectPosition collisionRayTrace( + World world, + int x, + int y, + int z, + Vec3 startVec, + Vec3 endVec, + float minX, + float minY, + float minZ, + float maxX, + float maxY, + float maxZ) { + startVec = startVec.addVector((double) (-x), (double) (-y), (double) (-z)); + endVec = endVec.addVector((double) (-x), (double) (-y), (double) (-z)); + Vec3 vec32 = startVec.getIntermediateWithXValue(endVec, minX); + Vec3 vec33 = startVec.getIntermediateWithXValue(endVec, maxX); + Vec3 vec34 = startVec.getIntermediateWithYValue(endVec, minY); + Vec3 vec35 = startVec.getIntermediateWithYValue(endVec, maxY); + Vec3 vec36 = startVec.getIntermediateWithZValue(endVec, minZ); + Vec3 vec37 = startVec.getIntermediateWithZValue(endVec, maxZ); - /** - * Ray traces through the blocks collision from start vector to end vector returning a ray trace hit. - */ - public static MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 startVec, Vec3 endVec, float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { - startVec = startVec.addVector((double) (-x), (double) (-y), (double) (-z)); - endVec = endVec.addVector((double) (-x), (double) (-y), (double) (-z)); - Vec3 vec32 = startVec.getIntermediateWithXValue(endVec, minX); - Vec3 vec33 = startVec.getIntermediateWithXValue(endVec, maxX); - Vec3 vec34 = startVec.getIntermediateWithYValue(endVec, minY); - Vec3 vec35 = startVec.getIntermediateWithYValue(endVec, maxY); - Vec3 vec36 = startVec.getIntermediateWithZValue(endVec, minZ); - Vec3 vec37 = startVec.getIntermediateWithZValue(endVec, maxZ); + if (!isVecInsideYZBounds(vec32, minY, minZ, maxY, maxZ)) { + vec32 = null; + } - if (!isVecInsideYZBounds(vec32, minY, minZ, maxY, maxZ)) { - vec32 = null; - } + if (!isVecInsideYZBounds(vec33, minY, minZ, maxY, maxZ)) { + vec33 = null; + } - if (!isVecInsideYZBounds(vec33, minY, minZ, maxY, maxZ)) { - vec33 = null; - } + if (!isVecInsideXZBounds(vec34, minX, minZ, maxX, maxZ)) { + vec34 = null; + } - if (!isVecInsideXZBounds(vec34, minX, minZ, maxX, maxZ)) { - vec34 = null; - } + if (!isVecInsideXZBounds(vec35, minX, minZ, maxX, maxZ)) { + vec35 = null; + } - if (!isVecInsideXZBounds(vec35, minX, minZ, maxX, maxZ)) { - vec35 = null; - } + if (!isVecInsideXYBounds(vec36, minX, minY, maxX, maxY)) { + vec36 = null; + } - if (!isVecInsideXYBounds(vec36, minX, minY, maxX, maxY)) { - vec36 = null; - } + if (!isVecInsideXYBounds(vec37, minX, minY, maxX, maxY)) { + vec37 = null; + } - if (!isVecInsideXYBounds(vec37, minX, minY, maxX, maxY)) { - vec37 = null; - } + Vec3 minHit = null; - Vec3 minHit = null; + if (vec32 != null && (minHit == null || startVec.squareDistanceTo(vec32) < startVec.squareDistanceTo(minHit))) { + minHit = vec32; + } - if (vec32 != null && (minHit == null || startVec.squareDistanceTo(vec32) < startVec.squareDistanceTo(minHit))) { - minHit = vec32; - } + if (vec33 != null && (minHit == null || startVec.squareDistanceTo(vec33) < startVec.squareDistanceTo(minHit))) { + minHit = vec33; + } - if (vec33 != null && (minHit == null || startVec.squareDistanceTo(vec33) < startVec.squareDistanceTo(minHit))) { - minHit = vec33; - } + if (vec34 != null && (minHit == null || startVec.squareDistanceTo(vec34) < startVec.squareDistanceTo(minHit))) { + minHit = vec34; + } - if (vec34 != null && (minHit == null || startVec.squareDistanceTo(vec34) < startVec.squareDistanceTo(minHit))) { - minHit = vec34; - } + if (vec35 != null && (minHit == null || startVec.squareDistanceTo(vec35) < startVec.squareDistanceTo(minHit))) { + minHit = vec35; + } - if (vec35 != null && (minHit == null || startVec.squareDistanceTo(vec35) < startVec.squareDistanceTo(minHit))) { - minHit = vec35; - } + if (vec36 != null && (minHit == null || startVec.squareDistanceTo(vec36) < startVec.squareDistanceTo(minHit))) { + minHit = vec36; + } - if (vec36 != null && (minHit == null || startVec.squareDistanceTo(vec36) < startVec.squareDistanceTo(minHit))) { - minHit = vec36; - } + if (vec37 != null && (minHit == null || startVec.squareDistanceTo(vec37) < startVec.squareDistanceTo(minHit))) { + minHit = vec37; + } - if (vec37 != null && (minHit == null || startVec.squareDistanceTo(vec37) < startVec.squareDistanceTo(minHit))) { - minHit = vec37; - } + if (minHit == null) { + return null; + } else { + byte sideHit = -1; - if (minHit == null) { - return null; - } else { - byte sideHit = -1; + if (minHit == vec32) { + sideHit = 4; + } - if (minHit == vec32) { - sideHit = 4; - } + if (minHit == vec33) { + sideHit = 5; + } - if (minHit == vec33) { - sideHit = 5; - } + if (minHit == vec34) { + sideHit = 0; + } - if (minHit == vec34) { - sideHit = 0; - } + if (minHit == vec35) { + sideHit = 1; + } - if (minHit == vec35) { - sideHit = 1; - } + if (minHit == vec36) { + sideHit = 2; + } - if (minHit == vec36) { - sideHit = 2; - } + if (minHit == vec37) { + sideHit = 3; + } - if (minHit == vec37) { - sideHit = 3; - } + return new MovingObjectPosition(x, y, z, sideHit, minHit.addVector((double) x, (double) y, (double) z)); + } + } - return new MovingObjectPosition(x, y, z, sideHit, minHit.addVector((double) x, (double) y, (double) z)); - } - } + /** + * Checks if a vector is within the Y and Z bounds of the block. + */ + private static boolean isVecInsideYZBounds(Vec3 vec, float minY, float minZ, float maxY, float maxZ) { + return vec != null && (vec.yCoord >= minY && vec.yCoord <= maxY && vec.zCoord >= minZ && vec.zCoord <= maxZ); + } - /** - * Checks if a vector is within the Y and Z bounds of the block. - */ - private static boolean isVecInsideYZBounds(Vec3 vec, float minY, float minZ, float maxY, float maxZ) { - return vec != null && (vec.yCoord >= minY && vec.yCoord <= maxY && vec.zCoord >= minZ && vec.zCoord <= maxZ); - } + /** + * Checks if a vector is within the X and Z bounds of the block. + */ + private static boolean isVecInsideXZBounds(Vec3 vec, float minX, float minZ, float maxX, float maxZ) { + return vec != null && (vec.xCoord >= minX && vec.xCoord <= maxX && vec.zCoord >= minZ && vec.zCoord <= maxZ); + } - /** - * Checks if a vector is within the X and Z bounds of the block. - */ - private static boolean isVecInsideXZBounds(Vec3 vec, float minX, float minZ, float maxX, float maxZ) { - return vec != null && (vec.xCoord >= minX && vec.xCoord <= maxX && vec.zCoord >= minZ && vec.zCoord <= maxZ); - } + /** + * Checks if a vector is within the X and Y bounds of the block. + */ + private static boolean isVecInsideXYBounds(Vec3 vec, float minX, float minY, float maxX, float maxY) { + return vec != null && (vec.xCoord >= minX && vec.xCoord <= maxX && vec.yCoord >= minY && vec.yCoord <= maxY); + } - /** - * Checks if a vector is within the X and Y bounds of the block. - */ - private static boolean isVecInsideXYBounds(Vec3 vec, float minX, float minY, float maxX, float maxY) { - return vec != null && (vec.xCoord >= minX && vec.xCoord <= maxX && vec.yCoord >= minY && vec.yCoord <= maxY); - } + private static Class BW_MetaGenerated_WerkstoffBlocksClass; + private static Block BWBlocks; + private static boolean bw = Loader.isModLoaded("bartworks"); - private static Class BW_MetaGenerated_WerkstoffBlocksClass; - private static Block BWBlocks; - private static boolean bw = Loader.isModLoaded("bartworks"); - static { - if (bw) - try { - BW_MetaGenerated_WerkstoffBlocksClass = (Class) Class.forName("com.github.bartimaeusnek.bartworks.system.material.BW_MetaGenerated_WerkstoffBlocks"); - BWBlocks = (Block) Class.forName("com.github.bartimaeusnek.bartworks.system.material.WerkstoffLoader").getField("BWBlocks").get(null); - } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) { - e.printStackTrace(); - } - } + static { + if (bw) + try { + BW_MetaGenerated_WerkstoffBlocksClass = (Class) Class.forName( + "com.github.bartimaeusnek.bartworks.system.material.BW_MetaGenerated_WerkstoffBlocks"); + BWBlocks = (Block) Class.forName("com.github.bartimaeusnek.bartworks.system.material.WerkstoffLoader") + .getField("BWBlocks") + .get(null); + } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + } - public static ItemStack getItemStackFromBlockBelow(World world, int x, int y, int z, Predicate stillInside) { - TileEntity tile; - Block block; - int depth = 0; + public static ItemStack getItemStackFromBlockBelow( + World world, int x, int y, int z, Predicate stillInside) { + TileEntity tile; + Block block; + int depth = 0; - do { - ++depth; - tile = world.getTileEntity(x, y - depth, z); - } while (stillInside.test(tile)); - block = world.getBlock(x, y - depth, z); + do { + ++depth; + tile = world.getTileEntity(x, y - depth, z); + } while (stillInside.test(tile)); + block = world.getBlock(x, y - depth, z); - if (bw && BW_MetaGenerated_WerkstoffBlocksClass.isInstance(block)) { - return new ItemStack(BWBlocks, 1, block.getDamageValue(world, x, y - depth, z)); - } + if (bw && BW_MetaGenerated_WerkstoffBlocksClass.isInstance(block)) { + return new ItemStack(BWBlocks, 1, block.getDamageValue(world, x, y - depth, z)); + } - return new ItemStack(block, 1, world.getBlockMetadata(x, y - depth, z)); - } -} \ No newline at end of file + return new ItemStack(block, 1, world.getBlockMetadata(x, y - depth, z)); + } +} diff --git a/src/main/java/forestry/core/utils/ClimateUtil.java b/src/main/java/forestry/core/utils/ClimateUtil.java index 946ea3fe7..6af399c60 100644 --- a/src/main/java/forestry/core/utils/ClimateUtil.java +++ b/src/main/java/forestry/core/utils/ClimateUtil.java @@ -10,190 +10,190 @@ ******************************************************************************/ package forestry.core.utils; -import java.util.ArrayList; -import java.util.Locale; - import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; import forestry.api.genetics.EnumTolerance; import forestry.api.genetics.IClimateHelper; +import java.util.ArrayList; +import java.util.Locale; public class ClimateUtil implements IClimateHelper { - public boolean isWithinLimits(EnumTemperature temperature, EnumHumidity humidity, - EnumTemperature baseTemp, EnumTolerance tolTemp, - EnumHumidity baseHumid, EnumTolerance tolHumid) { - if (!getToleratedTemperature(baseTemp, tolTemp).contains(temperature)) { - return false; - } - - return getToleratedHumidity(baseHumid, tolHumid).contains(humidity); - } + public boolean isWithinLimits( + EnumTemperature temperature, + EnumHumidity humidity, + EnumTemperature baseTemp, + EnumTolerance tolTemp, + EnumHumidity baseHumid, + EnumTolerance tolHumid) { + if (!getToleratedTemperature(baseTemp, tolTemp).contains(temperature)) { + return false; + } - public boolean isWithinLimits(EnumTemperature temperature, EnumTemperature baseTemp, EnumTolerance tolTemp) { - return getToleratedTemperature(baseTemp, tolTemp).contains(temperature); - } + return getToleratedHumidity(baseHumid, tolHumid).contains(humidity); + } - public boolean isWithinLimits(EnumHumidity humidity, EnumHumidity baseHumid, EnumTolerance tolHumid) { - return getToleratedHumidity(baseHumid, tolHumid).contains(humidity); - } - - public ArrayList getToleratedHumidity(EnumHumidity prefered, EnumTolerance tolerance) { + public boolean isWithinLimits(EnumTemperature temperature, EnumTemperature baseTemp, EnumTolerance tolTemp) { + return getToleratedTemperature(baseTemp, tolTemp).contains(temperature); + } - ArrayList tolerated = new ArrayList<>(); - tolerated.add(prefered); + public boolean isWithinLimits(EnumHumidity humidity, EnumHumidity baseHumid, EnumTolerance tolHumid) { + return getToleratedHumidity(baseHumid, tolHumid).contains(humidity); + } - switch (tolerance) { + public ArrayList getToleratedHumidity(EnumHumidity prefered, EnumTolerance tolerance) { - case BOTH_5: - case BOTH_4: - case BOTH_3: - case BOTH_2: - if (prefered.ordinal() + 2 < EnumHumidity.values().length) { - tolerated.add(EnumHumidity.values()[prefered.ordinal() + 2]); - } - if (prefered.ordinal() - 2 >= 0) { - tolerated.add(EnumHumidity.values()[prefered.ordinal() - 2]); - } - case BOTH_1: - if (prefered.ordinal() + 1 < EnumHumidity.values().length) { - tolerated.add(EnumHumidity.values()[prefered.ordinal() + 1]); - } - if (prefered.ordinal() - 1 >= 0) { - tolerated.add(EnumHumidity.values()[prefered.ordinal() - 1]); - } - return tolerated; + ArrayList tolerated = new ArrayList<>(); + tolerated.add(prefered); - case UP_5: - case UP_4: - case UP_3: - case UP_2: - if (prefered.ordinal() + 2 < EnumHumidity.values().length) { - tolerated.add(EnumHumidity.values()[prefered.ordinal() + 2]); - } - case UP_1: - if (prefered.ordinal() + 1 < EnumHumidity.values().length) { - tolerated.add(EnumHumidity.values()[prefered.ordinal() + 1]); - } - return tolerated; + switch (tolerance) { + case BOTH_5: + case BOTH_4: + case BOTH_3: + case BOTH_2: + if (prefered.ordinal() + 2 < EnumHumidity.values().length) { + tolerated.add(EnumHumidity.values()[prefered.ordinal() + 2]); + } + if (prefered.ordinal() - 2 >= 0) { + tolerated.add(EnumHumidity.values()[prefered.ordinal() - 2]); + } + case BOTH_1: + if (prefered.ordinal() + 1 < EnumHumidity.values().length) { + tolerated.add(EnumHumidity.values()[prefered.ordinal() + 1]); + } + if (prefered.ordinal() - 1 >= 0) { + tolerated.add(EnumHumidity.values()[prefered.ordinal() - 1]); + } + return tolerated; - case DOWN_5: - case DOWN_4: - case DOWN_3: - case DOWN_2: - if (prefered.ordinal() - 2 >= 0) { - tolerated.add(EnumHumidity.values()[prefered.ordinal() - 2]); - } - case DOWN_1: - if (prefered.ordinal() - 1 >= 0) { - tolerated.add(EnumHumidity.values()[prefered.ordinal() - 1]); - } - return tolerated; + case UP_5: + case UP_4: + case UP_3: + case UP_2: + if (prefered.ordinal() + 2 < EnumHumidity.values().length) { + tolerated.add(EnumHumidity.values()[prefered.ordinal() + 2]); + } + case UP_1: + if (prefered.ordinal() + 1 < EnumHumidity.values().length) { + tolerated.add(EnumHumidity.values()[prefered.ordinal() + 1]); + } + return tolerated; - default: - return tolerated; - } + case DOWN_5: + case DOWN_4: + case DOWN_3: + case DOWN_2: + if (prefered.ordinal() - 2 >= 0) { + tolerated.add(EnumHumidity.values()[prefered.ordinal() - 2]); + } + case DOWN_1: + if (prefered.ordinal() - 1 >= 0) { + tolerated.add(EnumHumidity.values()[prefered.ordinal() - 1]); + } + return tolerated; - } + default: + return tolerated; + } + } - public ArrayList getToleratedTemperature(EnumTemperature prefered, EnumTolerance tolerance) { + public ArrayList getToleratedTemperature(EnumTemperature prefered, EnumTolerance tolerance) { - ArrayList tolerated = new ArrayList<>(); - tolerated.add(prefered); + ArrayList tolerated = new ArrayList<>(); + tolerated.add(prefered); - switch (tolerance) { + switch (tolerance) { + case BOTH_5: + if (prefered.ordinal() + 5 < EnumTemperature.values().length) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() + 5]); + } + if (prefered.ordinal() - 5 >= 0) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() - 5]); + } + case BOTH_4: + if (prefered.ordinal() + 4 < EnumTemperature.values().length) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() + 4]); + } + if (prefered.ordinal() - 4 >= 0) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() - 4]); + } + case BOTH_3: + if (prefered.ordinal() + 3 < EnumTemperature.values().length) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() + 3]); + } + if (prefered.ordinal() - 3 >= 0) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() - 3]); + } + case BOTH_2: + if (prefered.ordinal() + 2 < EnumTemperature.values().length) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() + 2]); + } + if (prefered.ordinal() - 2 >= 0) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() - 2]); + } + case BOTH_1: + if (prefered.ordinal() + 1 < EnumTemperature.values().length) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() + 1]); + } + if (prefered.ordinal() - 1 >= 0) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() - 1]); + } + return tolerated; - case BOTH_5: - if (prefered.ordinal() + 5 < EnumTemperature.values().length) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() + 5]); - } - if (prefered.ordinal() - 5 >= 0) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() - 5]); - } - case BOTH_4: - if (prefered.ordinal() + 4 < EnumTemperature.values().length) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() + 4]); - } - if (prefered.ordinal() - 4 >= 0) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() - 4]); - } - case BOTH_3: - if (prefered.ordinal() + 3 < EnumTemperature.values().length) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() + 3]); - } - if (prefered.ordinal() - 3 >= 0) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() - 3]); - } - case BOTH_2: - if (prefered.ordinal() + 2 < EnumTemperature.values().length) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() + 2]); - } - if (prefered.ordinal() - 2 >= 0) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() - 2]); - } - case BOTH_1: - if (prefered.ordinal() + 1 < EnumTemperature.values().length) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() + 1]); - } - if (prefered.ordinal() - 1 >= 0) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() - 1]); - } - return tolerated; + case UP_5: + if (prefered.ordinal() + 5 < EnumTemperature.values().length) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() + 5]); + } + case UP_4: + if (prefered.ordinal() + 4 < EnumTemperature.values().length) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() + 4]); + } + case UP_3: + if (prefered.ordinal() + 3 < EnumTemperature.values().length) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() + 3]); + } + case UP_2: + if (prefered.ordinal() + 2 < EnumTemperature.values().length) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() + 2]); + } + case UP_1: + if (prefered.ordinal() + 1 < EnumTemperature.values().length) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() + 1]); + } + return tolerated; - case UP_5: - if (prefered.ordinal() + 5 < EnumTemperature.values().length) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() + 5]); - } - case UP_4: - if (prefered.ordinal() + 4 < EnumTemperature.values().length) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() + 4]); - } - case UP_3: - if (prefered.ordinal() + 3 < EnumTemperature.values().length) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() + 3]); - } - case UP_2: - if (prefered.ordinal() + 2 < EnumTemperature.values().length) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() + 2]); - } - case UP_1: - if (prefered.ordinal() + 1 < EnumTemperature.values().length) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() + 1]); - } - return tolerated; + case DOWN_5: + if (prefered.ordinal() - 5 >= 0) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() - 5]); + } + case DOWN_4: + if (prefered.ordinal() - 4 >= 0) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() - 4]); + } + case DOWN_3: + if (prefered.ordinal() - 3 >= 0) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() - 3]); + } + case DOWN_2: + if (prefered.ordinal() - 2 >= 0) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() - 2]); + } + case DOWN_1: + if (prefered.ordinal() - 1 >= 0) { + tolerated.add(EnumTemperature.values()[prefered.ordinal() - 1]); + } + return tolerated; - case DOWN_5: - if (prefered.ordinal() - 5 >= 0) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() - 5]); - } - case DOWN_4: - if (prefered.ordinal() - 4 >= 0) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() - 4]); - } - case DOWN_3: - if (prefered.ordinal() - 3 >= 0) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() - 3]); - } - case DOWN_2: - if (prefered.ordinal() - 2 >= 0) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() - 2]); - } - case DOWN_1: - if (prefered.ordinal() - 1 >= 0) { - tolerated.add(EnumTemperature.values()[prefered.ordinal() - 1]); - } - return tolerated; + default: + return tolerated; + } + } - default: - return tolerated; - } - } + public String toDisplay(EnumTemperature temperature) { + return StringUtil.localize("gui." + temperature.toString().toLowerCase(Locale.ENGLISH)); + } - public String toDisplay(EnumTemperature temperature) { - return StringUtil.localize("gui." + temperature.toString().toLowerCase(Locale.ENGLISH)); - } - - public String toDisplay(EnumHumidity humidity) { - return StringUtil.localize("gui." + humidity.toString().toLowerCase(Locale.ENGLISH)); - } + public String toDisplay(EnumHumidity humidity) { + return StringUtil.localize("gui." + humidity.toString().toLowerCase(Locale.ENGLISH)); + } } diff --git a/src/main/java/forestry/core/utils/ColourUtil.java b/src/main/java/forestry/core/utils/ColourUtil.java index 192f11def..147450779 100644 --- a/src/main/java/forestry/core/utils/ColourUtil.java +++ b/src/main/java/forestry/core/utils/ColourUtil.java @@ -1,38 +1,38 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils; - -public class ColourUtil { - - public static int addRGBComponents(int colour, int r, int g, int b) { - r = ((colour & 0xff0000) >> 16) + r; - g = ((colour & 0xff00) >> 8) + g; - b = ((colour & 0xff)) + b; - - r = r <= 255 ? r : 255; - g = g <= 255 ? g : 255; - b = b <= 255 ? b : 255; - - return ((r & 0x0ff) << 16) | ((g & 0x0ff) << 8) | (b & 0x0ff); - } - - public static int multiplyRGBComponents(int colour, float factor) { - int r = (int) (((colour & 0xff0000) >> 16) * factor); - int g = (int) (((colour & 0xff00) >> 8) * factor); - int b = (int) (((colour & 0xff)) * factor); - - r = r <= 255 ? r : 255; - g = g <= 255 ? g : 255; - b = b <= 255 ? b : 255; - - return ((r & 0x0ff) << 16) | ((g & 0x0ff) << 8) | (b & 0x0ff); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.utils; + +public class ColourUtil { + + public static int addRGBComponents(int colour, int r, int g, int b) { + r = ((colour & 0xff0000) >> 16) + r; + g = ((colour & 0xff00) >> 8) + g; + b = ((colour & 0xff)) + b; + + r = r <= 255 ? r : 255; + g = g <= 255 ? g : 255; + b = b <= 255 ? b : 255; + + return ((r & 0x0ff) << 16) | ((g & 0x0ff) << 8) | (b & 0x0ff); + } + + public static int multiplyRGBComponents(int colour, float factor) { + int r = (int) (((colour & 0xff0000) >> 16) * factor); + int g = (int) (((colour & 0xff00) >> 8) * factor); + int b = (int) (((colour & 0xff)) * factor); + + r = r <= 255 ? r : 255; + g = g <= 255 ? g : 255; + b = b <= 255 ? b : 255; + + return ((r & 0x0ff) << 16) | ((g & 0x0ff) << 8) | (b & 0x0ff); + } +} diff --git a/src/main/java/forestry/core/utils/DamageSourceForestry.java b/src/main/java/forestry/core/utils/DamageSourceForestry.java index d2abb1c7b..cbad6da50 100755 --- a/src/main/java/forestry/core/utils/DamageSourceForestry.java +++ b/src/main/java/forestry/core/utils/DamageSourceForestry.java @@ -17,22 +17,21 @@ import net.minecraft.util.IChatComponent; public class DamageSourceForestry extends DamageSource { - public DamageSourceForestry(String ident) { - super(ident); - setDamageBypassesArmor(); - } + public DamageSourceForestry(String ident) { + super(ident); + setDamageBypassesArmor(); + } - @Override - public IChatComponent func_151519_b(EntityLivingBase living) { - EntityLivingBase other = living.func_94060_bK(); - String ssp = "death." + this.damageType; - String smp = ssp + ".player"; - - if (other != null) { - return new ChatComponentTranslation(smp, living.func_145748_c_(), other.func_145748_c_()); - } else { - return new ChatComponentTranslation(ssp, living.func_145748_c_()); - } - } + @Override + public IChatComponent func_151519_b(EntityLivingBase living) { + EntityLivingBase other = living.func_94060_bK(); + String ssp = "death." + this.damageType; + String smp = ssp + ".player"; + if (other != null) { + return new ChatComponentTranslation(smp, living.func_145748_c_(), other.func_145748_c_()); + } else { + return new ChatComponentTranslation(ssp, living.func_145748_c_()); + } + } } diff --git a/src/main/java/forestry/core/utils/DayMonth.java b/src/main/java/forestry/core/utils/DayMonth.java index 24137806e..1a89d1572 100644 --- a/src/main/java/forestry/core/utils/DayMonth.java +++ b/src/main/java/forestry/core/utils/DayMonth.java @@ -1,102 +1,101 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils; - -import java.text.DateFormatSymbols; -import java.util.Calendar; - -/** - * Fed up with Date and Calendar and their shenanigans - */ -public class DayMonth { - - public final int day; - public final int month; - - public DayMonth() { - this.day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); - this.month = Calendar.getInstance().get(Calendar.MONTH) + 1; - } - - public DayMonth(int day, int month) { - this.day = day; - this.month = month; - } - - public boolean between(DayMonth start, DayMonth end) { - if (equals(start) || equals(end)) { - return true; - } - if (start.month > end.month) { - return after(start) || before(end); - } - return after(start) && before(end); - } - - public boolean before(DayMonth other) { - - if (other.month > this.month) { - return true; - } - - if (other.month < this.month) { - return false; - } - - return this.day < other.day; - } - - public boolean after(DayMonth other) { - - if (other.month < this.month) { - return true; - } - - if (other.month > this.month) { - return false; - } - - return this.day > other.day; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 89 * hash + this.day; - hash = 89 * hash + this.month; - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final DayMonth other = (DayMonth) obj; - if (this.day != other.day) { - return false; - } - if (this.month != other.month) { - return false; - } - return true; - } - - @Override - public String toString() { - String monthName = new DateFormatSymbols().getMonths()[month - 1]; - return monthName + ' ' + day; - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.utils; + +import java.text.DateFormatSymbols; +import java.util.Calendar; + +/** + * Fed up with Date and Calendar and their shenanigans + */ +public class DayMonth { + + public final int day; + public final int month; + + public DayMonth() { + this.day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); + this.month = Calendar.getInstance().get(Calendar.MONTH) + 1; + } + + public DayMonth(int day, int month) { + this.day = day; + this.month = month; + } + + public boolean between(DayMonth start, DayMonth end) { + if (equals(start) || equals(end)) { + return true; + } + if (start.month > end.month) { + return after(start) || before(end); + } + return after(start) && before(end); + } + + public boolean before(DayMonth other) { + + if (other.month > this.month) { + return true; + } + + if (other.month < this.month) { + return false; + } + + return this.day < other.day; + } + + public boolean after(DayMonth other) { + + if (other.month < this.month) { + return true; + } + + if (other.month > this.month) { + return false; + } + + return this.day > other.day; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 89 * hash + this.day; + hash = 89 * hash + this.month; + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final DayMonth other = (DayMonth) obj; + if (this.day != other.day) { + return false; + } + if (this.month != other.month) { + return false; + } + return true; + } + + @Override + public String toString() { + String monthName = new DateFormatSymbols().getMonths()[month - 1]; + return monthName + ' ' + day; + } +} diff --git a/src/main/java/forestry/core/utils/EntityUtil.java b/src/main/java/forestry/core/utils/EntityUtil.java index b8268a749..eaff72e98 100644 --- a/src/main/java/forestry/core/utils/EntityUtil.java +++ b/src/main/java/forestry/core/utils/EntityUtil.java @@ -1,78 +1,87 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils; - -import java.util.List; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityList; -import net.minecraft.entity.EntityLiving; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.MathHelper; -import net.minecraft.world.World; - -import cpw.mods.fml.common.registry.EntityRegistry; - -import forestry.api.core.ForestryAPI; -import forestry.core.entities.EntitySelector; - -public abstract class EntityUtil { - public static E spawnEntity(World world, Class entityClass, double x, double y, double z) { - E entityLiving = createEntity(world, entityClass); - if (entityLiving == null) { - return null; - } - return spawnEntity(world, entityLiving, x, y, z); - } - - public static E spawnEntity(World world, E living, double x, double y, double z) { - if (living == null) { - return null; - } - - living.setLocationAndAngles(x, y, z, MathHelper.wrapAngleTo180_float(world.rand.nextFloat() * 360.0f), 0.0f); - living.rotationYawHead = living.rotationYaw; - living.renderYawOffset = living.rotationYaw; - living.onSpawnWithEgg(null); - world.spawnEntityInWorld(living); - living.playLivingSound(); - return living; - } - - public static void registerEntity(Class entityClass, String ident, int id, int eggForeground, int eggBackground, int trackingRange, int updateFrequency, boolean sendVelocity) { - EntityRegistry.registerModEntity(entityClass, ident, id, ForestryAPI.instance, trackingRange, updateFrequency, sendVelocity); - Log.finer("Registered entity %s (%s) with id %s.", ident, entityClass.toString(), id); - } - - @SuppressWarnings("unchecked") - public static List getEntitiesWithinAABB(World world, Class entityClass, AxisAlignedBB boundingBox) { - return world.getEntitiesWithinAABB(entityClass, boundingBox); - } - - @SuppressWarnings("unchecked") - public static List selectEntitiesWithinAABB(World world, EntitySelector entitySelector, AxisAlignedBB boundingBox) { - return world.selectEntitiesWithinAABB(entitySelector.getEntityClass(), boundingBox, entitySelector); - } - - private static E createEntity(World world, Class entityClass) { - if (!EntityList.classToStringMapping.containsKey(entityClass)) { - return null; - } - - String entityString = (String) EntityList.classToStringMapping.get(entityClass); - if (entityString == null) { - return null; - } - - Entity entity = EntityList.createEntityByName(entityString, world); - return entityClass.cast(entity); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.utils; + +import cpw.mods.fml.common.registry.EntityRegistry; +import forestry.api.core.ForestryAPI; +import forestry.core.entities.EntitySelector; +import java.util.List; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityList; +import net.minecraft.entity.EntityLiving; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.MathHelper; +import net.minecraft.world.World; + +public abstract class EntityUtil { + public static E spawnEntity( + World world, Class entityClass, double x, double y, double z) { + E entityLiving = createEntity(world, entityClass); + if (entityLiving == null) { + return null; + } + return spawnEntity(world, entityLiving, x, y, z); + } + + public static E spawnEntity(World world, E living, double x, double y, double z) { + if (living == null) { + return null; + } + + living.setLocationAndAngles(x, y, z, MathHelper.wrapAngleTo180_float(world.rand.nextFloat() * 360.0f), 0.0f); + living.rotationYawHead = living.rotationYaw; + living.renderYawOffset = living.rotationYaw; + living.onSpawnWithEgg(null); + world.spawnEntityInWorld(living); + living.playLivingSound(); + return living; + } + + public static void registerEntity( + Class entityClass, + String ident, + int id, + int eggForeground, + int eggBackground, + int trackingRange, + int updateFrequency, + boolean sendVelocity) { + EntityRegistry.registerModEntity( + entityClass, ident, id, ForestryAPI.instance, trackingRange, updateFrequency, sendVelocity); + Log.finer("Registered entity %s (%s) with id %s.", ident, entityClass.toString(), id); + } + + @SuppressWarnings("unchecked") + public static List getEntitiesWithinAABB( + World world, Class entityClass, AxisAlignedBB boundingBox) { + return world.getEntitiesWithinAABB(entityClass, boundingBox); + } + + @SuppressWarnings("unchecked") + public static List selectEntitiesWithinAABB( + World world, EntitySelector entitySelector, AxisAlignedBB boundingBox) { + return world.selectEntitiesWithinAABB(entitySelector.getEntityClass(), boundingBox, entitySelector); + } + + private static E createEntity(World world, Class entityClass) { + if (!EntityList.classToStringMapping.containsKey(entityClass)) { + return null; + } + + String entityString = (String) EntityList.classToStringMapping.get(entityClass); + if (entityString == null) { + return null; + } + + Entity entity = EntityList.createEntityByName(entityString, world); + return entityClass.cast(entity); + } +} diff --git a/src/main/java/forestry/core/utils/ForestryModEnvWarningCallable.java b/src/main/java/forestry/core/utils/ForestryModEnvWarningCallable.java index 094ccb7d1..52ea9e75d 100755 --- a/src/main/java/forestry/core/utils/ForestryModEnvWarningCallable.java +++ b/src/main/java/forestry/core/utils/ForestryModEnvWarningCallable.java @@ -10,88 +10,88 @@ ******************************************************************************/ package forestry.core.utils; -import java.util.ArrayList; -import java.util.List; - import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.ICrashCallable; import cpw.mods.fml.common.Loader; import cpw.mods.fml.relauncher.Side; - import forestry.core.config.Constants; import forestry.plugins.PluginManager; +import java.util.ArrayList; +import java.util.List; /** * ICrashCallable for highlighting certain mods and listing disabled modules for crash reports. **/ public class ForestryModEnvWarningCallable implements ICrashCallable { - private final List modIDs; - private final List disabledModules; + private final List modIDs; + private final List disabledModules; - public static void register() { - ForestryModEnvWarningCallable callable = new ForestryModEnvWarningCallable(); - if (callable.modIDs.size() > 0 || callable.disabledModules.size() > 0) { - FMLCommonHandler.instance().registerCrashCallable(callable); - } - } + public static void register() { + ForestryModEnvWarningCallable callable = new ForestryModEnvWarningCallable(); + if (callable.modIDs.size() > 0 || callable.disabledModules.size() > 0) { + FMLCommonHandler.instance().registerCrashCallable(callable); + } + } - private ForestryModEnvWarningCallable() { - this.modIDs = new ArrayList<>(); + private ForestryModEnvWarningCallable() { + this.modIDs = new ArrayList<>(); - if (FMLCommonHandler.instance().getSide() == Side.CLIENT && FMLClientHandler.instance().hasOptifine()) { - modIDs.add("Optifine"); - } + if (FMLCommonHandler.instance().getSide() == Side.CLIENT + && FMLClientHandler.instance().hasOptifine()) { + modIDs.add("Optifine"); + } - if (Loader.isModLoaded("gregtech_addon")) { - modIDs.add("GregTech"); - } + if (Loader.isModLoaded("gregtech_addon")) { + modIDs.add("GregTech"); + } - try { - Class c = Class.forName("org.bukkit.Bukkit"); - if (c != null) { - modIDs.add("Bukkit, Cauldron, or other Bukkit replacement"); - } - } catch (Throwable ignored) { - // No need to do anything. - } + try { + Class c = Class.forName("org.bukkit.Bukkit"); + if (c != null) { + modIDs.add("Bukkit, Cauldron, or other Bukkit replacement"); + } + } catch (Throwable ignored) { + // No need to do anything. + } - this.disabledModules = new ArrayList<>(); - for (PluginManager.Module module : PluginManager.configDisabledModules) { - disabledModules.add(module.configName()); - } - } + this.disabledModules = new ArrayList<>(); + for (PluginManager.Module module : PluginManager.configDisabledModules) { + disabledModules.add(module.configName()); + } + } - @Override - public String call() throws Exception { - StringBuilder message = new StringBuilder(); - if (modIDs.size() > 0) { - message.append("Warning: You have mods that change the behavior of Minecraft, ForgeModLoader, and/or Minecraft Forge to your client: \r\n"); - message.append(modIDs.get(0)); - for (int i = 1; i < modIDs.size(); ++i) { - message.append(", ").append(modIDs.get(i)); - } - message.append("\r\nThese may have caused this error, and may not be supported. Try reproducing the crash WITHOUT these mods, and report it then."); - } + @Override + public String call() throws Exception { + StringBuilder message = new StringBuilder(); + if (modIDs.size() > 0) { + message.append( + "Warning: You have mods that change the behavior of Minecraft, ForgeModLoader, and/or Minecraft Forge to your client: \r\n"); + message.append(modIDs.get(0)); + for (int i = 1; i < modIDs.size(); ++i) { + message.append(", ").append(modIDs.get(i)); + } + message.append( + "\r\nThese may have caused this error, and may not be supported. Try reproducing the crash WITHOUT these mods, and report it then."); + } - if (disabledModules.size() > 0) { - if (message.length() > 0) { - message.append("\r\n"); - } - message.append("Info: The following plugins have been disabled in the config: "); - message.append(disabledModules.get(0)); - for (int i = 1; i < disabledModules.size(); ++i) { - message.append(", ").append(disabledModules.get(i)); - } - } + if (disabledModules.size() > 0) { + if (message.length() > 0) { + message.append("\r\n"); + } + message.append("Info: The following plugins have been disabled in the config: "); + message.append(disabledModules.get(0)); + for (int i = 1; i < disabledModules.size(); ++i) { + message.append(", ").append(disabledModules.get(i)); + } + } - return message.toString(); - } - - @Override - public String getLabel() { - return Constants.MOD + " "; - } + return message.toString(); + } + @Override + public String getLabel() { + return Constants.MOD + " "; + } } diff --git a/src/main/java/forestry/core/utils/GeneticsUtil.java b/src/main/java/forestry/core/utils/GeneticsUtil.java index 1ee97754c..f1ff5bf88 100644 --- a/src/main/java/forestry/core/utils/GeneticsUtil.java +++ b/src/main/java/forestry/core/utils/GeneticsUtil.java @@ -1,217 +1,220 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils; - -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; - -import com.mojang.authlib.GameProfile; - -import forestry.api.arboriculture.EnumGermlingType; -import forestry.api.arboriculture.ITree; -import forestry.api.arboriculture.TreeManager; -import forestry.api.core.IArmorNaturalist; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAlleleSpecies; -import forestry.api.genetics.IChromosomeType; -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.IMutation; -import forestry.api.genetics.IPollinatable; -import forestry.api.lepidopterology.IButterfly; -import forestry.api.lepidopterology.IButterflyNursery; -import forestry.arboriculture.genetics.pollination.CheckPollinatable; -import forestry.arboriculture.genetics.pollination.CheckPollinatableTree; -import forestry.arboriculture.genetics.pollination.ICheckPollinatable; -import forestry.core.config.Config; -import forestry.core.genetics.ItemGE; - -public class GeneticsUtil { - - private static Set ersatzSpecimenBlocks; - - private static Set getErsatzBlocks() { - if (ersatzSpecimenBlocks == null) { - ersatzSpecimenBlocks = new HashSet<>(); - for (ItemStack ersatzSpecimen : AlleleManager.ersatzSpecimen.keySet()) { - Block ersatzBlock = ItemStackUtil.getBlock(ersatzSpecimen); - if (ersatzBlock != null) { - ersatzSpecimenBlocks.add(ersatzBlock); - } - } - } - return ersatzSpecimenBlocks; - } - - private static boolean isErsatzBlock(Block block) { - return block != null && getErsatzBlocks().contains(block); - } - - public static boolean hasNaturalistEye(EntityPlayer player) { - if (player == null) { - return false; - } - - ItemStack armorItemStack = player.inventory.armorInventory[3]; - if (armorItemStack == null) { - return false; - } - - Item armorItem = armorItemStack.getItem(); - if (!(armorItem instanceof IArmorNaturalist)) { - return false; - } - - IArmorNaturalist armorNaturalist = (IArmorNaturalist) armorItem; - return armorNaturalist.canSeePollination(player, armorItemStack, true); - } - - public static boolean canNurse(IButterfly butterfly, World world, final int x, final int y, final int z) { - TileEntity tile = world.getTileEntity(x, y, z); - - if (tile instanceof IButterflyNursery) { - return ((IButterflyNursery) tile).canNurse(butterfly); - } - - // vanilla leaves can always be converted and then nurse - return getErsatzPollen(world, x, y, z) != null; - } - - /** - * Returns an ICheckPollinatable that can be checked but not mated. - * Used to check for pollination traits without altering the world by changing vanilla leaves to forestry ones. - */ - public static ICheckPollinatable getCheckPollinatable(World world, final int x, final int y, final int z) { - TileEntity tile = world.getTileEntity(x, y, z); - - if (tile instanceof IPollinatable) { - return new CheckPollinatable((IPollinatable) tile); - } - - ITree pollen = getErsatzPollen(world, x, y, z); - if (pollen != null) { - return new CheckPollinatableTree(pollen); - } - - return null; - } - - public static IPollinatable getOrCreatePollinatable(GameProfile owner, World world, final int x, final int y, final int z) { - TileEntity tile = world.getTileEntity(x, y, z); - - if (tile instanceof IPollinatable) { - return (IPollinatable) tile; - } - - if (Config.pollinateVanillaTrees) { - ITree pollen = getErsatzPollen(world, x, y, z); - if (pollen != null) { - pollen.setLeaves(world, owner, x, y, z); - return (IPollinatable) world.getTileEntity(x, y, z); - } - } - - return null; - } - - public static ITree getErsatzPollen(World world, final int x, final int y, final int z) { - Block block = world.getBlock(x, y, z); - if (!isErsatzBlock(block)) { - return null; - } - - int meta = world.getBlockMetadata(x, y, z); - - if (Blocks.leaves == block || Blocks.leaves2 == block) { - if ((meta & 4) != 0) { - // no-decay vanilla leaves. http://minecraft.gamepedia.com/Data_values#Leaves - // Treat them as decorative and don't pollinate. - return null; - } - if (block == Blocks.leaves2) { - meta = meta + 4; //Dark Oak and Acacia are their own leaf block, but added on the end of sapling - } - block = Blocks.sapling; - } - ItemStack itemStack = new ItemStack(block, 1, meta); - IIndividual tree = getGeneticEquivalent(itemStack); - if (tree instanceof ITree) { - return (ITree) tree; - } - - return null; - } - - public static IIndividual getGeneticEquivalent(ItemStack itemStack) { - if (itemStack == null) { - return null; - } - Item item = itemStack.getItem(); - if (item instanceof ItemGE) { - return ((ItemGE) item).getIndividual(itemStack); - } - - for (Map.Entry entry : AlleleManager.ersatzSaplings.entrySet()) { - if (ItemStackUtil.isIdenticalItem(itemStack, entry.getKey())) { - return entry.getValue().copy(); - } - } - return null; - } - - public static ItemStack convertSaplingToGeneticEquivalent(ItemStack foreign) { - if (foreign == null) { - return null; - } - - IIndividual tree = getGeneticEquivalent(foreign); - if (!(tree instanceof ITree)) { - return null; - } - - ItemStack ersatz = TreeManager.treeRoot.getMemberStack(tree, EnumGermlingType.SAPLING.ordinal()); - ersatz.stackSize = foreign.stackSize; - return ersatz; - } - - public static int getResearchComplexity(IAlleleSpecies species, IChromosomeType speciesChromosome) { - return 1 + getGeneticAdvancement(species, new HashSet(), speciesChromosome); - } - - private static int getGeneticAdvancement(IAlleleSpecies species, Set exclude, IChromosomeType speciesChromosome) { - int highest = 0; - exclude.add(species); - - for (IMutation mutation : species.getRoot().getPaths(species, speciesChromosome)) { - highest = getHighestAdvancement(mutation.getAllele0(), highest, exclude, speciesChromosome); - highest = getHighestAdvancement(mutation.getAllele1(), highest, exclude, speciesChromosome); - } - - return 1 + highest; - } - - private static int getHighestAdvancement(IAlleleSpecies mutationSpecies, int highest, Set exclude, IChromosomeType speciesChromosome) { - if (exclude.contains(mutationSpecies) || AlleleManager.alleleRegistry.isBlacklisted(mutationSpecies.getUID())) { - return highest; - } - - int otherAdvance = getGeneticAdvancement(mutationSpecies, exclude, speciesChromosome); - return otherAdvance > highest ? otherAdvance : highest; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.utils; + +import com.mojang.authlib.GameProfile; +import forestry.api.arboriculture.EnumGermlingType; +import forestry.api.arboriculture.ITree; +import forestry.api.arboriculture.TreeManager; +import forestry.api.core.IArmorNaturalist; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAlleleSpecies; +import forestry.api.genetics.IChromosomeType; +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.IMutation; +import forestry.api.genetics.IPollinatable; +import forestry.api.lepidopterology.IButterfly; +import forestry.api.lepidopterology.IButterflyNursery; +import forestry.arboriculture.genetics.pollination.CheckPollinatable; +import forestry.arboriculture.genetics.pollination.CheckPollinatableTree; +import forestry.arboriculture.genetics.pollination.ICheckPollinatable; +import forestry.core.config.Config; +import forestry.core.genetics.ItemGE; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; + +public class GeneticsUtil { + + private static Set ersatzSpecimenBlocks; + + private static Set getErsatzBlocks() { + if (ersatzSpecimenBlocks == null) { + ersatzSpecimenBlocks = new HashSet<>(); + for (ItemStack ersatzSpecimen : AlleleManager.ersatzSpecimen.keySet()) { + Block ersatzBlock = ItemStackUtil.getBlock(ersatzSpecimen); + if (ersatzBlock != null) { + ersatzSpecimenBlocks.add(ersatzBlock); + } + } + } + return ersatzSpecimenBlocks; + } + + private static boolean isErsatzBlock(Block block) { + return block != null && getErsatzBlocks().contains(block); + } + + public static boolean hasNaturalistEye(EntityPlayer player) { + if (player == null) { + return false; + } + + ItemStack armorItemStack = player.inventory.armorInventory[3]; + if (armorItemStack == null) { + return false; + } + + Item armorItem = armorItemStack.getItem(); + if (!(armorItem instanceof IArmorNaturalist)) { + return false; + } + + IArmorNaturalist armorNaturalist = (IArmorNaturalist) armorItem; + return armorNaturalist.canSeePollination(player, armorItemStack, true); + } + + public static boolean canNurse(IButterfly butterfly, World world, final int x, final int y, final int z) { + TileEntity tile = world.getTileEntity(x, y, z); + + if (tile instanceof IButterflyNursery) { + return ((IButterflyNursery) tile).canNurse(butterfly); + } + + // vanilla leaves can always be converted and then nurse + return getErsatzPollen(world, x, y, z) != null; + } + + /** + * Returns an ICheckPollinatable that can be checked but not mated. + * Used to check for pollination traits without altering the world by changing vanilla leaves to forestry ones. + */ + public static ICheckPollinatable getCheckPollinatable(World world, final int x, final int y, final int z) { + TileEntity tile = world.getTileEntity(x, y, z); + + if (tile instanceof IPollinatable) { + return new CheckPollinatable((IPollinatable) tile); + } + + ITree pollen = getErsatzPollen(world, x, y, z); + if (pollen != null) { + return new CheckPollinatableTree(pollen); + } + + return null; + } + + public static IPollinatable getOrCreatePollinatable( + GameProfile owner, World world, final int x, final int y, final int z) { + TileEntity tile = world.getTileEntity(x, y, z); + + if (tile instanceof IPollinatable) { + return (IPollinatable) tile; + } + + if (Config.pollinateVanillaTrees) { + ITree pollen = getErsatzPollen(world, x, y, z); + if (pollen != null) { + pollen.setLeaves(world, owner, x, y, z); + return (IPollinatable) world.getTileEntity(x, y, z); + } + } + + return null; + } + + public static ITree getErsatzPollen(World world, final int x, final int y, final int z) { + Block block = world.getBlock(x, y, z); + if (!isErsatzBlock(block)) { + return null; + } + + int meta = world.getBlockMetadata(x, y, z); + + if (Blocks.leaves == block || Blocks.leaves2 == block) { + if ((meta & 4) != 0) { + // no-decay vanilla leaves. http://minecraft.gamepedia.com/Data_values#Leaves + // Treat them as decorative and don't pollinate. + return null; + } + if (block == Blocks.leaves2) { + meta = meta + 4; // Dark Oak and Acacia are their own leaf block, but added on the end of sapling + } + block = Blocks.sapling; + } + ItemStack itemStack = new ItemStack(block, 1, meta); + IIndividual tree = getGeneticEquivalent(itemStack); + if (tree instanceof ITree) { + return (ITree) tree; + } + + return null; + } + + public static IIndividual getGeneticEquivalent(ItemStack itemStack) { + if (itemStack == null) { + return null; + } + Item item = itemStack.getItem(); + if (item instanceof ItemGE) { + return ((ItemGE) item).getIndividual(itemStack); + } + + for (Map.Entry entry : AlleleManager.ersatzSaplings.entrySet()) { + if (ItemStackUtil.isIdenticalItem(itemStack, entry.getKey())) { + return entry.getValue().copy(); + } + } + return null; + } + + public static ItemStack convertSaplingToGeneticEquivalent(ItemStack foreign) { + if (foreign == null) { + return null; + } + + IIndividual tree = getGeneticEquivalent(foreign); + if (!(tree instanceof ITree)) { + return null; + } + + ItemStack ersatz = TreeManager.treeRoot.getMemberStack(tree, EnumGermlingType.SAPLING.ordinal()); + ersatz.stackSize = foreign.stackSize; + return ersatz; + } + + public static int getResearchComplexity(IAlleleSpecies species, IChromosomeType speciesChromosome) { + return 1 + getGeneticAdvancement(species, new HashSet(), speciesChromosome); + } + + private static int getGeneticAdvancement( + IAlleleSpecies species, Set exclude, IChromosomeType speciesChromosome) { + int highest = 0; + exclude.add(species); + + for (IMutation mutation : species.getRoot().getPaths(species, speciesChromosome)) { + highest = getHighestAdvancement(mutation.getAllele0(), highest, exclude, speciesChromosome); + highest = getHighestAdvancement(mutation.getAllele1(), highest, exclude, speciesChromosome); + } + + return 1 + highest; + } + + private static int getHighestAdvancement( + IAlleleSpecies mutationSpecies, + int highest, + Set exclude, + IChromosomeType speciesChromosome) { + if (exclude.contains(mutationSpecies) || AlleleManager.alleleRegistry.isBlacklisted(mutationSpecies.getUID())) { + return highest; + } + + int otherAdvance = getGeneticAdvancement(mutationSpecies, exclude, speciesChromosome); + return otherAdvance > highest ? otherAdvance : highest; + } +} diff --git a/src/main/java/forestry/core/utils/InventoryUtil.java b/src/main/java/forestry/core/utils/InventoryUtil.java index fd18cc392..f9ee1d504 100644 --- a/src/main/java/forestry/core/utils/InventoryUtil.java +++ b/src/main/java/forestry/core/utils/InventoryUtil.java @@ -10,28 +10,8 @@ ******************************************************************************/ package forestry.core.utils; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; - -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; -import net.minecraftforge.oredict.OreDictionary; - +import buildcraft.api.transport.IPipeTile; import cpw.mods.fml.common.Optional; - import forestry.core.circuits.ISocketable; import forestry.core.inventory.filters.ArrayStackFilter; import forestry.core.inventory.filters.IStackFilter; @@ -43,691 +23,735 @@ import forestry.core.inventory.wrappers.InventoryIterator; import forestry.core.inventory.wrappers.SidedInventoryMapper; import forestry.core.tiles.AdjacentTileCache; import forestry.plugins.PluginManager; - -import buildcraft.api.transport.IPipeTile; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; +import net.minecraftforge.oredict.OreDictionary; public abstract class InventoryUtil { - public static IInventory getInventory(IInventory inv, ForgeDirection side) { - if (inv == null) { - return null; - } - if (inv instanceof ISidedInventory) { - inv = new SidedInventoryMapper((ISidedInventory) inv, side); - } - return inv; - } - - public static ItemStack depleteItem(ItemStack stack) { - if (stack.stackSize == 1) { - return stack.getItem().getContainerItem(stack); - } else { - stack.splitStack(1); - return stack; - } - } - - public static boolean isWildcard(ItemStack stack) { - return isWildcard(stack.getItemDamage()); - } - - public static boolean isWildcard(int damage) { - return damage == -1 || damage == OreDictionary.WILDCARD_VALUE; - } - - /** - * A more robust item comparison function. - * - * Compares stackSize as well. - * - * Two null stacks will return true, unlike the other functions. - * - * This function is primarily intended to be used to track changes to an - * ItemStack. - * - * @param a An ItemStack - * @param b An ItemStack - * @return True if equal - */ - public static boolean isItemEqualStrict(ItemStack a, ItemStack b) { - if (a == null && b == null) { - return true; - } - if (a == null || b == null) { - return false; - } - if (a.getItem() != b.getItem()) { - return false; - } - if (a.stackSize != b.stackSize) { - return false; - } - if (a.getItemDamage() != b.getItemDamage()) { - return false; - } - return a.stackTagCompound == null || a.stackTagCompound.equals(b.stackTagCompound); - } - - /** - * A more robust item comparison function. Supports items with damage = -1 - * matching any sub-type. - * - * @param a An ItemStack - * @param b An ItemStack - * @return True if equal - */ - public static boolean isItemEqual(ItemStack a, ItemStack b) { - return isItemEqual(a, b, true, true); - } - - public static boolean isItemEqual(final ItemStack a, final ItemStack b, final boolean matchDamage, final boolean matchNBT) { - if (a == null || b == null) { - return false; - } - if (a.getItem() != b.getItem()) { - return false; - } - if (matchNBT && !ItemStack.areItemStackTagsEqual(a, b)) { - return false; - } - if (matchDamage && a.getHasSubtypes()) { - if (isWildcard(a) || isWildcard(b)) { - return true; - } - return a.getItemDamage() == b.getItemDamage(); - } - return true; - } - - /** - * Returns true if the item is equal to any one of several possible matches. - */ - public static boolean isItemEqual(ItemStack stack, ItemStack... matches) { - for (ItemStack match : matches) { - if (isItemEqual(stack, match)) { - return true; - } - } - return false; - } - - /** - * Places an ItemStack in a destination IInventory. Will attempt to move as - * much of the stack as possible, returning any remainder. - * - * @param stack The ItemStack to put in the inventory. - * @param dest The destination IInventory. - * @return Null if itemStack was completely moved, a new itemStack with - * remaining stackSize if part or none of the stack was moved. - */ - public static ItemStack moveItemStack(ItemStack stack, IInventory dest) { - InventoryManipulator im = InventoryManipulator.get(dest); - return im.addStack(stack); - } - - /** - * Attempts to move an ItemStack from one inventory to another. - * - * @param source The source IInventory. - * @param dest The destination IInventory. - * @return true if any items were moved - */ - public static boolean moveItemStack(IInventory source, IInventory dest) { - InventoryManipulator im = InventoryManipulator.get(dest); - for (IInvSlot slot : InventoryIterator.getIterable(source)) { - ItemStack stack = slot.getStackInSlot(); - if (stack != null) { - ItemStack remainder = im.addStack(stack); - slot.setStackInSlot(remainder); - return !isItemEqualStrict(stack, remainder); - } - } - return false; - } - - /** - * Attempts to move an ItemStack from one inventory to another. - * - * @param source The source IInventory. - * @param destinations The destination IInventory. - * @return true if any items were moved - */ - public static boolean moveItemStack(IInventory source, Iterable destinations) { - for (IInventory dest : destinations) { - if (moveItemStack(source, dest)) { - return true; - } - } - return false; - } - - /** - * Removes and returns a single item from the inventory. - * - * @param inv The inventory - * @return An ItemStack - */ - public static ItemStack removeOneItem(IInventory inv) { - return removeOneItem(inv, StackFilter.ALL); - } - - /** - * Removes and returns a single item from the inventory that matches the - * filter. - * - * @param inv The inventory - * @param filter ItemStack to match against - * @return An ItemStack - */ - public static ItemStack removeOneItem(IInventory inv, ItemStack... filter) { - return removeOneItem(inv, new ArrayStackFilter(filter)); - } - - /** - * Removes and returns a single item from the inventory that matches the - * filter. - * - * @param inv The inventory - * @param filter EnumItemType to match against - * @return An ItemStack - */ - public static ItemStack removeOneItem(IInventory inv, IStackFilter filter) { - InventoryManipulator im = InventoryManipulator.get(inv); - return im.removeItem(filter); - } - - /** - * Attempts to move a single item from the source inventory into a adjacent Buildcraft pipe. - * If the attempt fails, the source Inventory will not be modified. - * - * @param source The source inventory - * @param tileCache The tile cache of the source block. - * @return true if an item was inserted, otherwise false. - */ - public static boolean moveOneItemToPipe(IInventory source, AdjacentTileCache tileCache) { - return moveOneItemToPipe(source, tileCache, ForgeDirection.VALID_DIRECTIONS); - } - - public static boolean moveOneItemToPipe(IInventory source, AdjacentTileCache tileCache, ForgeDirection[] directions) { - if (PluginManager.Module.BUILDCRAFT_TRANSPORT.isEnabled()) { - return internal_moveOneItemToPipe(source, tileCache, directions); - } - - return false; - } - - @Optional.Method(modid = "BuildCraftAPI|transport") - private static boolean internal_moveOneItemToPipe(IInventory source, AdjacentTileCache tileCache, ForgeDirection[] directions) { - IInventory invClone = new InventoryCopy(source); - ItemStack stackToMove = removeOneItem(invClone); - if (stackToMove == null) { - return false; - } - if (stackToMove.stackSize <= 0) { - return false; - } - - List> pipes = new ArrayList<>(); - boolean foundPipe = false; - for (ForgeDirection side : directions) { - TileEntity tile = tileCache.getTileOnSide(side); - if (tile instanceof IPipeTile) { - IPipeTile pipe = (IPipeTile) tile; - if (pipe.getPipeType() == IPipeTile.PipeType.ITEM && pipe.isPipeConnected(side.getOpposite())) { - pipes.add(new AbstractMap.SimpleEntry<>(side, pipe)); - foundPipe = true; - } - } - } - - if (!foundPipe) { - return false; - } - - int choice = tileCache.getSource().getWorldObj().rand.nextInt(pipes.size()); - Map.Entry pipe = pipes.get(choice); - if (pipe.getValue().injectItem(stackToMove, false, pipe.getKey().getOpposite(), null) > 0) { - if (removeOneItem(source, stackToMove) != null) { - pipe.getValue().injectItem(stackToMove, true, pipe.getKey().getOpposite(), null); - return true; - } - } - return false; - } - - /* REMOVAL */ - - /** - * Removes a set of items from an inventory. - * Removes the exact items first if they exist, and then removes crafting equivalents. - * If the inventory doesn't have all the required items, returns false without removing anything. - * If stowContainer is true, items with containers will have their container stowed. - */ - public static boolean removeSets(IInventory inventory, int count, ItemStack[] set, EntityPlayer player, boolean stowContainer, boolean oreDictionary, boolean craftingTools, boolean doRemove) { - ItemStack[] stock = getStacks(inventory); - - if (doRemove) { - ItemStack[] removed = removeSets(inventory, count, set, player, stowContainer, oreDictionary, craftingTools); - return removed != null && removed.length >= count; - } else { - return ItemStackUtil.containsSets(set, stock, oreDictionary, craftingTools) >= count; - } - } - - public static ItemStack[] removeSets(IInventory inventory, int count, ItemStack[] set, EntityPlayer player, boolean stowContainer, boolean oreDictionary, boolean craftingTools) { - ItemStack[] removed = new ItemStack[set.length]; - ItemStack[] stock = getStacks(inventory); - - if (ItemStackUtil.containsSets(set, stock, oreDictionary, craftingTools) < count) { - return null; - } - - for (int i = 0; i < set.length; i++) { - if (set[i] == null) { - continue; - } - ItemStack stackToRemove = set[i].copy(); - stackToRemove.stackSize *= count; - - // try to remove the exact stack first - ItemStack removedStack = removeStack(inventory, stackToRemove, player, stowContainer, false, false); - if (removedStack == null) { - // remove crafting equivalents next - removedStack = removeStack(inventory, stackToRemove, player, stowContainer, oreDictionary, craftingTools); - } - - removed[i] = removedStack; - } - return removed; - } - - /** - * Private Helper for removeSetsFromInventory. Assumes removal is possible. - */ - private static ItemStack removeStack(IInventory inventory, ItemStack stackToRemove, EntityPlayer player, boolean stowContainer, boolean oreDictionary, boolean craftingTools) { - for (int j = 0; j < inventory.getSizeInventory(); j++) { - ItemStack stackInSlot = inventory.getStackInSlot(j); - if (stackInSlot == null) { - continue; - } - - if (!ItemStackUtil.isCraftingEquivalent(stackToRemove, stackInSlot, oreDictionary, craftingTools)) { - continue; - } - - ItemStack removed = inventory.decrStackSize(j, stackToRemove.stackSize); - stackToRemove.stackSize -= removed.stackSize; - - if (stowContainer && stackToRemove.getItem().hasContainerItem(stackToRemove)) { - stowContainerItem(removed, inventory, j, player); - } - - if (stackToRemove.stackSize == 0) { - return removed; - } - } - return null; - } - - /* CONTAINS */ - - public static boolean contains(IInventory inventory, ItemStack[] query) { - return contains(inventory, query, 0, inventory.getSizeInventory()); - } - - public static boolean contains(IInventory inventory, ItemStack[] query, int startSlot, int slots) { - ItemStack[] stock = getStacks(inventory, startSlot, slots); - return ItemStackUtil.containsSets(query, stock) > 0; - } - - public static boolean containsPercent(IInventory inventory, float percent) { - return containsPercent(inventory, percent, 0, inventory.getSizeInventory()); - } - - public static boolean containsPercent(IInventory inventory, float percent, int slot1, int length) { - int amount = 0; - int stackMax = 0; - for (ItemStack itemStack : getStacks(inventory, slot1, length)) { - if (itemStack == null) { - stackMax += 64; - continue; - } - - amount += itemStack.stackSize; - stackMax += itemStack.getMaxStackSize(); - } - if (stackMax == 0) { - return false; - } - return ((float) amount / (float) stackMax) >= percent; - } - - public static boolean containsAmount(IInventory inventory, int amount) { - int total = 0; - int slot1 = 0; - int length = inventory.getSizeInventory(); - for (ItemStack itemStack : getStacks(inventory, slot1, length)) { - if (itemStack == null) { - continue; - } - total += itemStack.stackSize; - if (total >= amount) { - return true; - } - } - return false; - } - - public static boolean isEmpty(IInventory inventory, int slotStart, int slotCount) { - for (int i = slotStart; i < slotStart + slotCount; i++) { - if (inventory.getStackInSlot(i) != null) { - return false; - } - } - return true; - } - - public static ItemStack[] getStacks(IInventory inventory) { - ItemStack[] stacks = new ItemStack[inventory.getSizeInventory()]; - for (int i = 0; i < inventory.getSizeInventory(); i++) { - stacks[i] = inventory.getStackInSlot(i); - } - return stacks; - } - - public static ItemStack[] getStacks(IInventory inventory, int slot1, int length) { - ItemStack[] result = new ItemStack[length]; - for (int i = slot1; i < slot1 + length; i++) { - result[i - slot1] = inventory.getStackInSlot(i); - } - return result; - } - - public static boolean tryAddStacksCopy(IInventory inventory, ItemStack[] stacks, int startSlot, int slots, boolean all) { - - for (ItemStack stack : stacks) { - if (stack == null) { - continue; - } - - if (!tryAddStack(inventory, stack.copy(), startSlot, slots, all)) { - return false; - } - } - - return true; - } - - public static boolean tryAddStack(IInventory inventory, ItemStack stack, boolean all) { - return tryAddStack(inventory, stack, 0, inventory.getSizeInventory(), all, true); - } - - public static boolean tryAddStack(IInventory inventory, ItemStack stack, boolean all, boolean doAdd) { - return tryAddStack(inventory, stack, 0, inventory.getSizeInventory(), all, doAdd); - } - - /** - * Tries to add a stack to the specified slot range. - */ - public static boolean tryAddStack(IInventory inventory, ItemStack stack, int startSlot, int slots, boolean all) { - return tryAddStack(inventory, stack, startSlot, slots, all, true); - } - - public static boolean tryAddStack(IInventory inventory, ItemStack stack, int startSlot, int slots, boolean all, boolean doAdd) { - int added = addStack(inventory, stack, startSlot, slots, false); - boolean success = all ? (added == stack.stackSize) : (added > 0); - - if (success && doAdd) { - addStack(inventory, stack, startSlot, slots, true); - } - - return success; - } - - public static int addStack(IInventory inventory, ItemStack stack, boolean doAdd) { - return addStack(inventory, stack, 0, inventory.getSizeInventory(), doAdd); - } - - public static int addStack(IInventory inventory, ItemStack stack, int startSlot, int slots, boolean doAdd) { - - int added = 0; - // Add to existing stacks first - for (int i = startSlot; i < startSlot + slots; i++) { - - ItemStack inventoryStack = inventory.getStackInSlot(i); - // Empty slot. Add - if (inventoryStack == null || inventoryStack.getItem() == null) { - continue; - } - - // Already occupied by different item, skip this slot. - if (!inventoryStack.isStackable()) { - continue; - } - if (!inventoryStack.isItemEqual(stack)) { - continue; - } - if (!ItemStack.areItemStackTagsEqual(inventoryStack, stack)) { - continue; - } - - int remain = stack.stackSize - added; - int space = inventoryStack.getMaxStackSize() - inventoryStack.stackSize; - // No space left, skip this slot. - if (space <= 0) { - continue; - } - // Enough space - if (space >= remain) { - if (doAdd) { - inventoryStack.stackSize += remain; - } - return stack.stackSize; - } - - // Not enough space - if (doAdd) { - inventoryStack.stackSize = inventoryStack.getMaxStackSize(); - } - - added += space; - } - - if (added >= stack.stackSize) { - return added; - } - - for (int i = startSlot; i < startSlot + slots; i++) { - if (inventory.getStackInSlot(i) != null) { - continue; - } - - if (doAdd) { - inventory.setInventorySlotContents(i, stack.copy()); - inventory.getStackInSlot(i).stackSize = stack.stackSize - added; - } - return stack.stackSize; - - } - - return added; - } - - public static boolean stowInInventory(ItemStack itemstack, IInventory inventory, boolean doAdd) { - return stowInInventory(itemstack, inventory, doAdd, 0, inventory.getSizeInventory()); - } - - public static boolean stowInInventory(ItemStack itemstack, IInventory inventory, boolean doAdd, int slot1, int count) { - - boolean added = false; - - for (int i = slot1; i < slot1 + count; i++) { - ItemStack inventoryStack = inventory.getStackInSlot(i); - - // Grab those free slots - if (inventoryStack == null) { - if (doAdd) { - inventory.setInventorySlotContents(i, itemstack.copy()); - itemstack.stackSize = 0; - } - return true; - } - - // Already full - if (inventoryStack.stackSize >= inventoryStack.getMaxStackSize()) { - continue; - } - - // Not same type - if (!inventoryStack.isItemEqual(itemstack)) { - continue; - } - if (!ItemStack.areItemStackTagsEqual(inventoryStack, itemstack)) { - continue; - } - - int space = inventoryStack.getMaxStackSize() - inventoryStack.stackSize; - - // Enough space to add all - if (space > itemstack.stackSize) { - if (doAdd) { - inventoryStack.stackSize += itemstack.stackSize; - itemstack.stackSize = 0; - } - return true; - // Only part can be added - } else { - if (doAdd) { - inventoryStack.stackSize = inventoryStack.getMaxStackSize(); - itemstack.stackSize -= space; - } - added = true; - } - - } - - return added; - } - - public static void stowContainerItem(ItemStack itemstack, IInventory stowing, int slotIndex, EntityPlayer player) { - if (!itemstack.getItem().hasContainerItem(itemstack)) { - return; - } - - ItemStack container = itemstack.getItem().getContainerItem(itemstack); - - if (container.isItemStackDamageable() && container.getItemDamage() > container.getMaxDamage()) { - if (player != null) { - MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, container)); - } - container = null; - } - - if (container != null) { - - if (itemstack.getItem().doesContainerItemLeaveCraftingGrid(itemstack)) { - if (!tryAddStack(stowing, container, true)) { - if (player != null && !player.inventory.addItemStackToInventory(container)) { - player.dropPlayerItemWithRandomChoice(container, true); - } - } - } else { - if (!tryAddStack(stowing, container, slotIndex, 1, true)) { - if (!tryAddStack(stowing, container, true) && player != null) { - player.dropPlayerItemWithRandomChoice(container, true); - } - } - } - } - } - - public static void deepCopyInventoryContents(IInventory source, IInventory destination) { - if (source == null || destination == null) { - throw new IllegalArgumentException("Inventory can't be null. Source: " + source + ", Destination: " + destination); - } - if (source.getSizeInventory() != destination.getSizeInventory()) { - throw new IllegalArgumentException("Inventory sizes do not match. Source: " + source + ", Destination: " + destination); - } - - for (int i = 0; i < source.getSizeInventory(); i++) { - ItemStack stack = source.getStackInSlot(i); - if (stack != null) { - stack = stack.copy(); - } - destination.setInventorySlotContents(i, stack); - } - } - - public static void dropInventory(IInventory inventory, World world, double x, double y, double z) { - if (inventory == null) { - return; - } - - // Release inventory - for (int slot = 0; slot < inventory.getSizeInventory(); slot++) { - ItemStack itemstack = inventory.getStackInSlot(slot); - dropItemStackFromInventory(itemstack, world, x, y, z); - inventory.setInventorySlotContents(slot, null); - } - } - - public static void dropSockets(ISocketable socketable, World world, double x, double y, double z) { - for (int slot = 0; slot < socketable.getSocketCount(); slot++) { - ItemStack itemstack = socketable.getSocket(slot); - dropItemStackFromInventory(itemstack, world, x, y, z); - socketable.setSocket(slot, null); - } - } - - public static void dropItemStackFromInventory(ItemStack itemStack, World world, double x, double y, double z) { - if (itemStack == null) { - return; - } - - float f = world.rand.nextFloat() * 0.8F + 0.1F; - float f1 = world.rand.nextFloat() * 0.8F + 0.1F; - float f2 = world.rand.nextFloat() * 0.8F + 0.1F; - - while (itemStack.stackSize > 0) { - int stackPartial = world.rand.nextInt(21) + 10; - if (stackPartial > itemStack.stackSize) { - stackPartial = itemStack.stackSize; - } - ItemStack drop = itemStack.splitStack(stackPartial); - EntityItem entityitem = new EntityItem(world, x + f, y + f1, z + f2, drop); - float accel = 0.05F; - entityitem.motionX = (float) world.rand.nextGaussian() * accel; - entityitem.motionY = (float) world.rand.nextGaussian() * accel + 0.2F; - entityitem.motionZ = (float) world.rand.nextGaussian() * accel; - world.spawnEntityInWorld(entityitem); - } - } - - /* NBT */ - public static void readFromNBT(IInventory inventory, NBTTagCompound nbttagcompound) { - if (!nbttagcompound.hasKey(inventory.getInventoryName())) { - return; - } - - NBTTagList nbttaglist = nbttagcompound.getTagList(inventory.getInventoryName(), 10); - - for (int j = 0; j < nbttaglist.tagCount(); ++j) { - NBTTagCompound nbttagcompound2 = nbttaglist.getCompoundTagAt(j); - int index = nbttagcompound2.getByte("Slot"); - inventory.setInventorySlotContents(index, ItemStack.loadItemStackFromNBT(nbttagcompound2)); - } - } - - public static void writeToNBT(IInventory inventory, NBTTagCompound nbttagcompound) { - NBTTagList nbttaglist = new NBTTagList(); - for (int i = 0; i < inventory.getSizeInventory(); i++) { - if (inventory.getStackInSlot(i) != null) { - NBTTagCompound nbttagcompound2 = new NBTTagCompound(); - nbttagcompound2.setByte("Slot", (byte) i); - inventory.getStackInSlot(i).writeToNBT(nbttagcompound2); - nbttaglist.appendTag(nbttagcompound2); - } - } - nbttagcompound.setTag(inventory.getInventoryName(), nbttaglist); - } + public static IInventory getInventory(IInventory inv, ForgeDirection side) { + if (inv == null) { + return null; + } + if (inv instanceof ISidedInventory) { + inv = new SidedInventoryMapper((ISidedInventory) inv, side); + } + return inv; + } + + public static ItemStack depleteItem(ItemStack stack) { + if (stack.stackSize == 1) { + return stack.getItem().getContainerItem(stack); + } else { + stack.splitStack(1); + return stack; + } + } + + public static boolean isWildcard(ItemStack stack) { + return isWildcard(stack.getItemDamage()); + } + + public static boolean isWildcard(int damage) { + return damage == -1 || damage == OreDictionary.WILDCARD_VALUE; + } + + /** + * A more robust item comparison function. + * + * Compares stackSize as well. + * + * Two null stacks will return true, unlike the other functions. + * + * This function is primarily intended to be used to track changes to an + * ItemStack. + * + * @param a An ItemStack + * @param b An ItemStack + * @return True if equal + */ + public static boolean isItemEqualStrict(ItemStack a, ItemStack b) { + if (a == null && b == null) { + return true; + } + if (a == null || b == null) { + return false; + } + if (a.getItem() != b.getItem()) { + return false; + } + if (a.stackSize != b.stackSize) { + return false; + } + if (a.getItemDamage() != b.getItemDamage()) { + return false; + } + return a.stackTagCompound == null || a.stackTagCompound.equals(b.stackTagCompound); + } + + /** + * A more robust item comparison function. Supports items with damage = -1 + * matching any sub-type. + * + * @param a An ItemStack + * @param b An ItemStack + * @return True if equal + */ + public static boolean isItemEqual(ItemStack a, ItemStack b) { + return isItemEqual(a, b, true, true); + } + + public static boolean isItemEqual( + final ItemStack a, final ItemStack b, final boolean matchDamage, final boolean matchNBT) { + if (a == null || b == null) { + return false; + } + if (a.getItem() != b.getItem()) { + return false; + } + if (matchNBT && !ItemStack.areItemStackTagsEqual(a, b)) { + return false; + } + if (matchDamage && a.getHasSubtypes()) { + if (isWildcard(a) || isWildcard(b)) { + return true; + } + return a.getItemDamage() == b.getItemDamage(); + } + return true; + } + + /** + * Returns true if the item is equal to any one of several possible matches. + */ + public static boolean isItemEqual(ItemStack stack, ItemStack... matches) { + for (ItemStack match : matches) { + if (isItemEqual(stack, match)) { + return true; + } + } + return false; + } + + /** + * Places an ItemStack in a destination IInventory. Will attempt to move as + * much of the stack as possible, returning any remainder. + * + * @param stack The ItemStack to put in the inventory. + * @param dest The destination IInventory. + * @return Null if itemStack was completely moved, a new itemStack with + * remaining stackSize if part or none of the stack was moved. + */ + public static ItemStack moveItemStack(ItemStack stack, IInventory dest) { + InventoryManipulator im = InventoryManipulator.get(dest); + return im.addStack(stack); + } + + /** + * Attempts to move an ItemStack from one inventory to another. + * + * @param source The source IInventory. + * @param dest The destination IInventory. + * @return true if any items were moved + */ + public static boolean moveItemStack(IInventory source, IInventory dest) { + InventoryManipulator im = InventoryManipulator.get(dest); + for (IInvSlot slot : InventoryIterator.getIterable(source)) { + ItemStack stack = slot.getStackInSlot(); + if (stack != null) { + ItemStack remainder = im.addStack(stack); + slot.setStackInSlot(remainder); + return !isItemEqualStrict(stack, remainder); + } + } + return false; + } + + /** + * Attempts to move an ItemStack from one inventory to another. + * + * @param source The source IInventory. + * @param destinations The destination IInventory. + * @return true if any items were moved + */ + public static boolean moveItemStack(IInventory source, Iterable destinations) { + for (IInventory dest : destinations) { + if (moveItemStack(source, dest)) { + return true; + } + } + return false; + } + + /** + * Removes and returns a single item from the inventory. + * + * @param inv The inventory + * @return An ItemStack + */ + public static ItemStack removeOneItem(IInventory inv) { + return removeOneItem(inv, StackFilter.ALL); + } + + /** + * Removes and returns a single item from the inventory that matches the + * filter. + * + * @param inv The inventory + * @param filter ItemStack to match against + * @return An ItemStack + */ + public static ItemStack removeOneItem(IInventory inv, ItemStack... filter) { + return removeOneItem(inv, new ArrayStackFilter(filter)); + } + + /** + * Removes and returns a single item from the inventory that matches the + * filter. + * + * @param inv The inventory + * @param filter EnumItemType to match against + * @return An ItemStack + */ + public static ItemStack removeOneItem(IInventory inv, IStackFilter filter) { + InventoryManipulator im = InventoryManipulator.get(inv); + return im.removeItem(filter); + } + + /** + * Attempts to move a single item from the source inventory into a adjacent Buildcraft pipe. + * If the attempt fails, the source Inventory will not be modified. + * + * @param source The source inventory + * @param tileCache The tile cache of the source block. + * @return true if an item was inserted, otherwise false. + */ + public static boolean moveOneItemToPipe(IInventory source, AdjacentTileCache tileCache) { + return moveOneItemToPipe(source, tileCache, ForgeDirection.VALID_DIRECTIONS); + } + + public static boolean moveOneItemToPipe( + IInventory source, AdjacentTileCache tileCache, ForgeDirection[] directions) { + if (PluginManager.Module.BUILDCRAFT_TRANSPORT.isEnabled()) { + return internal_moveOneItemToPipe(source, tileCache, directions); + } + + return false; + } + + @Optional.Method(modid = "BuildCraftAPI|transport") + private static boolean internal_moveOneItemToPipe( + IInventory source, AdjacentTileCache tileCache, ForgeDirection[] directions) { + IInventory invClone = new InventoryCopy(source); + ItemStack stackToMove = removeOneItem(invClone); + if (stackToMove == null) { + return false; + } + if (stackToMove.stackSize <= 0) { + return false; + } + + List> pipes = new ArrayList<>(); + boolean foundPipe = false; + for (ForgeDirection side : directions) { + TileEntity tile = tileCache.getTileOnSide(side); + if (tile instanceof IPipeTile) { + IPipeTile pipe = (IPipeTile) tile; + if (pipe.getPipeType() == IPipeTile.PipeType.ITEM && pipe.isPipeConnected(side.getOpposite())) { + pipes.add(new AbstractMap.SimpleEntry<>(side, pipe)); + foundPipe = true; + } + } + } + + if (!foundPipe) { + return false; + } + + int choice = tileCache.getSource().getWorldObj().rand.nextInt(pipes.size()); + Map.Entry pipe = pipes.get(choice); + if (pipe.getValue().injectItem(stackToMove, false, pipe.getKey().getOpposite(), null) > 0) { + if (removeOneItem(source, stackToMove) != null) { + pipe.getValue().injectItem(stackToMove, true, pipe.getKey().getOpposite(), null); + return true; + } + } + return false; + } + + /* REMOVAL */ + + /** + * Removes a set of items from an inventory. + * Removes the exact items first if they exist, and then removes crafting equivalents. + * If the inventory doesn't have all the required items, returns false without removing anything. + * If stowContainer is true, items with containers will have their container stowed. + */ + public static boolean removeSets( + IInventory inventory, + int count, + ItemStack[] set, + EntityPlayer player, + boolean stowContainer, + boolean oreDictionary, + boolean craftingTools, + boolean doRemove) { + ItemStack[] stock = getStacks(inventory); + + if (doRemove) { + ItemStack[] removed = + removeSets(inventory, count, set, player, stowContainer, oreDictionary, craftingTools); + return removed != null && removed.length >= count; + } else { + return ItemStackUtil.containsSets(set, stock, oreDictionary, craftingTools) >= count; + } + } + + public static ItemStack[] removeSets( + IInventory inventory, + int count, + ItemStack[] set, + EntityPlayer player, + boolean stowContainer, + boolean oreDictionary, + boolean craftingTools) { + ItemStack[] removed = new ItemStack[set.length]; + ItemStack[] stock = getStacks(inventory); + + if (ItemStackUtil.containsSets(set, stock, oreDictionary, craftingTools) < count) { + return null; + } + + for (int i = 0; i < set.length; i++) { + if (set[i] == null) { + continue; + } + ItemStack stackToRemove = set[i].copy(); + stackToRemove.stackSize *= count; + + // try to remove the exact stack first + ItemStack removedStack = removeStack(inventory, stackToRemove, player, stowContainer, false, false); + if (removedStack == null) { + // remove crafting equivalents next + removedStack = + removeStack(inventory, stackToRemove, player, stowContainer, oreDictionary, craftingTools); + } + + removed[i] = removedStack; + } + return removed; + } + + /** + * Private Helper for removeSetsFromInventory. Assumes removal is possible. + */ + private static ItemStack removeStack( + IInventory inventory, + ItemStack stackToRemove, + EntityPlayer player, + boolean stowContainer, + boolean oreDictionary, + boolean craftingTools) { + for (int j = 0; j < inventory.getSizeInventory(); j++) { + ItemStack stackInSlot = inventory.getStackInSlot(j); + if (stackInSlot == null) { + continue; + } + + if (!ItemStackUtil.isCraftingEquivalent(stackToRemove, stackInSlot, oreDictionary, craftingTools)) { + continue; + } + + ItemStack removed = inventory.decrStackSize(j, stackToRemove.stackSize); + stackToRemove.stackSize -= removed.stackSize; + + if (stowContainer && stackToRemove.getItem().hasContainerItem(stackToRemove)) { + stowContainerItem(removed, inventory, j, player); + } + + if (stackToRemove.stackSize == 0) { + return removed; + } + } + return null; + } + + /* CONTAINS */ + + public static boolean contains(IInventory inventory, ItemStack[] query) { + return contains(inventory, query, 0, inventory.getSizeInventory()); + } + + public static boolean contains(IInventory inventory, ItemStack[] query, int startSlot, int slots) { + ItemStack[] stock = getStacks(inventory, startSlot, slots); + return ItemStackUtil.containsSets(query, stock) > 0; + } + + public static boolean containsPercent(IInventory inventory, float percent) { + return containsPercent(inventory, percent, 0, inventory.getSizeInventory()); + } + + public static boolean containsPercent(IInventory inventory, float percent, int slot1, int length) { + int amount = 0; + int stackMax = 0; + for (ItemStack itemStack : getStacks(inventory, slot1, length)) { + if (itemStack == null) { + stackMax += 64; + continue; + } + + amount += itemStack.stackSize; + stackMax += itemStack.getMaxStackSize(); + } + if (stackMax == 0) { + return false; + } + return ((float) amount / (float) stackMax) >= percent; + } + + public static boolean containsAmount(IInventory inventory, int amount) { + int total = 0; + int slot1 = 0; + int length = inventory.getSizeInventory(); + for (ItemStack itemStack : getStacks(inventory, slot1, length)) { + if (itemStack == null) { + continue; + } + total += itemStack.stackSize; + if (total >= amount) { + return true; + } + } + return false; + } + + public static boolean isEmpty(IInventory inventory, int slotStart, int slotCount) { + for (int i = slotStart; i < slotStart + slotCount; i++) { + if (inventory.getStackInSlot(i) != null) { + return false; + } + } + return true; + } + + public static ItemStack[] getStacks(IInventory inventory) { + ItemStack[] stacks = new ItemStack[inventory.getSizeInventory()]; + for (int i = 0; i < inventory.getSizeInventory(); i++) { + stacks[i] = inventory.getStackInSlot(i); + } + return stacks; + } + + public static ItemStack[] getStacks(IInventory inventory, int slot1, int length) { + ItemStack[] result = new ItemStack[length]; + for (int i = slot1; i < slot1 + length; i++) { + result[i - slot1] = inventory.getStackInSlot(i); + } + return result; + } + + public static boolean tryAddStacksCopy( + IInventory inventory, ItemStack[] stacks, int startSlot, int slots, boolean all) { + + for (ItemStack stack : stacks) { + if (stack == null) { + continue; + } + + if (!tryAddStack(inventory, stack.copy(), startSlot, slots, all)) { + return false; + } + } + + return true; + } + + public static boolean tryAddStack(IInventory inventory, ItemStack stack, boolean all) { + return tryAddStack(inventory, stack, 0, inventory.getSizeInventory(), all, true); + } + + public static boolean tryAddStack(IInventory inventory, ItemStack stack, boolean all, boolean doAdd) { + return tryAddStack(inventory, stack, 0, inventory.getSizeInventory(), all, doAdd); + } + + /** + * Tries to add a stack to the specified slot range. + */ + public static boolean tryAddStack(IInventory inventory, ItemStack stack, int startSlot, int slots, boolean all) { + return tryAddStack(inventory, stack, startSlot, slots, all, true); + } + + public static boolean tryAddStack( + IInventory inventory, ItemStack stack, int startSlot, int slots, boolean all, boolean doAdd) { + int added = addStack(inventory, stack, startSlot, slots, false); + boolean success = all ? (added == stack.stackSize) : (added > 0); + + if (success && doAdd) { + addStack(inventory, stack, startSlot, slots, true); + } + + return success; + } + + public static int addStack(IInventory inventory, ItemStack stack, boolean doAdd) { + return addStack(inventory, stack, 0, inventory.getSizeInventory(), doAdd); + } + + public static int addStack(IInventory inventory, ItemStack stack, int startSlot, int slots, boolean doAdd) { + + int added = 0; + // Add to existing stacks first + for (int i = startSlot; i < startSlot + slots; i++) { + + ItemStack inventoryStack = inventory.getStackInSlot(i); + // Empty slot. Add + if (inventoryStack == null || inventoryStack.getItem() == null) { + continue; + } + + // Already occupied by different item, skip this slot. + if (!inventoryStack.isStackable()) { + continue; + } + if (!inventoryStack.isItemEqual(stack)) { + continue; + } + if (!ItemStack.areItemStackTagsEqual(inventoryStack, stack)) { + continue; + } + + int remain = stack.stackSize - added; + int space = inventoryStack.getMaxStackSize() - inventoryStack.stackSize; + // No space left, skip this slot. + if (space <= 0) { + continue; + } + // Enough space + if (space >= remain) { + if (doAdd) { + inventoryStack.stackSize += remain; + } + return stack.stackSize; + } + + // Not enough space + if (doAdd) { + inventoryStack.stackSize = inventoryStack.getMaxStackSize(); + } + + added += space; + } + + if (added >= stack.stackSize) { + return added; + } + + for (int i = startSlot; i < startSlot + slots; i++) { + if (inventory.getStackInSlot(i) != null) { + continue; + } + + if (doAdd) { + inventory.setInventorySlotContents(i, stack.copy()); + inventory.getStackInSlot(i).stackSize = stack.stackSize - added; + } + return stack.stackSize; + } + + return added; + } + + public static boolean stowInInventory(ItemStack itemstack, IInventory inventory, boolean doAdd) { + return stowInInventory(itemstack, inventory, doAdd, 0, inventory.getSizeInventory()); + } + + public static boolean stowInInventory( + ItemStack itemstack, IInventory inventory, boolean doAdd, int slot1, int count) { + + boolean added = false; + + for (int i = slot1; i < slot1 + count; i++) { + ItemStack inventoryStack = inventory.getStackInSlot(i); + + // Grab those free slots + if (inventoryStack == null) { + if (doAdd) { + inventory.setInventorySlotContents(i, itemstack.copy()); + itemstack.stackSize = 0; + } + return true; + } + + // Already full + if (inventoryStack.stackSize >= inventoryStack.getMaxStackSize()) { + continue; + } + + // Not same type + if (!inventoryStack.isItemEqual(itemstack)) { + continue; + } + if (!ItemStack.areItemStackTagsEqual(inventoryStack, itemstack)) { + continue; + } + + int space = inventoryStack.getMaxStackSize() - inventoryStack.stackSize; + + // Enough space to add all + if (space > itemstack.stackSize) { + if (doAdd) { + inventoryStack.stackSize += itemstack.stackSize; + itemstack.stackSize = 0; + } + return true; + // Only part can be added + } else { + if (doAdd) { + inventoryStack.stackSize = inventoryStack.getMaxStackSize(); + itemstack.stackSize -= space; + } + added = true; + } + } + + return added; + } + + public static void stowContainerItem(ItemStack itemstack, IInventory stowing, int slotIndex, EntityPlayer player) { + if (!itemstack.getItem().hasContainerItem(itemstack)) { + return; + } + + ItemStack container = itemstack.getItem().getContainerItem(itemstack); + + if (container.isItemStackDamageable() && container.getItemDamage() > container.getMaxDamage()) { + if (player != null) { + MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, container)); + } + container = null; + } + + if (container != null) { + + if (itemstack.getItem().doesContainerItemLeaveCraftingGrid(itemstack)) { + if (!tryAddStack(stowing, container, true)) { + if (player != null && !player.inventory.addItemStackToInventory(container)) { + player.dropPlayerItemWithRandomChoice(container, true); + } + } + } else { + if (!tryAddStack(stowing, container, slotIndex, 1, true)) { + if (!tryAddStack(stowing, container, true) && player != null) { + player.dropPlayerItemWithRandomChoice(container, true); + } + } + } + } + } + + public static void deepCopyInventoryContents(IInventory source, IInventory destination) { + if (source == null || destination == null) { + throw new IllegalArgumentException( + "Inventory can't be null. Source: " + source + ", Destination: " + destination); + } + if (source.getSizeInventory() != destination.getSizeInventory()) { + throw new IllegalArgumentException( + "Inventory sizes do not match. Source: " + source + ", Destination: " + destination); + } + + for (int i = 0; i < source.getSizeInventory(); i++) { + ItemStack stack = source.getStackInSlot(i); + if (stack != null) { + stack = stack.copy(); + } + destination.setInventorySlotContents(i, stack); + } + } + + public static void dropInventory(IInventory inventory, World world, double x, double y, double z) { + if (inventory == null) { + return; + } + + // Release inventory + for (int slot = 0; slot < inventory.getSizeInventory(); slot++) { + ItemStack itemstack = inventory.getStackInSlot(slot); + dropItemStackFromInventory(itemstack, world, x, y, z); + inventory.setInventorySlotContents(slot, null); + } + } + + public static void dropSockets(ISocketable socketable, World world, double x, double y, double z) { + for (int slot = 0; slot < socketable.getSocketCount(); slot++) { + ItemStack itemstack = socketable.getSocket(slot); + dropItemStackFromInventory(itemstack, world, x, y, z); + socketable.setSocket(slot, null); + } + } + + public static void dropItemStackFromInventory(ItemStack itemStack, World world, double x, double y, double z) { + if (itemStack == null) { + return; + } + + float f = world.rand.nextFloat() * 0.8F + 0.1F; + float f1 = world.rand.nextFloat() * 0.8F + 0.1F; + float f2 = world.rand.nextFloat() * 0.8F + 0.1F; + + while (itemStack.stackSize > 0) { + int stackPartial = world.rand.nextInt(21) + 10; + if (stackPartial > itemStack.stackSize) { + stackPartial = itemStack.stackSize; + } + ItemStack drop = itemStack.splitStack(stackPartial); + EntityItem entityitem = new EntityItem(world, x + f, y + f1, z + f2, drop); + float accel = 0.05F; + entityitem.motionX = (float) world.rand.nextGaussian() * accel; + entityitem.motionY = (float) world.rand.nextGaussian() * accel + 0.2F; + entityitem.motionZ = (float) world.rand.nextGaussian() * accel; + world.spawnEntityInWorld(entityitem); + } + } + + /* NBT */ + public static void readFromNBT(IInventory inventory, NBTTagCompound nbttagcompound) { + if (!nbttagcompound.hasKey(inventory.getInventoryName())) { + return; + } + + NBTTagList nbttaglist = nbttagcompound.getTagList(inventory.getInventoryName(), 10); + + for (int j = 0; j < nbttaglist.tagCount(); ++j) { + NBTTagCompound nbttagcompound2 = nbttaglist.getCompoundTagAt(j); + int index = nbttagcompound2.getByte("Slot"); + inventory.setInventorySlotContents(index, ItemStack.loadItemStackFromNBT(nbttagcompound2)); + } + } + + public static void writeToNBT(IInventory inventory, NBTTagCompound nbttagcompound) { + NBTTagList nbttaglist = new NBTTagList(); + for (int i = 0; i < inventory.getSizeInventory(); i++) { + if (inventory.getStackInSlot(i) != null) { + NBTTagCompound nbttagcompound2 = new NBTTagCompound(); + nbttagcompound2.setByte("Slot", (byte) i); + inventory.getStackInSlot(i).writeToNBT(nbttagcompound2); + nbttaglist.appendTag(nbttagcompound2); + } + } + nbttagcompound.setTag(inventory.getInventoryName(), nbttaglist); + } } diff --git a/src/main/java/forestry/core/utils/ItemStackUtil.java b/src/main/java/forestry/core/utils/ItemStackUtil.java index 969880030..75b21f987 100644 --- a/src/main/java/forestry/core/utils/ItemStackUtil.java +++ b/src/main/java/forestry/core/utils/ItemStackUtil.java @@ -14,7 +14,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; - import net.minecraft.block.Block; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.Item; @@ -22,343 +21,345 @@ import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; - import net.minecraftforge.oredict.OreDictionary; public abstract class ItemStackUtil { - public static final ItemStack[] EMPTY_STACK_ARRAY = new ItemStack[0]; + public static final ItemStack[] EMPTY_STACK_ARRAY = new ItemStack[0]; - /** - * Compares item id, damage and NBT. Accepts wildcard damage. - */ - public static boolean isIdenticalItem(ItemStack lhs, ItemStack rhs) { - if (lhs == rhs) { - return true; - } + /** + * Compares item id, damage and NBT. Accepts wildcard damage. + */ + public static boolean isIdenticalItem(ItemStack lhs, ItemStack rhs) { + if (lhs == rhs) { + return true; + } - if (lhs == null || rhs == null) { - return false; - } + if (lhs == null || rhs == null) { + return false; + } - if (lhs.getItem() != rhs.getItem()) { - return false; - } + if (lhs.getItem() != rhs.getItem()) { + return false; + } - if (lhs.getItemDamage() != OreDictionary.WILDCARD_VALUE) { - if (lhs.getItemDamage() != rhs.getItemDamage()) { - return false; - } - } + if (lhs.getItemDamage() != OreDictionary.WILDCARD_VALUE) { + if (lhs.getItemDamage() != rhs.getItemDamage()) { + return false; + } + } - return ItemStack.areItemStackTagsEqual(lhs, rhs); - } + return ItemStack.areItemStackTagsEqual(lhs, rhs); + } - /** - * Merges the giving stack into the receiving stack as far as possible - */ - public static void mergeStacks(ItemStack giver, ItemStack receptor) { - if (receptor.stackSize >= 64) { - return; - } + /** + * Merges the giving stack into the receiving stack as far as possible + */ + public static void mergeStacks(ItemStack giver, ItemStack receptor) { + if (receptor.stackSize >= 64) { + return; + } - if (!receptor.isItemEqual(giver)) { - return; - } + if (!receptor.isItemEqual(giver)) { + return; + } - if (giver.stackSize <= (receptor.getMaxStackSize() - receptor.stackSize)) { - receptor.stackSize += giver.stackSize; - giver.stackSize = 0; - return; - } + if (giver.stackSize <= (receptor.getMaxStackSize() - receptor.stackSize)) { + receptor.stackSize += giver.stackSize; + giver.stackSize = 0; + return; + } - ItemStack temp = giver.splitStack(receptor.getMaxStackSize() - receptor.stackSize); - receptor.stackSize += temp.stackSize; - temp.stackSize = 0; - } + ItemStack temp = giver.splitStack(receptor.getMaxStackSize() - receptor.stackSize); + receptor.stackSize += temp.stackSize; + temp.stackSize = 0; + } - /** - * Creates a split stack of the specified amount, preserving NBT data, - * without decreasing the source stack. - */ - public static ItemStack createSplitStack(ItemStack stack, int amount) { - ItemStack split = new ItemStack(stack.getItem(), amount, stack.getItemDamage()); - if (stack.getTagCompound() != null) { - NBTTagCompound nbttagcompound = (NBTTagCompound) stack.getTagCompound().copy(); - split.setTagCompound(nbttagcompound); - } - return split; - } + /** + * Creates a split stack of the specified amount, preserving NBT data, + * without decreasing the source stack. + */ + public static ItemStack createSplitStack(ItemStack stack, int amount) { + ItemStack split = new ItemStack(stack.getItem(), amount, stack.getItemDamage()); + if (stack.getTagCompound() != null) { + NBTTagCompound nbttagcompound = + (NBTTagCompound) stack.getTagCompound().copy(); + split.setTagCompound(nbttagcompound); + } + return split; + } - /** - */ - public static ItemStack[] condenseStacks(ItemStack[] stacks) { - List condensed = new ArrayList<>(); + /** + */ + public static ItemStack[] condenseStacks(ItemStack[] stacks) { + List condensed = new ArrayList<>(); - for (ItemStack stack : stacks) { - if (stack == null) { - continue; - } - if (stack.stackSize <= 0) { - continue; - } + for (ItemStack stack : stacks) { + if (stack == null) { + continue; + } + if (stack.stackSize <= 0) { + continue; + } - boolean matched = false; - for (ItemStack cached : condensed) { - if ((cached.isItemEqual(stack) && ItemStack.areItemStackTagsEqual(cached, stack))) { - cached.stackSize += stack.stackSize; - matched = true; - } - } + boolean matched = false; + for (ItemStack cached : condensed) { + if ((cached.isItemEqual(stack) && ItemStack.areItemStackTagsEqual(cached, stack))) { + cached.stackSize += stack.stackSize; + matched = true; + } + } - if (!matched) { - ItemStack cached = stack.copy(); - condensed.add(cached); - } + if (!matched) { + ItemStack cached = stack.copy(); + condensed.add(cached); + } + } - } + return condensed.toArray(new ItemStack[condensed.size()]); + } - return condensed.toArray(new ItemStack[condensed.size()]); - } + public static boolean containsItemStack(Iterable list, ItemStack itemStack) { + for (ItemStack listStack : list) { + if (isIdenticalItem(listStack, itemStack)) { + return true; + } + } + return false; + } - public static boolean containsItemStack(Iterable list, ItemStack itemStack) { - for (ItemStack listStack : list) { - if (isIdenticalItem(listStack, itemStack)) { - return true; - } - } - return false; - } + /** + * Counts how many full sets are contained in the passed stock + */ + public static int containsSets(ItemStack[] set, ItemStack[] stock) { + return containsSets(set, stock, false, false); + } - /** - * Counts how many full sets are contained in the passed stock - */ - public static int containsSets(ItemStack[] set, ItemStack[] stock) { - return containsSets(set, stock, false, false); - } + /** + * Counts how many full sets are contained in the passed stock + */ + public static int containsSets(ItemStack[] set, ItemStack[] stock, boolean oreDictionary, boolean craftingTools) { + return containsSets(set, stock, oreDictionary, craftingTools, false); + } - /** - * Counts how many full sets are contained in the passed stock - */ - public static int containsSets(ItemStack[] set, ItemStack[] stock, boolean oreDictionary, boolean craftingTools) { - return containsSets(set, stock, oreDictionary, craftingTools, false); - } + /** + * Counts how many full sets are contained in the passed stock + */ + public static int containsSets( + ItemStack[] set, ItemStack[] stock, boolean oreDictionary, boolean craftingTools, boolean matchTags) { + int totalSets = 0; - /** - * Counts how many full sets are contained in the passed stock - */ - public static int containsSets(ItemStack[] set, ItemStack[] stock, boolean oreDictionary, boolean craftingTools, boolean matchTags) { - int totalSets = 0; + ItemStack[] condensedRequired = ItemStackUtil.condenseStacks(set); + ItemStack[] condensedOffered = ItemStackUtil.condenseStacks(stock); - ItemStack[] condensedRequired = ItemStackUtil.condenseStacks(set); - ItemStack[] condensedOffered = ItemStackUtil.condenseStacks(stock); + for (ItemStack req : condensedRequired) { - for (ItemStack req : condensedRequired) { + int reqCount = 0; + for (ItemStack offer : condensedOffered) { + if (isCraftingEquivalent(req, offer, oreDictionary, craftingTools) + && (!matchTags || ItemStack.areItemStackTagsEqual(req, offer))) { + int stackCount = (int) Math.floor((float) offer.stackSize / (float) req.stackSize); + reqCount = Math.max(reqCount, stackCount); + } + } - int reqCount = 0; - for (ItemStack offer : condensedOffered) { - if (isCraftingEquivalent(req, offer, oreDictionary, craftingTools) && (!matchTags || ItemStack.areItemStackTagsEqual(req, offer))) { - int stackCount = (int) Math.floor( (float) offer.stackSize / (float) req.stackSize); - reqCount = Math.max(reqCount, stackCount); - } - } + if (reqCount == 0) { + return 0; + } else if (totalSets == 0) { + totalSets = reqCount; + } else if (totalSets > reqCount) { + totalSets = reqCount; + } + } - if (reqCount == 0) { - return 0; - } else if (totalSets == 0) { - totalSets = reqCount; - } else if (totalSets > reqCount) { - totalSets = reqCount; - } - } + return totalSets; + } - return totalSets; - } + public static boolean equalSets(ItemStack[] set1, ItemStack[] set2) { + if (set1 == set2) { + return true; + } - public static boolean equalSets(ItemStack[] set1, ItemStack[] set2) { - if (set1 == set2) { - return true; - } + if (set1 == null || set2 == null) { + return false; + } - if (set1 == null || set2 == null) { - return false; - } + if (set1.length != set2.length) { + return false; + } - if (set1.length != set2.length) { - return false; - } + for (int i = 0; i < set1.length; i++) { + if (!isIdenticalItem(set1[i], set2[i])) { + return false; + } + } - for (int i = 0; i < set1.length; i++) { - if (!isIdenticalItem(set1[i], set2[i])) { - return false; - } - } + return true; + } - return true; - } + /** + * Compare two item stacks for crafting equivalency without oreDictionary or craftingTools + */ + public static boolean isCraftingEquivalent(ItemStack base, ItemStack comparison) { + if (base == null || comparison == null) { + return false; + } - /** - * Compare two item stacks for crafting equivalency without oreDictionary or craftingTools - */ - public static boolean isCraftingEquivalent(ItemStack base, ItemStack comparison) { - if (base == null || comparison == null) { - return false; - } + if (base.getItem() != comparison.getItem()) { + return false; + } - if (base.getItem() != comparison.getItem()) { - return false; - } + if (base.getItemDamage() != OreDictionary.WILDCARD_VALUE) { + if (base.getItemDamage() != comparison.getItemDamage()) { + return false; + } + } - if (base.getItemDamage() != OreDictionary.WILDCARD_VALUE) { - if (base.getItemDamage() != comparison.getItemDamage()) { - return false; - } - } + // When the base stackTagCompound is null or empty, treat it as a wildcard for crafting + if (base.stackTagCompound == null || base.stackTagCompound.hasNoTags()) { + return true; + } else { + return ItemStack.areItemStackTagsEqual(base, comparison); + } + } - // When the base stackTagCompound is null or empty, treat it as a wildcard for crafting - if (base.stackTagCompound == null || base.stackTagCompound.hasNoTags()) { - return true; - } else { - return ItemStack.areItemStackTagsEqual(base, comparison); - } - } + /** + * Compare two item stacks for crafting equivalency. + */ + public static boolean isCraftingEquivalent( + ItemStack base, ItemStack comparison, boolean oreDictionary, boolean craftingTools) { + if (isCraftingEquivalent(base, comparison)) { + return true; + } - /** - * Compare two item stacks for crafting equivalency. - */ - public static boolean isCraftingEquivalent(ItemStack base, ItemStack comparison, boolean oreDictionary, boolean craftingTools) { - if (isCraftingEquivalent(base, comparison)) { - return true; - } + if (base == null || comparison == null) { + return false; + } - if (base == null || comparison == null) { - return false; - } + if (craftingTools && isCraftingToolEquivalent(base, comparison)) { + return true; + } - if (craftingTools && isCraftingToolEquivalent(base, comparison)) { - return true; - } + if (base.hasTagCompound() && !base.stackTagCompound.hasNoTags()) { + if (!ItemStack.areItemStacksEqual(base, comparison)) { + return false; + } + } - if (base.hasTagCompound() && !base.stackTagCompound.hasNoTags()) { - if (!ItemStack.areItemStacksEqual(base, comparison)) { - return false; - } - } + if (oreDictionary) { + int[] idsBase = OreDictionary.getOreIDs(base); + Arrays.sort(idsBase); + int[] idsComp = OreDictionary.getOreIDs(comparison); + Arrays.sort(idsComp); - if (oreDictionary) { - int[] idsBase = OreDictionary.getOreIDs(base); - Arrays.sort(idsBase); - int[] idsComp = OreDictionary.getOreIDs(comparison); - Arrays.sort(idsComp); + // check if the sorted arrays "idsBase" and "idsComp" have any ID in common. + int iBase = 0; + int iComp = 0; + while (iBase < idsBase.length && iComp < idsComp.length) { + if (idsBase[iBase] < idsComp[iComp]) { + iBase++; + } else if (idsBase[iBase] > idsComp[iComp]) { + iComp++; + } else { + return true; + } + } + } - // check if the sorted arrays "idsBase" and "idsComp" have any ID in common. - int iBase = 0; - int iComp = 0; - while (iBase < idsBase.length && iComp < idsComp.length) { - if (idsBase[iBase] < idsComp[iComp]) { - iBase++; - } else if (idsBase[iBase] > idsComp[iComp]) { - iComp++; - } else { - return true; - } - } - } + return false; + } - return false; - } + public static boolean isCraftingToolEquivalent(ItemStack base, ItemStack comparison) { + if (base == null || comparison == null) { + return false; + } - public static boolean isCraftingToolEquivalent(ItemStack base, ItemStack comparison) { - if (base == null || comparison == null) { - return false; - } + Item baseItem = base.getItem(); + if (baseItem.doesContainerItemLeaveCraftingGrid(base)) { + return false; + } - Item baseItem = base.getItem(); - if (baseItem.doesContainerItemLeaveCraftingGrid(base)) { - return false; - } + if (baseItem != comparison.getItem()) { + return false; + } - if (baseItem != comparison.getItem()) { - return false; - } + if (base.stackTagCompound == null || base.stackTagCompound.hasNoTags()) { + // tool uses meta for damage + return true; + } else { + // tool uses NBT for damage + if (base.getItemDamage() == OreDictionary.WILDCARD_VALUE) { + return true; + } + return base.getItemDamage() == comparison.getItemDamage(); + } + } - if (base.stackTagCompound == null || base.stackTagCompound.hasNoTags()) { - // tool uses meta for damage - return true; - } else { - // tool uses NBT for damage - if (base.getItemDamage() == OreDictionary.WILDCARD_VALUE) { - return true; - } - return base.getItemDamage() == comparison.getItemDamage(); - } - } + public static void dropItemStackAsEntity(ItemStack items, World world, double x, double y, double z) { + dropItemStackAsEntity(items, world, x, y, z, 10); + } - public static void dropItemStackAsEntity(ItemStack items, World world, double x, double y, double z) { - dropItemStackAsEntity(items, world, x, y, z, 10); - } + public static void dropItemStackAsEntity( + ItemStack items, World world, double x, double y, double z, int delayForPickup) { + if (items.stackSize <= 0 || world.isRemote) { + return; + } - public static void dropItemStackAsEntity(ItemStack items, World world, double x, double y, double z, int delayForPickup) { - if (items.stackSize <= 0 || world.isRemote) { - return; - } + float f1 = 0.7F; + double d = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; + double d1 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; + double d2 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; + EntityItem entityitem = new EntityItem(world, x + d, y + d1, z + d2, items); + entityitem.delayBeforeCanPickup = delayForPickup; - float f1 = 0.7F; - double d = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; - double d1 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; - double d2 = (world.rand.nextFloat() * f1) + (1.0F - f1) * 0.5D; - EntityItem entityitem = new EntityItem(world, x + d, y + d1, z + d2, items); - entityitem.delayBeforeCanPickup = delayForPickup; + world.spawnEntityInWorld(entityitem); + } - world.spawnEntityInWorld(entityitem); - } + public static ItemStack copyWithRandomSize(ItemStack template, int max, Random rand) { + int size = rand.nextInt(max); + ItemStack created = template.copy(); + created.stackSize = size <= 0 ? 1 : Math.min(size, created.getMaxStackSize()); + return created; + } - public static ItemStack copyWithRandomSize(ItemStack template, int max, Random rand) { - int size = rand.nextInt(max); - ItemStack created = template.copy(); - created.stackSize = size <= 0 ? 1 : Math.min(size, created.getMaxStackSize()); - return created; - } + public static Block getBlock(ItemStack stack) { + Item item = stack.getItem(); - public static Block getBlock(ItemStack stack) { - Item item = stack.getItem(); + if (item instanceof ItemBlock) { + return ((ItemBlock) item).field_150939_a; + } else { + return null; + } + } - if (item instanceof ItemBlock) { - return ((ItemBlock) item).field_150939_a; - } else { - return null; - } - } + public static boolean equals(Block block, ItemStack stack) { + return block == getBlock(stack); + } - public static boolean equals(Block block, ItemStack stack) { - return block == getBlock(stack); - } + public static boolean equals(Block block, int meta, ItemStack stack) { + return block == getBlock(stack) && meta == stack.getItemDamage(); + } - public static boolean equals(Block block, int meta, ItemStack stack) { - return block == getBlock(stack) && meta == stack.getItemDamage(); - } + public static List parseItemStackStrings(String[] itemStackStrings, int missingMetaValue) { + List stacks = Stack.parseStackStrings(itemStackStrings, missingMetaValue); + return getItemStacks(stacks); + } - public static List parseItemStackStrings(String[] itemStackStrings, int missingMetaValue) { - List stacks = Stack.parseStackStrings(itemStackStrings, missingMetaValue); - return getItemStacks(stacks); - } - - public static List parseItemStackStrings(String itemStackStrings, int missingMetaValue) { - List stacks = Stack.parseStackStrings(itemStackStrings, missingMetaValue); - return getItemStacks(stacks); - } - - private static List getItemStacks(List stacks) { - List itemStacks = new ArrayList<>(stacks.size()); - for (Stack stack : stacks) { - Item item = stack.getItem(); - if (item != null) { - int meta = stack.getMeta(); - ItemStack itemStack = new ItemStack(item, 1, meta); - itemStacks.add(itemStack); - } - } - return itemStacks; - } + public static List parseItemStackStrings(String itemStackStrings, int missingMetaValue) { + List stacks = Stack.parseStackStrings(itemStackStrings, missingMetaValue); + return getItemStacks(stacks); + } + private static List getItemStacks(List stacks) { + List itemStacks = new ArrayList<>(stacks.size()); + for (Stack stack : stacks) { + Item item = stack.getItem(); + if (item != null) { + int meta = stack.getMeta(); + ItemStack itemStack = new ItemStack(item, 1, meta); + itemStacks.add(itemStack); + } + } + return itemStacks; + } } diff --git a/src/main/java/forestry/core/utils/Log.java b/src/main/java/forestry/core/utils/Log.java index d6114e8ac..ab3793e8b 100644 --- a/src/main/java/forestry/core/utils/Log.java +++ b/src/main/java/forestry/core/utils/Log.java @@ -10,130 +10,132 @@ ******************************************************************************/ package forestry.core.utils; +import forestry.core.config.Constants; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.message.MessageFormatMessage; -import forestry.core.config.Constants; - public abstract class Log { - /* FINEST */ - public static void finest(String message) { - log(Level.TRACE, message); - } + /* FINEST */ + public static void finest(String message) { + log(Level.TRACE, message); + } - public static void finest(String message, Object param) { - log(Level.TRACE, message, param); - } + public static void finest(String message, Object param) { + log(Level.TRACE, message, param); + } - public static void finest(String message, Object... params) { - log(Level.TRACE, message, params); - } + public static void finest(String message, Object... params) { + log(Level.TRACE, message, params); + } - /* FINER */ - public static void finer(String message) { - log(Level.TRACE, message); - } + /* FINER */ + public static void finer(String message) { + log(Level.TRACE, message); + } - public static void finer(String message, Object param) { - log(Level.TRACE, message, param); - } + public static void finer(String message, Object param) { + log(Level.TRACE, message, param); + } - public static void finer(String message, Object... params) { - log(Level.TRACE, message, params); - } + public static void finer(String message, Object... params) { + log(Level.TRACE, message, params); + } - /* FINE */ - public static void fine(String message) { - log(Level.DEBUG, message); - } + /* FINE */ + public static void fine(String message) { + log(Level.DEBUG, message); + } - public static void fine(String message, Object param) { - log(Level.DEBUG, message, param); - } + public static void fine(String message, Object param) { + log(Level.DEBUG, message, param); + } - public static void fine(String message, Object... params) { - log(Level.DEBUG, message, params); - } + public static void fine(String message, Object... params) { + log(Level.DEBUG, message, params); + } - /* INFO */ - public static void info(String message) { - log(Level.INFO, message); - } + /* INFO */ + public static void info(String message) { + log(Level.INFO, message); + } - public static void info(String message, Object param) { - log(Level.INFO, message, param); - } + public static void info(String message, Object param) { + log(Level.INFO, message, param); + } - public static void info(String message, Object... params) { - log(Level.INFO, message, params); - } + public static void info(String message, Object... params) { + log(Level.INFO, message, params); + } - /* WARNING */ - public static void warning(String message) { - log(Level.WARN, message); - } + /* WARNING */ + public static void warning(String message) { + log(Level.WARN, message); + } - public static void warning(String message, Object param) { - log(Level.WARN, message, param); - } + public static void warning(String message, Object param) { + log(Level.WARN, message, param); + } - public static void warning(String message, Object... params) { - log(Level.WARN, message, params); - } + public static void warning(String message, Object... params) { + log(Level.WARN, message, params); + } - /* SEVERE */ - public static void severe(String message) { - log(Level.FATAL, message); - } + /* SEVERE */ + public static void severe(String message) { + log(Level.FATAL, message); + } - public static void severe(String message, Object param) { - log(Level.FATAL, message, param); - } + public static void severe(String message, Object param) { + log(Level.FATAL, message, param); + } - public static void severe(String message, Object... params) { - log(Level.FATAL, message, params); - } + public static void severe(String message, Object... params) { + log(Level.FATAL, message, params); + } - /* GENERIC */ - private static void log(Level logLevel, String message) { - LogManager.getLogger(Constants.MOD).log(logLevel, message); - } + /* GENERIC */ + private static void log(Level logLevel, String message) { + LogManager.getLogger(Constants.MOD).log(logLevel, message); + } - private static void log(Level logLevel, String message, Object... params) { - LogManager.getLogger(Constants.MOD).log(logLevel, new MessageFormatMessage(String.format(message, params), params)); - } + private static void log(Level logLevel, String message, Object... params) { + LogManager.getLogger(Constants.MOD) + .log(logLevel, new MessageFormatMessage(String.format(message, params), params)); + } - /* EXCEPTIONS */ - public static void logThrowable(String msg, Throwable error, Object... args) { - logThrowable(Level.ERROR, msg, 3, error, args); - } + /* EXCEPTIONS */ + public static void logThrowable(String msg, Throwable error, Object... args) { + logThrowable(Level.ERROR, msg, 3, error, args); + } - public static void logThrowable(String msg, int lines, Throwable error, Object... args) { - logThrowable(Level.ERROR, msg, lines, error, args); - } + public static void logThrowable(String msg, int lines, Throwable error, Object... args) { + logThrowable(Level.ERROR, msg, lines, error, args); + } - public static void logThrowable(Level level, String msg, int lines, Throwable error, Object... args) { - StackTraceElement[] oldtrace = error.getStackTrace(); - if (lines < oldtrace.length) { - StackTraceElement[] newtrace = new StackTraceElement[lines]; - System.arraycopy(oldtrace, 0, newtrace, 0, newtrace.length); - error.setStackTrace(newtrace); - } - LogManager.getLogger(Constants.MOD).log(level, new MessageFormatMessage(msg, args), error); - } + public static void logThrowable(Level level, String msg, int lines, Throwable error, Object... args) { + StackTraceElement[] oldtrace = error.getStackTrace(); + if (lines < oldtrace.length) { + StackTraceElement[] newtrace = new StackTraceElement[lines]; + System.arraycopy(oldtrace, 0, newtrace, 0, newtrace.length); + error.setStackTrace(newtrace); + } + LogManager.getLogger(Constants.MOD).log(level, new MessageFormatMessage(msg, args), error); + } - public static void logErrorAPI(String mod, Throwable error, Class classFile) { - StringBuilder msg = new StringBuilder(mod); - msg.append(" API error, please update your mods. Error: ").append(error); - logThrowable(Level.ERROR, msg.toString(), 2, error); - - if (classFile != null) { - msg = new StringBuilder(mod); - msg.append(" API error: ").append(classFile.getSimpleName()).append(" is loaded from ").append(classFile.getProtectionDomain().getCodeSource().getLocation()); - log(Level.ERROR, msg.toString()); - } - } + public static void logErrorAPI(String mod, Throwable error, Class classFile) { + StringBuilder msg = new StringBuilder(mod); + msg.append(" API error, please update your mods. Error: ").append(error); + logThrowable(Level.ERROR, msg.toString(), 2, error); + if (classFile != null) { + msg = new StringBuilder(mod); + msg.append(" API error: ") + .append(classFile.getSimpleName()) + .append(" is loaded from ") + .append(classFile.getProtectionDomain().getCodeSource().getLocation()); + log(Level.ERROR, msg.toString()); + } + } } diff --git a/src/main/java/forestry/core/utils/ModUtil.java b/src/main/java/forestry/core/utils/ModUtil.java index 1fc279a44..ec09985ad 100644 --- a/src/main/java/forestry/core/utils/ModUtil.java +++ b/src/main/java/forestry/core/utils/ModUtil.java @@ -1,75 +1,75 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils; - -import cpw.mods.fml.common.API; -import cpw.mods.fml.common.Loader; -import cpw.mods.fml.common.ModContainer; -import cpw.mods.fml.common.versioning.ArtifactVersion; -import cpw.mods.fml.common.versioning.DefaultArtifactVersion; -import cpw.mods.fml.common.versioning.VersionParser; -import cpw.mods.fml.common.versioning.VersionRange; - -public abstract class ModUtil { - public static boolean isModLoaded(String modname) { - return Loader.isModLoaded(modname); - } - - public static boolean isModLoaded(String modname, String versionRangeString) { - if (!isModLoaded(modname)) { - return false; - } - - if (versionRangeString != null) { - ModContainer mod = Loader.instance().getIndexedModList().get(modname); - ArtifactVersion modVersion = mod.getProcessedVersion(); - - VersionRange versionRange = VersionParser.parseRange(versionRangeString); - DefaultArtifactVersion requiredVersion = new DefaultArtifactVersion(modname, versionRange); - - return requiredVersion.containsVersion(modVersion); - } - - return true; - } - - public static boolean isAPILoaded(String apiName) { - return isAPILoaded(apiName, null); - } - - public static boolean isAPILoaded(String apiName, String versionRangeString) { - Package apiPackage = Package.getPackage(apiName); - if (apiPackage == null) { - return false; - } - - API apiAnnotation = apiPackage.getAnnotation(API.class); - if (apiAnnotation == null) { - return false; - } - - if (versionRangeString != null) { - String apiVersionString = apiAnnotation.apiVersion(); - if (apiVersionString == null) { - return false; - } - - VersionRange versionRange = VersionParser.parseRange(versionRangeString); - - DefaultArtifactVersion givenVersion = new DefaultArtifactVersion(apiName, apiVersionString); - DefaultArtifactVersion requiredVersion = new DefaultArtifactVersion(apiName, versionRange); - - return requiredVersion.containsVersion(givenVersion); - } - - return true; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.utils; + +import cpw.mods.fml.common.API; +import cpw.mods.fml.common.Loader; +import cpw.mods.fml.common.ModContainer; +import cpw.mods.fml.common.versioning.ArtifactVersion; +import cpw.mods.fml.common.versioning.DefaultArtifactVersion; +import cpw.mods.fml.common.versioning.VersionParser; +import cpw.mods.fml.common.versioning.VersionRange; + +public abstract class ModUtil { + public static boolean isModLoaded(String modname) { + return Loader.isModLoaded(modname); + } + + public static boolean isModLoaded(String modname, String versionRangeString) { + if (!isModLoaded(modname)) { + return false; + } + + if (versionRangeString != null) { + ModContainer mod = Loader.instance().getIndexedModList().get(modname); + ArtifactVersion modVersion = mod.getProcessedVersion(); + + VersionRange versionRange = VersionParser.parseRange(versionRangeString); + DefaultArtifactVersion requiredVersion = new DefaultArtifactVersion(modname, versionRange); + + return requiredVersion.containsVersion(modVersion); + } + + return true; + } + + public static boolean isAPILoaded(String apiName) { + return isAPILoaded(apiName, null); + } + + public static boolean isAPILoaded(String apiName, String versionRangeString) { + Package apiPackage = Package.getPackage(apiName); + if (apiPackage == null) { + return false; + } + + API apiAnnotation = apiPackage.getAnnotation(API.class); + if (apiAnnotation == null) { + return false; + } + + if (versionRangeString != null) { + String apiVersionString = apiAnnotation.apiVersion(); + if (apiVersionString == null) { + return false; + } + + VersionRange versionRange = VersionParser.parseRange(versionRangeString); + + DefaultArtifactVersion givenVersion = new DefaultArtifactVersion(apiName, apiVersionString); + DefaultArtifactVersion requiredVersion = new DefaultArtifactVersion(apiName, versionRange); + + return requiredVersion.containsVersion(givenVersion); + } + + return true; + } +} diff --git a/src/main/java/forestry/core/utils/NBTUtil.java b/src/main/java/forestry/core/utils/NBTUtil.java index f5b1c267e..ad4b4ce73 100644 --- a/src/main/java/forestry/core/utils/NBTUtil.java +++ b/src/main/java/forestry/core/utils/NBTUtil.java @@ -11,10 +11,9 @@ package forestry.core.utils; import com.google.common.collect.ForwardingList; - +import cpw.mods.fml.common.ObfuscationReflectionHelper; import java.util.ArrayList; import java.util.List; - import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagByte; import net.minecraft.nbt.NBTTagByteArray; @@ -29,64 +28,59 @@ import net.minecraft.nbt.NBTTagLong; import net.minecraft.nbt.NBTTagShort; import net.minecraft.nbt.NBTTagString; -import cpw.mods.fml.common.ObfuscationReflectionHelper; - /** * @author CovertJaguar */ public abstract class NBTUtil { - public enum EnumNBTType { + public enum EnumNBTType { + END(NBTTagEnd.class), + BYTE(NBTTagByte.class), + SHORT(NBTTagShort.class), + INT(NBTTagInt.class), + LONG(NBTTagLong.class), + FLOAT(NBTTagFloat.class), + DOUBLE(NBTTagDouble.class), + BYTE_ARRAY(NBTTagByteArray.class), + STRING(NBTTagString.class), + LIST(NBTTagList.class), + COMPOUND(NBTTagCompound.class), + INT_ARRAY(NBTTagIntArray.class); + public static final EnumNBTType[] VALUES = values(); + public final Class classObject; - END(NBTTagEnd.class), - BYTE(NBTTagByte.class), - SHORT(NBTTagShort.class), - INT(NBTTagInt.class), - LONG(NBTTagLong.class), - FLOAT(NBTTagFloat.class), - DOUBLE(NBTTagDouble.class), - BYTE_ARRAY(NBTTagByteArray.class), - STRING(NBTTagString.class), - LIST(NBTTagList.class), - COMPOUND(NBTTagCompound.class), - INT_ARRAY(NBTTagIntArray.class); - public static final EnumNBTType[] VALUES = values(); - public final Class classObject; + EnumNBTType(Class c) { + this.classObject = c; + } - EnumNBTType(Class c) { - this.classObject = c; - } + public static EnumNBTType fromClass(Class c) { + for (EnumNBTType type : VALUES) { + if (type.classObject == c) { + return type; + } + } + return null; + } + } - public static EnumNBTType fromClass(Class c) { - for (EnumNBTType type : VALUES) { - if (type.classObject == c) { - return type; - } - } - return null; - } + public static NBTList getNBTList(NBTTagCompound nbt, String tag, EnumNBTType type) { + NBTTagList nbtList = nbt.getTagList(tag, type.ordinal()); + return new NBTList<>(nbtList); + } - } + public static class NBTList extends ForwardingList { - public static NBTList getNBTList(NBTTagCompound nbt, String tag, EnumNBTType type) { - NBTTagList nbtList = nbt.getTagList(tag, type.ordinal()); - return new NBTList<>(nbtList); - } + private final ArrayList backingList; + private final NBTTagList nbtList; - public static class NBTList extends ForwardingList { + public NBTList(NBTTagList nbtList) { + this.nbtList = nbtList; + backingList = ObfuscationReflectionHelper.getPrivateValue(NBTTagList.class, nbtList, 0); + } - private final ArrayList backingList; - private final NBTTagList nbtList; - - public NBTList(NBTTagList nbtList) { - this.nbtList = nbtList; - backingList = ObfuscationReflectionHelper.getPrivateValue(NBTTagList.class, nbtList, 0); - } - - @Override - protected List delegate() { - return backingList; - } - - } + @Override + protected List delegate() { + return backingList; + } + } } diff --git a/src/main/java/forestry/core/utils/PlayerUtil.java b/src/main/java/forestry/core/utils/PlayerUtil.java index 96868f11a..bbbaccd5d 100644 --- a/src/main/java/forestry/core/utils/PlayerUtil.java +++ b/src/main/java/forestry/core/utils/PlayerUtil.java @@ -10,68 +10,64 @@ ******************************************************************************/ package forestry.core.utils; +import com.mojang.authlib.GameProfile; +import forestry.core.access.IOwnable; import java.util.UUID; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraft.world.WorldServer; - -import com.mojang.authlib.GameProfile; - import net.minecraftforge.common.util.FakePlayerFactory; -import forestry.core.access.IOwnable; - public abstract class PlayerUtil { - //TODO: use null everywhere instead of an emptyUUID - private static final UUID emptyUUID = new UUID(0, 0); + // TODO: use null everywhere instead of an emptyUUID + private static final UUID emptyUUID = new UUID(0, 0); - public static boolean isSameGameProfile(GameProfile player1, GameProfile player2) { - if (player1 == null || player2 == null) { - return false; - } + public static boolean isSameGameProfile(GameProfile player1, GameProfile player2) { + if (player1 == null || player2 == null) { + return false; + } - UUID id1 = player1.getId(); - UUID id2 = player2.getId(); - if (id1 != null && id2 != null && !id1.equals(emptyUUID) && !id2.equals(emptyUUID)) { - return id1.equals(id2); - } + UUID id1 = player1.getId(); + UUID id2 = player2.getId(); + if (id1 != null && id2 != null && !id1.equals(emptyUUID) && !id2.equals(emptyUUID)) { + return id1.equals(id2); + } - return player1.getName() != null && player1.getName().equals(player2.getName()); - } + return player1.getName() != null && player1.getName().equals(player2.getName()); + } - public static String getOwnerName(IOwnable ownable) { - GameProfile profile = ownable.getOwner(); - if (profile == null) { - return StringUtil.localize("gui.derelict"); - } else { - return profile.getName(); - } - } + public static String getOwnerName(IOwnable ownable) { + GameProfile profile = ownable.getOwner(); + if (profile == null) { + return StringUtil.localize("gui.derelict"); + } else { + return profile.getName(); + } + } - /** - * Get a player for a given World and GameProfile. - * If they are not in the World, returns a FakePlayer. - * Do not store references to the return value, to prevent worlds staying in memory. - */ - public static EntityPlayer getPlayer(World world, GameProfile profile) { - if (world == null) { - throw new IllegalArgumentException("World cannot be null"); - } + /** + * Get a player for a given World and GameProfile. + * If they are not in the World, returns a FakePlayer. + * Do not store references to the return value, to prevent worlds staying in memory. + */ + public static EntityPlayer getPlayer(World world, GameProfile profile) { + if (world == null) { + throw new IllegalArgumentException("World cannot be null"); + } - if (profile == null || profile.getName() == null) { - if (world instanceof WorldServer) { - return FakePlayerFactory.getMinecraft((WorldServer) world); - } else { - return null; - } - } - - EntityPlayer player = world.getPlayerEntityByName(profile.getName()); - if (player == null && world instanceof WorldServer) { - player = FakePlayerFactory.get((WorldServer) world, profile); - } - return player; - } + if (profile == null || profile.getName() == null) { + if (world instanceof WorldServer) { + return FakePlayerFactory.getMinecraft((WorldServer) world); + } else { + return null; + } + } + + EntityPlayer player = world.getPlayerEntityByName(profile.getName()); + if (player == null && world instanceof WorldServer) { + player = FakePlayerFactory.get((WorldServer) world, profile); + } + return player; + } } diff --git a/src/main/java/forestry/core/utils/SlotUtil.java b/src/main/java/forestry/core/utils/SlotUtil.java index c3cce6774..6e53032b2 100644 --- a/src/main/java/forestry/core/utils/SlotUtil.java +++ b/src/main/java/forestry/core/utils/SlotUtil.java @@ -1,288 +1,290 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils; - -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Slot; -import net.minecraft.inventory.SlotCrafting; -import net.minecraft.item.ItemStack; - -import forestry.core.gui.slots.SlotForestry; - -public abstract class SlotUtil { - - public static boolean isSlotInRange(int slotIndex, int start, int count) { - return (slotIndex >= start) && (slotIndex < start + count); - } - - public static ItemStack slotClickPhantom(SlotForestry slot, int mouseButton, int modifier, EntityPlayer player) { - ItemStack stack = null; - - ItemStack stackSlot = slot.getStack(); - if (stackSlot != null) { - stack = stackSlot.copy(); - } - - if (mouseButton == 2) { - fillPhantomSlot(slot, null, mouseButton); - } else if (mouseButton == 0 || mouseButton == 1) { - InventoryPlayer playerInv = player.inventory; - - ItemStack stackHeld = playerInv.getItemStack(); - - if (stackSlot == null) { - if (stackHeld != null && slot.isItemValid(stackHeld)) { - fillPhantomSlot(slot, stackHeld, mouseButton); - } - } else if (stackHeld == null) { - adjustPhantomSlot(slot, mouseButton, modifier); - } else if (slot.isItemValid(stackHeld)) { - if (ItemStackUtil.isIdenticalItem(stackSlot, stackHeld)) { - adjustPhantomSlot(slot, mouseButton, modifier); - } else { - fillPhantomSlot(slot, stackHeld, mouseButton); - } - } - } else if (mouseButton == 5) { - InventoryPlayer playerInv = player.inventory; - ItemStack stackHeld = playerInv.getItemStack(); - if (!slot.getHasStack()) { - fillPhantomSlot(slot, stackHeld, mouseButton); - } - } - return stack; - } - - public static ItemStack transferStackInSlot(List inventorySlots, EntityPlayer player, int slotIndex) { - Slot slot = (Slot) inventorySlots.get(slotIndex); - if (slot == null || !slot.getHasStack()) { - return null; - } - - boolean fromCraftingSlot = (slot instanceof SlotCrafting); - - int numSlots = inventorySlots.size(); - ItemStack stackInSlot = slot.getStack(); - ItemStack originalStack = stackInSlot.copy(); - - if (!shiftItemStack(inventorySlots, stackInSlot, slotIndex, numSlots, fromCraftingSlot)) { - return null; - } - - slot.onSlotChange(stackInSlot, originalStack); - if (stackInSlot.stackSize <= 0) { - slot.putStack(null); - } else { - slot.onSlotChanged(); - } - - if (stackInSlot.stackSize == originalStack.stackSize) { - return null; - } - - slot.onPickupFromSlot(player, stackInSlot); - return originalStack; - } - - private static boolean shiftItemStack(List inventorySlots, ItemStack stackInSlot, int slotIndex, int numSlots, boolean fromCraftingSlot) { - if (isInPlayerInventory(slotIndex)) { - if (shiftToMachineInventory(inventorySlots, stackInSlot, numSlots)) { - return true; - } - - if (isInPlayerHotbar(slotIndex)) { - return shiftToPlayerInventoryNoHotbar(inventorySlots, stackInSlot); - } else { - return shiftToHotbar(inventorySlots, stackInSlot); - } - } else { - if (fromCraftingSlot) { - if (shiftToMachineInventory(inventorySlots, stackInSlot, numSlots)) { - return true; - } - } - return shiftToPlayerInventory(inventorySlots, stackInSlot); - } - } - - private static void adjustPhantomSlot(SlotForestry slot, int mouseButton, int modifier) { - if (!slot.canAdjustPhantom()) { - return; - } - ItemStack stackSlot = slot.getStack(); - int stackSize; - if (modifier == 1) { - stackSize = mouseButton == 0 ? (stackSlot.stackSize + 1) / 2 : stackSlot.stackSize * 2; - } else { - stackSize = mouseButton == 0 ? stackSlot.stackSize - 1 : stackSlot.stackSize + 1; - } - - if (stackSize > slot.getSlotStackLimit()) { - stackSize = slot.getSlotStackLimit(); - } - - stackSlot.stackSize = stackSize; - - if (stackSlot.stackSize <= 0) { - stackSlot = null; - } - - slot.putStack(stackSlot); - } - - private static void fillPhantomSlot(SlotForestry slot, ItemStack stackHeld, int mouseButton) { - if (!slot.canAdjustPhantom()) { - return; - } - - if (stackHeld == null) { - slot.putStack(null); - return; - } - - int stackSize = mouseButton == 0 ? stackHeld.stackSize : 1; - if (stackSize > slot.getSlotStackLimit()) { - stackSize = slot.getSlotStackLimit(); - } - ItemStack phantomStack = stackHeld.copy(); - phantomStack.stackSize = stackSize; - - slot.putStack(phantomStack); - } - - private static boolean shiftItemStackToRange(List inventorySlots, ItemStack stackToShift, int start, int count) { - boolean changed = shiftItemStackToRangeMerge(inventorySlots, stackToShift, start, count); - changed |= shiftItemStackToRangeOpenSlots(inventorySlots, stackToShift, start, count); - return changed; - } - - private static boolean shiftItemStackToRangeMerge(List inventorySlots, ItemStack stackToShift, int start, int count) { - if (stackToShift == null || !stackToShift.isStackable() || stackToShift.stackSize <= 0) { - return false; - } - - boolean changed = false; - for (int slotIndex = start; stackToShift.stackSize > 0 && slotIndex < start + count; slotIndex++) { - Slot slot = (Slot) inventorySlots.get(slotIndex); - ItemStack stackInSlot = slot.getStack(); - if (stackInSlot != null && ItemStackUtil.isIdenticalItem(stackInSlot, stackToShift)) { - int resultingStackSize = stackInSlot.stackSize + stackToShift.stackSize; - int max = Math.min(stackToShift.getMaxStackSize(), slot.getSlotStackLimit()); - if (resultingStackSize <= max) { - stackToShift.stackSize = 0; - stackInSlot.stackSize = resultingStackSize; - slot.onSlotChanged(); - changed = true; - } else if (stackInSlot.stackSize < max) { - stackToShift.stackSize -= max - stackInSlot.stackSize; - stackInSlot.stackSize = max; - slot.onSlotChanged(); - changed = true; - } - } - } - return changed; - } - - private static boolean shiftItemStackToRangeOpenSlots(List inventorySlots, ItemStack stackToShift, int start, int count) { - if (stackToShift == null || stackToShift.stackSize <= 0) { - return false; - } - - boolean changed = false; - for (int slotIndex = start; stackToShift.stackSize > 0 && slotIndex < start + count; slotIndex++) { - Slot slot = (Slot) inventorySlots.get(slotIndex); - ItemStack stackInSlot = slot.getStack(); - if (stackInSlot == null) { - int max = Math.min(stackToShift.getMaxStackSize(), slot.getSlotStackLimit()); - stackInSlot = stackToShift.copy(); - stackInSlot.stackSize = Math.min(stackToShift.stackSize, max); - stackToShift.stackSize -= stackInSlot.stackSize; - slot.putStack(stackInSlot); - slot.onSlotChanged(); - changed = true; - } - } - return changed; - } - - private static final int playerInventorySize = 9 * 4; - private static final int playerHotbarSize = 9; - - private static boolean isInPlayerInventory(int slotIndex) { - return slotIndex < playerInventorySize; - } - - private static boolean isInPlayerHotbar(int slotIndex) { - return SlotUtil.isSlotInRange(slotIndex, playerInventorySize - playerHotbarSize, playerInventorySize); - } - - private static boolean shiftToPlayerInventory(List inventorySlots, ItemStack stackInSlot) { - int playerHotbarStart = playerInventorySize - playerHotbarSize; - - // try to merge with existing stacks, hotbar first - boolean shifted = shiftItemStackToRangeMerge(inventorySlots, stackInSlot, playerHotbarStart, playerHotbarSize); - shifted |= shiftItemStackToRangeMerge(inventorySlots, stackInSlot, 0, playerHotbarStart); - - // shift to open slots, hotbar first - shifted |= shiftItemStackToRangeOpenSlots(inventorySlots, stackInSlot, playerHotbarStart, playerHotbarSize); - shifted |= shiftItemStackToRangeOpenSlots(inventorySlots, stackInSlot, 0, playerHotbarStart); - return shifted; - } - - private static boolean shiftToPlayerInventoryNoHotbar(List inventorySlots, ItemStack stackInSlot) { - int playerHotbarStart = playerInventorySize - playerHotbarSize; - return shiftItemStackToRange(inventorySlots, stackInSlot, 0, playerHotbarStart); - } - - private static boolean shiftToHotbar(List inventorySlots, ItemStack stackInSlot) { - int playerHotbarStart = playerInventorySize - playerHotbarSize; - return shiftItemStackToRange(inventorySlots, stackInSlot, playerHotbarStart, playerHotbarSize); - } - - private static boolean shiftToMachineInventory(List inventorySlots, ItemStack stackToShift, int numSlots) { - boolean success = false; - if (stackToShift.isStackable()) { - success = shiftToMachineInventory(inventorySlots, stackToShift, numSlots, true); - } - if (stackToShift.stackSize > 0) { - success |= shiftToMachineInventory(inventorySlots, stackToShift, numSlots, false); - } - return success; - } - - // if mergeOnly = true, don't shift into empty slots. - private static boolean shiftToMachineInventory(List inventorySlots, ItemStack stackToShift, int numSlots, boolean mergeOnly) { - for (int machineIndex = playerInventorySize; machineIndex < numSlots; machineIndex++) { -// System.out.println("SlotUtil::shiftToMachineinventory"); - Slot slot = (Slot) inventorySlots.get(machineIndex); - if (mergeOnly && slot.getStack() == null) { - continue; - } - if (slot instanceof SlotForestry) { - SlotForestry slotForestry = (SlotForestry) slot; - if (!slotForestry.canShift() || slotForestry.isPhantom()) { - continue; - } - } - if (!slot.isItemValid(stackToShift)) { - continue; - } - if (shiftItemStackToRange(inventorySlots, stackToShift, machineIndex, 1)) { - return true; - } - } - return false; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.utils; + +import forestry.core.gui.slots.SlotForestry; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.inventory.SlotCrafting; +import net.minecraft.item.ItemStack; + +public abstract class SlotUtil { + + public static boolean isSlotInRange(int slotIndex, int start, int count) { + return (slotIndex >= start) && (slotIndex < start + count); + } + + public static ItemStack slotClickPhantom(SlotForestry slot, int mouseButton, int modifier, EntityPlayer player) { + ItemStack stack = null; + + ItemStack stackSlot = slot.getStack(); + if (stackSlot != null) { + stack = stackSlot.copy(); + } + + if (mouseButton == 2) { + fillPhantomSlot(slot, null, mouseButton); + } else if (mouseButton == 0 || mouseButton == 1) { + InventoryPlayer playerInv = player.inventory; + + ItemStack stackHeld = playerInv.getItemStack(); + + if (stackSlot == null) { + if (stackHeld != null && slot.isItemValid(stackHeld)) { + fillPhantomSlot(slot, stackHeld, mouseButton); + } + } else if (stackHeld == null) { + adjustPhantomSlot(slot, mouseButton, modifier); + } else if (slot.isItemValid(stackHeld)) { + if (ItemStackUtil.isIdenticalItem(stackSlot, stackHeld)) { + adjustPhantomSlot(slot, mouseButton, modifier); + } else { + fillPhantomSlot(slot, stackHeld, mouseButton); + } + } + } else if (mouseButton == 5) { + InventoryPlayer playerInv = player.inventory; + ItemStack stackHeld = playerInv.getItemStack(); + if (!slot.getHasStack()) { + fillPhantomSlot(slot, stackHeld, mouseButton); + } + } + return stack; + } + + public static ItemStack transferStackInSlot(List inventorySlots, EntityPlayer player, int slotIndex) { + Slot slot = (Slot) inventorySlots.get(slotIndex); + if (slot == null || !slot.getHasStack()) { + return null; + } + + boolean fromCraftingSlot = (slot instanceof SlotCrafting); + + int numSlots = inventorySlots.size(); + ItemStack stackInSlot = slot.getStack(); + ItemStack originalStack = stackInSlot.copy(); + + if (!shiftItemStack(inventorySlots, stackInSlot, slotIndex, numSlots, fromCraftingSlot)) { + return null; + } + + slot.onSlotChange(stackInSlot, originalStack); + if (stackInSlot.stackSize <= 0) { + slot.putStack(null); + } else { + slot.onSlotChanged(); + } + + if (stackInSlot.stackSize == originalStack.stackSize) { + return null; + } + + slot.onPickupFromSlot(player, stackInSlot); + return originalStack; + } + + private static boolean shiftItemStack( + List inventorySlots, ItemStack stackInSlot, int slotIndex, int numSlots, boolean fromCraftingSlot) { + if (isInPlayerInventory(slotIndex)) { + if (shiftToMachineInventory(inventorySlots, stackInSlot, numSlots)) { + return true; + } + + if (isInPlayerHotbar(slotIndex)) { + return shiftToPlayerInventoryNoHotbar(inventorySlots, stackInSlot); + } else { + return shiftToHotbar(inventorySlots, stackInSlot); + } + } else { + if (fromCraftingSlot) { + if (shiftToMachineInventory(inventorySlots, stackInSlot, numSlots)) { + return true; + } + } + return shiftToPlayerInventory(inventorySlots, stackInSlot); + } + } + + private static void adjustPhantomSlot(SlotForestry slot, int mouseButton, int modifier) { + if (!slot.canAdjustPhantom()) { + return; + } + ItemStack stackSlot = slot.getStack(); + int stackSize; + if (modifier == 1) { + stackSize = mouseButton == 0 ? (stackSlot.stackSize + 1) / 2 : stackSlot.stackSize * 2; + } else { + stackSize = mouseButton == 0 ? stackSlot.stackSize - 1 : stackSlot.stackSize + 1; + } + + if (stackSize > slot.getSlotStackLimit()) { + stackSize = slot.getSlotStackLimit(); + } + + stackSlot.stackSize = stackSize; + + if (stackSlot.stackSize <= 0) { + stackSlot = null; + } + + slot.putStack(stackSlot); + } + + private static void fillPhantomSlot(SlotForestry slot, ItemStack stackHeld, int mouseButton) { + if (!slot.canAdjustPhantom()) { + return; + } + + if (stackHeld == null) { + slot.putStack(null); + return; + } + + int stackSize = mouseButton == 0 ? stackHeld.stackSize : 1; + if (stackSize > slot.getSlotStackLimit()) { + stackSize = slot.getSlotStackLimit(); + } + ItemStack phantomStack = stackHeld.copy(); + phantomStack.stackSize = stackSize; + + slot.putStack(phantomStack); + } + + private static boolean shiftItemStackToRange(List inventorySlots, ItemStack stackToShift, int start, int count) { + boolean changed = shiftItemStackToRangeMerge(inventorySlots, stackToShift, start, count); + changed |= shiftItemStackToRangeOpenSlots(inventorySlots, stackToShift, start, count); + return changed; + } + + private static boolean shiftItemStackToRangeMerge( + List inventorySlots, ItemStack stackToShift, int start, int count) { + if (stackToShift == null || !stackToShift.isStackable() || stackToShift.stackSize <= 0) { + return false; + } + + boolean changed = false; + for (int slotIndex = start; stackToShift.stackSize > 0 && slotIndex < start + count; slotIndex++) { + Slot slot = (Slot) inventorySlots.get(slotIndex); + ItemStack stackInSlot = slot.getStack(); + if (stackInSlot != null && ItemStackUtil.isIdenticalItem(stackInSlot, stackToShift)) { + int resultingStackSize = stackInSlot.stackSize + stackToShift.stackSize; + int max = Math.min(stackToShift.getMaxStackSize(), slot.getSlotStackLimit()); + if (resultingStackSize <= max) { + stackToShift.stackSize = 0; + stackInSlot.stackSize = resultingStackSize; + slot.onSlotChanged(); + changed = true; + } else if (stackInSlot.stackSize < max) { + stackToShift.stackSize -= max - stackInSlot.stackSize; + stackInSlot.stackSize = max; + slot.onSlotChanged(); + changed = true; + } + } + } + return changed; + } + + private static boolean shiftItemStackToRangeOpenSlots( + List inventorySlots, ItemStack stackToShift, int start, int count) { + if (stackToShift == null || stackToShift.stackSize <= 0) { + return false; + } + + boolean changed = false; + for (int slotIndex = start; stackToShift.stackSize > 0 && slotIndex < start + count; slotIndex++) { + Slot slot = (Slot) inventorySlots.get(slotIndex); + ItemStack stackInSlot = slot.getStack(); + if (stackInSlot == null) { + int max = Math.min(stackToShift.getMaxStackSize(), slot.getSlotStackLimit()); + stackInSlot = stackToShift.copy(); + stackInSlot.stackSize = Math.min(stackToShift.stackSize, max); + stackToShift.stackSize -= stackInSlot.stackSize; + slot.putStack(stackInSlot); + slot.onSlotChanged(); + changed = true; + } + } + return changed; + } + + private static final int playerInventorySize = 9 * 4; + private static final int playerHotbarSize = 9; + + private static boolean isInPlayerInventory(int slotIndex) { + return slotIndex < playerInventorySize; + } + + private static boolean isInPlayerHotbar(int slotIndex) { + return SlotUtil.isSlotInRange(slotIndex, playerInventorySize - playerHotbarSize, playerInventorySize); + } + + private static boolean shiftToPlayerInventory(List inventorySlots, ItemStack stackInSlot) { + int playerHotbarStart = playerInventorySize - playerHotbarSize; + + // try to merge with existing stacks, hotbar first + boolean shifted = shiftItemStackToRangeMerge(inventorySlots, stackInSlot, playerHotbarStart, playerHotbarSize); + shifted |= shiftItemStackToRangeMerge(inventorySlots, stackInSlot, 0, playerHotbarStart); + + // shift to open slots, hotbar first + shifted |= shiftItemStackToRangeOpenSlots(inventorySlots, stackInSlot, playerHotbarStart, playerHotbarSize); + shifted |= shiftItemStackToRangeOpenSlots(inventorySlots, stackInSlot, 0, playerHotbarStart); + return shifted; + } + + private static boolean shiftToPlayerInventoryNoHotbar(List inventorySlots, ItemStack stackInSlot) { + int playerHotbarStart = playerInventorySize - playerHotbarSize; + return shiftItemStackToRange(inventorySlots, stackInSlot, 0, playerHotbarStart); + } + + private static boolean shiftToHotbar(List inventorySlots, ItemStack stackInSlot) { + int playerHotbarStart = playerInventorySize - playerHotbarSize; + return shiftItemStackToRange(inventorySlots, stackInSlot, playerHotbarStart, playerHotbarSize); + } + + private static boolean shiftToMachineInventory(List inventorySlots, ItemStack stackToShift, int numSlots) { + boolean success = false; + if (stackToShift.isStackable()) { + success = shiftToMachineInventory(inventorySlots, stackToShift, numSlots, true); + } + if (stackToShift.stackSize > 0) { + success |= shiftToMachineInventory(inventorySlots, stackToShift, numSlots, false); + } + return success; + } + + // if mergeOnly = true, don't shift into empty slots. + private static boolean shiftToMachineInventory( + List inventorySlots, ItemStack stackToShift, int numSlots, boolean mergeOnly) { + for (int machineIndex = playerInventorySize; machineIndex < numSlots; machineIndex++) { + // System.out.println("SlotUtil::shiftToMachineinventory"); + Slot slot = (Slot) inventorySlots.get(machineIndex); + if (mergeOnly && slot.getStack() == null) { + continue; + } + if (slot instanceof SlotForestry) { + SlotForestry slotForestry = (SlotForestry) slot; + if (!slotForestry.canShift() || slotForestry.isPhantom()) { + continue; + } + } + if (!slot.isItemValid(stackToShift)) { + continue; + } + if (shiftItemStackToRange(inventorySlots, stackToShift, machineIndex, 1)) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/forestry/core/utils/Stack.java b/src/main/java/forestry/core/utils/Stack.java index 9c92367d9..e39fead9b 100644 --- a/src/main/java/forestry/core/utils/Stack.java +++ b/src/main/java/forestry/core/utils/Stack.java @@ -1,106 +1,108 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.item.Item; - -import net.minecraftforge.oredict.OreDictionary; - -import cpw.mods.fml.common.registry.GameData; - -public class Stack { - private final String name; - private final int meta; - - public Stack(String name, int meta) { - this.name = name; - this.meta = meta; - } - - public static List parseStackStrings(String itemStackStrings, int missingMetaValue) { - String[] parts = itemStackStrings.split("(\\s*;\\s*)+"); - return parseStackStrings(parts, missingMetaValue); - } - - public static List parseStackStrings(String[] parts, int missingMetaValue) { - - List stacks = new ArrayList<>(); - - for (String itemStackString : parts) { - Stack stack = parseStackString(itemStackString, missingMetaValue); - if (stack != null) { - stacks.add(stack); - } - } - - return stacks; - } - - public static Stack parseStackString(String stackString, int missingMetaValue) { - if (stackString == null) { - return null; - } - - stackString = stackString.trim(); - if (stackString.isEmpty()) { - return null; - } - - String[] parts = stackString.split(":+"); - - if (parts.length != 2 && parts.length != 3) { - Log.warning("Stack string (" + stackString + ") isn't formatted properly. Suitable formats are :, :: or ::*, e.g. IC2:blockWall:*"); - return null; - } - - String name = parts[0] + ':' + parts[1]; - int meta; - - if (parts.length == 2) { - meta = missingMetaValue; - } else { - try { - meta = parts[2].equals("*") ? OreDictionary.WILDCARD_VALUE : NumberFormat.getIntegerInstance().parse(parts[2]).intValue(); - } catch (ParseException e) { - Log.warning("ItemStack string (" + stackString + ") has improperly formatted metadata. Suitable metadata are integer values or *."); - return null; - } - } - - return new Stack(name, meta); - } - - public Item getItem() { - Item item = GameData.getItemRegistry().getRaw(name); - if (item == null) { - Log.warning("Failed to find item for (" + name + ") in the Forge registry."); - } - return item; - } - - public Block getBlock() { - Block block = GameData.getBlockRegistry().getRaw(name); - if (block == null) { - Log.warning("Failed to find block for (" + name + ") in the Forge registry."); - } - return block; - } - - public int getMeta() { - return meta; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.utils; + +import cpw.mods.fml.common.registry.GameData; +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraftforge.oredict.OreDictionary; + +public class Stack { + private final String name; + private final int meta; + + public Stack(String name, int meta) { + this.name = name; + this.meta = meta; + } + + public static List parseStackStrings(String itemStackStrings, int missingMetaValue) { + String[] parts = itemStackStrings.split("(\\s*;\\s*)+"); + return parseStackStrings(parts, missingMetaValue); + } + + public static List parseStackStrings(String[] parts, int missingMetaValue) { + + List stacks = new ArrayList<>(); + + for (String itemStackString : parts) { + Stack stack = parseStackString(itemStackString, missingMetaValue); + if (stack != null) { + stacks.add(stack); + } + } + + return stacks; + } + + public static Stack parseStackString(String stackString, int missingMetaValue) { + if (stackString == null) { + return null; + } + + stackString = stackString.trim(); + if (stackString.isEmpty()) { + return null; + } + + String[] parts = stackString.split(":+"); + + if (parts.length != 2 && parts.length != 3) { + Log.warning( + "Stack string (" + stackString + + ") isn't formatted properly. Suitable formats are :, :: or ::*, e.g. IC2:blockWall:*"); + return null; + } + + String name = parts[0] + ':' + parts[1]; + int meta; + + if (parts.length == 2) { + meta = missingMetaValue; + } else { + try { + meta = parts[2].equals("*") + ? OreDictionary.WILDCARD_VALUE + : NumberFormat.getIntegerInstance().parse(parts[2]).intValue(); + } catch (ParseException e) { + Log.warning("ItemStack string (" + stackString + + ") has improperly formatted metadata. Suitable metadata are integer values or *."); + return null; + } + } + + return new Stack(name, meta); + } + + public Item getItem() { + Item item = GameData.getItemRegistry().getRaw(name); + if (item == null) { + Log.warning("Failed to find item for (" + name + ") in the Forge registry."); + } + return item; + } + + public Block getBlock() { + Block block = GameData.getBlockRegistry().getRaw(name); + if (block == null) { + Log.warning("Failed to find block for (" + name + ") in the Forge registry."); + } + return block; + } + + public int getMeta() { + return meta; + } +} diff --git a/src/main/java/forestry/core/utils/StringUtil.java b/src/main/java/forestry/core/utils/StringUtil.java index 6115ef81c..7074f9cbc 100755 --- a/src/main/java/forestry/core/utils/StringUtil.java +++ b/src/main/java/forestry/core/utils/StringUtil.java @@ -10,8 +10,8 @@ ******************************************************************************/ package forestry.core.utils; +import forestry.core.proxy.Proxies; import java.util.IllegalFormatException; - import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; @@ -19,101 +19,112 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; -import forestry.core.proxy.Proxies; - public class StringUtil { - public static boolean canTranslate(String key) { - return StatCollector.canTranslate("for." + key); - } + public static boolean canTranslate(String key) { + return StatCollector.canTranslate("for." + key); + } - public static boolean canTranslateTile(String key) { - return StatCollector.canTranslate("tile.for." + key); - } + public static boolean canTranslateTile(String key) { + return StatCollector.canTranslate("tile.for." + key); + } - public static String localize(String key) { - return StatCollector.translateToLocal("for." + key).replace("\\n", "\n").replace("@", "%").replace("\\%", "@"); - } + public static String localize(String key) { + return StatCollector.translateToLocal("for." + key) + .replace("\\n", "\n") + .replace("@", "%") + .replace("\\%", "@"); + } - public static String localizeTile(String key) { - return StatCollector.translateToLocal("tile.for." + key).replace("\\n", "\n").replace("@", "%").replace("\\%", "@"); - } + public static String localizeTile(String key) { + return StatCollector.translateToLocal("tile.for." + key) + .replace("\\n", "\n") + .replace("@", "%") + .replace("\\%", "@"); + } - public static String localizeAndFormat(String key, Object... args) { - return localizeAndFormatRaw("for." + key, args); - } + public static String localizeAndFormat(String key, Object... args) { + return localizeAndFormatRaw("for." + key, args); + } - /** - * Same as localizeAndFormat, only without the "for." prefix. Used for specific items. - */ - public static String localizeAndFormatRaw(String key, Object... args) { - String text = StatCollector.translateToLocal(key).replace("\\n", "\n").replace("@", "%").replace("\\%", "@"); + /** + * Same as localizeAndFormat, only without the "for." prefix. Used for specific items. + */ + public static String localizeAndFormatRaw(String key, Object... args) { + String text = StatCollector.translateToLocal(key) + .replace("\\n", "\n") + .replace("@", "%") + .replace("\\%", "@"); - try { - return String.format(text, args); - } catch (IllegalFormatException ex) { - return "Format error: " + text; - } - } + try { + return String.format(text, args); + } catch (IllegalFormatException ex) { + return "Format error: " + text; + } + } - public static String cleanTags(String tag) { - return tag.replaceAll("[Ff]orestry\\p{Punct}", "").replaceAll("\\.[Ff]or\\p{Punct}", ".").replaceFirst("^tile\\.", "").replaceFirst("^item\\.", ""); - } + public static String cleanTags(String tag) { + return tag.replaceAll("[Ff]orestry\\p{Punct}", "") + .replaceAll("\\.[Ff]or\\p{Punct}", ".") + .replaceFirst("^tile\\.", "") + .replaceFirst("^item\\.", ""); + } - public static String cleanItemName(ItemStack stack) { - return cleanTags(stack.getUnlocalizedName()); - } + public static String cleanItemName(ItemStack stack) { + return cleanTags(stack.getUnlocalizedName()); + } - public static String cleanItemName(Item item) { - return cleanTags(item.getUnlocalizedName()); - } + public static String cleanItemName(Item item) { + return cleanTags(item.getUnlocalizedName()); + } - public static String cleanBlockName(Block block) { - return cleanTags(block.getUnlocalizedName()); - } + public static String cleanBlockName(Block block) { + return cleanTags(block.getUnlocalizedName()); + } - public static String append(String delim, String source, String appendix) { - if (source.length() <= 0) { - return appendix; - } + public static String append(String delim, String source, String appendix) { + if (source.length() <= 0) { + return appendix; + } - if (appendix.length() <= 0) { - return source; - } + if (appendix.length() <= 0) { + return source; + } - return source + delim + appendix; - } + return source + delim + appendix; + } - public static String readableBoolean(boolean flag, String trueStr, String falseStr) { - if (flag) { - return trueStr; - } else { - return falseStr; - } - } + public static String readableBoolean(boolean flag, String trueStr, String falseStr) { + if (flag) { + return trueStr; + } else { + return falseStr; + } + } - public static String floatAsPercent(float val) { - return (int) (val * 100) + " %"; - } + public static String floatAsPercent(float val) { + return (int) (val * 100) + " %"; + } - public static String line(int length) { - StringBuilder line = new StringBuilder(); - for (int i = 0; i < length; i++) { - line.append('-'); - } + public static String line(int length) { + StringBuilder line = new StringBuilder(); + for (int i = 0; i < length; i++) { + line.append('-'); + } - return line.toString(); - } + return line.toString(); + } - public static int getLineHeight(int maxWidth, String... strings) { - Minecraft minecraft = Proxies.common.getClientInstance(); - FontRenderer fontRenderer = minecraft.fontRenderer; + public static int getLineHeight(int maxWidth, String... strings) { + Minecraft minecraft = Proxies.common.getClientInstance(); + FontRenderer fontRenderer = minecraft.fontRenderer; - int lineCount = 0; - for (String string : strings) { - lineCount += fontRenderer.listFormattedStringToWidth(string, maxWidth).size(); - } + int lineCount = 0; + for (String string : strings) { + lineCount += + fontRenderer.listFormattedStringToWidth(string, maxWidth).size(); + } - return lineCount * fontRenderer.FONT_HEIGHT; - } + return lineCount * fontRenderer.FONT_HEIGHT; + } } diff --git a/src/main/java/forestry/core/utils/datastructures/FluidMap.java b/src/main/java/forestry/core/utils/datastructures/FluidMap.java index 6b02f95be..03181e19d 100644 --- a/src/main/java/forestry/core/utils/datastructures/FluidMap.java +++ b/src/main/java/forestry/core/utils/datastructures/FluidMap.java @@ -15,38 +15,38 @@ import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; public class FluidMap extends StackMap { - private static final long serialVersionUID = 15891293315299994L; + private static final long serialVersionUID = 15891293315299994L; - @Override - protected boolean areEqual(Fluid a, Object b) { - if (b instanceof FluidStack) { - return ((FluidStack) b).getFluid() == a; - } - if (b instanceof Fluid) { - return b == a; - } - if (b instanceof String) { - return b.equals(a.getName()); - } - return false; - } + @Override + protected boolean areEqual(Fluid a, Object b) { + if (b instanceof FluidStack) { + return ((FluidStack) b).getFluid() == a; + } + if (b instanceof Fluid) { + return b == a; + } + if (b instanceof String) { + return b.equals(a.getName()); + } + return false; + } - @Override - protected boolean isValidKey(Object key) { - return key instanceof FluidStack || key instanceof Fluid || key instanceof String; - } + @Override + protected boolean isValidKey(Object key) { + return key instanceof FluidStack || key instanceof Fluid || key instanceof String; + } - @Override - protected Fluid getStack(Object key) { - if (key instanceof FluidStack) { - return ((FluidStack) key).getFluid(); - } - if (key instanceof Fluid) { - return (Fluid) key; - } - if (key instanceof String) { - return FluidRegistry.getFluid((String) key); - } - return null; - } + @Override + protected Fluid getStack(Object key) { + if (key instanceof FluidStack) { + return ((FluidStack) key).getFluid(); + } + if (key instanceof Fluid) { + return (Fluid) key; + } + if (key instanceof String) { + return FluidRegistry.getFluid((String) key); + } + return null; + } } diff --git a/src/main/java/forestry/core/utils/datastructures/ItemStackMap.java b/src/main/java/forestry/core/utils/datastructures/ItemStackMap.java index 578af5186..0ab715318 100644 --- a/src/main/java/forestry/core/utils/datastructures/ItemStackMap.java +++ b/src/main/java/forestry/core/utils/datastructures/ItemStackMap.java @@ -12,42 +12,40 @@ package forestry.core.utils.datastructures; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; - import net.minecraftforge.oredict.OreDictionary; public class ItemStackMap extends StackMap { - private static final long serialVersionUID = -8511966739130702305L; + private static final long serialVersionUID = -8511966739130702305L; - @Override - protected boolean areEqual(ItemStack a, Object b) { - if (b instanceof ItemStack) { - ItemStack b2 = (ItemStack) b; - return a.isItemEqual(b2) && ItemStack.areItemStackTagsEqual(a, b2); - } - if (b instanceof Item) { - return a.getItem() == b; - } - if (b instanceof String) { - for (ItemStack stack : OreDictionary.getOres((String) b)) { - if (areEqual(a, stack)) { - return true; - } - } - } - return false; - } + @Override + protected boolean areEqual(ItemStack a, Object b) { + if (b instanceof ItemStack) { + ItemStack b2 = (ItemStack) b; + return a.isItemEqual(b2) && ItemStack.areItemStackTagsEqual(a, b2); + } + if (b instanceof Item) { + return a.getItem() == b; + } + if (b instanceof String) { + for (ItemStack stack : OreDictionary.getOres((String) b)) { + if (areEqual(a, stack)) { + return true; + } + } + } + return false; + } - @Override - protected boolean isValidKey(Object key) { - return key instanceof ItemStack || key instanceof Item || key instanceof String; - } - - @Override - protected ItemStack getStack(Object key) { - if (key instanceof ItemStack) { - return (ItemStack) key; - } - return null; - } + @Override + protected boolean isValidKey(Object key) { + return key instanceof ItemStack || key instanceof Item || key instanceof String; + } + @Override + protected ItemStack getStack(Object key) { + if (key instanceof ItemStack) { + return (ItemStack) key; + } + return null; + } } diff --git a/src/main/java/forestry/core/utils/datastructures/RevolvingList.java b/src/main/java/forestry/core/utils/datastructures/RevolvingList.java index 8faf699fc..679d06cfb 100644 --- a/src/main/java/forestry/core/utils/datastructures/RevolvingList.java +++ b/src/main/java/forestry/core/utils/datastructures/RevolvingList.java @@ -11,7 +11,6 @@ package forestry.core.utils.datastructures; import com.google.common.collect.ForwardingCollection; - import java.util.Collection; import java.util.Deque; import java.util.LinkedList; @@ -22,55 +21,53 @@ import java.util.LinkedList; */ public class RevolvingList extends ForwardingCollection { - private final Deque list = new LinkedList<>(); + private final Deque list = new LinkedList<>(); - public RevolvingList() { - } + public RevolvingList() {} - public RevolvingList(Collection collection) { - list.addAll(collection); - } + public RevolvingList(Collection collection) { + list.addAll(collection); + } - @Override - protected Collection delegate() { - return list; - } + @Override + protected Collection delegate() { + return list; + } - public void rotateLeft() { - if (list.isEmpty()) { - return; - } - list.addFirst(list.removeLast()); - } + public void rotateLeft() { + if (list.isEmpty()) { + return; + } + list.addFirst(list.removeLast()); + } - public void rotateRight() { - if (list.isEmpty()) { - return; - } - list.addLast(list.removeFirst()); - } + public void rotateRight() { + if (list.isEmpty()) { + return; + } + list.addLast(list.removeFirst()); + } - public T getCurrent() { - if (list.isEmpty()) { - return null; - } - return list.getFirst(); - } + public T getCurrent() { + if (list.isEmpty()) { + return null; + } + return list.getFirst(); + } - public void setCurrent(T e) { - if (!contains(e)) { - return; - } - - if (e == null) { - while (getCurrent() != null) { - rotateRight(); - } - } else { - while (getCurrent() == null || !getCurrent().equals(e)) { - rotateRight(); - } - } - } + public void setCurrent(T e) { + if (!contains(e)) { + return; + } + if (e == null) { + while (getCurrent() != null) { + rotateRight(); + } + } else { + while (getCurrent() == null || !getCurrent().equals(e)) { + rotateRight(); + } + } + } } diff --git a/src/main/java/forestry/core/utils/datastructures/StackMap.java b/src/main/java/forestry/core/utils/datastructures/StackMap.java index 5fdd3ca6a..0edbc20b1 100644 --- a/src/main/java/forestry/core/utils/datastructures/StackMap.java +++ b/src/main/java/forestry/core/utils/datastructures/StackMap.java @@ -21,68 +21,67 @@ import java.util.Map; * @author Alex Binnie */ public abstract class StackMap extends HashMap { - - @Override - public final T put(P key, T value) { - if (isValidKey(key) && key != null && value != null) { - return super.put(key, value); - } - return null; - } - private static final long serialVersionUID = 5383477742290646466L; + @Override + public final T put(P key, T value) { + if (isValidKey(key) && key != null && value != null) { + return super.put(key, value); + } + return null; + } - @Override - public final boolean containsKey(Object key) { - P stack = getStack(key); - if (stack == null) { - return false; - } - for (Map.Entry entry : this.entrySet()) { - if (areEqual(stack, entry.getKey())) { - return true; - } - } - return super.containsKey(key); - } + private static final long serialVersionUID = 5383477742290646466L; - @Override - public final T get(Object key) { - P stack = getStack(key); - if (stack == null) { - return null; - } - for (Map.Entry entry : this.entrySet()) { - if (areEqual(stack, entry.getKey())) { - return entry.getValue(); - } - } - return super.get(key); - } + @Override + public final boolean containsKey(Object key) { + P stack = getStack(key); + if (stack == null) { + return false; + } + for (Map.Entry entry : this.entrySet()) { + if (areEqual(stack, entry.getKey())) { + return true; + } + } + return super.containsKey(key); + } - /** - * Is a, the key used to lookup, equivelant to the key b - * - * @param a - * @param b - * @return - */ - protected abstract boolean areEqual(P a, Object b); - - /** - * Can this key be added to the map - * - * @param key - * @return - */ - protected abstract boolean isValidKey(Object key); + @Override + public final T get(Object key) { + P stack = getStack(key); + if (stack == null) { + return null; + } + for (Map.Entry entry : this.entrySet()) { + if (areEqual(stack, entry.getKey())) { + return entry.getValue(); + } + } + return super.get(key); + } - /** - * Converts a key used to lookup something into P (ItemStack or FluidStack) - * - * @param key - * @return - */ - protected abstract P getStack(Object key); + /** + * Is a, the key used to lookup, equivelant to the key b + * + * @param a + * @param b + * @return + */ + protected abstract boolean areEqual(P a, Object b); + /** + * Can this key be added to the map + * + * @param key + * @return + */ + protected abstract boolean isValidKey(Object key); + + /** + * Converts a key used to lookup something into P (ItemStack or FluidStack) + * + * @param key + * @return + */ + protected abstract P getStack(Object key); } diff --git a/src/main/java/forestry/core/utils/vect/IVect.java b/src/main/java/forestry/core/utils/vect/IVect.java index 5cb86d085..124517e80 100644 --- a/src/main/java/forestry/core/utils/vect/IVect.java +++ b/src/main/java/forestry/core/utils/vect/IVect.java @@ -1,40 +1,38 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils.vect; - -import net.minecraft.util.ChunkCoordinates; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.api.farming.FarmDirection; - -/** - * Represents a position or dimensions. - */ -public interface IVect { - int getX(); - - int getY(); - - int getZ(); - - IVect add(IVect other); - - IVect add(int x, int y, int z); - - IVect add(ForgeDirection direction); - - IVect add(FarmDirection direction); - - IVect add(ChunkCoordinates coordinates); - - int[] toArray(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.utils.vect; + +import forestry.api.farming.FarmDirection; +import net.minecraft.util.ChunkCoordinates; +import net.minecraftforge.common.util.ForgeDirection; + +/** + * Represents a position or dimensions. + */ +public interface IVect { + int getX(); + + int getY(); + + int getZ(); + + IVect add(IVect other); + + IVect add(int x, int y, int z); + + IVect add(ForgeDirection direction); + + IVect add(FarmDirection direction); + + IVect add(ChunkCoordinates coordinates); + + int[] toArray(); +} diff --git a/src/main/java/forestry/core/utils/vect/MutableVect.java b/src/main/java/forestry/core/utils/vect/MutableVect.java index 02f0b227a..ddd58aae5 100644 --- a/src/main/java/forestry/core/utils/vect/MutableVect.java +++ b/src/main/java/forestry/core/utils/vect/MutableVect.java @@ -1,145 +1,143 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils.vect; - -import net.minecraft.util.ChunkCoordinates; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.api.farming.FarmDirection; - -/** - * Represents changeable positions or dimensions. - */ -public class MutableVect implements IVect { - public int x; - public int y; - public int z; - - public MutableVect(int x, int y, int z) { - this.x = x; - this.y = y; - this.z = z; - } - - public MutableVect(ForgeDirection direction) { - this.x = direction.offsetX; - this.y = direction.offsetY; - this.z = direction.offsetZ; - } - - public MutableVect(int[] dim) { - if (dim.length != 3) { - throw new RuntimeException("Cannot instantiate a vector with less or more than 3 points."); - } - - this.x = dim[0]; - this.y = dim[1]; - this.z = dim[2]; - } - - public MutableVect(ChunkCoordinates coordinates) { - this.x = coordinates.posX; - this.y = coordinates.posY; - this.z = coordinates.posZ; - } - - public MutableVect(IVect vect) { - this.x = vect.getX(); - this.y = vect.getY(); - this.z = vect.getZ(); - } - - public MutableVect add(IVect other) { - x += other.getX(); - y += other.getY(); - z += other.getZ(); - return this; - } - - public MutableVect add(int x, int y, int z) { - this.x += x; - this.y += y; - this.z += z; - return this; - } - - @Override - public MutableVect add(ForgeDirection direction) { - this.x += direction.offsetX; - this.y += direction.offsetY; - this.z += direction.offsetZ; - return this; - } - - @Override - public MutableVect add(FarmDirection direction) { - return add(direction.getForgeDirection()); - } - - @Override - public MutableVect add(ChunkCoordinates coordinates) { - this.x += coordinates.posX; - this.y += coordinates.posY; - this.z += coordinates.posZ; - return this; - } - - @Override - public int[] toArray() { - return new int[]{x, y, z}; - } - - public MutableVect multiply(float factor) { - this.x *= factor; - this.y *= factor; - this.z *= factor; - return this; - } - - public boolean advancePositionInArea(Vect area) { - // Increment z first until end reached - if (z < area.z - 1) { - z++; - } else { - z = 0; - - if (x < area.x - 1) { - x++; - } else { - x = 0; - - if (y < area.y - 1) { - y++; - } else { - return false; - } - } - } - - return true; - } - - @Override - public int getX() { - return x; - } - - @Override - public int getY() { - return y; - } - - @Override - public int getZ() { - return z; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.utils.vect; + +import forestry.api.farming.FarmDirection; +import net.minecraft.util.ChunkCoordinates; +import net.minecraftforge.common.util.ForgeDirection; + +/** + * Represents changeable positions or dimensions. + */ +public class MutableVect implements IVect { + public int x; + public int y; + public int z; + + public MutableVect(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + + public MutableVect(ForgeDirection direction) { + this.x = direction.offsetX; + this.y = direction.offsetY; + this.z = direction.offsetZ; + } + + public MutableVect(int[] dim) { + if (dim.length != 3) { + throw new RuntimeException("Cannot instantiate a vector with less or more than 3 points."); + } + + this.x = dim[0]; + this.y = dim[1]; + this.z = dim[2]; + } + + public MutableVect(ChunkCoordinates coordinates) { + this.x = coordinates.posX; + this.y = coordinates.posY; + this.z = coordinates.posZ; + } + + public MutableVect(IVect vect) { + this.x = vect.getX(); + this.y = vect.getY(); + this.z = vect.getZ(); + } + + public MutableVect add(IVect other) { + x += other.getX(); + y += other.getY(); + z += other.getZ(); + return this; + } + + public MutableVect add(int x, int y, int z) { + this.x += x; + this.y += y; + this.z += z; + return this; + } + + @Override + public MutableVect add(ForgeDirection direction) { + this.x += direction.offsetX; + this.y += direction.offsetY; + this.z += direction.offsetZ; + return this; + } + + @Override + public MutableVect add(FarmDirection direction) { + return add(direction.getForgeDirection()); + } + + @Override + public MutableVect add(ChunkCoordinates coordinates) { + this.x += coordinates.posX; + this.y += coordinates.posY; + this.z += coordinates.posZ; + return this; + } + + @Override + public int[] toArray() { + return new int[] {x, y, z}; + } + + public MutableVect multiply(float factor) { + this.x *= factor; + this.y *= factor; + this.z *= factor; + return this; + } + + public boolean advancePositionInArea(Vect area) { + // Increment z first until end reached + if (z < area.z - 1) { + z++; + } else { + z = 0; + + if (x < area.x - 1) { + x++; + } else { + x = 0; + + if (y < area.y - 1) { + y++; + } else { + return false; + } + } + } + + return true; + } + + @Override + public int getX() { + return x; + } + + @Override + public int getY() { + return y; + } + + @Override + public int getZ() { + return z; + } +} diff --git a/src/main/java/forestry/core/utils/vect/Vect.java b/src/main/java/forestry/core/utils/vect/Vect.java index 323ba1c03..faa02b4e6 100644 --- a/src/main/java/forestry/core/utils/vect/Vect.java +++ b/src/main/java/forestry/core/utils/vect/Vect.java @@ -1,175 +1,172 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils.vect; - -import java.util.Random; - -import net.minecraft.entity.Entity; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChunkCoordinates; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.api.farming.FarmDirection; - -/** - * Represents an unchangeable position or dimensions. - */ -public class Vect implements IVect { - public final int x; - public final int y; - public final int z; - - public Vect(int[] dim) { - if (dim.length != 3) { - throw new RuntimeException("Cannot instantiate a vector with less or more than 3 points."); - } - - this.x = dim[0]; - this.y = dim[1]; - this.z = dim[2]; - } - - public Vect(IVect vect) { - this.x = vect.getX(); - this.y = vect.getY(); - this.z = vect.getZ(); - } - - public Vect(ForgeDirection direction) { - this.x = direction.offsetX; - this.y = direction.offsetY; - this.z = direction.offsetZ; - } - - public Vect(int x, int y, int z) { - this.x = x; - this.y = y; - this.z = z; - } - - public Vect(ChunkCoordinates coordinates) { - this.x = coordinates.posX; - this.y = coordinates.posY; - this.z = coordinates.posZ; - } - - public Vect(TileEntity entity) { - this.x = entity.xCoord; - this.y = entity.yCoord; - this.z = entity.zCoord; - } - - public Vect(Entity entity) { - this.x = (int) Math.round(entity.posX); - this.y = (int) Math.round(entity.posY); - this.z = (int) Math.round(entity.posZ); - } - - public static Vect getRandomPositionInArea(Random random, IVect area) { - int x = random.nextInt(area.getX()); - int y = random.nextInt(area.getY()); - int z = random.nextInt(area.getZ()); - return new Vect(x, y, z); - } - - public static Vect add(IVect... vects) { - int x = 0; - int y = 0; - int z = 0; - for (IVect vect : vects) { - x += vect.getX(); - y += vect.getY(); - z += vect.getZ(); - } - return new Vect(x, y, z); - } - - @Override - public Vect add(IVect other) { - return new Vect(x + other.getX(), y + other.getY(), z + other.getZ()); - } - - @Override - public Vect add(int x, int y, int z) { - return new Vect(this.x + x, this.y + y, this.z + z); - } - - @Override - public Vect add(ForgeDirection direction) { - return add(direction.offsetX, direction.offsetY, direction.offsetZ); - } - - @Override - public Vect add(FarmDirection direction) { - return add(direction.getForgeDirection()); - } - - @Override - public Vect add(ChunkCoordinates coordinates) { - return add(coordinates.posX, coordinates.posY, coordinates.posZ); - } - - @Override - public int[] toArray() { - return new int[]{x, y, z}; - } - - public Vect multiply(int factor) { - return new Vect(x * factor, y * factor, z * factor); - } - - public Vect multiply(float factor) { - return new Vect(Math.round(x * factor), Math.round(y * factor), Math.round(z * factor)); - } - - @Override - public String toString() { - return String.format("%sx%sx%s", x, y, z); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + x; - result = prime * result + y; - result = prime * result + z; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof Vect)) { - return false; - } - Vect other = (Vect) obj; - return (x == other.x) && (y == other.y) && (z == other.z); - } - - @Override - public int getX() { - return x; - } - - @Override - public int getY() { - return y; - } - - @Override - public int getZ() { - return z; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.utils.vect; + +import forestry.api.farming.FarmDirection; +import java.util.Random; +import net.minecraft.entity.Entity; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChunkCoordinates; +import net.minecraftforge.common.util.ForgeDirection; + +/** + * Represents an unchangeable position or dimensions. + */ +public class Vect implements IVect { + public final int x; + public final int y; + public final int z; + + public Vect(int[] dim) { + if (dim.length != 3) { + throw new RuntimeException("Cannot instantiate a vector with less or more than 3 points."); + } + + this.x = dim[0]; + this.y = dim[1]; + this.z = dim[2]; + } + + public Vect(IVect vect) { + this.x = vect.getX(); + this.y = vect.getY(); + this.z = vect.getZ(); + } + + public Vect(ForgeDirection direction) { + this.x = direction.offsetX; + this.y = direction.offsetY; + this.z = direction.offsetZ; + } + + public Vect(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + + public Vect(ChunkCoordinates coordinates) { + this.x = coordinates.posX; + this.y = coordinates.posY; + this.z = coordinates.posZ; + } + + public Vect(TileEntity entity) { + this.x = entity.xCoord; + this.y = entity.yCoord; + this.z = entity.zCoord; + } + + public Vect(Entity entity) { + this.x = (int) Math.round(entity.posX); + this.y = (int) Math.round(entity.posY); + this.z = (int) Math.round(entity.posZ); + } + + public static Vect getRandomPositionInArea(Random random, IVect area) { + int x = random.nextInt(area.getX()); + int y = random.nextInt(area.getY()); + int z = random.nextInt(area.getZ()); + return new Vect(x, y, z); + } + + public static Vect add(IVect... vects) { + int x = 0; + int y = 0; + int z = 0; + for (IVect vect : vects) { + x += vect.getX(); + y += vect.getY(); + z += vect.getZ(); + } + return new Vect(x, y, z); + } + + @Override + public Vect add(IVect other) { + return new Vect(x + other.getX(), y + other.getY(), z + other.getZ()); + } + + @Override + public Vect add(int x, int y, int z) { + return new Vect(this.x + x, this.y + y, this.z + z); + } + + @Override + public Vect add(ForgeDirection direction) { + return add(direction.offsetX, direction.offsetY, direction.offsetZ); + } + + @Override + public Vect add(FarmDirection direction) { + return add(direction.getForgeDirection()); + } + + @Override + public Vect add(ChunkCoordinates coordinates) { + return add(coordinates.posX, coordinates.posY, coordinates.posZ); + } + + @Override + public int[] toArray() { + return new int[] {x, y, z}; + } + + public Vect multiply(int factor) { + return new Vect(x * factor, y * factor, z * factor); + } + + public Vect multiply(float factor) { + return new Vect(Math.round(x * factor), Math.round(y * factor), Math.round(z * factor)); + } + + @Override + public String toString() { + return String.format("%sx%sx%s", x, y, z); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + x; + result = prime * result + y; + result = prime * result + z; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof Vect)) { + return false; + } + Vect other = (Vect) obj; + return (x == other.x) && (y == other.y) && (z == other.z); + } + + @Override + public int getX() { + return x; + } + + @Override + public int getY() { + return y; + } + + @Override + public int getZ() { + return z; + } +} diff --git a/src/main/java/forestry/core/utils/vect/VectUtil.java b/src/main/java/forestry/core/utils/vect/VectUtil.java index c435dd36f..7f8e0f38d 100644 --- a/src/main/java/forestry/core/utils/vect/VectUtil.java +++ b/src/main/java/forestry/core/utils/vect/VectUtil.java @@ -1,43 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils.vect; - -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; - -public final class VectUtil { - public static boolean isAirBlock(World world, IVect position) { - return world.isAirBlock(position.getX(), position.getY(), position.getZ()); - } - - public static boolean isWoodBlock(World world, IVect position) { - Block block = getBlock(world, position); - return block.isWood(world, position.getX(), position.getY(), position.getZ()); - } - - public static TileEntity getTile(World world, IVect position) { - return world.getTileEntity(position.getX(), position.getY(), position.getZ()); - } - - public static Block getBlock(World world, IVect position) { - return world.getBlock(position.getX(), position.getY(), position.getZ()); - } - - public static int getBlockMeta(World world, IVect position) { - return world.getBlockMetadata(position.getX(), position.getY(), position.getZ()); - } - - public static ItemStack getAsItemStack(World world, IVect position) { - return new ItemStack(getBlock(world, position), 1, getBlockMeta(world, position)); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.utils.vect; + +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; + +public final class VectUtil { + public static boolean isAirBlock(World world, IVect position) { + return world.isAirBlock(position.getX(), position.getY(), position.getZ()); + } + + public static boolean isWoodBlock(World world, IVect position) { + Block block = getBlock(world, position); + return block.isWood(world, position.getX(), position.getY(), position.getZ()); + } + + public static TileEntity getTile(World world, IVect position) { + return world.getTileEntity(position.getX(), position.getY(), position.getZ()); + } + + public static Block getBlock(World world, IVect position) { + return world.getBlock(position.getX(), position.getY(), position.getZ()); + } + + public static int getBlockMeta(World world, IVect position) { + return world.getBlockMetadata(position.getX(), position.getY(), position.getZ()); + } + + public static ItemStack getAsItemStack(World world, IVect position) { + return new ItemStack(getBlock(world, position), 1, getBlockMeta(world, position)); + } +} diff --git a/src/main/java/forestry/core/worldgen/BlockType.java b/src/main/java/forestry/core/worldgen/BlockType.java index 85bb27fd0..d0c175bf3 100755 --- a/src/main/java/forestry/core/worldgen/BlockType.java +++ b/src/main/java/forestry/core/worldgen/BlockType.java @@ -10,29 +10,25 @@ ******************************************************************************/ package forestry.core.worldgen; +import forestry.core.config.Constants; import net.minecraft.block.Block; import net.minecraft.world.World; - import net.minecraftforge.common.util.ForgeDirection; -import forestry.core.config.Constants; - public class BlockType implements IBlockType { - private final Block block; - protected int meta; + private final Block block; + protected int meta; - public BlockType(Block block, int meta) { - this.block = block; - this.meta = meta; - } + public BlockType(Block block, int meta) { + this.block = block; + this.meta = meta; + } - @Override - public void setDirection(ForgeDirection facing) { + @Override + public void setDirection(ForgeDirection facing) {} - } - - @Override - public void setBlock(World world, int x, int y, int z) { - world.setBlock(x, y, z, block, meta, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); - } + @Override + public void setBlock(World world, int x, int y, int z) { + world.setBlock(x, y, z, block, meta, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); + } } diff --git a/src/main/java/forestry/core/worldgen/BlockTypeTileForestry.java b/src/main/java/forestry/core/worldgen/BlockTypeTileForestry.java index 4bb4359f0..75ad5f6bb 100644 --- a/src/main/java/forestry/core/worldgen/BlockTypeTileForestry.java +++ b/src/main/java/forestry/core/worldgen/BlockTypeTileForestry.java @@ -1,59 +1,57 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.worldgen; - -import net.minecraft.block.Block; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.core.config.Constants; -import forestry.core.tiles.TileForestry; - -public class BlockTypeTileForestry implements IBlockType { - private final Block block; - private final int meta; - private ForgeDirection direction; - - public BlockTypeTileForestry(Block block, int meta) { - this.block = block; - this.meta = meta; - } - - @Override - public void setDirection(ForgeDirection facing) { - this.direction = facing; - } - - @Override - public void setBlock(World world, int x, int y, int z) { - boolean placed = world.setBlock(x, y, z, block, meta, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); - if (!placed) { - return; - } - - Block worldBlock = world.getBlock(x, y, z); - if (!Block.isEqualTo(block, worldBlock)) { - return; - } - - TileEntity tile = world.getTileEntity(x, y, z); - if (!(tile instanceof TileForestry)) { - world.setBlockToAir(x, y, z); - return; - } - - TileForestry tileForestry = (TileForestry) tile; - - tileForestry.setOrientation(direction); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.worldgen; + +import forestry.core.config.Constants; +import forestry.core.tiles.TileForestry; +import net.minecraft.block.Block; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +public class BlockTypeTileForestry implements IBlockType { + private final Block block; + private final int meta; + private ForgeDirection direction; + + public BlockTypeTileForestry(Block block, int meta) { + this.block = block; + this.meta = meta; + } + + @Override + public void setDirection(ForgeDirection facing) { + this.direction = facing; + } + + @Override + public void setBlock(World world, int x, int y, int z) { + boolean placed = world.setBlock(x, y, z, block, meta, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); + if (!placed) { + return; + } + + Block worldBlock = world.getBlock(x, y, z); + if (!Block.isEqualTo(block, worldBlock)) { + return; + } + + TileEntity tile = world.getTileEntity(x, y, z); + if (!(tile instanceof TileForestry)) { + world.setBlockToAir(x, y, z); + return; + } + + TileForestry tileForestry = (TileForestry) tile; + + tileForestry.setOrientation(direction); + } +} diff --git a/src/main/java/forestry/core/worldgen/BlockTypeVoid.java b/src/main/java/forestry/core/worldgen/BlockTypeVoid.java index 28a727c1b..0b54589cc 100644 --- a/src/main/java/forestry/core/worldgen/BlockTypeVoid.java +++ b/src/main/java/forestry/core/worldgen/BlockTypeVoid.java @@ -15,13 +15,12 @@ import net.minecraft.world.World; public class BlockTypeVoid extends BlockType { - public BlockTypeVoid() { - super(Blocks.air, 0); - } - - @Override - public void setBlock(World world, int x, int y, int z) { - world.setBlockToAir(x, y, z); - } + public BlockTypeVoid() { + super(Blocks.air, 0); + } + @Override + public void setBlock(World world, int x, int y, int z) { + world.setBlockToAir(x, y, z); + } } diff --git a/src/main/java/forestry/core/worldgen/IBlockType.java b/src/main/java/forestry/core/worldgen/IBlockType.java index fbb0d2666..db7c9d919 100644 --- a/src/main/java/forestry/core/worldgen/IBlockType.java +++ b/src/main/java/forestry/core/worldgen/IBlockType.java @@ -1,21 +1,20 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.worldgen; - -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - -public interface IBlockType { - void setDirection(ForgeDirection facing); - - void setBlock(World world, int x, int y, int z); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.worldgen; + +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +public interface IBlockType { + void setDirection(ForgeDirection facing); + + void setBlock(World world, int x, int y, int z); +} diff --git a/src/main/java/forestry/core/worldgen/WorldGenBase.java b/src/main/java/forestry/core/worldgen/WorldGenBase.java index a83cca5c5..293f8ff1d 100755 --- a/src/main/java/forestry/core/worldgen/WorldGenBase.java +++ b/src/main/java/forestry/core/worldgen/WorldGenBase.java @@ -10,131 +10,148 @@ ******************************************************************************/ package forestry.core.worldgen; +import forestry.arboriculture.worldgen.ITreeBlockType; import java.util.Random; - import net.minecraft.world.World; import net.minecraft.world.gen.feature.WorldGenerator; - import net.minecraftforge.common.util.ForgeDirection; -import forestry.arboriculture.worldgen.ITreeBlockType; - public abstract class WorldGenBase extends WorldGenerator { - protected enum EnumReplaceMode { + protected enum EnumReplaceMode { + NONE, + ALL, + SOFT + } - NONE, ALL, SOFT - } + public static class Vector { - public static class Vector { + public Vector(float f, float h, float g) { + this.x = f; + this.y = h; + this.z = g; + } - public Vector(float f, float h, float g) { - this.x = f; - this.y = h; - this.z = g; - } + public final float x; + public final float y; + public final float z; - public final float x; - public final float y; - public final float z; + public static double distance(Vector a, Vector b) { + return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2) + Math.pow(a.z - b.z, 2)); + } - public static double distance(Vector a, Vector b) { - return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2) + Math.pow(a.z - b.z, 2)); - } + public static ForgeDirection direction(Vector a, Vector b) { + int x = (int) Math.abs(a.x - b.x); + int y = (int) Math.abs(a.y - b.y); + int z = (int) Math.abs(a.z - b.z); + int max = Math.max(x, Math.max(y, z)); + if (max == x) { + return ForgeDirection.EAST; + } else if (max == z) { + return ForgeDirection.SOUTH; + } else { + return ForgeDirection.UP; + } + } + } - public static ForgeDirection direction(Vector a, Vector b) { - int x = (int) Math.abs(a.x - b.x); - int y = (int) Math.abs(a.y - b.y); - int z = (int) Math.abs(a.z - b.z); - int max = Math.max(x, Math.max(y, z)); - if (max == x) { - return ForgeDirection.EAST; - } else if (max == z) { - return ForgeDirection.SOUTH; - } else { - return ForgeDirection.UP; - } - } - } + @Override + public final boolean generate(World world, Random random, int x, int y, int z) { + return generate(world, x, y, z, false); + } - @Override - public final boolean generate(World world, Random random, int x, int y, int z) { - return generate(world, x, y, z, false); - } + public boolean generate(World world, int x, int y, int z, boolean forced) { + return false; + } - public boolean generate(World world, int x, int y, int z, boolean forced) { - return false; - } + protected abstract boolean addBlock(World world, int x, int y, int z, ITreeBlockType type, EnumReplaceMode replace); - protected abstract boolean addBlock(World world, int x, int y, int z, ITreeBlockType type, EnumReplaceMode replace); + protected final void generateCuboid( + World world, Vector start, Vector area, ITreeBlockType block, EnumReplaceMode replace) { + for (int x = (int) start.x; x < (int) start.x + area.x; x++) { + for (int y = (int) start.y; y < (int) start.y + area.y; y++) { + for (int z = (int) start.z; z < (int) start.z + area.z; z++) { + addBlock(world, x, y, z, block, replace); + } + } + } + } - protected final void generateCuboid(World world, Vector start, Vector area, ITreeBlockType block, EnumReplaceMode replace) { - for (int x = (int) start.x; x < (int) start.x + area.x; x++) { - for (int y = (int) start.y; y < (int) start.y + area.y; y++) { - for (int z = (int) start.z; z < (int) start.z + area.z; z++) { - addBlock(world, x, y, z, block, replace); - } - } - } - } + /* + * Center is the bottom middle of the cylinder + */ + protected final void generateCylinder( + World world, Vector center, float radius, int height, ITreeBlockType block, EnumReplaceMode replace) { + Vector start = new Vector(center.x - radius, center.y, center.z - radius); + Vector area = new Vector(radius * 2 + 1, height, radius * 2 + 1); + for (int x = (int) start.x; x < (int) start.x + area.x; x++) { + for (int y = (int) start.y; y < (int) start.y + area.y; y++) { + for (int z = (int) start.z; z < (int) start.z + area.z; z++) { + Vector position = new Vector(x, y, z); + Vector treeCenter = new Vector(center.x, y, center.z); + if (Vector.distance(position, treeCenter) <= (radius) + 0.01) { + ForgeDirection direction = Vector.direction(position, treeCenter); + block.setDirection(direction); + addBlock(world, x, y, z, block, replace); + } + } + } + } + } - /* - * Center is the bottom middle of the cylinder - */ - protected final void generateCylinder(World world, Vector center, float radius, int height, ITreeBlockType block, EnumReplaceMode replace) { - Vector start = new Vector(center.x - radius, center.y, center.z - radius); - Vector area = new Vector(radius * 2 + 1, height, radius * 2 + 1); - for (int x = (int) start.x; x < (int) start.x + area.x; x++) { - for (int y = (int) start.y; y < (int) start.y + area.y; y++) { - for (int z = (int) start.z; z < (int) start.z + area.z; z++) { - Vector position = new Vector(x, y, z); - Vector treeCenter = new Vector(center.x, y, center.z); - if (Vector.distance(position, treeCenter) <= (radius) + 0.01) { - ForgeDirection direction = Vector.direction(position, treeCenter); - block.setDirection(direction); - addBlock(world, x, y, z, block, replace); - } - } - } - } - } + protected final void generateCircle( + World world, + Vector center, + float radius, + int width, + int height, + ITreeBlockType block, + EnumReplaceMode replace) { + generateCircle(world, center, radius, width, height, block, 1.0f, replace); + } - protected final void generateCircle(World world, Vector center, float radius, int width, int height, ITreeBlockType block, EnumReplaceMode replace) { - generateCircle(world, center, radius, width, height, block, 1.0f, replace); - } + protected final void generateCircle( + World world, + Vector center, + float radius, + int width, + int height, + ITreeBlockType block, + float chance, + EnumReplaceMode replace) { + Vector start = new Vector(center.x - radius, center.y, center.z - radius); + Vector area = new Vector(radius * 2 + 1, height, radius * 2 + 1); - protected final void generateCircle(World world, Vector center, float radius, int width, int height, ITreeBlockType block, float chance, EnumReplaceMode replace) { - Vector start = new Vector(center.x - radius, center.y, center.z - radius); - Vector area = new Vector(radius * 2 + 1, height, radius * 2 + 1); + for (int x = (int) start.x; x < (int) start.x + area.x; x++) { + for (int y = (int) start.y; y < (int) start.y + area.y; y++) { + for (int z = (int) start.z; z < (int) start.z + area.z; z++) { - for (int x = (int) start.x; x < (int) start.x + area.x; x++) { - for (int y = (int) start.y; y < (int) start.y + area.y; y++) { - for (int z = (int) start.z; z < (int) start.z + area.z; z++) { + if (world.rand.nextFloat() > chance) { + continue; + } - if (world.rand.nextFloat() > chance) { - continue; - } + double distance = Vector.distance(new Vector(x, y, z), new Vector(center.x, y, center.z)); + if ((radius - width - 0.01 < distance && distance <= (radius) + 0.01)) { + addBlock(world, x, y, z, block, replace); + } + } + } + } + } - double distance = Vector.distance(new Vector(x, y, z), new Vector(center.x, y, center.z)); - if ((radius - width - 0.01 < distance && distance <= (radius) + 0.01)) { - addBlock(world, x, y, z, block, replace); - } - } - } - } - } - - protected final void generateSphere(World world, Vector center, int radius, ITreeBlockType block, EnumReplaceMode replace) { - Vector start = new Vector(center.x - radius, center.y - radius, center.z - radius); - Vector area = new Vector(radius * 2 + 1, radius * 2 + 1, radius * 2 + 1); - for (int x = (int) start.x; x < (int) start.x + area.x; x++) { - for (int y = (int) start.y; y < (int) start.y + area.y; y++) { - for (int z = (int) start.z; z < (int) start.z + area.z; z++) { - if (Vector.distance(new Vector(x, y, z), new Vector(center.x, center.y, center.z)) <= (radius) + 0.01) { - addBlock(world, x, y, z, block, replace); - } - } - } - } - } + protected final void generateSphere( + World world, Vector center, int radius, ITreeBlockType block, EnumReplaceMode replace) { + Vector start = new Vector(center.x - radius, center.y - radius, center.z - radius); + Vector area = new Vector(radius * 2 + 1, radius * 2 + 1, radius * 2 + 1); + for (int x = (int) start.x; x < (int) start.x + area.x; x++) { + for (int y = (int) start.y; y < (int) start.y + area.y; y++) { + for (int z = (int) start.z; z < (int) start.z + area.z; z++) { + if (Vector.distance(new Vector(x, y, z), new Vector(center.x, center.y, center.z)) + <= (radius) + 0.01) { + addBlock(world, x, y, z, block, replace); + } + } + } + } + } } diff --git a/src/main/java/forestry/core/worldgen/WorldGenMinableMeta.java b/src/main/java/forestry/core/worldgen/WorldGenMinableMeta.java index 1f5d14f7f..6dc865856 100755 --- a/src/main/java/forestry/core/worldgen/WorldGenMinableMeta.java +++ b/src/main/java/forestry/core/worldgen/WorldGenMinableMeta.java @@ -10,79 +10,83 @@ ******************************************************************************/ package forestry.core.worldgen; +import forestry.core.config.Constants; import java.util.Random; - import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.gen.feature.WorldGenerator; -import forestry.core.config.Constants; - public class WorldGenMinableMeta extends WorldGenerator { - private final Block mineableBlock; - private final int mineableBlockMeta; - private final int numberOfBlocks; + private final Block mineableBlock; + private final int mineableBlockMeta; + private final int numberOfBlocks; - public WorldGenMinableMeta(Block block, int meta, int numberOfBlocks) { - mineableBlock = block; - mineableBlockMeta = meta; - this.numberOfBlocks = numberOfBlocks; - } + public WorldGenMinableMeta(Block block, int meta, int numberOfBlocks) { + mineableBlock = block; + mineableBlockMeta = meta; + this.numberOfBlocks = numberOfBlocks; + } - @Override - public boolean generate(World world, Random random, int i, int j, int k) { + @Override + public boolean generate(World world, Random random, int i, int j, int k) { - boolean hasGenerated = false; + boolean hasGenerated = false; - float randomBase = random.nextFloat() * 3.141593F; - double d = (i + 8) + (MathHelper.sin(randomBase) * numberOfBlocks) / 8F; - double d1 = (i + 8) - (MathHelper.sin(randomBase) * numberOfBlocks) / 8F; - double d2 = (k + 8) + (MathHelper.cos(randomBase) * numberOfBlocks) / 8F; - double d3 = (k + 8) - (MathHelper.cos(randomBase) * numberOfBlocks) / 8F; - double d4 = (j + random.nextInt(3)) - 2; - double d5 = (j + random.nextInt(3)) - 2; + float randomBase = random.nextFloat() * 3.141593F; + double d = (i + 8) + (MathHelper.sin(randomBase) * numberOfBlocks) / 8F; + double d1 = (i + 8) - (MathHelper.sin(randomBase) * numberOfBlocks) / 8F; + double d2 = (k + 8) + (MathHelper.cos(randomBase) * numberOfBlocks) / 8F; + double d3 = (k + 8) - (MathHelper.cos(randomBase) * numberOfBlocks) / 8F; + double d4 = (j + random.nextInt(3)) - 2; + double d5 = (j + random.nextInt(3)) - 2; - for (int l = 0; l <= numberOfBlocks; l++) { - double d6 = d + ((d1 - d) * l) / numberOfBlocks; - double d7 = d4 + ((d5 - d4) * l) / numberOfBlocks; - double d8 = d2 + ((d3 - d2) * l) / numberOfBlocks; - double d9 = (random.nextDouble() * numberOfBlocks) / 16D; - double d10 = (MathHelper.sin((l * 3.141593F) / numberOfBlocks) + 1.0F) * d9 + 1.0D; - double d11 = (MathHelper.sin((l * 3.141593F) / numberOfBlocks) + 1.0F) * d9 + 1.0D; - int xStart = MathHelper.floor_double(d6 - d10 / 2D); - int yStart = MathHelper.floor_double(d7 - d11 / 2D); - int zStart = MathHelper.floor_double(d8 - d10 / 2D); - int xEnd = MathHelper.floor_double(d6 + d10 / 2D); - int yEnd = MathHelper.floor_double(d7 + d11 / 2D); - int zEnd = MathHelper.floor_double(d8 + d10 / 2D); + for (int l = 0; l <= numberOfBlocks; l++) { + double d6 = d + ((d1 - d) * l) / numberOfBlocks; + double d7 = d4 + ((d5 - d4) * l) / numberOfBlocks; + double d8 = d2 + ((d3 - d2) * l) / numberOfBlocks; + double d9 = (random.nextDouble() * numberOfBlocks) / 16D; + double d10 = (MathHelper.sin((l * 3.141593F) / numberOfBlocks) + 1.0F) * d9 + 1.0D; + double d11 = (MathHelper.sin((l * 3.141593F) / numberOfBlocks) + 1.0F) * d9 + 1.0D; + int xStart = MathHelper.floor_double(d6 - d10 / 2D); + int yStart = MathHelper.floor_double(d7 - d11 / 2D); + int zStart = MathHelper.floor_double(d8 - d10 / 2D); + int xEnd = MathHelper.floor_double(d6 + d10 / 2D); + int yEnd = MathHelper.floor_double(d7 + d11 / 2D); + int zEnd = MathHelper.floor_double(d8 + d10 / 2D); - for (int targetX = xStart; targetX <= xEnd; targetX++) { - double d12 = ((targetX + 0.5D) - d6) / (d10 / 2D); - if (d12 * d12 >= 1.0D) { - continue; - } + for (int targetX = xStart; targetX <= xEnd; targetX++) { + double d12 = ((targetX + 0.5D) - d6) / (d10 / 2D); + if (d12 * d12 >= 1.0D) { + continue; + } - for (int targetY = yStart; targetY <= yEnd; targetY++) { - double d13 = ((targetY + 0.5D) - d7) / (d11 / 2D); - if (d12 * d12 + d13 * d13 >= 1.0D) { - continue; - } + for (int targetY = yStart; targetY <= yEnd; targetY++) { + double d13 = ((targetY + 0.5D) - d7) / (d11 / 2D); + if (d12 * d12 + d13 * d13 >= 1.0D) { + continue; + } - for (int targetZ = zStart; targetZ <= zEnd; targetZ++) { - double d14 = ((targetZ + 0.5D) - d8) / (d10 / 2D); - if (d12 * d12 + d13 * d13 + d14 * d14 < 1.0D && world.getBlock(targetX, targetY, targetZ) == Blocks.stone) { - world.setBlock(targetX, targetY, targetZ, mineableBlock, mineableBlockMeta, Constants.FLAG_BLOCK_SYNCH); - hasGenerated = true; - } - } - } - } - } - - return hasGenerated; - } + for (int targetZ = zStart; targetZ <= zEnd; targetZ++) { + double d14 = ((targetZ + 0.5D) - d8) / (d10 / 2D); + if (d12 * d12 + d13 * d13 + d14 * d14 < 1.0D + && world.getBlock(targetX, targetY, targetZ) == Blocks.stone) { + world.setBlock( + targetX, + targetY, + targetZ, + mineableBlock, + mineableBlockMeta, + Constants.FLAG_BLOCK_SYNCH); + hasGenerated = true; + } + } + } + } + } + return hasGenerated; + } } diff --git a/src/main/java/forestry/core/worldgen/WorldGenerator.java b/src/main/java/forestry/core/worldgen/WorldGenerator.java index f95632995..8f8baef2c 100644 --- a/src/main/java/forestry/core/worldgen/WorldGenerator.java +++ b/src/main/java/forestry/core/worldgen/WorldGenerator.java @@ -10,90 +10,95 @@ ******************************************************************************/ package forestry.core.worldgen; -import java.util.Random; - -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; - -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.terraingen.PopulateChunkEvent; - import cpw.mods.fml.common.IWorldGenerator; import cpw.mods.fml.common.eventhandler.SubscribeEvent; - import forestry.core.blocks.BlockResourceOre; import forestry.core.config.Config; import forestry.plugins.PluginCore; import forestry.plugins.PluginManager; +import java.util.Random; +import net.minecraft.world.World; +import net.minecraft.world.chunk.IChunkProvider; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.terraingen.PopulateChunkEvent; public class WorldGenerator implements IWorldGenerator { - private WorldGenMinableMeta apatiteGenerator; - private WorldGenMinableMeta copperGenerator; - private WorldGenMinableMeta tinGenerator; + private WorldGenMinableMeta apatiteGenerator; + private WorldGenMinableMeta copperGenerator; + private WorldGenMinableMeta tinGenerator; - public WorldGenerator() { - MinecraftForge.EVENT_BUS.register(this); - } + public WorldGenerator() { + MinecraftForge.EVENT_BUS.register(this); + } - @Override - public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { - generateWorld(random, chunkX, chunkZ, world); - } + @Override + public void generate( + Random random, + int chunkX, + int chunkZ, + World world, + IChunkProvider chunkGenerator, + IChunkProvider chunkProvider) { + generateWorld(random, chunkX, chunkZ, world); + } - @SubscribeEvent - public void populateChunk(PopulateChunkEvent.Post event) { - // / PLUGIN WORLD GENERATION - PluginManager.populateChunk(event.chunkProvider, event.world, event.rand, event.chunkX, event.chunkZ, event.hasVillageGenerated); - } + @SubscribeEvent + public void populateChunk(PopulateChunkEvent.Post event) { + // / PLUGIN WORLD GENERATION + PluginManager.populateChunk( + event.chunkProvider, event.world, event.rand, event.chunkX, event.chunkZ, event.hasVillageGenerated); + } - public void retroGen(Random random, int chunkX, int chunkZ, World world) { - generateWorld(random, chunkX, chunkZ, world); - PluginManager.populateChunkRetroGen(world, random, chunkX, chunkZ); - world.getChunkFromChunkCoords(chunkX, chunkZ).setChunkModified(); - } + public void retroGen(Random random, int chunkX, int chunkZ, World world) { + generateWorld(random, chunkX, chunkZ, world); + PluginManager.populateChunkRetroGen(world, random, chunkX, chunkZ); + world.getChunkFromChunkCoords(chunkX, chunkZ).setChunkModified(); + } - private void generateWorld(Random random, int chunkX, int chunkZ, World world) { + private void generateWorld(Random random, int chunkX, int chunkZ, World world) { - if (apatiteGenerator == null) { - apatiteGenerator = new WorldGenMinableMeta(PluginCore.blocks.resources, BlockResourceOre.ResourceType.APATITE.ordinal(), 36); - copperGenerator = new WorldGenMinableMeta(PluginCore.blocks.resources, BlockResourceOre.ResourceType.COPPER.ordinal(), 6); - tinGenerator = new WorldGenMinableMeta(PluginCore.blocks.resources, BlockResourceOre.ResourceType.TIN.ordinal(), 6); - } + if (apatiteGenerator == null) { + apatiteGenerator = new WorldGenMinableMeta( + PluginCore.blocks.resources, BlockResourceOre.ResourceType.APATITE.ordinal(), 36); + copperGenerator = new WorldGenMinableMeta( + PluginCore.blocks.resources, BlockResourceOre.ResourceType.COPPER.ordinal(), 6); + tinGenerator = new WorldGenMinableMeta( + PluginCore.blocks.resources, BlockResourceOre.ResourceType.TIN.ordinal(), 6); + } - // shift to world coordinates - chunkX = chunkX << 4; - chunkZ = chunkZ << 4; + // shift to world coordinates + chunkX = chunkX << 4; + chunkZ = chunkZ << 4; - // / APATITE - if (Config.generateApatiteOre) { - if (random.nextFloat() < 0.8f) { - int randPosX = chunkX + random.nextInt(16); - int randPosY = random.nextInt(world.getActualHeight() - 72) + 56; // Does not generate below y = 64 - int randPosZ = chunkZ + random.nextInt(16); - apatiteGenerator.generate(world, random, randPosX, randPosY, randPosZ); - } - } + // / APATITE + if (Config.generateApatiteOre) { + if (random.nextFloat() < 0.8f) { + int randPosX = chunkX + random.nextInt(16); + int randPosY = random.nextInt(world.getActualHeight() - 72) + 56; // Does not generate below y = 64 + int randPosZ = chunkZ + random.nextInt(16); + apatiteGenerator.generate(world, random, randPosX, randPosY, randPosZ); + } + } - // / COPPER - if (Config.generateCopperOre) { - for (int i = 0; i < 20; i++) { - int randPosX = chunkX + random.nextInt(16); - int randPosY = random.nextInt(76) + 32; - int randPosZ = chunkZ + random.nextInt(16); - copperGenerator.generate(world, random, randPosX, randPosY, randPosZ); - } - } - - // / TIN - if (Config.generateTinOre) { - for (int i = 0; i < 18; i++) { - int randPosX = chunkX + random.nextInt(16); - int randPosY = random.nextInt(76) + 16; - int randPosZ = chunkZ + random.nextInt(16); - tinGenerator.generate(world, random, randPosX, randPosY, randPosZ); - } - } - } + // / COPPER + if (Config.generateCopperOre) { + for (int i = 0; i < 20; i++) { + int randPosX = chunkX + random.nextInt(16); + int randPosY = random.nextInt(76) + 32; + int randPosZ = chunkZ + random.nextInt(16); + copperGenerator.generate(world, random, randPosX, randPosY, randPosZ); + } + } + // / TIN + if (Config.generateTinOre) { + for (int i = 0; i < 18; i++) { + int randPosX = chunkX + random.nextInt(16); + int randPosY = random.nextInt(76) + 16; + int randPosZ = chunkZ + random.nextInt(16); + tinGenerator.generate(world, random, randPosX, randPosY, randPosZ); + } + } + } } diff --git a/src/main/java/forestry/energy/EnergyManager.java b/src/main/java/forestry/energy/EnergyManager.java index 48e433baa..d29e64870 100644 --- a/src/main/java/forestry/energy/EnergyManager.java +++ b/src/main/java/forestry/energy/EnergyManager.java @@ -1,221 +1,220 @@ package forestry.energy; -import java.io.IOException; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import cofh.api.energy.EnergyStorage; +import cofh.api.energy.IEnergyHandler; +import cofh.api.energy.IEnergyReceiver; import forestry.api.core.ForestryAPI; import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; import forestry.core.tiles.TileEngine; import forestry.core.utils.BlockUtil; - -import cofh.api.energy.EnergyStorage; -import cofh.api.energy.IEnergyHandler; -import cofh.api.energy.IEnergyReceiver; +import java.io.IOException; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class EnergyManager implements IEnergyHandler, IStreamable { - private enum EnergyTransferMode { - EXTRACT, RECEIVE, BOTH - } + private enum EnergyTransferMode { + EXTRACT, + RECEIVE, + BOTH + } - private final EnergyStorage energyStorage; - private EnergyTransferMode mode = EnergyTransferMode.BOTH; + private final EnergyStorage energyStorage; + private EnergyTransferMode mode = EnergyTransferMode.BOTH; - public EnergyManager(int maxTransfer, int capacity) { - this.energyStorage = new EnergyStorage(scaleForDifficulty(capacity), scaleForDifficulty(maxTransfer), scaleForDifficulty(maxTransfer)); - } + public EnergyManager(int maxTransfer, int capacity) { + this.energyStorage = new EnergyStorage( + scaleForDifficulty(capacity), scaleForDifficulty(maxTransfer), scaleForDifficulty(maxTransfer)); + } - public static int scaleForDifficulty(int energyPerUse) { - return Math.round(energyPerUse * ForestryAPI.activeMode.getFloatSetting("energy.demand.modifier")); - } + public static int scaleForDifficulty(int energyPerUse) { + return Math.round(energyPerUse * ForestryAPI.activeMode.getFloatSetting("energy.demand.modifier")); + } - public void setExtractOnly() { - mode = EnergyTransferMode.EXTRACT; - } + public void setExtractOnly() { + mode = EnergyTransferMode.EXTRACT; + } - public void setReceiveOnly() { - mode = EnergyTransferMode.RECEIVE; - } + public void setReceiveOnly() { + mode = EnergyTransferMode.RECEIVE; + } - private boolean canExtract() { - switch (mode) { - case EXTRACT: - case BOTH: - return true; - } - return false; - } + private boolean canExtract() { + switch (mode) { + case EXTRACT: + case BOTH: + return true; + } + return false; + } - private boolean canReceive() { - switch (mode) { - case RECEIVE: - case BOTH: - return true; - } - return false; - } + private boolean canReceive() { + switch (mode) { + case RECEIVE: + case BOTH: + return true; + } + return false; + } - /* NBT */ - public EnergyManager readFromNBT(NBTTagCompound nbt) { + /* NBT */ + public EnergyManager readFromNBT(NBTTagCompound nbt) { - NBTTagCompound energyManagerNBT = nbt.getCompoundTag("EnergyManager"); - NBTTagCompound energyStorageNBT = energyManagerNBT.getCompoundTag("EnergyStorage"); - energyStorage.readFromNBT(energyStorageNBT); + NBTTagCompound energyManagerNBT = nbt.getCompoundTag("EnergyManager"); + NBTTagCompound energyStorageNBT = energyManagerNBT.getCompoundTag("EnergyStorage"); + energyStorage.readFromNBT(energyStorageNBT); - return this; - } + return this; + } - public NBTTagCompound writeToNBT(NBTTagCompound nbt) { + public NBTTagCompound writeToNBT(NBTTagCompound nbt) { - NBTTagCompound energyStorageNBT = new NBTTagCompound(); - energyStorage.writeToNBT(energyStorageNBT); + NBTTagCompound energyStorageNBT = new NBTTagCompound(); + energyStorage.writeToNBT(energyStorageNBT); - NBTTagCompound energyManagerNBT = new NBTTagCompound(); - energyManagerNBT.setTag("EnergyStorage", energyStorageNBT); - nbt.setTag("EnergyManager", energyManagerNBT); + NBTTagCompound energyManagerNBT = new NBTTagCompound(); + energyManagerNBT.setTag("EnergyStorage", energyStorageNBT); + nbt.setTag("EnergyManager", energyManagerNBT); - return nbt; - } + return nbt; + } - /* Packets */ - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - int energyStored = energyStorage.getEnergyStored(); - data.writeInt(energyStored); - } + /* Packets */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + int energyStored = energyStorage.getEnergyStored(); + data.writeInt(energyStored); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - int energyStored = data.readInt(); - energyStorage.setEnergyStored(energyStored); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + int energyStored = data.readInt(); + energyStorage.setEnergyStored(energyStored); + } - public int toGuiInt() { - return energyStorage.getEnergyStored(); - } + public int toGuiInt() { + return energyStorage.getEnergyStored(); + } - public void fromGuiInt(int packetInt) { - energyStorage.setEnergyStored(packetInt); - } + public void fromGuiInt(int packetInt) { + energyStorage.setEnergyStored(packetInt); + } - /* IEnergyHandler */ - @Override - public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { - if (!canReceive()) { - return 0; - } - return energyStorage.receiveEnergy(maxReceive, simulate); - } + /* IEnergyHandler */ + @Override + public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + if (!canReceive()) { + return 0; + } + return energyStorage.receiveEnergy(maxReceive, simulate); + } - @Override - public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { - if (!canExtract()) { - return 0; - } - return energyStorage.extractEnergy(maxExtract, simulate); - } + @Override + public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { + if (!canExtract()) { + return 0; + } + return energyStorage.extractEnergy(maxExtract, simulate); + } - @Override - public int getEnergyStored(ForgeDirection from) { - return energyStorage.getEnergyStored(); - } + @Override + public int getEnergyStored(ForgeDirection from) { + return energyStorage.getEnergyStored(); + } - public int getTotalEnergyStored() { - return energyStorage.getEnergyStored(); - } + public int getTotalEnergyStored() { + return energyStorage.getEnergyStored(); + } - @Override - public int getMaxEnergyStored(ForgeDirection from) { - return energyStorage.getMaxEnergyStored(); - } + @Override + public int getMaxEnergyStored(ForgeDirection from) { + return energyStorage.getMaxEnergyStored(); + } - public int getMaxEnergyStored() { - return energyStorage.getMaxEnergyStored(); - } + public int getMaxEnergyStored() { + return energyStorage.getMaxEnergyStored(); + } - public int getMaxEnergyReceived() { - return energyStorage.getMaxReceive(); - } + public int getMaxEnergyReceived() { + return energyStorage.getMaxReceive(); + } - @Override - public boolean canConnectEnergy(ForgeDirection from) { - return true; - } + @Override + public boolean canConnectEnergy(ForgeDirection from) { + return true; + } - /** - * Consumes one work cycle's worth of energy. - * - * @return true if the energy to do work was consumed - */ - public boolean consumeEnergyToDoWork(int ticksPerWorkCycle, int energyPerWorkCycle) { - int energyPerCycle = (int) Math.ceil(energyPerWorkCycle / (float) ticksPerWorkCycle); - if (energyStorage.getEnergyStored() < energyPerCycle) { - return false; - } + /** + * Consumes one work cycle's worth of energy. + * + * @return true if the energy to do work was consumed + */ + public boolean consumeEnergyToDoWork(int ticksPerWorkCycle, int energyPerWorkCycle) { + int energyPerCycle = (int) Math.ceil(energyPerWorkCycle / (float) ticksPerWorkCycle); + if (energyStorage.getEnergyStored() < energyPerCycle) { + return false; + } - energyStorage.modifyEnergyStored(-energyPerCycle); - return true; - } + energyStorage.modifyEnergyStored(-energyPerCycle); + return true; + } - /** - * @return whether this can send energy to the target tile - */ - public boolean canSendEnergy(ForgeDirection orientation, TileEntity tile) { - return sendEnergy(orientation, tile, Integer.MAX_VALUE, true) > 0; - } + /** + * @return whether this can send energy to the target tile + */ + public boolean canSendEnergy(ForgeDirection orientation, TileEntity tile) { + return sendEnergy(orientation, tile, Integer.MAX_VALUE, true) > 0; + } - /** - * Sends as much energy as it can to the tile at orientation. - * For power sources. Ignores canExtract() - * - * @return amount sent - */ - public int sendEnergy(ForgeDirection orientation, TileEntity tile) { - return sendEnergy(orientation, tile, Integer.MAX_VALUE, false); - } + /** + * Sends as much energy as it can to the tile at orientation. + * For power sources. Ignores canExtract() + * + * @return amount sent + */ + public int sendEnergy(ForgeDirection orientation, TileEntity tile) { + return sendEnergy(orientation, tile, Integer.MAX_VALUE, false); + } - /** - * Sends amount of energy to the tile at orientation. - * For power sources. Ignores canExtract() - * - * @return amount sent - */ - public int sendEnergy(ForgeDirection orientation, TileEntity tile, int amount, boolean simulate) { - int sent = 0; - if (BlockUtil.isEnergyReceiverOrEngine(orientation.getOpposite(), tile)) { - int extractable = energyStorage.extractEnergy(amount, true); - if (extractable > 0) { + /** + * Sends amount of energy to the tile at orientation. + * For power sources. Ignores canExtract() + * + * @return amount sent + */ + public int sendEnergy(ForgeDirection orientation, TileEntity tile, int amount, boolean simulate) { + int sent = 0; + if (BlockUtil.isEnergyReceiverOrEngine(orientation.getOpposite(), tile)) { + int extractable = energyStorage.extractEnergy(amount, true); + if (extractable > 0) { - if (tile instanceof IEnergyReceiver) { - IEnergyReceiver receptor = (IEnergyReceiver) tile; - sent = receptor.receiveEnergy(orientation.getOpposite(), extractable, simulate); - } else if (tile instanceof TileEngine) { - TileEngine receptor = (TileEngine) tile; - sent = receptor.getEnergyManager().receiveEnergy(orientation.getOpposite(), extractable, simulate); - } + if (tile instanceof IEnergyReceiver) { + IEnergyReceiver receptor = (IEnergyReceiver) tile; + sent = receptor.receiveEnergy(orientation.getOpposite(), extractable, simulate); + } else if (tile instanceof TileEngine) { + TileEngine receptor = (TileEngine) tile; + sent = receptor.getEnergyManager().receiveEnergy(orientation.getOpposite(), extractable, simulate); + } - energyStorage.extractEnergy(sent, simulate); - } - } - return sent; - } + energyStorage.extractEnergy(sent, simulate); + } + } + return sent; + } - /** - * Drains an amount of energy, due to decay from lack of work or other factors - */ - public void drainEnergy(int amount) { - energyStorage.modifyEnergyStored(-amount); - } + /** + * Drains an amount of energy, due to decay from lack of work or other factors + */ + public void drainEnergy(int amount) { + energyStorage.modifyEnergyStored(-amount); + } - /** - * Creates an amount of energy, generated by engines - */ - public void generateEnergy(int amount) { - energyStorage.modifyEnergyStored(amount); - } + /** + * Creates an amount of energy, generated by engines + */ + public void generateEnergy(int amount) { + energyStorage.modifyEnergyStored(amount); + } } diff --git a/src/main/java/forestry/energy/blocks/BlockEngine.java b/src/main/java/forestry/energy/blocks/BlockEngine.java index 2741cede3..bba977fe7 100644 --- a/src/main/java/forestry/energy/blocks/BlockEngine.java +++ b/src/main/java/forestry/energy/blocks/BlockEngine.java @@ -1,113 +1,124 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.blocks; - -import com.google.common.collect.ImmutableList; - -import java.util.EnumMap; -import java.util.List; - -import net.minecraft.entity.Entity; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.core.blocks.BlockBase; -import forestry.core.tiles.TileEngine; -import forestry.core.tiles.TileUtil; - -public class BlockEngine extends BlockBase { - private static final EnumMap> boundingBoxesForDirections = new EnumMap<>(ForgeDirection.class); - - static { - boundingBoxesForDirections.put(ForgeDirection.DOWN, ImmutableList.of( - AxisAlignedBB.getBoundingBox(0.0, 0.5, 0.0, 1.0, 1.0, 1.0), AxisAlignedBB.getBoundingBox(0.25, 0.0, 0.25, 0.75, 0.5, 0.75) - )); - boundingBoxesForDirections.put(ForgeDirection.UP, ImmutableList.of( - AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, 1.0, 0.5, 1.0), AxisAlignedBB.getBoundingBox(0.25, 0.5, 0.25, 0.75, 1.0, 0.75) - )); - boundingBoxesForDirections.put(ForgeDirection.NORTH, ImmutableList.of( - AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.5, 1.0, 1.0, 1.0), AxisAlignedBB.getBoundingBox(0.25, 0.25, 0.0, 0.75, 0.75, 0.5) - )); - boundingBoxesForDirections.put(ForgeDirection.SOUTH, ImmutableList.of( - AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, 1.0, 1.0, 0.5), AxisAlignedBB.getBoundingBox(0.25, 0.25, 0.5, 0.75, 0.75, 1.0) - )); - boundingBoxesForDirections.put(ForgeDirection.WEST, ImmutableList.of( - AxisAlignedBB.getBoundingBox(0.5, 0.0, 0.0, 1.0, 1.0, 1.0), AxisAlignedBB.getBoundingBox(0.0, 0.25, 0.25, 0.5, 0.75, 0.75) - )); - boundingBoxesForDirections.put(ForgeDirection.EAST, ImmutableList.of( - AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, 0.5, 1.0, 1.0), AxisAlignedBB.getBoundingBox(0.5, 0.25, 0.25, 1.0, 0.75, 0.75) - )); - } - - public BlockEngine() { - super(true); - } - - @Override - @SuppressWarnings("unchecked") - public void addCollisionBoxesToList(World world, int x, int y, int z, AxisAlignedBB mask, List list, Entity colliding) { - TileEngine tile = TileUtil.getTile(world, x, y, z, TileEngine.class); - if (tile == null) { - super.addCollisionBoxesToList(world, x, y, z, mask, list, colliding); - return; - } - - ForgeDirection orientation = tile.getOrientation(); - List boundingBoxes = boundingBoxesForDirections.get(orientation); - if (boundingBoxes == null) { - return; - } - - for (AxisAlignedBB boundingBoxBase : boundingBoxes) { - AxisAlignedBB boundingBox = boundingBoxBase.getOffsetBoundingBox(x, y, z); - if (mask.intersectsWith(boundingBox)) { - list.add(boundingBox); - } - } - } - - @Override - public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 origin, Vec3 direction) { - TileEngine tile = TileUtil.getTile(world, x, y, z, TileEngine.class); - if (tile == null) { - return super.collisionRayTrace(world, x, y, z, origin, direction); - } - - ForgeDirection orientation = tile.getOrientation(); - List boundingBoxes = boundingBoxesForDirections.get(orientation); - if (boundingBoxes == null) { - return super.collisionRayTrace(world, x, y, z, origin, direction); - } - - MovingObjectPosition nearestIntersection = null; - for (AxisAlignedBB boundingBoxBase : boundingBoxes) { - AxisAlignedBB boundingBox = boundingBoxBase.getOffsetBoundingBox(x, y, z); - MovingObjectPosition intersection = boundingBox.calculateIntercept(origin, direction); - if (intersection != null) { - if (nearestIntersection == null || (intersection.hitVec.distanceTo(origin) < nearestIntersection.hitVec.distanceTo(origin))) { - nearestIntersection = intersection; - } - } - } - - if (nearestIntersection != null) { - nearestIntersection.blockX = x; - nearestIntersection.blockY = y; - nearestIntersection.blockZ = z; - } - - return nearestIntersection; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.energy.blocks; + +import com.google.common.collect.ImmutableList; +import forestry.core.blocks.BlockBase; +import forestry.core.tiles.TileEngine; +import forestry.core.tiles.TileUtil; +import java.util.EnumMap; +import java.util.List; +import net.minecraft.entity.Entity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +public class BlockEngine extends BlockBase { + private static final EnumMap> boundingBoxesForDirections = + new EnumMap<>(ForgeDirection.class); + + static { + boundingBoxesForDirections.put( + ForgeDirection.DOWN, + ImmutableList.of( + AxisAlignedBB.getBoundingBox(0.0, 0.5, 0.0, 1.0, 1.0, 1.0), + AxisAlignedBB.getBoundingBox(0.25, 0.0, 0.25, 0.75, 0.5, 0.75))); + boundingBoxesForDirections.put( + ForgeDirection.UP, + ImmutableList.of( + AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, 1.0, 0.5, 1.0), + AxisAlignedBB.getBoundingBox(0.25, 0.5, 0.25, 0.75, 1.0, 0.75))); + boundingBoxesForDirections.put( + ForgeDirection.NORTH, + ImmutableList.of( + AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.5, 1.0, 1.0, 1.0), + AxisAlignedBB.getBoundingBox(0.25, 0.25, 0.0, 0.75, 0.75, 0.5))); + boundingBoxesForDirections.put( + ForgeDirection.SOUTH, + ImmutableList.of( + AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, 1.0, 1.0, 0.5), + AxisAlignedBB.getBoundingBox(0.25, 0.25, 0.5, 0.75, 0.75, 1.0))); + boundingBoxesForDirections.put( + ForgeDirection.WEST, + ImmutableList.of( + AxisAlignedBB.getBoundingBox(0.5, 0.0, 0.0, 1.0, 1.0, 1.0), + AxisAlignedBB.getBoundingBox(0.0, 0.25, 0.25, 0.5, 0.75, 0.75))); + boundingBoxesForDirections.put( + ForgeDirection.EAST, + ImmutableList.of( + AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, 0.5, 1.0, 1.0), + AxisAlignedBB.getBoundingBox(0.5, 0.25, 0.25, 1.0, 0.75, 0.75))); + } + + public BlockEngine() { + super(true); + } + + @Override + @SuppressWarnings("unchecked") + public void addCollisionBoxesToList( + World world, int x, int y, int z, AxisAlignedBB mask, List list, Entity colliding) { + TileEngine tile = TileUtil.getTile(world, x, y, z, TileEngine.class); + if (tile == null) { + super.addCollisionBoxesToList(world, x, y, z, mask, list, colliding); + return; + } + + ForgeDirection orientation = tile.getOrientation(); + List boundingBoxes = boundingBoxesForDirections.get(orientation); + if (boundingBoxes == null) { + return; + } + + for (AxisAlignedBB boundingBoxBase : boundingBoxes) { + AxisAlignedBB boundingBox = boundingBoxBase.getOffsetBoundingBox(x, y, z); + if (mask.intersectsWith(boundingBox)) { + list.add(boundingBox); + } + } + } + + @Override + public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 origin, Vec3 direction) { + TileEngine tile = TileUtil.getTile(world, x, y, z, TileEngine.class); + if (tile == null) { + return super.collisionRayTrace(world, x, y, z, origin, direction); + } + + ForgeDirection orientation = tile.getOrientation(); + List boundingBoxes = boundingBoxesForDirections.get(orientation); + if (boundingBoxes == null) { + return super.collisionRayTrace(world, x, y, z, origin, direction); + } + + MovingObjectPosition nearestIntersection = null; + for (AxisAlignedBB boundingBoxBase : boundingBoxes) { + AxisAlignedBB boundingBox = boundingBoxBase.getOffsetBoundingBox(x, y, z); + MovingObjectPosition intersection = boundingBox.calculateIntercept(origin, direction); + if (intersection != null) { + if (nearestIntersection == null + || (intersection.hitVec.distanceTo(origin) < nearestIntersection.hitVec.distanceTo(origin))) { + nearestIntersection = intersection; + } + } + } + + if (nearestIntersection != null) { + nearestIntersection.blockX = x; + nearestIntersection.blockY = y; + nearestIntersection.blockZ = z; + } + + return nearestIntersection; + } +} diff --git a/src/main/java/forestry/energy/blocks/BlockEngineType.java b/src/main/java/forestry/energy/blocks/BlockEngineType.java index dd8506473..b22e4dbd2 100644 --- a/src/main/java/forestry/energy/blocks/BlockEngineType.java +++ b/src/main/java/forestry/energy/blocks/BlockEngineType.java @@ -1,68 +1,68 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.blocks; - -import forestry.core.blocks.IMachinePropertiesTESR; -import forestry.core.config.Constants; -import forestry.core.proxy.Proxies; -import forestry.core.render.IBlockRenderer; -import forestry.core.tiles.TileForestry; -import forestry.energy.tiles.TileEngineBiogas; -import forestry.energy.tiles.TileEngineClockwork; -import forestry.energy.tiles.TileEngineElectric; -import forestry.energy.tiles.TileEnginePeat; -import forestry.energy.tiles.TileGenerator; -import forestry.plugins.PluginEnergy; - -public enum BlockEngineType implements IMachinePropertiesTESR { - ELECTRIC(TileEngineElectric.class, "EngineTin", "/engine_tin_"), - PEAT(TileEnginePeat.class, "EngineCopper", "/engine_copper_"), - BIOGAS(TileEngineBiogas.class, "EngineBronze", "/engine_bronze_"), - GENERATOR(TileGenerator.class, "Generator", "/generator_") { - @Override - public IBlockRenderer getRenderer() { - return Proxies.render.getRenderDefaultMachine(texturePath); - } - }, - CLOCKWORK(TileEngineClockwork.class, "EngineClockwork", "/engine_clock_"); - - public static final BlockEngineType[] VALUES = values(); - - private final String teIdent; - private final Class teClass; - protected final String texturePath; - - BlockEngineType(Class teClass, String teName, String textureName) { - this.teIdent = "forestry." + teName; - this.teClass = teClass; - this.texturePath = Constants.TEXTURE_PATH_BLOCKS + textureName; - } - - @Override - public int getMeta() { - return ordinal(); - } - - @Override - public String getTeIdent() { - return teIdent; - } - - @Override - public Class getTeClass() { - return teClass; - } - - @Override - public IBlockRenderer getRenderer() { - return PluginEnergy.proxy.getRenderDefaultEngine(texturePath); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.energy.blocks; + +import forestry.core.blocks.IMachinePropertiesTESR; +import forestry.core.config.Constants; +import forestry.core.proxy.Proxies; +import forestry.core.render.IBlockRenderer; +import forestry.core.tiles.TileForestry; +import forestry.energy.tiles.TileEngineBiogas; +import forestry.energy.tiles.TileEngineClockwork; +import forestry.energy.tiles.TileEngineElectric; +import forestry.energy.tiles.TileEnginePeat; +import forestry.energy.tiles.TileGenerator; +import forestry.plugins.PluginEnergy; + +public enum BlockEngineType implements IMachinePropertiesTESR { + ELECTRIC(TileEngineElectric.class, "EngineTin", "/engine_tin_"), + PEAT(TileEnginePeat.class, "EngineCopper", "/engine_copper_"), + BIOGAS(TileEngineBiogas.class, "EngineBronze", "/engine_bronze_"), + GENERATOR(TileGenerator.class, "Generator", "/generator_") { + @Override + public IBlockRenderer getRenderer() { + return Proxies.render.getRenderDefaultMachine(texturePath); + } + }, + CLOCKWORK(TileEngineClockwork.class, "EngineClockwork", "/engine_clock_"); + + public static final BlockEngineType[] VALUES = values(); + + private final String teIdent; + private final Class teClass; + protected final String texturePath; + + BlockEngineType(Class teClass, String teName, String textureName) { + this.teIdent = "forestry." + teName; + this.teClass = teClass; + this.texturePath = Constants.TEXTURE_PATH_BLOCKS + textureName; + } + + @Override + public int getMeta() { + return ordinal(); + } + + @Override + public String getTeIdent() { + return teIdent; + } + + @Override + public Class getTeClass() { + return teClass; + } + + @Override + public IBlockRenderer getRenderer() { + return PluginEnergy.proxy.getRenderDefaultEngine(texturePath); + } +} diff --git a/src/main/java/forestry/energy/blocks/BlockRegistryEnergy.java b/src/main/java/forestry/energy/blocks/BlockRegistryEnergy.java index 816fa4295..5dd7e24c0 100644 --- a/src/main/java/forestry/energy/blocks/BlockRegistryEnergy.java +++ b/src/main/java/forestry/energy/blocks/BlockRegistryEnergy.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.blocks; - -import forestry.core.blocks.BlockRegistry; -import forestry.core.items.ItemBlockForestry; - -public class BlockRegistryEnergy extends BlockRegistry { - public final BlockEngine engine; - - public BlockRegistryEnergy() { - engine = registerBlock(new BlockEngine(), ItemBlockForestry.class, "engine"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.energy.blocks; + +import forestry.core.blocks.BlockRegistry; +import forestry.core.items.ItemBlockForestry; + +public class BlockRegistryEnergy extends BlockRegistry { + public final BlockEngine engine; + + public BlockRegistryEnergy() { + engine = registerBlock(new BlockEngine(), ItemBlockForestry.class, "engine"); + } +} diff --git a/src/main/java/forestry/energy/circuits/CircuitElectricBoost.java b/src/main/java/forestry/energy/circuits/CircuitElectricBoost.java index 5cca5bf28..1cd7f01ac 100755 --- a/src/main/java/forestry/energy/circuits/CircuitElectricBoost.java +++ b/src/main/java/forestry/energy/circuits/CircuitElectricBoost.java @@ -12,10 +12,9 @@ package forestry.energy.circuits; public class CircuitElectricBoost extends CircuitElectricChange { - public CircuitElectricBoost(String uid, int limit, int eu, int rf) { - super(uid, false); - this.setLimit(limit); - this.configureChange(eu, rf); - } - + public CircuitElectricBoost(String uid, int limit, int eu, int rf) { + super(uid, false); + this.setLimit(limit); + this.configureChange(eu, rf); + } } diff --git a/src/main/java/forestry/energy/circuits/CircuitElectricChange.java b/src/main/java/forestry/energy/circuits/CircuitElectricChange.java index cecb6f416..d5590d1ad 100755 --- a/src/main/java/forestry/energy/circuits/CircuitElectricChange.java +++ b/src/main/java/forestry/energy/circuits/CircuitElectricChange.java @@ -15,49 +15,48 @@ import forestry.energy.tiles.TileEngineElectric; public abstract class CircuitElectricChange extends Circuit { - private int euChange = 7; - private int rfChange = 20; + private int euChange = 7; + private int rfChange = 20; - protected CircuitElectricChange(String uid, boolean requiresDiscovery) { - super(uid, requiresDiscovery); - } + protected CircuitElectricChange(String uid, boolean requiresDiscovery) { + super(uid, requiresDiscovery); + } - protected void configureChange(int euChange, int rfChange) { - this.euChange = euChange; - this.rfChange = rfChange; - } + protected void configureChange(int euChange, int rfChange) { + this.euChange = euChange; + this.rfChange = rfChange; + } - @Override - public boolean isCircuitable(Object tile) { - return tile instanceof TileEngineElectric; - } + @Override + public boolean isCircuitable(Object tile) { + return tile instanceof TileEngineElectric; + } - @Override - public void onInsertion(int slot, Object tile) { - if (!isCircuitable(tile)) { - return; - } + @Override + public void onInsertion(int slot, Object tile) { + if (!isCircuitable(tile)) { + return; + } - TileEngineElectric engine = (TileEngineElectric) tile; - engine.changeEnergyConfig(euChange, rfChange, 2 * euChange); - } + TileEngineElectric engine = (TileEngineElectric) tile; + engine.changeEnergyConfig(euChange, rfChange, 2 * euChange); + } - @Override - public void onLoad(int slot, Object tile) { - onInsertion(slot, tile); - } + @Override + public void onLoad(int slot, Object tile) { + onInsertion(slot, tile); + } - @Override - public void onRemoval(int slot, Object tile) { - if (!isCircuitable(tile)) { - return; - } + @Override + public void onRemoval(int slot, Object tile) { + if (!isCircuitable(tile)) { + return; + } - TileEngineElectric engine = (TileEngineElectric) tile; - engine.changeEnergyConfig(-euChange, -rfChange, -(2 * euChange)); - } + TileEngineElectric engine = (TileEngineElectric) tile; + engine.changeEnergyConfig(-euChange, -rfChange, -(2 * euChange)); + } - @Override - public void onTick(int slot, Object tile) { - } + @Override + public void onTick(int slot, Object tile) {} } diff --git a/src/main/java/forestry/energy/circuits/CircuitElectricChoke.java b/src/main/java/forestry/energy/circuits/CircuitElectricChoke.java index 859aae6bc..cd940c53f 100755 --- a/src/main/java/forestry/energy/circuits/CircuitElectricChoke.java +++ b/src/main/java/forestry/energy/circuits/CircuitElectricChoke.java @@ -12,9 +12,9 @@ package forestry.energy.circuits; public class CircuitElectricChoke extends CircuitElectricChange { - public CircuitElectricChoke(String uid) { - super(uid, false); - this.configureChange(-2, -10); - this.setLimit(1); - } + public CircuitElectricChoke(String uid) { + super(uid, false); + this.configureChange(-2, -10); + this.setLimit(1); + } } diff --git a/src/main/java/forestry/energy/circuits/CircuitElectricEfficiency.java b/src/main/java/forestry/energy/circuits/CircuitElectricEfficiency.java index d44ebd816..878195d6d 100755 --- a/src/main/java/forestry/energy/circuits/CircuitElectricEfficiency.java +++ b/src/main/java/forestry/energy/circuits/CircuitElectricEfficiency.java @@ -12,10 +12,9 @@ package forestry.energy.circuits; public class CircuitElectricEfficiency extends CircuitElectricChange { - public CircuitElectricEfficiency(String uid) { - super(uid, false); - this.setLimit(1); - this.configureChange(-1, 0); - } - + public CircuitElectricEfficiency(String uid) { + super(uid, false); + this.setLimit(1); + this.configureChange(-1, 0); + } } diff --git a/src/main/java/forestry/energy/gui/ContainerEngineBiogas.java b/src/main/java/forestry/energy/gui/ContainerEngineBiogas.java index 82b748cff..caa8406e3 100644 --- a/src/main/java/forestry/energy/gui/ContainerEngineBiogas.java +++ b/src/main/java/forestry/energy/gui/ContainerEngineBiogas.java @@ -10,36 +10,35 @@ ******************************************************************************/ package forestry.energy.gui; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.ICrafting; - import forestry.core.gui.ContainerLiquidTanks; import forestry.core.gui.slots.SlotFiltered; import forestry.energy.inventory.InventoryEngineBiogas; import forestry.energy.tiles.TileEngineBiogas; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.ICrafting; public class ContainerEngineBiogas extends ContainerLiquidTanks { - public ContainerEngineBiogas(InventoryPlayer player, TileEngineBiogas engine) { - super(engine, player, 8, 84); + public ContainerEngineBiogas(InventoryPlayer player, TileEngineBiogas engine) { + super(engine, player, 8, 84); - this.addSlotToContainer(new SlotFiltered(engine, InventoryEngineBiogas.SLOT_CAN, 143, 40)); - } + this.addSlotToContainer(new SlotFiltered(engine, InventoryEngineBiogas.SLOT_CAN, 143, 40)); + } - @Override - public void updateProgressBar(int messageId, int data) { - super.updateProgressBar(messageId, data); + @Override + public void updateProgressBar(int messageId, int data) { + super.updateProgressBar(messageId, data); - tile.getGUINetworkData(messageId, data); - } + tile.getGUINetworkData(messageId, data); + } - @Override - @SuppressWarnings("unchecked") - public void detectAndSendChanges() { - super.detectAndSendChanges(); + @Override + @SuppressWarnings("unchecked") + public void detectAndSendChanges() { + super.detectAndSendChanges(); - for (Object crafter : crafters) { - tile.sendGUINetworkData(this, (ICrafting) crafter); - } - } + for (Object crafter : crafters) { + tile.sendGUINetworkData(this, (ICrafting) crafter); + } + } } diff --git a/src/main/java/forestry/energy/gui/ContainerEngineElectric.java b/src/main/java/forestry/energy/gui/ContainerEngineElectric.java index 9bd9f3ba3..16fb53599 100644 --- a/src/main/java/forestry/energy/gui/ContainerEngineElectric.java +++ b/src/main/java/forestry/energy/gui/ContainerEngineElectric.java @@ -10,37 +10,34 @@ ******************************************************************************/ package forestry.energy.gui; -import forestry.core.network.packets.PacketGuiUpdate; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.ICrafting; - import forestry.core.gui.ContainerSocketed; import forestry.core.gui.slots.SlotFiltered; +import forestry.core.network.packets.PacketGuiUpdate; import forestry.energy.tiles.InventoryEngineElectric; import forestry.energy.tiles.TileEngineElectric; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerEngineElectric extends ContainerSocketed { - public ContainerEngineElectric(InventoryPlayer player, TileEngineElectric tile) { - super(tile, player, 8, 84); + public ContainerEngineElectric(InventoryPlayer player, TileEngineElectric tile) { + super(tile, player, 8, 84); - this.addSlotToContainer(new SlotFiltered(tile, InventoryEngineElectric.SLOT_BATTERY, 84, 53)); - } + this.addSlotToContainer(new SlotFiltered(tile, InventoryEngineElectric.SLOT_BATTERY, 84, 53)); + } - @Override - public void updateProgressBar(int i, int j) { - if (tile != null) { - tile.getGUINetworkData(i, j); - } - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - if (tile != null) { - PacketGuiUpdate packet = new PacketGuiUpdate(tile); - sendPacketToCrafters(packet); - } - } + @Override + public void updateProgressBar(int i, int j) { + if (tile != null) { + tile.getGUINetworkData(i, j); + } + } + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + if (tile != null) { + PacketGuiUpdate packet = new PacketGuiUpdate(tile); + sendPacketToCrafters(packet); + } + } } diff --git a/src/main/java/forestry/energy/gui/ContainerEnginePeat.java b/src/main/java/forestry/energy/gui/ContainerEnginePeat.java index 3952be592..a637a7844 100644 --- a/src/main/java/forestry/energy/gui/ContainerEnginePeat.java +++ b/src/main/java/forestry/energy/gui/ContainerEnginePeat.java @@ -10,40 +10,39 @@ ******************************************************************************/ package forestry.energy.gui; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.ICrafting; - import forestry.core.gui.ContainerTile; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.energy.tiles.TileEnginePeat; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.ICrafting; public class ContainerEnginePeat extends ContainerTile { - public ContainerEnginePeat(InventoryPlayer player, TileEnginePeat tile) { - super(tile, player, 8, 84); + public ContainerEnginePeat(InventoryPlayer player, TileEnginePeat tile) { + super(tile, player, 8, 84); - this.addSlotToContainer(new SlotFiltered(tile, 0, 44, 46)); + this.addSlotToContainer(new SlotFiltered(tile, 0, 44, 46)); - this.addSlotToContainer(new SlotOutput(tile, 1, 98, 35)); - this.addSlotToContainer(new SlotOutput(tile, 2, 98, 53)); - this.addSlotToContainer(new SlotOutput(tile, 3, 116, 35)); - this.addSlotToContainer(new SlotOutput(tile, 4, 116, 53)); - } + this.addSlotToContainer(new SlotOutput(tile, 1, 98, 35)); + this.addSlotToContainer(new SlotOutput(tile, 2, 98, 53)); + this.addSlotToContainer(new SlotOutput(tile, 3, 116, 35)); + this.addSlotToContainer(new SlotOutput(tile, 4, 116, 53)); + } - @Override - public void updateProgressBar(int i, int j) { - if (tile != null) { - tile.getGUINetworkData(i, j); - } - } + @Override + public void updateProgressBar(int i, int j) { + if (tile != null) { + tile.getGUINetworkData(i, j); + } + } - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); - for (Object crafter : crafters) { - tile.sendGUINetworkData(this, (ICrafting) crafter); - } - } + for (Object crafter : crafters) { + tile.sendGUINetworkData(this, (ICrafting) crafter); + } + } } diff --git a/src/main/java/forestry/energy/gui/ContainerGenerator.java b/src/main/java/forestry/energy/gui/ContainerGenerator.java index fc10d9e64..9b826b0db 100755 --- a/src/main/java/forestry/energy/gui/ContainerGenerator.java +++ b/src/main/java/forestry/energy/gui/ContainerGenerator.java @@ -10,36 +10,35 @@ ******************************************************************************/ package forestry.energy.gui; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.ICrafting; - import forestry.core.gui.ContainerLiquidTanks; import forestry.core.gui.slots.SlotFiltered; import forestry.energy.inventory.InventoryGenerator; import forestry.energy.tiles.TileGenerator; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.ICrafting; public class ContainerGenerator extends ContainerLiquidTanks { - public ContainerGenerator(InventoryPlayer player, TileGenerator tile) { - super(tile, player, 8, 84); + public ContainerGenerator(InventoryPlayer player, TileGenerator tile) { + super(tile, player, 8, 84); - this.addSlotToContainer(new SlotFiltered(tile, InventoryGenerator.SLOT_CAN, 22, 38)); - } + this.addSlotToContainer(new SlotFiltered(tile, InventoryGenerator.SLOT_CAN, 22, 38)); + } - @Override - public void updateProgressBar(int messageId, int data) { - super.updateProgressBar(messageId, data); + @Override + public void updateProgressBar(int messageId, int data) { + super.updateProgressBar(messageId, data); - tile.getGUINetworkData(messageId, data); - } + tile.getGUINetworkData(messageId, data); + } - @Override - @SuppressWarnings("unchecked") - public void detectAndSendChanges() { - super.detectAndSendChanges(); + @Override + @SuppressWarnings("unchecked") + public void detectAndSendChanges() { + super.detectAndSendChanges(); - for (Object crafter : crafters) { - tile.sendGUINetworkData(this, (ICrafting) crafter); - } - } + for (Object crafter : crafters) { + tile.sendGUINetworkData(this, (ICrafting) crafter); + } + } } diff --git a/src/main/java/forestry/energy/gui/GuiEngine.java b/src/main/java/forestry/energy/gui/GuiEngine.java index a75ecfae3..bc2a74080 100755 --- a/src/main/java/forestry/energy/gui/GuiEngine.java +++ b/src/main/java/forestry/energy/gui/GuiEngine.java @@ -10,62 +10,60 @@ ******************************************************************************/ package forestry.energy.gui; -import net.minecraft.inventory.Container; - import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.ledgers.Ledger; import forestry.core.render.TextureManager; import forestry.core.tiles.TileEngine; import forestry.core.utils.StringUtil; +import net.minecraft.inventory.Container; public abstract class GuiEngine extends GuiForestryTitled { - protected GuiEngine(String texture, C container, I tile) { - super(texture, container, tile); - } + protected GuiEngine(String texture, C container, I tile) { + super(texture, container, tile); + } - @Override - public void initGui() { - super.initGui(); - ledgerManager.insert(new EngineLedger()); - } + @Override + public void initGui() { + super.initGui(); + ledgerManager.insert(new EngineLedger()); + } - protected class EngineLedger extends Ledger { + protected class EngineLedger extends Ledger { - public EngineLedger() { - super(ledgerManager, "power"); - maxHeight = 94; - } + public EngineLedger() { + super(ledgerManager, "power"); + maxHeight = 94; + } - @Override - public void draw(int x, int y) { + @Override + public void draw(int x, int y) { - // Draw background - drawBackground(x, y); + // Draw background + drawBackground(x, y); - // Draw icon - drawIcon(TextureManager.getInstance().getDefault("misc/energy"), x + 3, y + 4); + // Draw icon + drawIcon(TextureManager.getInstance().getDefault("misc/energy"), x + 3, y + 4); - if (!isFullyOpened()) { - return; - } + if (!isFullyOpened()) { + return; + } - drawHeader(StringUtil.localize("gui.energy"), x + 22, y + 8); + drawHeader(StringUtil.localize("gui.energy"), x + 22, y + 8); - drawSubheader(StringUtil.localize("gui.currentOutput") + ':', x + 22, y + 20); - drawText(inventory.getCurrentOutput() + " RF/t", x + 22, y + 32); + drawSubheader(StringUtil.localize("gui.currentOutput") + ':', x + 22, y + 20); + drawText(inventory.getCurrentOutput() + " RF/t", x + 22, y + 32); - drawSubheader(StringUtil.localize("gui.stored") + ':', x + 22, y + 44); - drawText(inventory.getEnergyManager().getEnergyStored(inventory.getOrientation()) + " RF", x + 22, y + 56); + drawSubheader(StringUtil.localize("gui.stored") + ':', x + 22, y + 44); + drawText(inventory.getEnergyManager().getEnergyStored(inventory.getOrientation()) + " RF", x + 22, y + 56); - drawSubheader(StringUtil.localize("gui.heat") + ':', x + 22, y + 68); - drawText((((double) inventory.getHeat() / (double) 10) + 20.0) + " C", x + 22, y + 80); - } - - @Override - public String getTooltip() { - return inventory.getCurrentOutput() + " RF/t"; - } - } + drawSubheader(StringUtil.localize("gui.heat") + ':', x + 22, y + 68); + drawText((((double) inventory.getHeat() / (double) 10) + 20.0) + " C", x + 22, y + 80); + } + @Override + public String getTooltip() { + return inventory.getCurrentOutput() + " RF/t"; + } + } } diff --git a/src/main/java/forestry/energy/gui/GuiEngineBiogas.java b/src/main/java/forestry/energy/gui/GuiEngineBiogas.java index fe7c795f7..ff4ab7fd1 100644 --- a/src/main/java/forestry/energy/gui/GuiEngineBiogas.java +++ b/src/main/java/forestry/energy/gui/GuiEngineBiogas.java @@ -10,32 +10,32 @@ ******************************************************************************/ package forestry.energy.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.widgets.TankWidget; import forestry.energy.gui.widgets.BiogasSlot; import forestry.energy.tiles.TileEngineBiogas; +import net.minecraft.entity.player.InventoryPlayer; public class GuiEngineBiogas extends GuiEngine { - public GuiEngineBiogas(InventoryPlayer inventory, TileEngineBiogas tile) { - super(Constants.TEXTURE_PATH_GUI + "/bioengine.png", new ContainerEngineBiogas(inventory, tile), tile); - widgetManager.add(new TankWidget(widgetManager, 89, 19, 0)); - widgetManager.add(new TankWidget(widgetManager, 107, 19, 1)); + public GuiEngineBiogas(InventoryPlayer inventory, TileEngineBiogas tile) { + super(Constants.TEXTURE_PATH_GUI + "/bioengine.png", new ContainerEngineBiogas(inventory, tile), tile); + widgetManager.add(new TankWidget(widgetManager, 89, 19, 0)); + widgetManager.add(new TankWidget(widgetManager, 107, 19, 1)); - widgetManager.add(new BiogasSlot(widgetManager, 30, 47, 2)); - } + widgetManager.add(new BiogasSlot(widgetManager, 30, 47, 2)); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - int temperature = inventory.getOperatingTemperatureScaled(16); - if (temperature > 16) { - temperature = 16; - } - if (temperature > 0) { - drawTexturedModalRect(guiLeft + 53, guiTop + 47 + 16 - temperature, 176, 60 + 16 - temperature, 4, temperature); - } - } + int temperature = inventory.getOperatingTemperatureScaled(16); + if (temperature > 16) { + temperature = 16; + } + if (temperature > 0) { + drawTexturedModalRect( + guiLeft + 53, guiTop + 47 + 16 - temperature, 176, 60 + 16 - temperature, 4, temperature); + } + } } diff --git a/src/main/java/forestry/energy/gui/GuiEngineElectric.java b/src/main/java/forestry/energy/gui/GuiEngineElectric.java index 9e5cdaef8..26f7c6afa 100644 --- a/src/main/java/forestry/energy/gui/GuiEngineElectric.java +++ b/src/main/java/forestry/energy/gui/GuiEngineElectric.java @@ -10,37 +10,35 @@ ******************************************************************************/ package forestry.energy.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.widgets.SocketWidget; import forestry.core.render.EnumTankLevel; import forestry.energy.tiles.TileEngineElectric; +import net.minecraft.entity.player.InventoryPlayer; public class GuiEngineElectric extends GuiEngine { - public GuiEngineElectric(InventoryPlayer inventory, TileEngineElectric tile) { - super(Constants.TEXTURE_PATH_GUI + "/electricalengine.png", new ContainerEngineElectric(inventory, tile), tile); - widgetManager.add(new SocketWidget(this.widgetManager, 30, 40, tile, 0)); - } + public GuiEngineElectric(InventoryPlayer inventory, TileEngineElectric tile) { + super(Constants.TEXTURE_PATH_GUI + "/electricalengine.png", new ContainerEngineElectric(inventory, tile), tile); + widgetManager.add(new SocketWidget(this.widgetManager, 30, 40, tile, 0)); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - TileEngineElectric engine = inventory; - int storageHeight = engine.getStorageScaled(46); - int storageMaxHeight = engine.getStorageScaled(100); - EnumTankLevel rated = EnumTankLevel.rateTankLevel(storageMaxHeight); + TileEngineElectric engine = inventory; + int storageHeight = engine.getStorageScaled(46); + int storageMaxHeight = engine.getStorageScaled(100); + EnumTankLevel rated = EnumTankLevel.rateTankLevel(storageMaxHeight); - drawHealthMeter(guiLeft + 74, guiTop + 25, storageHeight, rated); - } + drawHealthMeter(guiLeft + 74, guiTop + 25, storageHeight, rated); + } - private void drawHealthMeter(int x, int y, int height, EnumTankLevel rated) { - int i = 176 + rated.getLevelScaled(16); - int k = 0; - - this.drawTexturedModalRect(x, y + 46 - height, i, k + 46 - height, 4, height); - } + private void drawHealthMeter(int x, int y, int height, EnumTankLevel rated) { + int i = 176 + rated.getLevelScaled(16); + int k = 0; + this.drawTexturedModalRect(x, y + 46 - height, i, k + 46 - height, 4, height); + } } diff --git a/src/main/java/forestry/energy/gui/GuiEnginePeat.java b/src/main/java/forestry/energy/gui/GuiEnginePeat.java index 83dd75f16..81202aa86 100644 --- a/src/main/java/forestry/energy/gui/GuiEnginePeat.java +++ b/src/main/java/forestry/energy/gui/GuiEnginePeat.java @@ -10,26 +10,25 @@ ******************************************************************************/ package forestry.energy.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.energy.tiles.TileEnginePeat; +import net.minecraft.entity.player.InventoryPlayer; public class GuiEnginePeat extends GuiEngine { - public GuiEnginePeat(InventoryPlayer inventory, TileEnginePeat tile) { - super(Constants.TEXTURE_PATH_GUI + "/peatengine.png", new ContainerEnginePeat(inventory, tile), tile); - } + public GuiEnginePeat(InventoryPlayer inventory, TileEnginePeat tile) { + super(Constants.TEXTURE_PATH_GUI + "/peatengine.png", new ContainerEnginePeat(inventory, tile), tile); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - TileEnginePeat engine = inventory; - int progress; - if (engine.isBurning()) { - progress = engine.getBurnTimeRemainingScaled(12); - this.drawTexturedModalRect(guiLeft + 45, guiTop + 27 + 12 - progress, 176, 12 - progress, 14, progress + 2); - } - } + TileEnginePeat engine = inventory; + int progress; + if (engine.isBurning()) { + progress = engine.getBurnTimeRemainingScaled(12); + this.drawTexturedModalRect(guiLeft + 45, guiTop + 27 + 12 - progress, 176, 12 - progress, 14, progress + 2); + } + } } diff --git a/src/main/java/forestry/energy/gui/GuiGenerator.java b/src/main/java/forestry/energy/gui/GuiGenerator.java index 01b536bf7..9bc2fb39c 100755 --- a/src/main/java/forestry/energy/gui/GuiGenerator.java +++ b/src/main/java/forestry/energy/gui/GuiGenerator.java @@ -10,28 +10,26 @@ ******************************************************************************/ package forestry.energy.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; import forestry.energy.tiles.TileGenerator; +import net.minecraft.entity.player.InventoryPlayer; public class GuiGenerator extends GuiForestryTitled { - public GuiGenerator(InventoryPlayer inventory, TileGenerator tile) { - super(Constants.TEXTURE_PATH_GUI + "/generator.png", new ContainerGenerator(inventory, tile), tile); - widgetManager.add(new TankWidget(this.widgetManager, 49, 17, 0)); - } + public GuiGenerator(InventoryPlayer inventory, TileGenerator tile) { + super(Constants.TEXTURE_PATH_GUI + "/generator.png", new ContainerGenerator(inventory, tile), tile); + widgetManager.add(new TankWidget(this.widgetManager, 49, 17, 0)); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - - int progress = inventory.getStoredScaled(49); - if (progress > 0) { - drawTexturedModalRect(guiLeft + 108, guiTop + 38, 176, 91, progress, 18); - } - } + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + int progress = inventory.getStoredScaled(49); + if (progress > 0) { + drawTexturedModalRect(guiLeft + 108, guiTop + 38, 176, 91, progress, 18); + } + } } diff --git a/src/main/java/forestry/energy/gui/widgets/BiogasSlot.java b/src/main/java/forestry/energy/gui/widgets/BiogasSlot.java index c3def307c..cb80b50b1 100644 --- a/src/main/java/forestry/energy/gui/widgets/BiogasSlot.java +++ b/src/main/java/forestry/energy/gui/widgets/BiogasSlot.java @@ -1,44 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.gui.widgets; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; - -import forestry.core.gui.tooltips.ToolTip; -import forestry.core.gui.widgets.ReservoirWidget; -import forestry.core.gui.widgets.WidgetManager; -import forestry.core.utils.StringUtil; - -public class BiogasSlot extends ReservoirWidget { - public BiogasSlot(WidgetManager manager, int xPos, int yPos, int slot) { - super(manager, xPos, yPos, slot); - } - - @Override - public ToolTip getToolTip(int mouseX, int mouseY) { - IFluidTank tank = getTank(); - ToolTip toolTip = new ToolTip(); - FluidStack fluid = tank.getFluid(); - if (fluid == null) { - toolTip.add(StringUtil.localize("gui.empty")); - } else { - toolTip.add(fluid.getLocalizedName()); - } - - return toolTip; - } - - @Override - public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - // do not allow pipette - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.energy.gui.widgets; + +import forestry.core.gui.tooltips.ToolTip; +import forestry.core.gui.widgets.ReservoirWidget; +import forestry.core.gui.widgets.WidgetManager; +import forestry.core.utils.StringUtil; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.IFluidTank; + +public class BiogasSlot extends ReservoirWidget { + public BiogasSlot(WidgetManager manager, int xPos, int yPos, int slot) { + super(manager, xPos, yPos, slot); + } + + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + IFluidTank tank = getTank(); + ToolTip toolTip = new ToolTip(); + FluidStack fluid = tank.getFluid(); + if (fluid == null) { + toolTip.add(StringUtil.localize("gui.empty")); + } else { + toolTip.add(fluid.getLocalizedName()); + } + + return toolTip; + } + + @Override + public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { + // do not allow pipette + } +} diff --git a/src/main/java/forestry/energy/inventory/InventoryEngineBiogas.java b/src/main/java/forestry/energy/inventory/InventoryEngineBiogas.java index 813eb1b62..c33476429 100644 --- a/src/main/java/forestry/energy/inventory/InventoryEngineBiogas.java +++ b/src/main/java/forestry/energy/inventory/InventoryEngineBiogas.java @@ -1,37 +1,35 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.inventory; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.Fluid; - -import forestry.core.fluids.FluidHelper; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.energy.tiles.TileEngineBiogas; - -public class InventoryEngineBiogas extends InventoryAdapterTile { - public static final short SLOT_CAN = 0; - - public InventoryEngineBiogas(TileEngineBiogas engineBronze) { - super(engineBronze, 1, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_CAN) { - Fluid fluid = FluidHelper.getFluidInContainer(itemStack); - return tile.getTankManager().accepts(fluid); - } - - return false; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.energy.inventory; + +import forestry.core.fluids.FluidHelper; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.energy.tiles.TileEngineBiogas; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; + +public class InventoryEngineBiogas extends InventoryAdapterTile { + public static final short SLOT_CAN = 0; + + public InventoryEngineBiogas(TileEngineBiogas engineBronze) { + super(engineBronze, 1, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_CAN) { + Fluid fluid = FluidHelper.getFluidInContainer(itemStack); + return tile.getTankManager().accepts(fluid); + } + + return false; + } +} diff --git a/src/main/java/forestry/energy/inventory/InventoryEnginePeat.java b/src/main/java/forestry/energy/inventory/InventoryEnginePeat.java index baa2c3b4e..62f186a21 100644 --- a/src/main/java/forestry/energy/inventory/InventoryEnginePeat.java +++ b/src/main/java/forestry/energy/inventory/InventoryEnginePeat.java @@ -1,38 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.inventory; - -import net.minecraft.item.ItemStack; - -import forestry.api.fuels.FuelManager; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.utils.SlotUtil; -import forestry.energy.tiles.TileEnginePeat; - -public class InventoryEnginePeat extends InventoryAdapterTile { - public static final short SLOT_FUEL = 0; - public static final short SLOT_WASTE_1 = 1; - public static final short SLOT_WASTE_COUNT = 4; - - public InventoryEnginePeat(TileEnginePeat engineCopper) { - super(engineCopper, 5, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return slotIndex == SLOT_FUEL && FuelManager.copperEngineFuel.containsKey(itemStack); - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { - return SlotUtil.isSlotInRange(slotIndex, SLOT_WASTE_1, SLOT_WASTE_COUNT); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.energy.inventory; + +import forestry.api.fuels.FuelManager; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.core.utils.SlotUtil; +import forestry.energy.tiles.TileEnginePeat; +import net.minecraft.item.ItemStack; + +public class InventoryEnginePeat extends InventoryAdapterTile { + public static final short SLOT_FUEL = 0; + public static final short SLOT_WASTE_1 = 1; + public static final short SLOT_WASTE_COUNT = 4; + + public InventoryEnginePeat(TileEnginePeat engineCopper) { + super(engineCopper, 5, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return slotIndex == SLOT_FUEL && FuelManager.copperEngineFuel.containsKey(itemStack); + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { + return SlotUtil.isSlotInRange(slotIndex, SLOT_WASTE_1, SLOT_WASTE_COUNT); + } +} diff --git a/src/main/java/forestry/energy/inventory/InventoryGenerator.java b/src/main/java/forestry/energy/inventory/InventoryGenerator.java index 457e5e269..41bfe81f6 100644 --- a/src/main/java/forestry/energy/inventory/InventoryGenerator.java +++ b/src/main/java/forestry/energy/inventory/InventoryGenerator.java @@ -1,37 +1,35 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.inventory; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.Fluid; - -import forestry.core.fluids.FluidHelper; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.energy.tiles.TileGenerator; - -public class InventoryGenerator extends InventoryAdapterTile { - public static final short SLOT_CAN = 0; - - public InventoryGenerator(TileGenerator generator) { - super(generator, 1, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_CAN) { - Fluid fluid = FluidHelper.getFluidInContainer(itemStack); - return tile.getTankManager().accepts(fluid); - } - - return false; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.energy.inventory; + +import forestry.core.fluids.FluidHelper; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.energy.tiles.TileGenerator; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; + +public class InventoryGenerator extends InventoryAdapterTile { + public static final short SLOT_CAN = 0; + + public InventoryGenerator(TileGenerator generator) { + super(generator, 1, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_CAN) { + Fluid fluid = FluidHelper.getFluidInContainer(itemStack); + return tile.getTankManager().accepts(fluid); + } + + return false; + } +} diff --git a/src/main/java/forestry/energy/proxy/ProxyEnergy.java b/src/main/java/forestry/energy/proxy/ProxyEnergy.java index 23ce67da2..74539574f 100755 --- a/src/main/java/forestry/energy/proxy/ProxyEnergy.java +++ b/src/main/java/forestry/energy/proxy/ProxyEnergy.java @@ -13,7 +13,7 @@ package forestry.energy.proxy; import forestry.core.render.IBlockRenderer; public class ProxyEnergy { - public IBlockRenderer getRenderDefaultEngine(String gfxBase) { - return null; - } + public IBlockRenderer getRenderDefaultEngine(String gfxBase) { + return null; + } } diff --git a/src/main/java/forestry/energy/proxy/ProxyEnergyClient.java b/src/main/java/forestry/energy/proxy/ProxyEnergyClient.java index 20e9fd89a..a49ca950a 100644 --- a/src/main/java/forestry/energy/proxy/ProxyEnergyClient.java +++ b/src/main/java/forestry/energy/proxy/ProxyEnergyClient.java @@ -15,8 +15,7 @@ import forestry.energy.render.RenderEngine; public class ProxyEnergyClient extends ProxyEnergy { - public IBlockRenderer getRenderDefaultEngine(String gfxBase) { - return new RenderEngine(gfxBase); - } - + public IBlockRenderer getRenderDefaultEngine(String gfxBase) { + return new RenderEngine(gfxBase); + } } diff --git a/src/main/java/forestry/energy/render/RenderEngine.java b/src/main/java/forestry/energy/render/RenderEngine.java index 4a9537047..84d3a3581 100755 --- a/src/main/java/forestry/energy/render/RenderEngine.java +++ b/src/main/java/forestry/energy/render/RenderEngine.java @@ -10,16 +10,6 @@ ******************************************************************************/ package forestry.energy.render; -import net.minecraft.client.model.ModelBase; -import net.minecraft.client.model.ModelRenderer; -import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ResourceLocation; - -import net.minecraftforge.common.util.ForgeDirection; - -import org.lwjgl.opengl.GL11; - import forestry.core.config.Constants; import forestry.core.proxy.Proxies; import forestry.core.render.ForestryResource; @@ -27,186 +17,199 @@ import forestry.core.render.IBlockRenderer; import forestry.core.tiles.TemperatureState; import forestry.core.tiles.TileEngine; import forestry.core.utils.Log; +import net.minecraft.client.model.ModelBase; +import net.minecraft.client.model.ModelRenderer; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.common.util.ForgeDirection; +import org.lwjgl.opengl.GL11; public class RenderEngine extends TileEntitySpecialRenderer implements IBlockRenderer { - private final ModelBase model = new ModelBase() { - }; - private final ModelRenderer boiler; - private final ModelRenderer trunk; - private final ModelRenderer piston; - private final ModelRenderer extension; + private final ModelBase model = new ModelBase() {}; + private final ModelRenderer boiler; + private final ModelRenderer trunk; + private final ModelRenderer piston; + private final ModelRenderer extension; - private enum Textures { + private enum Textures { + BASE, + PISTON, + EXTENSION, + TRUNK_HIGHEST, + TRUNK_HIGHER, + TRUNK_HIGH, + TRUNK_MEDIUM, + TRUNK_LOW + } - BASE, PISTON, EXTENSION, TRUNK_HIGHEST, TRUNK_HIGHER, TRUNK_HIGH, TRUNK_MEDIUM, TRUNK_LOW - } + private ResourceLocation[] textures; + private static final float[] angleMap = new float[6]; - private ResourceLocation[] textures; - private static final float[] angleMap = new float[6]; + static { + angleMap[ForgeDirection.EAST.ordinal()] = (float) -Math.PI / 2; + angleMap[ForgeDirection.WEST.ordinal()] = (float) Math.PI / 2; + angleMap[ForgeDirection.UP.ordinal()] = 0; + angleMap[ForgeDirection.DOWN.ordinal()] = (float) Math.PI; + angleMap[ForgeDirection.SOUTH.ordinal()] = (float) Math.PI / 2; + angleMap[ForgeDirection.NORTH.ordinal()] = (float) -Math.PI / 2; + } - static { - angleMap[ForgeDirection.EAST.ordinal()] = (float) -Math.PI / 2; - angleMap[ForgeDirection.WEST.ordinal()] = (float) Math.PI / 2; - angleMap[ForgeDirection.UP.ordinal()] = 0; - angleMap[ForgeDirection.DOWN.ordinal()] = (float) Math.PI; - angleMap[ForgeDirection.SOUTH.ordinal()] = (float) Math.PI / 2; - angleMap[ForgeDirection.NORTH.ordinal()] = (float) -Math.PI / 2; - } + public RenderEngine() { + boiler = new ModelRenderer(model, 0, 0); + boiler.addBox(-8F, -8F, -8F, 16, 6, 16); + boiler.rotationPointX = 8; + boiler.rotationPointY = 8; + boiler.rotationPointZ = 8; - public RenderEngine() { - boiler = new ModelRenderer(model, 0, 0); - boiler.addBox(-8F, -8F, -8F, 16, 6, 16); - boiler.rotationPointX = 8; - boiler.rotationPointY = 8; - boiler.rotationPointZ = 8; + trunk = new ModelRenderer(model, 0, 0); + trunk.addBox(-4F, -4F, -4F, 8, 12, 8); + trunk.rotationPointX = 8F; + trunk.rotationPointY = 8F; + trunk.rotationPointZ = 8F; - trunk = new ModelRenderer(model, 0, 0); - trunk.addBox(-4F, -4F, -4F, 8, 12, 8); - trunk.rotationPointX = 8F; - trunk.rotationPointY = 8F; - trunk.rotationPointZ = 8F; + piston = new ModelRenderer(model, 0, 0); + piston.addBox(-6F, -2, -6F, 12, 4, 12); + piston.rotationPointX = 8F; + piston.rotationPointY = 8F; + piston.rotationPointZ = 8F; - piston = new ModelRenderer(model, 0, 0); - piston.addBox(-6F, -2, -6F, 12, 4, 12); - piston.rotationPointX = 8F; - piston.rotationPointY = 8F; - piston.rotationPointZ = 8F; + extension = new ModelRenderer(model, 0, 0); + extension.addBox(-5F, -3, -5F, 10, 2, 10); + extension.rotationPointX = 8F; + extension.rotationPointY = 8F; + extension.rotationPointZ = 8F; + } - extension = new ModelRenderer(model, 0, 0); - extension.addBox(-5F, -3, -5F, 10, 2, 10); - extension.rotationPointX = 8F; - extension.rotationPointY = 8F; - extension.rotationPointZ = 8F; - } + public RenderEngine(String baseTexture) { + this(); - public RenderEngine(String baseTexture) { - this(); + textures = new ResourceLocation[] { + new ForestryResource(baseTexture + "base.png"), + new ForestryResource(baseTexture + "piston.png"), + new ForestryResource(baseTexture + "extension.png"), + new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/engine_trunk_highest.png"), + new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/engine_trunk_higher.png"), + new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/engine_trunk_high.png"), + new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/engine_trunk_medium.png"), + new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/engine_trunk_low.png"), + }; + } - textures = new ResourceLocation[]{ - new ForestryResource(baseTexture + "base.png"), - new ForestryResource(baseTexture + "piston.png"), - new ForestryResource(baseTexture + "extension.png"), - new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/engine_trunk_highest.png"), - new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/engine_trunk_higher.png"), - new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/engine_trunk_high.png"), - new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/engine_trunk_medium.png"), - new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/engine_trunk_low.png"),}; - } + @Override + public void inventoryRender(double x, double y, double z) { + render(TemperatureState.COOL, 0.25F, ForgeDirection.UP, x, y, z); + } - @Override - public void inventoryRender(double x, double y, double z) { - render(TemperatureState.COOL, 0.25F, ForgeDirection.UP, x, y, z); - } + @Override + public void renderTileEntityAt(TileEntity tile, double d, double d1, double d2, float f) { + if (tile instanceof TileEngine) { + TileEngine tileEngine = (TileEngine) tile; + render(tileEngine.getTemperatureState(), tileEngine.progress, tileEngine.getOrientation(), d, d1, d2); + } else { + Log.severe("Tried to render a tile entity that is not an engine: " + tile); + } + } - @Override - public void renderTileEntityAt(TileEntity tile, double d, double d1, double d2, float f) { - if (tile instanceof TileEngine) { - TileEngine tileEngine = (TileEngine) tile; - render(tileEngine.getTemperatureState(), tileEngine.progress, tileEngine.getOrientation(), d, d1, d2); - } else { - Log.severe("Tried to render a tile entity that is not an engine: " + tile); - } - } + private void render( + TemperatureState state, float progress, ForgeDirection orientation, double x, double y, double z) { - private void render(TemperatureState state, float progress, ForgeDirection orientation, double x, double y, double z) { + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glColor3f(1, 1, 1); - GL11.glPushMatrix(); - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_CULL_FACE); - GL11.glColor3f(1, 1, 1); + GL11.glTranslatef((float) x, (float) y, (float) z); - GL11.glTranslatef((float) x, (float) y, (float) z); + float step; - float step; + if (progress > 0.5) { + step = 5.99F - (progress - 0.5F) * 2F * 5.99F; + } else { + step = progress * 2F * 5.99F; + } - if (progress > 0.5) { - step = 5.99F - (progress - 0.5F) * 2F * 5.99F; - } else { - step = progress * 2F * 5.99F; - } + float tfactor = step / 16; - float tfactor = step / 16; + float[] angle = {0, 0, 0}; + float[] translate = {orientation.offsetX, orientation.offsetY, orientation.offsetZ}; - float[] angle = {0, 0, 0}; - float[] translate = {orientation.offsetX, orientation.offsetY, orientation.offsetZ}; + switch (orientation) { + case EAST: + case WEST: + case DOWN: + angle[2] = angleMap[orientation.ordinal()]; + break; + case SOUTH: + case NORTH: + default: + angle[0] = angleMap[orientation.ordinal()]; + break; + } - switch (orientation) { - case EAST: - case WEST: - case DOWN: - angle[2] = angleMap[orientation.ordinal()]; - break; - case SOUTH: - case NORTH: - default: - angle[0] = angleMap[orientation.ordinal()]; - break; - } + boiler.rotateAngleX = angle[0]; + boiler.rotateAngleY = angle[1]; + boiler.rotateAngleZ = angle[2]; - boiler.rotateAngleX = angle[0]; - boiler.rotateAngleY = angle[1]; - boiler.rotateAngleZ = angle[2]; + trunk.rotateAngleX = angle[0]; + trunk.rotateAngleY = angle[1]; + trunk.rotateAngleZ = angle[2]; - trunk.rotateAngleX = angle[0]; - trunk.rotateAngleY = angle[1]; - trunk.rotateAngleZ = angle[2]; + piston.rotateAngleX = angle[0]; + piston.rotateAngleY = angle[1]; + piston.rotateAngleZ = angle[2]; - piston.rotateAngleX = angle[0]; - piston.rotateAngleY = angle[1]; - piston.rotateAngleZ = angle[2]; + extension.rotateAngleX = angle[0]; + extension.rotateAngleY = angle[1]; + extension.rotateAngleZ = angle[2]; - extension.rotateAngleX = angle[0]; - extension.rotateAngleY = angle[1]; - extension.rotateAngleZ = angle[2]; + float factor = (float) (1.0 / 16.0); - float factor = (float) (1.0 / 16.0); + Proxies.render.bindTexture(textures[Textures.BASE.ordinal()]); + boiler.render(factor); - Proxies.render.bindTexture(textures[Textures.BASE.ordinal()]); - boiler.render(factor); + Proxies.render.bindTexture(textures[Textures.PISTON.ordinal()]); + GL11.glTranslatef(translate[0] * tfactor, translate[1] * tfactor, translate[2] * tfactor); + piston.render(factor); + GL11.glTranslatef(-translate[0] * tfactor, -translate[1] * tfactor, -translate[2] * tfactor); - Proxies.render.bindTexture(textures[Textures.PISTON.ordinal()]); - GL11.glTranslatef(translate[0] * tfactor, translate[1] * tfactor, translate[2] * tfactor); - piston.render(factor); - GL11.glTranslatef(-translate[0] * tfactor, -translate[1] * tfactor, -translate[2] * tfactor); + ResourceLocation texture; - ResourceLocation texture; + switch (state) { + case OVERHEATING: + texture = textures[Textures.TRUNK_HIGHEST.ordinal()]; + break; + case RUNNING_HOT: + texture = textures[Textures.TRUNK_HIGHER.ordinal()]; + break; + case OPERATING_TEMPERATURE: + texture = textures[Textures.TRUNK_HIGH.ordinal()]; + break; + case WARMED_UP: + texture = textures[Textures.TRUNK_MEDIUM.ordinal()]; + break; + case COOL: + default: + texture = textures[Textures.TRUNK_LOW.ordinal()]; + break; + } + Proxies.render.bindTexture(texture); + trunk.render(factor); - switch (state) { - case OVERHEATING: - texture = textures[Textures.TRUNK_HIGHEST.ordinal()]; - break; - case RUNNING_HOT: - texture = textures[Textures.TRUNK_HIGHER.ordinal()]; - break; - case OPERATING_TEMPERATURE: - texture = textures[Textures.TRUNK_HIGH.ordinal()]; - break; - case WARMED_UP: - texture = textures[Textures.TRUNK_MEDIUM.ordinal()]; - break; - case COOL: - default: - texture = textures[Textures.TRUNK_LOW.ordinal()]; - break; + Proxies.render.bindTexture(textures[Textures.EXTENSION.ordinal()]); + float chamberf = 2F / 16F; - } - Proxies.render.bindTexture(texture); - trunk.render(factor); + if (step > 0) { + for (int i = 0; i <= step + 2; i += 2) { + extension.render(factor); + GL11.glTranslatef(translate[0] * chamberf, translate[1] * chamberf, translate[2] * chamberf); + } + } - Proxies.render.bindTexture(textures[Textures.EXTENSION.ordinal()]); - float chamberf = 2F / 16F; - - if (step > 0) { - for (int i = 0; i <= step + 2; i += 2) { - extension.render(factor); - GL11.glTranslatef(translate[0] * chamberf, translate[1] * chamberf, translate[2] * chamberf); - } - } - - GL11.glPopAttrib(); - GL11.glPopMatrix(); - } + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } } diff --git a/src/main/java/forestry/energy/tiles/EngineDefinition.java b/src/main/java/forestry/energy/tiles/EngineDefinition.java index 23b74d231..9919256ad 100644 --- a/src/main/java/forestry/energy/tiles/EngineDefinition.java +++ b/src/main/java/forestry/energy/tiles/EngineDefinition.java @@ -10,26 +10,25 @@ ******************************************************************************/ package forestry.energy.tiles; -import net.minecraft.world.IBlockAccess; - import forestry.core.blocks.IMachinePropertiesTESR; import forestry.core.tiles.MachineDefinition; import forestry.core.tiles.TileEngine; import forestry.core.tiles.TileUtil; +import net.minecraft.world.IBlockAccess; public class EngineDefinition extends MachineDefinition { - public EngineDefinition(IMachinePropertiesTESR properties) { - super(properties); - } + public EngineDefinition(IMachinePropertiesTESR properties) { + super(properties); + } - @Override - public boolean isSolidOnSide(IBlockAccess world, int x, int y, int z, int side) { - TileEngine tile = TileUtil.getTile(world, x, y, z, TileEngine.class); - if (tile == null) { - return false; - } + @Override + public boolean isSolidOnSide(IBlockAccess world, int x, int y, int z, int side) { + TileEngine tile = TileUtil.getTile(world, x, y, z, TileEngine.class); + if (tile == null) { + return false; + } - return tile.getOrientation().getOpposite().ordinal() == side; - } + return tile.getOrientation().getOpposite().ordinal() == side; + } } diff --git a/src/main/java/forestry/energy/tiles/InventoryEngineElectric.java b/src/main/java/forestry/energy/tiles/InventoryEngineElectric.java index 58c94e1c9..9dea8bf51 100644 --- a/src/main/java/forestry/energy/tiles/InventoryEngineElectric.java +++ b/src/main/java/forestry/energy/tiles/InventoryEngineElectric.java @@ -1,33 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.tiles; - -import net.minecraft.item.ItemStack; - -import forestry.core.inventory.InventoryAdapterTile; - -import ic2.api.item.ElectricItem; - -public class InventoryEngineElectric extends InventoryAdapterTile { - public static final short SLOT_BATTERY = 0; - - public InventoryEngineElectric(TileEngineElectric engineTin) { - super(engineTin, 1, "electrical"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_BATTERY) { - return ElectricItem.manager.getCharge(itemStack) > 0; - } - return false; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.energy.tiles; + +import forestry.core.inventory.InventoryAdapterTile; +import ic2.api.item.ElectricItem; +import net.minecraft.item.ItemStack; + +public class InventoryEngineElectric extends InventoryAdapterTile { + public static final short SLOT_BATTERY = 0; + + public InventoryEngineElectric(TileEngineElectric engineTin) { + super(engineTin, 1, "electrical"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_BATTERY) { + return ElectricItem.manager.getCharge(itemStack) > 0; + } + return false; + } +} diff --git a/src/main/java/forestry/energy/tiles/TileEngineBiogas.java b/src/main/java/forestry/energy/tiles/TileEngineBiogas.java index d986b536b..be9dbdf75 100644 --- a/src/main/java/forestry/energy/tiles/TileEngineBiogas.java +++ b/src/main/java/forestry/energy/tiles/TileEngineBiogas.java @@ -10,21 +10,6 @@ ******************************************************************************/ package forestry.energy.tiles; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.ICrafting; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; - import forestry.api.core.IErrorLogic; import forestry.api.fuels.EngineBronzeFuel; import forestry.api.fuels.FuelManager; @@ -42,306 +27,316 @@ import forestry.core.tiles.TileEngine; import forestry.energy.gui.ContainerEngineBiogas; import forestry.energy.gui.GuiEngineBiogas; import forestry.energy.inventory.InventoryEngineBiogas; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; public class TileEngineBiogas extends TileEngine implements ISidedInventory, ILiquidTankTile, IFluidHandler { - private final FilteredTank fuelTank; - private final FilteredTank heatingTank; - private final StandardTank burnTank; - private final TankManager tankManager; + private final FilteredTank fuelTank; + private final FilteredTank heatingTank; + private final StandardTank burnTank; + private final TankManager tankManager; - private boolean shutdown; // true if the engine is too cold and needs to warm itself up. + private boolean shutdown; // true if the engine is too cold and needs to warm itself up. - public TileEngineBiogas() { - super("engine.bronze", Constants.ENGINE_BRONZE_HEAT_MAX, 300000); + public TileEngineBiogas() { + super("engine.bronze", Constants.ENGINE_BRONZE_HEAT_MAX, 300000); - setInternalInventory(new InventoryEngineBiogas(this)); + setInternalInventory(new InventoryEngineBiogas(this)); - fuelTank = new FilteredTank(Constants.ENGINE_TANK_CAPACITY, FuelManager.bronzeEngineFuel.keySet()); - fuelTank.tankMode = StandardTank.TankMode.DEFAULT; - heatingTank = new FilteredTank(Constants.ENGINE_TANK_CAPACITY, FluidRegistry.LAVA); - heatingTank.tankMode = StandardTank.TankMode.INPUT; - burnTank = new StandardTank(Constants.BUCKET_VOLUME); - burnTank.tankMode = StandardTank.TankMode.INTERNAL; - this.tankManager = new TankManager(this, fuelTank, heatingTank, burnTank); - } + fuelTank = new FilteredTank(Constants.ENGINE_TANK_CAPACITY, FuelManager.bronzeEngineFuel.keySet()); + fuelTank.tankMode = StandardTank.TankMode.DEFAULT; + heatingTank = new FilteredTank(Constants.ENGINE_TANK_CAPACITY, FluidRegistry.LAVA); + heatingTank.tankMode = StandardTank.TankMode.INPUT; + burnTank = new StandardTank(Constants.BUCKET_VOLUME); + burnTank.tankMode = StandardTank.TankMode.INTERNAL; + this.tankManager = new TankManager(this, fuelTank, heatingTank, burnTank); + } - @Override - public TankManager getTankManager() { - return tankManager; - } + @Override + public TankManager getTankManager() { + return tankManager; + } - public Fluid getBurnTankFluidType() { - return burnTank.getFluidType(); - } + public Fluid getBurnTankFluidType() { + return burnTank.getFluidType(); + } - @Override - public void updateServerSide() { - super.updateServerSide(); - if (!updateOnInterval(20)) { - return; - } + @Override + public void updateServerSide() { + super.updateServerSide(); + if (!updateOnInterval(20)) { + return; + } - // Check if we have suitable items waiting in the item slot - FluidHelper.drainContainers(tankManager, this, InventoryEngineBiogas.SLOT_CAN); + // Check if we have suitable items waiting in the item slot + FluidHelper.drainContainers(tankManager, this, InventoryEngineBiogas.SLOT_CAN); - IErrorLogic errorLogic = getErrorLogic(); + IErrorLogic errorLogic = getErrorLogic(); - boolean hasHeat = getHeatLevel() > 0.2 || heatingTank.getFluidAmount() > 0; - errorLogic.setCondition(!hasHeat, EnumErrorCode.NO_HEAT); + boolean hasHeat = getHeatLevel() > 0.2 || heatingTank.getFluidAmount() > 0; + errorLogic.setCondition(!hasHeat, EnumErrorCode.NO_HEAT); - boolean hasFuel = burnTank.getFluidAmount() > 0 || fuelTank.getFluidAmount() > 0; - errorLogic.setCondition(!hasFuel, EnumErrorCode.NO_FUEL); - } + boolean hasFuel = burnTank.getFluidAmount() > 0 || fuelTank.getFluidAmount() > 0; + errorLogic.setCondition(!hasFuel, EnumErrorCode.NO_FUEL); + } - /** - * Burns fuel increasing stored energy - */ - @Override - public void burn() { + /** + * Burns fuel increasing stored energy + */ + @Override + public void burn() { - currentOutput = 0; + currentOutput = 0; - if (isRedstoneActivated() && (fuelTank.getFluidAmount() >= Constants.BUCKET_VOLUME || burnTank.getFluidAmount() > 0)) { + if (isRedstoneActivated() + && (fuelTank.getFluidAmount() >= Constants.BUCKET_VOLUME || burnTank.getFluidAmount() > 0)) { - double heatStage = getHeatLevel(); + double heatStage = getHeatLevel(); - // If we have reached a safe temperature, enable energy transfer - if (heatStage > 0.25 && shutdown) { - shutdown(false); - } else if (shutdown) + // If we have reached a safe temperature, enable energy transfer + if (heatStage > 0.25 && shutdown) { + shutdown(false); + } else if (shutdown) { + if (heatingTank.getFluidAmount() > 0 && Fluids.LAVA.is(heatingTank.getFluid())) { + addHeat(Constants.ENGINE_HEAT_VALUE_LAVA); + heatingTank.drain(1, true); + } + } - { - if (heatingTank.getFluidAmount() > 0 && Fluids.LAVA.is(heatingTank.getFluid())) { - addHeat(Constants.ENGINE_HEAT_VALUE_LAVA); - heatingTank.drain(1, true); - } - } + // We need a minimum temperature to generate energy + if (heatStage > 0.2) { + if (burnTank.getFluidAmount() > 0) { + FluidStack drained = burnTank.drain(1, true); + currentOutput = determineFuelValue(drained.getFluid()); + energyManager.generateEnergy(currentOutput); + } else { + FluidStack fuel = fuelTank.drain(Constants.BUCKET_VOLUME, true); + int burnTime = determineBurnTime(fuel.getFluid()); + fuel.amount = burnTime; + burnTank.setCapacity(burnTime); + burnTank.setFluid(fuel); + } + } else { + shutdown(true); + } + } + } - // We need a minimum temperature to generate energy - if (heatStage > 0.2) { - if (burnTank.getFluidAmount() > 0) { - FluidStack drained = burnTank.drain(1, true); - currentOutput = determineFuelValue(drained.getFluid()); - energyManager.generateEnergy(currentOutput); - } else { - FluidStack fuel = fuelTank.drain(Constants.BUCKET_VOLUME, true); - int burnTime = determineBurnTime(fuel.getFluid()); - fuel.amount = burnTime; - burnTank.setCapacity(burnTime); - burnTank.setFluid(fuel); - } - } else { - shutdown(true); - } - } - } + private void shutdown(boolean val) { + shutdown = val; + } - private void shutdown(boolean val) { - shutdown = val; - } + @Override + public int dissipateHeat() { + if (heat <= 0) { + return 0; + } - @Override - public int dissipateHeat() { - if (heat <= 0) { - return 0; - } + int loss = 1; // Basic loss even when running - int loss = 1; // Basic loss even when running + if (!isBurning()) { + loss++; + } - if (!isBurning()) { - loss++; - } + double heatStage = getHeatLevel(); + if (heatStage > 0.55) { + loss++; + } - double heatStage = getHeatLevel(); - if (heatStage > 0.55) { - loss++; - } + // Lose extra heat when using water as fuel. + if (fuelTank.getFluidAmount() > 0) { + FluidStack fuelFluidStack = fuelTank.getFluid(); + EngineBronzeFuel fuel = FuelManager.bronzeEngineFuel.get(fuelFluidStack.getFluid()); + if (fuel != null) { + loss = loss * fuel.dissipationMultiplier; + } + } - // Lose extra heat when using water as fuel. - if (fuelTank.getFluidAmount() > 0) { - FluidStack fuelFluidStack = fuelTank.getFluid(); - EngineBronzeFuel fuel = FuelManager.bronzeEngineFuel.get(fuelFluidStack.getFluid()); - if (fuel != null) { - loss = loss * fuel.dissipationMultiplier; - } - } + heat -= loss; + return loss; + } - heat -= loss; - return loss; - } + @Override + public int generateHeat() { - @Override - public int generateHeat() { + int generate = 0; - int generate = 0; + if (isRedstoneActivated() && burnTank.getFluidAmount() > 0) { + double heatStage = getHeatLevel(); + if (heatStage >= 0.75) { + generate += Constants.ENGINE_BRONZE_HEAT_GENERATION_ENERGY * 3; + } else if (heatStage > 0.24) { + generate += Constants.ENGINE_BRONZE_HEAT_GENERATION_ENERGY * 2; + } else if (heatStage > 0.2) { + generate += Constants.ENGINE_BRONZE_HEAT_GENERATION_ENERGY; + } + } - if (isRedstoneActivated() && burnTank.getFluidAmount() > 0) { - double heatStage = getHeatLevel(); - if (heatStage >= 0.75) { - generate += Constants.ENGINE_BRONZE_HEAT_GENERATION_ENERGY * 3; - } else if (heatStage > 0.24) { - generate += Constants.ENGINE_BRONZE_HEAT_GENERATION_ENERGY * 2; - } else if (heatStage > 0.2) { - generate += Constants.ENGINE_BRONZE_HEAT_GENERATION_ENERGY; - } - } + heat += generate; + return generate; + } - heat += generate; - return generate; + /** + * Returns the fuel value (power per cycle) an item of the passed fluid + */ + private static int determineFuelValue(Fluid fluid) { + if (FuelManager.bronzeEngineFuel.containsKey(fluid)) { + return FuelManager.bronzeEngineFuel.get(fluid).powerPerCycle; + } else { + return 0; + } + } - } + /** + * @return Duration of burn cycle of one bucket + */ + private static int determineBurnTime(Fluid fluid) { + if (FuelManager.bronzeEngineFuel.containsKey(fluid)) { + return FuelManager.bronzeEngineFuel.get(fluid).burnDuration; + } else { + return 0; + } + } - /** - * Returns the fuel value (power per cycle) an item of the passed fluid - */ - private static int determineFuelValue(Fluid fluid) { - if (FuelManager.bronzeEngineFuel.containsKey(fluid)) { - return FuelManager.bronzeEngineFuel.get(fluid).powerPerCycle; - } else { - return 0; - } - } + // / STATE INFORMATION + @Override + protected boolean isBurning() { + return mayBurn() && burnTank.getFluidAmount() > 0; + } - /** - * @return Duration of burn cycle of one bucket - */ - private static int determineBurnTime(Fluid fluid) { - if (FuelManager.bronzeEngineFuel.containsKey(fluid)) { - return FuelManager.bronzeEngineFuel.get(fluid).burnDuration; - } else { - return 0; - } - } + @Override + public int getBurnTimeRemainingScaled(int i) { + if (burnTank.getCapacity() == 0) { + return 0; + } - // / STATE INFORMATION - @Override - protected boolean isBurning() { - return mayBurn() && burnTank.getFluidAmount() > 0; - } + return (burnTank.getFluidAmount() * i) / burnTank.getCapacity(); + } - @Override - public int getBurnTimeRemainingScaled(int i) { - if (burnTank.getCapacity() == 0) { - return 0; - } + public int getOperatingTemperatureScaled(int i) { + return (int) Math.round((heat * i) / (maxHeat * 0.2)); + } - return (burnTank.getFluidAmount() * i) / burnTank.getCapacity(); - } + @Override + public void readFromNBT(NBTTagCompound nbt) { + super.readFromNBT(nbt); - public int getOperatingTemperatureScaled(int i) { - return (int) Math.round((heat * i) / (maxHeat * 0.2)); - } + // legacy + { + if (nbt.hasKey("currentFluid")) { + Fluid fluid = FluidRegistry.getFluid(nbt.getString("currentFluid")); + if (fluid != null) { + int burnTime = nbt.getInteger("EngineBurnTime"); + int totalTime = nbt.getInteger("EngineTotalTime"); + burnTank.setCapacity(totalTime); + burnTank.setFluid(new FluidStack(fluid, burnTime)); + } + } + } - @Override - public void readFromNBT(NBTTagCompound nbt) { - super.readFromNBT(nbt); + if (nbt.hasKey("shutdown")) { + shutdown = nbt.getBoolean("shutdown"); + } + tankManager.readFromNBT(nbt); + } - //legacy - { - if (nbt.hasKey("currentFluid")) { - Fluid fluid = FluidRegistry.getFluid(nbt.getString("currentFluid")); - if (fluid != null) { - int burnTime = nbt.getInteger("EngineBurnTime"); - int totalTime = nbt.getInteger("EngineTotalTime"); - burnTank.setCapacity(totalTime); - burnTank.setFluid(new FluidStack(fluid, burnTime)); - } - } - } + @Override + public void writeToNBT(NBTTagCompound nbt) { + super.writeToNBT(nbt); + nbt.setBoolean("shutdown", shutdown); + tankManager.writeToNBT(nbt); + } - if (nbt.hasKey("shutdown")) { - shutdown = nbt.getBoolean("shutdown"); - } - tankManager.readFromNBT(nbt); - } + /* NETWORK */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeBoolean(shutdown); + tankManager.writeData(data); + } - @Override - public void writeToNBT(NBTTagCompound nbt) { - super.writeToNBT(nbt); - nbt.setBoolean("shutdown", shutdown); - tankManager.writeToNBT(nbt); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + shutdown = data.readBoolean(); + tankManager.readData(data); + } - /* NETWORK */ - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeBoolean(shutdown); - tankManager.writeData(data); - } + /* GUI */ + @Override + public void getGUINetworkData(int id, int data) { + switch (id) { + case 0: + currentOutput = data; + break; + case 1: + energyManager.fromGuiInt(data); + break; + case 2: + heat = data; + break; + case 3: + burnTank.setCapacity(data); + break; + } + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - shutdown = data.readBoolean(); - tankManager.readData(data); - } + @Override + public void sendGUINetworkData(Container containerEngine, ICrafting iCrafting) { + iCrafting.sendProgressBarUpdate(containerEngine, 0, currentOutput); + iCrafting.sendProgressBarUpdate(containerEngine, 1, energyManager.toGuiInt()); + iCrafting.sendProgressBarUpdate(containerEngine, 2, heat); + iCrafting.sendProgressBarUpdate(containerEngine, 3, burnTank.getCapacity()); + } - /* GUI */ - @Override - public void getGUINetworkData(int id, int data) { - switch (id) { - case 0: - currentOutput = data; - break; - case 1: - energyManager.fromGuiInt(data); - break; - case 2: - heat = data; - break; - case 3: - burnTank.setCapacity(data); - break; - } - } + // IFluidHandler + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } - @Override - public void sendGUINetworkData(Container containerEngine, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(containerEngine, 0, currentOutput); - iCrafting.sendProgressBarUpdate(containerEngine, 1, energyManager.toGuiInt()); - iCrafting.sendProgressBarUpdate(containerEngine, 2, heat); - iCrafting.sendProgressBarUpdate(containerEngine, 3, burnTank.getCapacity()); - } + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } - // IFluidHandler - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return tankManager.fill(from, resource, doFill); - } + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return tankManager.drain(from, resource, doDrain); - } + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return tankManager.drain(from, maxDrain, doDrain); - } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return tankManager.canFill(from, fluid); - } + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return tankManager.canDrain(from, fluid); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiEngineBiogas(player.inventory, this); + } - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return tankManager.getTankInfo(from); - } - - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiEngineBiogas(player.inventory, this); - } - - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerEngineBiogas(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerEngineBiogas(player.inventory, this); + } } diff --git a/src/main/java/forestry/energy/tiles/TileEngineClockwork.java b/src/main/java/forestry/energy/tiles/TileEngineClockwork.java index 4190fd4c8..102db4580 100644 --- a/src/main/java/forestry/energy/tiles/TileEngineClockwork.java +++ b/src/main/java/forestry/energy/tiles/TileEngineClockwork.java @@ -10,163 +10,164 @@ ******************************************************************************/ package forestry.energy.tiles; +import forestry.core.config.Constants; +import forestry.core.tiles.TemperatureState; +import forestry.core.tiles.TileEngine; +import forestry.core.utils.DamageSourceForestry; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; import net.minecraft.nbt.NBTTagCompound; - import net.minecraftforge.common.util.FakePlayer; -import forestry.core.config.Constants; -import forestry.core.tiles.TemperatureState; -import forestry.core.tiles.TileEngine; -import forestry.core.utils.DamageSourceForestry; - public class TileEngineClockwork extends TileEngine { - private final static float WIND_EXHAUSTION = 0.05f; - private final static float WIND_TENSION_BASE = 0.5f; - private final static int WIND_DELAY = 10; - - private static final int ENGINE_CLOCKWORK_HEAT_MAX = 300000; - private static final int ENGINE_CLOCKWORK_ENERGY_PER_CYCLE = 2; - private static final float ENGINE_CLOCKWORK_WIND_MAX = 8f; + private static final float WIND_EXHAUSTION = 0.05f; + private static final float WIND_TENSION_BASE = 0.5f; + private static final int WIND_DELAY = 10; - private static final DamageSourceForestry damageSourceEngineClockwork = new DamageSourceForestry("engine.clockwork"); - - private float tension = 0.0f; - private short delay = 0; - - public TileEngineClockwork() { - super(null, ENGINE_CLOCKWORK_HEAT_MAX, 10000); - } - - @Override - public void openGui(EntityPlayer player) { - - if (!(player instanceof EntityPlayerMP)) { - return; - } + private static final int ENGINE_CLOCKWORK_HEAT_MAX = 300000; + private static final int ENGINE_CLOCKWORK_ENERGY_PER_CYCLE = 2; + private static final float ENGINE_CLOCKWORK_WIND_MAX = 8f; - if (player instanceof FakePlayer) { - return; - } - - if (tension <= 0) { - tension = WIND_TENSION_BASE; - } else if (tension < ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE) { - tension += (ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE - tension) / (ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE) * WIND_TENSION_BASE; - } else { - return; - } - - player.addExhaustion(WIND_EXHAUSTION); - if (tension > ENGINE_CLOCKWORK_WIND_MAX + (0.1 * WIND_TENSION_BASE)) { - player.attackEntityFrom(damageSourceEngineClockwork, 6); - } - tension = tension > ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE ? ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE : tension; - delay = WIND_DELAY; - setNeedsNetworkUpdate(); - } + private static final DamageSourceForestry damageSourceEngineClockwork = + new DamageSourceForestry("engine.clockwork"); - /* LOADING & SAVING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - tension = nbttagcompound.getFloat("Wound"); - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - nbttagcompound.setFloat("Wound", tension); - } - - @Override - public boolean isRedstoneActivated() { - return true; - } + private float tension = 0.0f; + private short delay = 0; - @Override - public int dissipateHeat() { - return 0; - } + public TileEngineClockwork() { + super(null, ENGINE_CLOCKWORK_HEAT_MAX, 10000); + } - @Override - public int generateHeat() { - return 0; - } + @Override + public void openGui(EntityPlayer player) { - @Override - public boolean mayBurn() { - return true; - } + if (!(player instanceof EntityPlayerMP)) { + return; + } - @Override - public void burn() { - - heat = (int) (tension * 10000); - - if (delay > 0) { - delay--; - return; - } - - if (!isBurning()) { - return; - } - - if (tension > 0.01f) { - tension *= 0.9995f; - } else { - tension = 0; - } - energyManager.generateEnergy(ENGINE_CLOCKWORK_ENERGY_PER_CYCLE * (int) tension); - } + if (player instanceof FakePlayer) { + return; + } - @Override - protected boolean isBurning() { - return tension > 0; - } + if (tension <= 0) { + tension = WIND_TENSION_BASE; + } else if (tension < ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE) { + tension += (ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE - tension) + / (ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE) + * WIND_TENSION_BASE; + } else { + return; + } - @Override - public TemperatureState getTemperatureState() { - TemperatureState state = TemperatureState.getState(heat / 10000, ENGINE_CLOCKWORK_WIND_MAX); - if (state == TemperatureState.MELTING) { - state = TemperatureState.OVERHEATING; - } - return state; - } + player.addExhaustion(WIND_EXHAUSTION); + if (tension > ENGINE_CLOCKWORK_WIND_MAX + (0.1 * WIND_TENSION_BASE)) { + player.attackEntityFrom(damageSourceEngineClockwork, 6); + } + tension = tension > ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE + ? ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE + : tension; + delay = WIND_DELAY; + setNeedsNetworkUpdate(); + } - @Override - public float getPistonSpeed() { - if (delay > 0) { - return 0; - } - - float fromClockwork = (tension / ENGINE_CLOCKWORK_WIND_MAX) * Constants.ENGINE_PISTON_SPEED_MAX; + /* LOADING & SAVING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + tension = nbttagcompound.getFloat("Wound"); + } - fromClockwork = Math.round(fromClockwork * 100f) / 100f; + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + nbttagcompound.setFloat("Wound", tension); + } - return fromClockwork; - } - - @Override - public void getGUINetworkData(int i, int j) { - } + @Override + public boolean isRedstoneActivated() { + return true; + } - @Override - public void sendGUINetworkData(Container containerEngine, ICrafting iCrafting) { - } + @Override + public int dissipateHeat() { + return 0; + } - @Override - public Object getGui(EntityPlayer player, int data) { - return null; - } + @Override + public int generateHeat() { + return 0; + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return null; - } + @Override + public boolean mayBurn() { + return true; + } + + @Override + public void burn() { + + heat = (int) (tension * 10000); + + if (delay > 0) { + delay--; + return; + } + + if (!isBurning()) { + return; + } + + if (tension > 0.01f) { + tension *= 0.9995f; + } else { + tension = 0; + } + energyManager.generateEnergy(ENGINE_CLOCKWORK_ENERGY_PER_CYCLE * (int) tension); + } + + @Override + protected boolean isBurning() { + return tension > 0; + } + + @Override + public TemperatureState getTemperatureState() { + TemperatureState state = TemperatureState.getState(heat / 10000, ENGINE_CLOCKWORK_WIND_MAX); + if (state == TemperatureState.MELTING) { + state = TemperatureState.OVERHEATING; + } + return state; + } + + @Override + public float getPistonSpeed() { + if (delay > 0) { + return 0; + } + + float fromClockwork = (tension / ENGINE_CLOCKWORK_WIND_MAX) * Constants.ENGINE_PISTON_SPEED_MAX; + + fromClockwork = Math.round(fromClockwork * 100f) / 100f; + + return fromClockwork; + } + + @Override + public void getGUINetworkData(int i, int j) {} + + @Override + public void sendGUINetworkData(Container containerEngine, ICrafting iCrafting) {} + + @Override + public Object getGui(EntityPlayer player, int data) { + return null; + } + + @Override + public Object getContainer(EntityPlayer player, int data) { + return null; + } } diff --git a/src/main/java/forestry/energy/tiles/TileEngineElectric.java b/src/main/java/forestry/energy/tiles/TileEngineElectric.java index 9b8e03869..441a0c5ba 100644 --- a/src/main/java/forestry/energy/tiles/TileEngineElectric.java +++ b/src/main/java/forestry/energy/tiles/TileEngineElectric.java @@ -28,6 +28,7 @@ import forestry.energy.gui.ContainerEngineElectric; import forestry.energy.gui.GuiEngineElectric; import forestry.plugins.compat.PluginIC2; import ic2.api.energy.prefab.BasicSink; +import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; @@ -35,289 +36,286 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.io.IOException; - public class TileEngineElectric extends TileEngine implements ISocketable, IInventory, IStreamableGui { - protected static class EuConfig { + protected static class EuConfig { - public int euForCycle; - public int rfPerCycle; - public int euStorage; + public int euForCycle; + public int rfPerCycle; + public int euStorage; - public EuConfig() { - this.euForCycle = Constants.ENGINE_TIN_EU_FOR_CYCLE; - this.rfPerCycle = Constants.ENGINE_TIN_ENERGY_PER_CYCLE; - this.euStorage = Constants.ENGINE_TIN_MAX_EU_STORED; - } - } + public EuConfig() { + this.euForCycle = Constants.ENGINE_TIN_EU_FOR_CYCLE; + this.rfPerCycle = Constants.ENGINE_TIN_ENERGY_PER_CYCLE; + this.euStorage = Constants.ENGINE_TIN_MAX_EU_STORED; + } + } - private final InventoryAdapter sockets = new InventoryAdapter(1, "sockets"); - private final EuConfig euConfig = new EuConfig(); + private final InventoryAdapter sockets = new InventoryAdapter(1, "sockets"); + private final EuConfig euConfig = new EuConfig(); - private BasicSink ic2EnergySink; + private BasicSink ic2EnergySink; - public TileEngineElectric() { - super("engine.tin", Constants.ENGINE_ELECTRIC_HEAT_MAX, 100000); + public TileEngineElectric() { + super("engine.tin", Constants.ENGINE_ELECTRIC_HEAT_MAX, 100000); - setInternalInventory(new InventoryEngineElectric(this)); + setInternalInventory(new InventoryEngineElectric(this)); - if (PluginIC2.instance.isAvailable()) { - ic2EnergySink = new BasicSink(this, euConfig.euStorage, 3); - } - } + if (PluginIC2.instance.isAvailable()) { + ic2EnergySink = new BasicSink(this, euConfig.euStorage, 3); + } + } - // / SAVING / LOADING - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); + // / SAVING / LOADING + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); - if (ic2EnergySink != null) { - ic2EnergySink.readFromNBT(nbttagcompound); - } - sockets.readFromNBT(nbttagcompound); + if (ic2EnergySink != null) { + ic2EnergySink.readFromNBT(nbttagcompound); + } + sockets.readFromNBT(nbttagcompound); - ItemStack chip = sockets.getStackInSlot(0); - if (chip != null) { - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(chip); - if (chipset != null) { - chipset.onLoad(this); - } - } - } + ItemStack chip = sockets.getStackInSlot(0); + if (chip != null) { + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(chip); + if (chipset != null) { + chipset.onLoad(this); + } + } + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - if (ic2EnergySink != null) { - ic2EnergySink.writeToNBT(nbttagcompound); - } - sockets.writeToNBT(nbttagcompound); - } + if (ic2EnergySink != null) { + ic2EnergySink.writeToNBT(nbttagcompound); + } + sockets.writeToNBT(nbttagcompound); + } - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - data.writeVarInt(currentOutput); - data.writeVarInt(heat); - sockets.writeData(data); - energyManager.writeData(data); - final boolean hasIc2EnergySink = (ic2EnergySink != null); - data.writeBoolean(hasIc2EnergySink); - if (hasIc2EnergySink) { - data.writeVarInt((int) ic2EnergySink.getEnergyStored()); - } - } + @Override + public void writeGuiData(DataOutputStreamForestry data) throws IOException { + data.writeVarInt(currentOutput); + data.writeVarInt(heat); + sockets.writeData(data); + energyManager.writeData(data); + final boolean hasIc2EnergySink = (ic2EnergySink != null); + data.writeBoolean(hasIc2EnergySink); + if (hasIc2EnergySink) { + data.writeVarInt((int) ic2EnergySink.getEnergyStored()); + } + } - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - currentOutput = data.readVarInt(); - heat = data.readVarInt(); - sockets.readData(data); - energyManager.readData(data); - final boolean hasIc2EnergySink = data.readBoolean(); - if (hasIc2EnergySink) { - final int energyStored = data.readVarInt(); - ic2EnergySink.setEnergyStored(energyStored); - } - } + @Override + public void readGuiData(DataInputStreamForestry data) throws IOException { + currentOutput = data.readVarInt(); + heat = data.readVarInt(); + sockets.readData(data); + energyManager.readData(data); + final boolean hasIc2EnergySink = data.readBoolean(); + if (hasIc2EnergySink) { + final int energyStored = data.readVarInt(); + ic2EnergySink.setEnergyStored(energyStored); + } + } - @Override - public void onChunkUnload() { - if (ic2EnergySink != null) { - ic2EnergySink.onChunkUnload(); - } + @Override + public void onChunkUnload() { + if (ic2EnergySink != null) { + ic2EnergySink.onChunkUnload(); + } - super.onChunkUnload(); - } + super.onChunkUnload(); + } - @Override - public void invalidate() { - if (ic2EnergySink != null) { - ic2EnergySink.invalidate(); - } + @Override + public void invalidate() { + if (ic2EnergySink != null) { + ic2EnergySink.invalidate(); + } - super.invalidate(); - } + super.invalidate(); + } - // / HEAT MANAGEMENT - @Override - public int dissipateHeat() { - if (heat <= 0) { - return 0; - } + // / HEAT MANAGEMENT + @Override + public int dissipateHeat() { + if (heat <= 0) { + return 0; + } - int loss = 0; + int loss = 0; - if (!isBurning() || !isRedstoneActivated()) { - loss += 1; - } + if (!isBurning() || !isRedstoneActivated()) { + loss += 1; + } - TemperatureState tempState = getTemperatureState(); - if (tempState == TemperatureState.OVERHEATING || tempState == TemperatureState.OPERATING_TEMPERATURE) { - loss += 1; - } + TemperatureState tempState = getTemperatureState(); + if (tempState == TemperatureState.OVERHEATING || tempState == TemperatureState.OPERATING_TEMPERATURE) { + loss += 1; + } - heat -= loss; - return loss; - } + heat -= loss; + return loss; + } - @Override - public int generateHeat() { + @Override + public int generateHeat() { - int gain = 0; - if (isRedstoneActivated() && isBurning()) { - gain++; - if (((double) energyManager.getTotalEnergyStored() / (double) energyManager.getMaxEnergyStored()) > 0.5) { - gain++; - } - } + int gain = 0; + if (isRedstoneActivated() && isBurning()) { + gain++; + if (((double) energyManager.getTotalEnergyStored() / (double) energyManager.getMaxEnergyStored()) > 0.5) { + gain++; + } + } - addHeat(gain); - return gain; - } + addHeat(gain); + return gain; + } - // / WORK - @Override - public void updateServerSide() { - IErrorLogic errorLogic = getErrorLogic(); + // / WORK + @Override + public void updateServerSide() { + IErrorLogic errorLogic = getErrorLogic(); - // No work to be done if IC2 is unavailable. - if (errorLogic.setCondition(ic2EnergySink == null, EnumErrorCode.NO_ENERGY_NET)) { - return; - } + // No work to be done if IC2 is unavailable. + if (errorLogic.setCondition(ic2EnergySink == null, EnumErrorCode.NO_ENERGY_NET)) { + return; + } - ic2EnergySink.updateEntity(); + ic2EnergySink.updateEntity(); - super.updateServerSide(); + super.updateServerSide(); - if (forceCooldown) { - return; - } + if (forceCooldown) { + return; + } - if (getStackInSlot(InventoryEngineElectric.SLOT_BATTERY) != null) { - replenishFromBattery(InventoryEngineElectric.SLOT_BATTERY); - } + if (getStackInSlot(InventoryEngineElectric.SLOT_BATTERY) != null) { + replenishFromBattery(InventoryEngineElectric.SLOT_BATTERY); + } - // Updating of gui delayed to prevent it from going crazy - if (!updateOnInterval(80)) { - return; - } + // Updating of gui delayed to prevent it from going crazy + if (!updateOnInterval(80)) { + return; + } - boolean canUseEnergy = ic2EnergySink.canUseEnergy(euConfig.euForCycle); - errorLogic.setCondition(!canUseEnergy, EnumErrorCode.NO_FUEL); - } + boolean canUseEnergy = ic2EnergySink.canUseEnergy(euConfig.euForCycle); + errorLogic.setCondition(!canUseEnergy, EnumErrorCode.NO_FUEL); + } - @Override - public void burn() { + @Override + public void burn() { - currentOutput = 0; + currentOutput = 0; - if (!isRedstoneActivated()) { - return; - } + if (!isRedstoneActivated()) { + return; + } - if (ic2EnergySink.useEnergy(euConfig.euForCycle)) { - currentOutput = euConfig.rfPerCycle; - energyManager.generateEnergy(euConfig.rfPerCycle); - } + if (ic2EnergySink.useEnergy(euConfig.euForCycle)) { + currentOutput = euConfig.rfPerCycle; + energyManager.generateEnergy(euConfig.rfPerCycle); + } + } - } + private void replenishFromBattery(int slot) { + if (!isRedstoneActivated()) { + return; + } - private void replenishFromBattery(int slot) { - if (!isRedstoneActivated()) { - return; - } + ic2EnergySink.discharge(getStackInSlot(slot), euConfig.euForCycle * 3); + } - ic2EnergySink.discharge(getStackInSlot(slot), euConfig.euForCycle * 3); - } + // / STATE INFORMATION + @Override + protected boolean isBurning() { + return mayBurn() && ic2EnergySink != null && ic2EnergySink.canUseEnergy(euConfig.euForCycle); + } - // / STATE INFORMATION - @Override - protected boolean isBurning() { - return mayBurn() && ic2EnergySink != null && ic2EnergySink.canUseEnergy(euConfig.euForCycle); - } + public int getStorageScaled(int i) { + if (ic2EnergySink == null) { + return 0; + } - public int getStorageScaled(int i) { - if (ic2EnergySink == null) { - return 0; - } + return Math.min(i, (int) (ic2EnergySink.getEnergyStored() * i) / ic2EnergySink.getCapacity()); + } - return Math.min(i, (int) (ic2EnergySink.getEnergyStored() * i) / ic2EnergySink.getCapacity()); - } + // / SMP GUI + @Override + public void getGUINetworkData(int i, int j) { + // handled by IStreamableGui + } - // / SMP GUI - @Override - public void getGUINetworkData(int i, int j) { - // handled by IStreamableGui - } + @Override + public void sendGUINetworkData(Container containerEngine, ICrafting iCrafting) { + // handled by IStreamableGui + } - @Override - public void sendGUINetworkData(Container containerEngine, ICrafting iCrafting) { - // handled by IStreamableGui - } + // / ENERGY CONFIG CHANGE + public void changeEnergyConfig(int euChange, int rfChange, int storageChange) { + euConfig.euForCycle += euChange; + euConfig.rfPerCycle += rfChange; + euConfig.euStorage += storageChange; - // / ENERGY CONFIG CHANGE - public void changeEnergyConfig(int euChange, int rfChange, int storageChange) { - euConfig.euForCycle += euChange; - euConfig.rfPerCycle += rfChange; - euConfig.euStorage += storageChange; + if (ic2EnergySink != null) { + ic2EnergySink.setCapacity(euConfig.euStorage); + } + } - if (ic2EnergySink != null) { - ic2EnergySink.setCapacity(euConfig.euStorage); - } - } + /* ISocketable */ + @Override + public int getSocketCount() { + return sockets.getSizeInventory(); + } - /* ISocketable */ - @Override - public int getSocketCount() { - return sockets.getSizeInventory(); - } + @Override + public ItemStack getSocket(int slot) { + return sockets.getStackInSlot(slot); + } - @Override - public ItemStack getSocket(int slot) { - return sockets.getStackInSlot(slot); - } + @Override + public void setSocket(int slot, ItemStack stack) { - @Override - public void setSocket(int slot, ItemStack stack) { + if (stack != null && !ChipsetManager.circuitRegistry.isChipset(stack)) { + return; + } - if (stack != null && !ChipsetManager.circuitRegistry.isChipset(stack)) { - return; - } + // Dispose correctly of old chipsets + if (sockets.getStackInSlot(slot) != null) { + if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(sockets.getStackInSlot(slot)); + if (chipset != null) { + chipset.onRemoval(this); + } + } + } - // Dispose correctly of old chipsets - if (sockets.getStackInSlot(slot) != null) { - if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(sockets.getStackInSlot(slot)); - if (chipset != null) { - chipset.onRemoval(this); - } - } - } + sockets.setInventorySlotContents(slot, stack); + if (stack == null) { + return; + } - sockets.setInventorySlotContents(slot, stack); - if (stack == null) { - return; - } + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(stack); + if (chipset != null) { + chipset.onInsertion(this); + } + } - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(stack); - if (chipset != null) { - chipset.onInsertion(this); - } - } + @Override + public ICircuitSocketType getSocketType() { + return CircuitSocketType.ELECTRIC_ENGINE; + } - @Override - public ICircuitSocketType getSocketType() { - return CircuitSocketType.ELECTRIC_ENGINE; - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiEngineElectric(player.inventory, this); + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiEngineElectric(player.inventory, this); - } - - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerEngineElectric(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerEngineElectric(player.inventory, this); + } } diff --git a/src/main/java/forestry/energy/tiles/TileEnginePeat.java b/src/main/java/forestry/energy/tiles/TileEnginePeat.java index c58bfbe3d..1de97b698 100644 --- a/src/main/java/forestry/energy/tiles/TileEnginePeat.java +++ b/src/main/java/forestry/energy/tiles/TileEnginePeat.java @@ -10,24 +10,9 @@ ******************************************************************************/ package forestry.energy.tiles; -import java.util.Collection; -import java.util.LinkedList; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.ICrafting; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.statements.ITriggerExternal; import cpw.mods.fml.common.Optional; import cpw.mods.fml.common.registry.GameData; - import forestry.api.fuels.FuelManager; import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; @@ -42,312 +27,326 @@ import forestry.energy.gui.GuiEnginePeat; import forestry.energy.inventory.InventoryEnginePeat; import forestry.factory.triggers.FactoryTriggers; import forestry.plugins.PluginCore; - -import buildcraft.api.statements.ITriggerExternal; +import java.util.Collection; +import java.util.LinkedList; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TileEnginePeat extends TileEngine implements ISidedInventory { - private Item fuelItem; - private int fuelItemMeta; - private int burnTime; - private int totalBurnTime; - private int ashProduction; - private final int ashForItem; - private final AdjacentInventoryCache inventoryCache = new AdjacentInventoryCache(this, getTileCache()); + private Item fuelItem; + private int fuelItemMeta; + private int burnTime; + private int totalBurnTime; + private int ashProduction; + private final int ashForItem; + private final AdjacentInventoryCache inventoryCache = new AdjacentInventoryCache(this, getTileCache()); - public TileEnginePeat() { - super("engine.copper", Constants.ENGINE_COPPER_HEAT_MAX, 200000); + public TileEnginePeat() { + super("engine.copper", Constants.ENGINE_COPPER_HEAT_MAX, 200000); - ashForItem = Constants.ENGINE_COPPER_ASH_FOR_ITEM; - setInternalInventory(new InventoryEnginePeat(this)); - } + ashForItem = Constants.ENGINE_COPPER_ASH_FOR_ITEM; + setInternalInventory(new InventoryEnginePeat(this)); + } - private int getFuelSlot() { - IInventoryAdapter inventory = getInternalInventory(); - if (inventory.getStackInSlot(InventoryEnginePeat.SLOT_FUEL) == null) { - return -1; - } + private int getFuelSlot() { + IInventoryAdapter inventory = getInternalInventory(); + if (inventory.getStackInSlot(InventoryEnginePeat.SLOT_FUEL) == null) { + return -1; + } - if (determineFuelValue(inventory.getStackInSlot(InventoryEnginePeat.SLOT_FUEL)) > 0) { - return InventoryEnginePeat.SLOT_FUEL; - } + if (determineFuelValue(inventory.getStackInSlot(InventoryEnginePeat.SLOT_FUEL)) > 0) { + return InventoryEnginePeat.SLOT_FUEL; + } - return -1; - } + return -1; + } - private int getFreeWasteSlot() { - IInventoryAdapter inventory = getInternalInventory(); - for (int i = InventoryEnginePeat.SLOT_WASTE_1; i <= InventoryEnginePeat.SLOT_WASTE_COUNT; i++) { - ItemStack waste = inventory.getStackInSlot(i); - if (waste == null) { - return i; - } + private int getFreeWasteSlot() { + IInventoryAdapter inventory = getInternalInventory(); + for (int i = InventoryEnginePeat.SLOT_WASTE_1; i <= InventoryEnginePeat.SLOT_WASTE_COUNT; i++) { + ItemStack waste = inventory.getStackInSlot(i); + if (waste == null) { + return i; + } - if (waste.getItem() != PluginCore.items.ash) { - continue; - } + if (waste.getItem() != PluginCore.items.ash) { + continue; + } - if (waste.stackSize < 64) { - return i; - } - } + if (waste.stackSize < 64) { + return i; + } + } - return -1; - } + return -1; + } - @Override - public void updateServerSide() { - super.updateServerSide(); + @Override + public void updateServerSide() { + super.updateServerSide(); - if (!updateOnInterval(40)) { - return; - } + if (!updateOnInterval(40)) { + return; + } - dumpStash(); + dumpStash(); - int fuelSlot = getFuelSlot(); - boolean hasFuel = fuelSlot >= 0 && determineBurnDuration(getInternalInventory().getStackInSlot(fuelSlot)) > 0; - getErrorLogic().setCondition(!hasFuel, EnumErrorCode.NO_FUEL); - } + int fuelSlot = getFuelSlot(); + boolean hasFuel = + fuelSlot >= 0 && determineBurnDuration(getInternalInventory().getStackInSlot(fuelSlot)) > 0; + getErrorLogic().setCondition(!hasFuel, EnumErrorCode.NO_FUEL); + } - @Override - public void burn() { + @Override + public void burn() { - currentOutput = 0; + currentOutput = 0; - if (burnTime > 0) { - burnTime--; - addAsh(1); + if (burnTime > 0) { + burnTime--; + addAsh(1); - if (isRedstoneActivated()) { - currentOutput = determineFuelValue(new ItemStack(fuelItem, 1, fuelItemMeta)); - energyManager.generateEnergy(currentOutput); - } - } else if (isRedstoneActivated()) { - int fuelSlot = getFuelSlot(); - int wasteSlot = getFreeWasteSlot(); + if (isRedstoneActivated()) { + currentOutput = determineFuelValue(new ItemStack(fuelItem, 1, fuelItemMeta)); + energyManager.generateEnergy(currentOutput); + } + } else if (isRedstoneActivated()) { + int fuelSlot = getFuelSlot(); + int wasteSlot = getFreeWasteSlot(); - if (fuelSlot >= 0 && wasteSlot >= 0) { - IInventoryAdapter inventory = getInternalInventory(); - burnTime = totalBurnTime = determineBurnDuration(inventory.getStackInSlot(fuelSlot)); - if (burnTime > 0) { - fuelItem = inventory.getStackInSlot(fuelSlot).getItem(); - decrStackSize(fuelSlot, 1); - } - } - } - } + if (fuelSlot >= 0 && wasteSlot >= 0) { + IInventoryAdapter inventory = getInternalInventory(); + burnTime = totalBurnTime = determineBurnDuration(inventory.getStackInSlot(fuelSlot)); + if (burnTime > 0) { + fuelItem = inventory.getStackInSlot(fuelSlot).getItem(); + decrStackSize(fuelSlot, 1); + } + } + } + } - @Override - public int dissipateHeat() { - if (heat <= 0) { - return 0; - } + @Override + public int dissipateHeat() { + if (heat <= 0) { + return 0; + } - int loss = 0; + int loss = 0; - if (!isBurning()) { - loss += 1; - } + if (!isBurning()) { + loss += 1; + } - TemperatureState tempState = getTemperatureState(); - if (tempState == TemperatureState.OVERHEATING || tempState == TemperatureState.OPERATING_TEMPERATURE) { - loss += 1; - } + TemperatureState tempState = getTemperatureState(); + if (tempState == TemperatureState.OVERHEATING || tempState == TemperatureState.OPERATING_TEMPERATURE) { + loss += 1; + } - heat -= loss; - return loss; - } + heat -= loss; + return loss; + } - @Override - public int generateHeat() { + @Override + public int generateHeat() { - int heatToAdd = 0; + int heatToAdd = 0; - if (isBurning()) { - heatToAdd++; - if (((double) energyManager.getTotalEnergyStored() / (double) energyManager.getMaxEnergyStored()) > 0.5) { - heatToAdd++; - } - } + if (isBurning()) { + heatToAdd++; + if (((double) energyManager.getTotalEnergyStored() / (double) energyManager.getMaxEnergyStored()) > 0.5) { + heatToAdd++; + } + } - addHeat(heatToAdd); - return heatToAdd; - } + addHeat(heatToAdd); + return heatToAdd; + } - private void addAsh(int amount) { + private void addAsh(int amount) { - ashProduction += amount; - if (ashProduction < ashForItem) { - return; - } + ashProduction += amount; + if (ashProduction < ashForItem) { + return; + } - // If we have reached the necessary amount, we need to add ash - int wasteSlot = getFreeWasteSlot(); - if (wasteSlot >= 0) { - IInventoryAdapter inventory = getInternalInventory(); - if (inventory.getStackInSlot(wasteSlot) == null) { - inventory.setInventorySlotContents(wasteSlot, PluginCore.items.ash.getItemStack()); - } else { - inventory.getStackInSlot(wasteSlot).stackSize++; - } - } - // Reset - ashProduction = 0; - // try to dump stash - dumpStash(); - } + // If we have reached the necessary amount, we need to add ash + int wasteSlot = getFreeWasteSlot(); + if (wasteSlot >= 0) { + IInventoryAdapter inventory = getInternalInventory(); + if (inventory.getStackInSlot(wasteSlot) == null) { + inventory.setInventorySlotContents(wasteSlot, PluginCore.items.ash.getItemStack()); + } else { + inventory.getStackInSlot(wasteSlot).stackSize++; + } + } + // Reset + ashProduction = 0; + // try to dump stash + dumpStash(); + } - /** - * Returns the fuel value (power per cycle) an item of the passed ItemStack provides - */ - private static int determineFuelValue(ItemStack fuel) { - if (FuelManager.copperEngineFuel.containsKey(fuel)) { - return FuelManager.copperEngineFuel.get(fuel).powerPerCycle; - } else { - return 0; - } - } + /** + * Returns the fuel value (power per cycle) an item of the passed ItemStack provides + */ + private static int determineFuelValue(ItemStack fuel) { + if (FuelManager.copperEngineFuel.containsKey(fuel)) { + return FuelManager.copperEngineFuel.get(fuel).powerPerCycle; + } else { + return 0; + } + } - /** - * Returns the fuel value (power per cycle) an item of the passed ItemStack provides - */ - private static int determineBurnDuration(ItemStack fuel) { - if (FuelManager.copperEngineFuel.containsKey(fuel)) { - return FuelManager.copperEngineFuel.get(fuel).burnDuration; - } else { - return 0; - } - } + /** + * Returns the fuel value (power per cycle) an item of the passed ItemStack provides + */ + private static int determineBurnDuration(ItemStack fuel) { + if (FuelManager.copperEngineFuel.containsKey(fuel)) { + return FuelManager.copperEngineFuel.get(fuel).burnDuration; + } else { + return 0; + } + } - /* AUTO-EJECTING */ - private IInventory getWasteInventory() { - IInventoryAdapter inventory = getInternalInventory(); - if (inventory == null) { - return null; - } + /* AUTO-EJECTING */ + private IInventory getWasteInventory() { + IInventoryAdapter inventory = getInternalInventory(); + if (inventory == null) { + return null; + } - return new InventoryMapper(inventory, InventoryEnginePeat.SLOT_WASTE_1, InventoryEnginePeat.SLOT_WASTE_COUNT); - } + return new InventoryMapper(inventory, InventoryEnginePeat.SLOT_WASTE_1, InventoryEnginePeat.SLOT_WASTE_COUNT); + } - private void dumpStash() { - IInventory wasteInventory = getWasteInventory(); - if (wasteInventory == null) { - return; - } + private void dumpStash() { + IInventory wasteInventory = getWasteInventory(); + if (wasteInventory == null) { + return; + } - if (!InventoryUtil.moveOneItemToPipe(wasteInventory, getTileCache())) { - InventoryUtil.moveItemStack(wasteInventory, inventoryCache.getAdjacentInventories()); - } - } + if (!InventoryUtil.moveOneItemToPipe(wasteInventory, getTileCache())) { + InventoryUtil.moveItemStack(wasteInventory, inventoryCache.getAdjacentInventories()); + } + } - // / STATE INFORMATION - @Override - public boolean isBurning() { - return mayBurn() && burnTime > 0; - } + // / STATE INFORMATION + @Override + public boolean isBurning() { + return mayBurn() && burnTime > 0; + } - @Override - public int getBurnTimeRemainingScaled(int i) { - if (totalBurnTime == 0) { - return 0; - } + @Override + public int getBurnTimeRemainingScaled(int i) { + if (totalBurnTime == 0) { + return 0; + } - return (burnTime * i) / totalBurnTime; - } + return (burnTime * i) / totalBurnTime; + } - @Override - public boolean hasFuelMin(float percentage) { - int fuelSlot = this.getFuelSlot(); - if (fuelSlot < 0) { - return false; - } + @Override + public boolean hasFuelMin(float percentage) { + int fuelSlot = this.getFuelSlot(); + if (fuelSlot < 0) { + return false; + } - IInventoryAdapter inventory = getInternalInventory(); - return ((float) inventory.getStackInSlot(fuelSlot).stackSize / (float) inventory.getStackInSlot(fuelSlot).getMaxStackSize()) > percentage; - } + IInventoryAdapter inventory = getInternalInventory(); + return ((float) inventory.getStackInSlot(fuelSlot).stackSize + / (float) inventory.getStackInSlot(fuelSlot).getMaxStackSize()) + > percentage; + } - // / LOADING AND SAVING - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); + // / LOADING AND SAVING + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); - String fuelItemName = nbttagcompound.getString("EngineFuelItem"); + String fuelItemName = nbttagcompound.getString("EngineFuelItem"); - if (!fuelItemName.isEmpty()) { - fuelItem = GameData.getItemRegistry().getRaw(fuelItemName); - } + if (!fuelItemName.isEmpty()) { + fuelItem = GameData.getItemRegistry().getRaw(fuelItemName); + } - fuelItemMeta = nbttagcompound.getInteger("EngineFuelMeta"); - burnTime = nbttagcompound.getInteger("EngineBurnTime"); - totalBurnTime = nbttagcompound.getInteger("EngineTotalTime"); - if (nbttagcompound.hasKey("AshProduction")) { - ashProduction = nbttagcompound.getInteger("AshProduction"); - } - } + fuelItemMeta = nbttagcompound.getInteger("EngineFuelMeta"); + burnTime = nbttagcompound.getInteger("EngineBurnTime"); + totalBurnTime = nbttagcompound.getInteger("EngineTotalTime"); + if (nbttagcompound.hasKey("AshProduction")) { + ashProduction = nbttagcompound.getInteger("AshProduction"); + } + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - if (fuelItem != null) { - nbttagcompound.setString("EngineFuelItem", GameData.getItemRegistry().getNameForObject(fuelItem)); - } + if (fuelItem != null) { + nbttagcompound.setString( + "EngineFuelItem", GameData.getItemRegistry().getNameForObject(fuelItem)); + } - nbttagcompound.setInteger("EngineFuelMeta", fuelItemMeta); - nbttagcompound.setInteger("EngineBurnTime", burnTime); - nbttagcompound.setInteger("EngineTotalTime", totalBurnTime); - nbttagcompound.setInteger("AshProduction", ashProduction); - } + nbttagcompound.setInteger("EngineFuelMeta", fuelItemMeta); + nbttagcompound.setInteger("EngineBurnTime", burnTime); + nbttagcompound.setInteger("EngineTotalTime", totalBurnTime); + nbttagcompound.setInteger("AshProduction", ashProduction); + } - // / SMP GUI - @Override - public void getGUINetworkData(int i, int j) { + // / SMP GUI + @Override + public void getGUINetworkData(int i, int j) { - switch (i) { - case 0: - burnTime = j; - break; - case 1: - totalBurnTime = j; - break; - case 2: - currentOutput = j; - break; - case 3: - energyManager.fromGuiInt(j); - break; - case 4: - heat = j; - break; - } - } + switch (i) { + case 0: + burnTime = j; + break; + case 1: + totalBurnTime = j; + break; + case 2: + currentOutput = j; + break; + case 3: + energyManager.fromGuiInt(j); + break; + case 4: + heat = j; + break; + } + } - @Override - public void sendGUINetworkData(Container containerEngine, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(containerEngine, 0, burnTime); - iCrafting.sendProgressBarUpdate(containerEngine, 1, totalBurnTime); - iCrafting.sendProgressBarUpdate(containerEngine, 2, currentOutput); - iCrafting.sendProgressBarUpdate(containerEngine, 3, energyManager.toGuiInt()); - iCrafting.sendProgressBarUpdate(containerEngine, 4, heat); - } + @Override + public void sendGUINetworkData(Container containerEngine, ICrafting iCrafting) { + iCrafting.sendProgressBarUpdate(containerEngine, 0, burnTime); + iCrafting.sendProgressBarUpdate(containerEngine, 1, totalBurnTime); + iCrafting.sendProgressBarUpdate(containerEngine, 2, currentOutput); + iCrafting.sendProgressBarUpdate(containerEngine, 3, energyManager.toGuiInt()); + iCrafting.sendProgressBarUpdate(containerEngine, 4, heat); + } - /* ITriggerProvider */ - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { - LinkedList res = new LinkedList<>(); - res.add(FactoryTriggers.lowFuel25); - res.add(FactoryTriggers.lowFuel10); - return res; - } + /* ITriggerProvider */ + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { + LinkedList res = new LinkedList<>(); + res.add(FactoryTriggers.lowFuel25); + res.add(FactoryTriggers.lowFuel10); + return res; + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiEnginePeat(player.inventory, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiEnginePeat(player.inventory, this); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerEnginePeat(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerEnginePeat(player.inventory, this); + } } diff --git a/src/main/java/forestry/energy/tiles/TileGenerator.java b/src/main/java/forestry/energy/tiles/TileGenerator.java index 90a7a7cad..0ce2b54d9 100644 --- a/src/main/java/forestry/energy/tiles/TileGenerator.java +++ b/src/main/java/forestry/energy/tiles/TileGenerator.java @@ -10,20 +10,6 @@ ******************************************************************************/ package forestry.energy.tiles; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.ICrafting; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; - import forestry.api.core.IErrorLogic; import forestry.api.fuels.FuelManager; import forestry.api.fuels.GeneratorFuel; @@ -42,201 +28,212 @@ import forestry.energy.gui.ContainerGenerator; import forestry.energy.gui.GuiGenerator; import forestry.energy.inventory.InventoryGenerator; import forestry.plugins.compat.PluginIC2; - import ic2.api.energy.prefab.BasicSource; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; -public class TileGenerator extends TileBase implements ISidedInventory, ILiquidTankTile, IFluidHandler, IRenderableTile { - private static final int maxEnergy = 30000; +public class TileGenerator extends TileBase + implements ISidedInventory, ILiquidTankTile, IFluidHandler, IRenderableTile { + private static final int maxEnergy = 30000; - private final TankManager tankManager; - private final FilteredTank resourceTank; + private final TankManager tankManager; + private final FilteredTank resourceTank; - private int tickCount = 0; + private int tickCount = 0; - private BasicSource ic2EnergySource; + private BasicSource ic2EnergySource; - public TileGenerator() { - super("generator"); + public TileGenerator() { + super("generator"); - setInternalInventory(new InventoryGenerator(this)); + setInternalInventory(new InventoryGenerator(this)); - resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, FuelManager.generatorFuel.keySet()); - tankManager = new TankManager(this, resourceTank); + resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, FuelManager.generatorFuel.keySet()); + tankManager = new TankManager(this, resourceTank); - if (PluginIC2.instance.isAvailable()) { - ic2EnergySource = new BasicSource(this, maxEnergy, 1); - } - } + if (PluginIC2.instance.isAvailable()) { + ic2EnergySource = new BasicSource(this, maxEnergy, 1); + } + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - if (ic2EnergySource != null) { - ic2EnergySource.writeToNBT(nbttagcompound); - } + if (ic2EnergySource != null) { + ic2EnergySource.writeToNBT(nbttagcompound); + } - tankManager.writeToNBT(nbttagcompound); - } + tankManager.writeToNBT(nbttagcompound); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); - if (ic2EnergySource != null) { - ic2EnergySource.readFromNBT(nbttagcompound); - } + if (ic2EnergySource != null) { + ic2EnergySource.readFromNBT(nbttagcompound); + } - tankManager.readFromNBT(nbttagcompound); - } + tankManager.readFromNBT(nbttagcompound); + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - tankManager.writeData(data); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + tankManager.writeData(data); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - tankManager.readData(data); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + tankManager.readData(data); + } - @Override - public void onChunkUnload() { - if (ic2EnergySource != null) { - ic2EnergySource.onChunkUnload(); - } + @Override + public void onChunkUnload() { + if (ic2EnergySource != null) { + ic2EnergySource.onChunkUnload(); + } - super.onChunkUnload(); - } + super.onChunkUnload(); + } - @Override - public void invalidate() { - if (ic2EnergySource != null) { - ic2EnergySource.invalidate(); - } + @Override + public void invalidate() { + if (ic2EnergySource != null) { + ic2EnergySource.invalidate(); + } - super.invalidate(); - } + super.invalidate(); + } - @Override - public void updateServerSide() { - if (updateOnInterval(20)) { - FluidHelper.drainContainers(tankManager, this, InventoryGenerator.SLOT_CAN); - } + @Override + public void updateServerSide() { + if (updateOnInterval(20)) { + FluidHelper.drainContainers(tankManager, this, InventoryGenerator.SLOT_CAN); + } - IErrorLogic errorLogic = getErrorLogic(); + IErrorLogic errorLogic = getErrorLogic(); - // No work to be done if IC2 is unavailable. - if (errorLogic.setCondition(ic2EnergySource == null, EnumErrorCode.NO_ENERGY_NET)) { - return; - } + // No work to be done if IC2 is unavailable. + if (errorLogic.setCondition(ic2EnergySource == null, EnumErrorCode.NO_ENERGY_NET)) { + return; + } - ic2EnergySource.updateEntity(); + ic2EnergySource.updateEntity(); - if (resourceTank.getFluidAmount() > 0) { - GeneratorFuel fuel = FuelManager.generatorFuel.get(resourceTank.getFluid().getFluid()); - if (resourceTank.canDrain(fuel.fuelConsumed) && ic2EnergySource.getFreeCapacity() >= fuel.eu) { - ic2EnergySource.addEnergy(fuel.eu); - this.tickCount++; + if (resourceTank.getFluidAmount() > 0) { + GeneratorFuel fuel = + FuelManager.generatorFuel.get(resourceTank.getFluid().getFluid()); + if (resourceTank.canDrain(fuel.fuelConsumed) && ic2EnergySource.getFreeCapacity() >= fuel.eu) { + ic2EnergySource.addEnergy(fuel.eu); + this.tickCount++; - if (tickCount >= fuel.rate) { - tickCount = 0; - resourceTank.drain(fuel.fuelConsumed.amount, true); - } - } + if (tickCount >= fuel.rate) { + tickCount = 0; + resourceTank.drain(fuel.fuelConsumed.amount, true); + } + } + } - } + boolean hasFuel = resourceTank.getFluidAmount() > 0; + errorLogic.setCondition(!hasFuel, EnumErrorCode.NO_FUEL); + } - boolean hasFuel = resourceTank.getFluidAmount() > 0; - errorLogic.setCondition(!hasFuel, EnumErrorCode.NO_FUEL); - } + public boolean isWorking() { + return resourceTank.getFluidAmount() > 0; + } - public boolean isWorking() { - return resourceTank.getFluidAmount() > 0; - } + public int getResourceScaled(int i) { + return (resourceTank.getFluidAmount() * i) / Constants.PROCESSOR_TANK_CAPACITY; + } - public int getResourceScaled(int i) { - return (resourceTank.getFluidAmount() * i) / Constants.PROCESSOR_TANK_CAPACITY; - } + public int getStoredScaled(int i) { + if (ic2EnergySource == null) { + return 0; + } - public int getStoredScaled(int i) { - if (ic2EnergySource == null) { - return 0; - } + return (int) (ic2EnergySource.getEnergyStored() * i) / maxEnergy; + } - return (int) (ic2EnergySource.getEnergyStored() * i) / maxEnergy; - } + @Override + public TankRenderInfo getResourceTankInfo() { + return new TankRenderInfo(resourceTank); + } - @Override - public TankRenderInfo getResourceTankInfo() { - return new TankRenderInfo(resourceTank); - } + @Override + public TankRenderInfo getProductTankInfo() { + return TankRenderInfo.EMPTY; + } - @Override - public TankRenderInfo getProductTankInfo() { - return TankRenderInfo.EMPTY; - } + /* SMP GUI */ + public void getGUINetworkData(int i, int j) { + if (i == 0) { + if (ic2EnergySource != null) { + ic2EnergySource.setEnergyStored(j); + } + } + } - /* SMP GUI */ - public void getGUINetworkData(int i, int j) { - if (i == 0) { - if (ic2EnergySource != null) { - ic2EnergySource.setEnergyStored(j); - } - } - } + public void sendGUINetworkData(Container container, ICrafting iCrafting) { + if (ic2EnergySource != null) { + iCrafting.sendProgressBarUpdate(container, 0, (short) ic2EnergySource.getEnergyStored()); + } + } - public void sendGUINetworkData(Container container, ICrafting iCrafting) { - if (ic2EnergySource != null) { - iCrafting.sendProgressBarUpdate(container, 0, (short) ic2EnergySource.getEnergyStored()); - } - } + /* ILiquidTankTile */ + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } - /* ILiquidTankTile */ - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return tankManager.fill(from, resource, doFill); - } + @Override + public TankManager getTankManager() { + return tankManager; + } - @Override - public TankManager getTankManager() { - return tankManager; - } + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return tankManager.drain(from, resource, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return tankManager.drain(from, maxDrain, doDrain); - } + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return tankManager.canFill(from, fluid); - } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return tankManager.canDrain(from, fluid); - } + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return tankManager.getTankInfo(from); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiGenerator(player.inventory, this); + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiGenerator(player.inventory, this); - } - - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerGenerator(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerGenerator(player.inventory, this); + } } diff --git a/src/main/java/forestry/factory/DummyManagers.java b/src/main/java/forestry/factory/DummyManagers.java index c0463c194..88547ef13 100644 --- a/src/main/java/forestry/factory/DummyManagers.java +++ b/src/main/java/forestry/factory/DummyManagers.java @@ -1,160 +1,139 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; - -import javax.annotation.Nullable; -import java.util.Map; -import java.util.Set; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.ICarpenterManager; -import forestry.api.recipes.ICarpenterRecipe; -import forestry.api.recipes.ICentrifugeManager; -import forestry.api.recipes.ICentrifugeRecipe; -import forestry.api.recipes.ICraftingProvider; -import forestry.api.recipes.IFabricatorManager; -import forestry.api.recipes.IFabricatorRecipe; -import forestry.api.recipes.IFabricatorSmeltingManager; -import forestry.api.recipes.IFabricatorSmeltingRecipe; -import forestry.api.recipes.IFermenterManager; -import forestry.api.recipes.IFermenterRecipe; -import forestry.api.recipes.IForestryRecipe; -import forestry.api.recipes.IMoistenerManager; -import forestry.api.recipes.IMoistenerRecipe; -import forestry.api.recipes.ISqueezerManager; -import forestry.api.recipes.ISqueezerRecipe; -import forestry.api.recipes.IStillManager; -import forestry.api.recipes.IStillRecipe; - -public class DummyManagers { - - public static abstract class DummyCraftingProvider implements ICraftingProvider { - @Override - public boolean addRecipe(T recipe) { - return false; - } - - @Override - public boolean removeRecipe(T recipe) { - return false; - } - - @Override - public Set recipes() { - return ImmutableSet.of(); - } - - @Override - public Map getRecipes() { - return ImmutableMap.of(); - } - } - - public static class DummyCarpenterManager extends DummyCraftingProvider implements ICarpenterManager { - - @Override - public void addRecipe(ItemStack box, ItemStack product, Object... materials) { - - } - - @Override - public void addRecipe(int packagingTime, ItemStack box, ItemStack product, Object... materials) { - - } - - @Override - public void addRecipe(int packagingTime, FluidStack liquid, ItemStack box, ItemStack product, Object... materials) { - - } - } - - public static class DummyCentrifugeManager extends DummyCraftingProvider implements ICentrifugeManager { - - @Override - public void addRecipe(int timePerItem, ItemStack resource, Map products) { - - } - } - - public static class DummyFabricatorManager extends DummyCraftingProvider implements IFabricatorManager { - - @Override - public void addRecipe(ItemStack plan, FluidStack molten, ItemStack result, Object[] pattern) { - - } - - @Override - public void addSmelting(ItemStack resource, FluidStack molten, int meltingPoint) { - - } - } - - public static class DummyFabricatorSmeltingManager extends DummyCraftingProvider implements IFabricatorSmeltingManager { - - @Override - public void addSmelting(ItemStack resource, FluidStack molten, int meltingPoint) { - - } - } - - public static class DummyFermenterManager extends DummyCraftingProvider implements IFermenterManager { - - @Override - public void addRecipe(ItemStack resource, int fermentationValue, float modifier, FluidStack output, FluidStack liquid) { - - } - - @Override - public void addRecipe(ItemStack resource, int fermentationValue, float modifier, FluidStack output) { - - } - } - - public static class DummyMoistenerManager extends DummyCraftingProvider implements IMoistenerManager { - - @Override - public void addRecipe(ItemStack resource, ItemStack product, int timePerItem) { - - } - } - - public static class DummySqueezerManager extends DummyCraftingProvider implements ISqueezerManager { - - @Override - public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid, ItemStack remnants, int chance) { - - } - - @Override - public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid) { - - } - - @Override - public void addContainerRecipe(int timePerItem, ItemStack emptyContainer, @Nullable ItemStack remnants, float chance) { - - } - } - - public static class DummyStillManager extends DummyCraftingProvider implements IStillManager { - - @Override - public void addRecipe(int cyclesPerUnit, FluidStack input, FluidStack output) { - - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import forestry.api.recipes.ICarpenterManager; +import forestry.api.recipes.ICarpenterRecipe; +import forestry.api.recipes.ICentrifugeManager; +import forestry.api.recipes.ICentrifugeRecipe; +import forestry.api.recipes.ICraftingProvider; +import forestry.api.recipes.IFabricatorManager; +import forestry.api.recipes.IFabricatorRecipe; +import forestry.api.recipes.IFabricatorSmeltingManager; +import forestry.api.recipes.IFabricatorSmeltingRecipe; +import forestry.api.recipes.IFermenterManager; +import forestry.api.recipes.IFermenterRecipe; +import forestry.api.recipes.IForestryRecipe; +import forestry.api.recipes.IMoistenerManager; +import forestry.api.recipes.IMoistenerRecipe; +import forestry.api.recipes.ISqueezerManager; +import forestry.api.recipes.ISqueezerRecipe; +import forestry.api.recipes.IStillManager; +import forestry.api.recipes.IStillRecipe; +import java.util.Map; +import java.util.Set; +import javax.annotation.Nullable; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; + +public class DummyManagers { + + public abstract static class DummyCraftingProvider implements ICraftingProvider { + @Override + public boolean addRecipe(T recipe) { + return false; + } + + @Override + public boolean removeRecipe(T recipe) { + return false; + } + + @Override + public Set recipes() { + return ImmutableSet.of(); + } + + @Override + public Map getRecipes() { + return ImmutableMap.of(); + } + } + + public static class DummyCarpenterManager extends DummyCraftingProvider + implements ICarpenterManager { + + @Override + public void addRecipe(ItemStack box, ItemStack product, Object... materials) {} + + @Override + public void addRecipe(int packagingTime, ItemStack box, ItemStack product, Object... materials) {} + + @Override + public void addRecipe( + int packagingTime, FluidStack liquid, ItemStack box, ItemStack product, Object... materials) {} + } + + public static class DummyCentrifugeManager extends DummyCraftingProvider + implements ICentrifugeManager { + + @Override + public void addRecipe(int timePerItem, ItemStack resource, Map products) {} + } + + public static class DummyFabricatorManager extends DummyCraftingProvider + implements IFabricatorManager { + + @Override + public void addRecipe(ItemStack plan, FluidStack molten, ItemStack result, Object[] pattern) {} + + @Override + public void addSmelting(ItemStack resource, FluidStack molten, int meltingPoint) {} + } + + public static class DummyFabricatorSmeltingManager extends DummyCraftingProvider + implements IFabricatorSmeltingManager { + + @Override + public void addSmelting(ItemStack resource, FluidStack molten, int meltingPoint) {} + } + + public static class DummyFermenterManager extends DummyCraftingProvider + implements IFermenterManager { + + @Override + public void addRecipe( + ItemStack resource, int fermentationValue, float modifier, FluidStack output, FluidStack liquid) {} + + @Override + public void addRecipe(ItemStack resource, int fermentationValue, float modifier, FluidStack output) {} + } + + public static class DummyMoistenerManager extends DummyCraftingProvider + implements IMoistenerManager { + + @Override + public void addRecipe(ItemStack resource, ItemStack product, int timePerItem) {} + } + + public static class DummySqueezerManager extends DummyCraftingProvider + implements ISqueezerManager { + + @Override + public void addRecipe( + int timePerItem, ItemStack[] resources, FluidStack liquid, ItemStack remnants, int chance) {} + + @Override + public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid) {} + + @Override + public void addContainerRecipe( + int timePerItem, ItemStack emptyContainer, @Nullable ItemStack remnants, float chance) {} + } + + public static class DummyStillManager extends DummyCraftingProvider implements IStillManager { + + @Override + public void addRecipe(int cyclesPerUnit, FluidStack input, FluidStack output) {} + } +} diff --git a/src/main/java/forestry/factory/blocks/BlockFactoryPlain.java b/src/main/java/forestry/factory/blocks/BlockFactoryPlain.java index 344a60426..4baeed21d 100644 --- a/src/main/java/forestry/factory/blocks/BlockFactoryPlain.java +++ b/src/main/java/forestry/factory/blocks/BlockFactoryPlain.java @@ -1,19 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.blocks; - -import forestry.core.blocks.BlockBase; - -public class BlockFactoryPlain extends BlockBase { - public BlockFactoryPlain() { - super(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.blocks; + +import forestry.core.blocks.BlockBase; + +public class BlockFactoryPlain extends BlockBase { + public BlockFactoryPlain() { + super(); + } +} diff --git a/src/main/java/forestry/factory/blocks/BlockFactoryPlainType.java b/src/main/java/forestry/factory/blocks/BlockFactoryPlainType.java index 14b52f4cd..debce92ad 100644 --- a/src/main/java/forestry/factory/blocks/BlockFactoryPlainType.java +++ b/src/main/java/forestry/factory/blocks/BlockFactoryPlainType.java @@ -1,53 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.blocks; - -import java.util.Locale; - -import org.apache.commons.lang3.text.WordUtils; - -import forestry.core.blocks.IMachineProperties; -import forestry.core.tiles.TileForestry; -import forestry.factory.tiles.TileFabricator; -import forestry.factory.tiles.TileRaintank; -import forestry.factory.tiles.TileWorktable; - -public enum BlockFactoryPlainType implements IMachineProperties { - FABRICATOR(TileFabricator.class), - RAINTANK(TileRaintank.class), - WORKTABLE(TileWorktable.class); - - public static final BlockFactoryPlainType[] VALUES = values(); - - private final String teIdent; - private final Class teClass; - - BlockFactoryPlainType(Class teClass) { - String name = toString().toLowerCase(Locale.ENGLISH); - this.teIdent = "forestry." + WordUtils.capitalize(name); - this.teClass = teClass; - } - - @Override - public int getMeta() { - return ordinal(); - } - - @Override - public String getTeIdent() { - return teIdent; - } - - @Override - public Class getTeClass() { - return teClass; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.blocks; + +import forestry.core.blocks.IMachineProperties; +import forestry.core.tiles.TileForestry; +import forestry.factory.tiles.TileFabricator; +import forestry.factory.tiles.TileRaintank; +import forestry.factory.tiles.TileWorktable; +import java.util.Locale; +import org.apache.commons.lang3.text.WordUtils; + +public enum BlockFactoryPlainType implements IMachineProperties { + FABRICATOR(TileFabricator.class), + RAINTANK(TileRaintank.class), + WORKTABLE(TileWorktable.class); + + public static final BlockFactoryPlainType[] VALUES = values(); + + private final String teIdent; + private final Class teClass; + + BlockFactoryPlainType(Class teClass) { + String name = toString().toLowerCase(Locale.ENGLISH); + this.teIdent = "forestry." + WordUtils.capitalize(name); + this.teClass = teClass; + } + + @Override + public int getMeta() { + return ordinal(); + } + + @Override + public String getTeIdent() { + return teIdent; + } + + @Override + public Class getTeClass() { + return teClass; + } +} diff --git a/src/main/java/forestry/factory/blocks/BlockFactoryTESR.java b/src/main/java/forestry/factory/blocks/BlockFactoryTESR.java index 219166525..9543d577f 100644 --- a/src/main/java/forestry/factory/blocks/BlockFactoryTESR.java +++ b/src/main/java/forestry/factory/blocks/BlockFactoryTESR.java @@ -1,19 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.blocks; - -import forestry.core.blocks.BlockBase; - -public class BlockFactoryTESR extends BlockBase { - public BlockFactoryTESR() { - super(true); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.blocks; + +import forestry.core.blocks.BlockBase; + +public class BlockFactoryTESR extends BlockBase { + public BlockFactoryTESR() { + super(true); + } +} diff --git a/src/main/java/forestry/factory/blocks/BlockFactoryTesrType.java b/src/main/java/forestry/factory/blocks/BlockFactoryTesrType.java index f9bf618f8..64b6335d9 100644 --- a/src/main/java/forestry/factory/blocks/BlockFactoryTesrType.java +++ b/src/main/java/forestry/factory/blocks/BlockFactoryTesrType.java @@ -1,78 +1,76 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.blocks; - -import java.util.Locale; - -import org.apache.commons.lang3.text.WordUtils; - -import forestry.core.blocks.IMachinePropertiesTESR; -import forestry.core.config.Constants; -import forestry.core.proxy.Proxies; -import forestry.core.render.IBlockRenderer; -import forestry.core.tiles.TileForestry; -import forestry.factory.tiles.TileBottler; -import forestry.factory.tiles.TileCarpenter; -import forestry.factory.tiles.TileCentrifuge; -import forestry.factory.tiles.TileFermenter; -import forestry.factory.tiles.TileMillRainmaker; -import forestry.factory.tiles.TileMoistener; -import forestry.factory.tiles.TileSqueezer; -import forestry.factory.tiles.TileStill; - -public enum BlockFactoryTesrType implements IMachinePropertiesTESR { - BOTTLER(TileBottler.class), - CARPENTER(TileCarpenter.class), - CENTRIFUGE(TileCentrifuge.class), - FERMENTER(TileFermenter.class), - MOISTENER(TileMoistener.class), - SQUEEZER(TileSqueezer.class), - STILL(TileStill.class), - RAINMAKER(TileMillRainmaker.class) { - @Override - public IBlockRenderer getRenderer() { - return Proxies.render.getRenderMill(Constants.TEXTURE_PATH_BLOCKS + "/rainmaker_"); - } - }; - - public static final BlockFactoryTesrType[] VALUES = values(); - - private final String teIdent; - private final Class teClass; - private final String name; - - BlockFactoryTesrType(Class teClass) { - String name = toString().toLowerCase(Locale.ENGLISH); - this.teIdent = "forestry." + WordUtils.capitalize(name); - this.teClass = teClass; - this.name = name; - } - - @Override - public int getMeta() { - return ordinal(); - } - - @Override - public String getTeIdent() { - return teIdent; - } - - @Override - public Class getTeClass() { - return teClass; - } - - @Override - public IBlockRenderer getRenderer() { - return Proxies.render.getRenderDefaultMachine(Constants.TEXTURE_PATH_BLOCKS + "/" + name + "_"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.blocks; + +import forestry.core.blocks.IMachinePropertiesTESR; +import forestry.core.config.Constants; +import forestry.core.proxy.Proxies; +import forestry.core.render.IBlockRenderer; +import forestry.core.tiles.TileForestry; +import forestry.factory.tiles.TileBottler; +import forestry.factory.tiles.TileCarpenter; +import forestry.factory.tiles.TileCentrifuge; +import forestry.factory.tiles.TileFermenter; +import forestry.factory.tiles.TileMillRainmaker; +import forestry.factory.tiles.TileMoistener; +import forestry.factory.tiles.TileSqueezer; +import forestry.factory.tiles.TileStill; +import java.util.Locale; +import org.apache.commons.lang3.text.WordUtils; + +public enum BlockFactoryTesrType implements IMachinePropertiesTESR { + BOTTLER(TileBottler.class), + CARPENTER(TileCarpenter.class), + CENTRIFUGE(TileCentrifuge.class), + FERMENTER(TileFermenter.class), + MOISTENER(TileMoistener.class), + SQUEEZER(TileSqueezer.class), + STILL(TileStill.class), + RAINMAKER(TileMillRainmaker.class) { + @Override + public IBlockRenderer getRenderer() { + return Proxies.render.getRenderMill(Constants.TEXTURE_PATH_BLOCKS + "/rainmaker_"); + } + }; + + public static final BlockFactoryTesrType[] VALUES = values(); + + private final String teIdent; + private final Class teClass; + private final String name; + + BlockFactoryTesrType(Class teClass) { + String name = toString().toLowerCase(Locale.ENGLISH); + this.teIdent = "forestry." + WordUtils.capitalize(name); + this.teClass = teClass; + this.name = name; + } + + @Override + public int getMeta() { + return ordinal(); + } + + @Override + public String getTeIdent() { + return teIdent; + } + + @Override + public Class getTeClass() { + return teClass; + } + + @Override + public IBlockRenderer getRenderer() { + return Proxies.render.getRenderDefaultMachine(Constants.TEXTURE_PATH_BLOCKS + "/" + name + "_"); + } +} diff --git a/src/main/java/forestry/factory/blocks/BlockRegistryFactory.java b/src/main/java/forestry/factory/blocks/BlockRegistryFactory.java index 2e1ea9d60..43431cf7b 100644 --- a/src/main/java/forestry/factory/blocks/BlockRegistryFactory.java +++ b/src/main/java/forestry/factory/blocks/BlockRegistryFactory.java @@ -1,25 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.blocks; - -import forestry.core.blocks.BlockRegistry; -import forestry.core.items.ItemBlockForestry; -import forestry.core.items.ItemBlockNBT; - -public class BlockRegistryFactory extends BlockRegistry { - public final BlockFactoryTESR factoryTESR; - public final BlockFactoryPlain factoryPlain; - - public BlockRegistryFactory() { - factoryTESR = registerBlock(new BlockFactoryTESR(), ItemBlockForestry.class, "factory"); - factoryPlain = registerBlock(new BlockFactoryPlain(), ItemBlockNBT.class, "factory2"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.blocks; + +import forestry.core.blocks.BlockRegistry; +import forestry.core.items.ItemBlockForestry; +import forestry.core.items.ItemBlockNBT; + +public class BlockRegistryFactory extends BlockRegistry { + public final BlockFactoryTESR factoryTESR; + public final BlockFactoryPlain factoryPlain; + + public BlockRegistryFactory() { + factoryTESR = registerBlock(new BlockFactoryTESR(), ItemBlockForestry.class, "factory"); + factoryPlain = registerBlock(new BlockFactoryPlain(), ItemBlockNBT.class, "factory2"); + } +} diff --git a/src/main/java/forestry/factory/circuits/CircuitSpeedUpgrade.java b/src/main/java/forestry/factory/circuits/CircuitSpeedUpgrade.java index f142632f4..6ee876661 100644 --- a/src/main/java/forestry/factory/circuits/CircuitSpeedUpgrade.java +++ b/src/main/java/forestry/factory/circuits/CircuitSpeedUpgrade.java @@ -15,49 +15,48 @@ import forestry.core.circuits.ISpeedUpgradable; public class CircuitSpeedUpgrade extends Circuit { - private final double speedBoost; - private final float powerDraw; + private final double speedBoost; + private final float powerDraw; - public CircuitSpeedUpgrade(String uid, double speedBoost, float powerDraw, int limit) { - super(uid, false); - this.setLimit(limit); - this.speedBoost = speedBoost; - this.powerDraw = powerDraw; - } + public CircuitSpeedUpgrade(String uid, double speedBoost, float powerDraw, int limit) { + super(uid, false); + this.setLimit(limit); + this.speedBoost = speedBoost; + this.powerDraw = powerDraw; + } - @Override - public boolean isCircuitable(Object tile) { - return tile instanceof ISpeedUpgradable; - } + @Override + public boolean isCircuitable(Object tile) { + return tile instanceof ISpeedUpgradable; + } - @Override - public void onInsertion(int slot, Object tile) { - if (!isCircuitable(tile)) { - return; - } - if (tile instanceof ISpeedUpgradable) { - ISpeedUpgradable machine = (ISpeedUpgradable) tile; - machine.applySpeedUpgrade(speedBoost, powerDraw); - } - } + @Override + public void onInsertion(int slot, Object tile) { + if (!isCircuitable(tile)) { + return; + } + if (tile instanceof ISpeedUpgradable) { + ISpeedUpgradable machine = (ISpeedUpgradable) tile; + machine.applySpeedUpgrade(speedBoost, powerDraw); + } + } - @Override - public void onLoad(int slot, Object tile) { - onInsertion(slot, tile); - } + @Override + public void onLoad(int slot, Object tile) { + onInsertion(slot, tile); + } - @Override - public void onRemoval(int slot, Object tile) { - if (!isCircuitable(tile)) { - return; - } - if (tile instanceof ISpeedUpgradable) { - ISpeedUpgradable machine = (ISpeedUpgradable) tile; - machine.applySpeedUpgrade(-speedBoost, -powerDraw); - } - } + @Override + public void onRemoval(int slot, Object tile) { + if (!isCircuitable(tile)) { + return; + } + if (tile instanceof ISpeedUpgradable) { + ISpeedUpgradable machine = (ISpeedUpgradable) tile; + machine.applySpeedUpgrade(-speedBoost, -powerDraw); + } + } - @Override - public void onTick(int slot, Object tile) { - } + @Override + public void onTick(int slot, Object tile) {} } diff --git a/src/main/java/forestry/factory/gui/ContainerBottler.java b/src/main/java/forestry/factory/gui/ContainerBottler.java index a04323ad7..27b403551 100755 --- a/src/main/java/forestry/factory/gui/ContainerBottler.java +++ b/src/main/java/forestry/factory/gui/ContainerBottler.java @@ -10,21 +10,20 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.gui.ContainerLiquidTanks; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.factory.inventory.InventoryBottler; import forestry.factory.tiles.TileBottler; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerBottler extends ContainerLiquidTanks { - public ContainerBottler(InventoryPlayer player, TileBottler tile) { - super(tile, player, 8, 84); + public ContainerBottler(InventoryPlayer player, TileBottler tile) { + super(tile, player, 8, 84); - this.addSlotToContainer(new SlotFiltered(tile, InventoryBottler.SLOT_INPUT_EMPTY_CAN, 116, 19)); - this.addSlotToContainer(new SlotOutput(tile, InventoryBottler.SLOT_OUTPUT, 116, 55)); - this.addSlotToContainer(new SlotFiltered(tile, InventoryBottler.SLOT_INPUT_FULL_CAN, 26, 38)); - } + this.addSlotToContainer(new SlotFiltered(tile, InventoryBottler.SLOT_INPUT_EMPTY_CAN, 116, 19)); + this.addSlotToContainer(new SlotOutput(tile, InventoryBottler.SLOT_OUTPUT, 116, 55)); + this.addSlotToContainer(new SlotFiltered(tile, InventoryBottler.SLOT_INPUT_FULL_CAN, 26, 38)); + } } diff --git a/src/main/java/forestry/factory/gui/ContainerCarpenter.java b/src/main/java/forestry/factory/gui/ContainerCarpenter.java index 3ab09b7b1..0af372415 100755 --- a/src/main/java/forestry/factory/gui/ContainerCarpenter.java +++ b/src/main/java/forestry/factory/gui/ContainerCarpenter.java @@ -10,11 +10,6 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; - import forestry.core.gui.ContainerLiquidTanks; import forestry.core.gui.IContainerCrafting; import forestry.core.gui.slots.SlotCraftMatrix; @@ -24,57 +19,62 @@ import forestry.core.gui.slots.SlotOutput; import forestry.core.network.packets.PacketItemStackDisplay; import forestry.factory.inventory.InventoryCarpenter; import forestry.factory.tiles.TileCarpenter; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; public class ContainerCarpenter extends ContainerLiquidTanks implements IContainerCrafting { - public ContainerCarpenter(InventoryPlayer inventoryplayer, TileCarpenter tile) { - super(tile, inventoryplayer, 8, 136); + public ContainerCarpenter(InventoryPlayer inventoryplayer, TileCarpenter tile) { + super(tile, inventoryplayer, 8, 136); - // Internal inventory - for (int i = 0; i < 2; i++) { - for (int k = 0; k < 9; k++) { - addSlotToContainer(new Slot(tile, InventoryCarpenter.SLOT_INVENTORY_1 + k + i * 9, 8 + k * 18, 90 + i * 18)); - } - } + // Internal inventory + for (int i = 0; i < 2; i++) { + for (int k = 0; k < 9; k++) { + addSlotToContainer( + new Slot(tile, InventoryCarpenter.SLOT_INVENTORY_1 + k + i * 9, 8 + k * 18, 90 + i * 18)); + } + } - // Liquid Input - this.addSlotToContainer(new SlotFiltered(tile, InventoryCarpenter.SLOT_CAN_INPUT, 120, 20)); - // Boxes - this.addSlotToContainer(new SlotFiltered(tile, InventoryCarpenter.SLOT_BOX, 83, 20)); - // Product - this.addSlotToContainer(new SlotOutput(tile, InventoryCarpenter.SLOT_PRODUCT, 120, 56)); + // Liquid Input + this.addSlotToContainer(new SlotFiltered(tile, InventoryCarpenter.SLOT_CAN_INPUT, 120, 20)); + // Boxes + this.addSlotToContainer(new SlotFiltered(tile, InventoryCarpenter.SLOT_BOX, 83, 20)); + // Product + this.addSlotToContainer(new SlotOutput(tile, InventoryCarpenter.SLOT_PRODUCT, 120, 56)); - // Craft Preview display - addSlotToContainer(new SlotLocked(tile.getCraftPreviewInventory(), 0, 80, 51)); + // Craft Preview display + addSlotToContainer(new SlotLocked(tile.getCraftPreviewInventory(), 0, 80, 51)); - // Crafting matrix - for (int l = 0; l < 3; l++) { - for (int k1 = 0; k1 < 3; k1++) { - addSlotToContainer(new SlotCraftMatrix(this, tile.getCraftingInventory(), k1 + l * 3, 10 + k1 * 18, 20 + l * 18)); - } - } - } + // Crafting matrix + for (int l = 0; l < 3; l++) { + for (int k1 = 0; k1 < 3; k1++) { + addSlotToContainer( + new SlotCraftMatrix(this, tile.getCraftingInventory(), k1 + l * 3, 10 + k1 * 18, 20 + l * 18)); + } + } + } - @Override - public void onCraftMatrixChanged(IInventory iinventory, int slot) { - tile.checkRecipe(); - } + @Override + public void onCraftMatrixChanged(IInventory iinventory, int slot) { + tile.checkRecipe(); + } - private ItemStack oldCraftPreview; + private ItemStack oldCraftPreview; - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); - IInventory craftPreviewInventory = tile.getCraftPreviewInventory(); + IInventory craftPreviewInventory = tile.getCraftPreviewInventory(); - ItemStack newCraftPreview = craftPreviewInventory.getStackInSlot(0); - if (!ItemStack.areItemStacksEqual(oldCraftPreview, newCraftPreview)) { - oldCraftPreview = newCraftPreview; - - PacketItemStackDisplay packet = new PacketItemStackDisplay(tile, newCraftPreview); - sendPacketToCrafters(packet); - } - } + ItemStack newCraftPreview = craftPreviewInventory.getStackInSlot(0); + if (!ItemStack.areItemStacksEqual(oldCraftPreview, newCraftPreview)) { + oldCraftPreview = newCraftPreview; + PacketItemStackDisplay packet = new PacketItemStackDisplay(tile, newCraftPreview); + sendPacketToCrafters(packet); + } + } } diff --git a/src/main/java/forestry/factory/gui/ContainerCentrifuge.java b/src/main/java/forestry/factory/gui/ContainerCentrifuge.java index 15a87b588..c438cfddb 100755 --- a/src/main/java/forestry/factory/gui/ContainerCentrifuge.java +++ b/src/main/java/forestry/factory/gui/ContainerCentrifuge.java @@ -10,27 +10,25 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.gui.ContainerSocketed; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.factory.tiles.TileCentrifuge; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerCentrifuge extends ContainerSocketed { - public ContainerCentrifuge(InventoryPlayer player, TileCentrifuge tile) { - super(tile, player, 8, 84); + public ContainerCentrifuge(InventoryPlayer player, TileCentrifuge tile) { + super(tile, player, 8, 84); - // Resource - this.addSlotToContainer(new SlotFiltered(tile, 0, 30, 37)); - - // Product Inventory - for (int l = 0; l < 3; l++) { - for (int k = 0; k < 3; k++) { - addSlotToContainer(new SlotOutput(tile, 1 + k + l * 3, 98 + k * 18, 19 + l * 18)); - } - } - } + // Resource + this.addSlotToContainer(new SlotFiltered(tile, 0, 30, 37)); + // Product Inventory + for (int l = 0; l < 3; l++) { + for (int k = 0; k < 3; k++) { + addSlotToContainer(new SlotOutput(tile, 1 + k + l * 3, 98 + k * 18, 19 + l * 18)); + } + } + } } diff --git a/src/main/java/forestry/factory/gui/ContainerFabricator.java b/src/main/java/forestry/factory/gui/ContainerFabricator.java index 92b92c627..eb0e5850d 100755 --- a/src/main/java/forestry/factory/gui/ContainerFabricator.java +++ b/src/main/java/forestry/factory/gui/ContainerFabricator.java @@ -10,11 +10,6 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.ICrafting; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.Slot; - import forestry.core.gui.ContainerLiquidTanks; import forestry.core.gui.IContainerCrafting; import forestry.core.gui.slots.SlotCraftMatrix; @@ -23,55 +18,63 @@ import forestry.core.gui.slots.SlotOutput; import forestry.factory.inventory.InventoryFabricator; import forestry.factory.inventory.InventoryGhostCrafting; import forestry.factory.tiles.TileFabricator; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.ICrafting; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; public class ContainerFabricator extends ContainerLiquidTanks implements IContainerCrafting { - public ContainerFabricator(InventoryPlayer playerInventory, TileFabricator tile) { - super(tile, playerInventory, 8, 129); + public ContainerFabricator(InventoryPlayer playerInventory, TileFabricator tile) { + super(tile, playerInventory, 8, 129); - // Internal inventory - for (int i = 0; i < 2; i++) { - for (int k = 0; k < 9; k++) { - addSlotToContainer(new Slot(tile, InventoryFabricator.SLOT_INVENTORY_1 + k + i * 9, 8 + k * 18, 84 + i * 18)); - } - } + // Internal inventory + for (int i = 0; i < 2; i++) { + for (int k = 0; k < 9; k++) { + addSlotToContainer( + new Slot(tile, InventoryFabricator.SLOT_INVENTORY_1 + k + i * 9, 8 + k * 18, 84 + i * 18)); + } + } - // Molten resource - this.addSlotToContainer(new SlotFiltered(tile, InventoryFabricator.SLOT_METAL, 26, 21)); + // Molten resource + this.addSlotToContainer(new SlotFiltered(tile, InventoryFabricator.SLOT_METAL, 26, 21)); - // Plan - this.addSlotToContainer(new SlotFiltered(tile, InventoryFabricator.SLOT_PLAN, 139, 17)); + // Plan + this.addSlotToContainer(new SlotFiltered(tile, InventoryFabricator.SLOT_PLAN, 139, 17)); - // Result - this.addSlotToContainer(new SlotOutput(tile, InventoryFabricator.SLOT_RESULT, 139, 53)); + // Result + this.addSlotToContainer(new SlotOutput(tile, InventoryFabricator.SLOT_RESULT, 139, 53)); - // Crafting matrix - for (int l = 0; l < 3; l++) { - for (int k = 0; k < 3; k++) { - addSlotToContainer(new SlotCraftMatrix(this, tile.getCraftingInventory(), InventoryGhostCrafting.SLOT_CRAFTING_1 + k + l * 3, 67 + k * 18, 17 + l * 18)); - } - } - } + // Crafting matrix + for (int l = 0; l < 3; l++) { + for (int k = 0; k < 3; k++) { + addSlotToContainer(new SlotCraftMatrix( + this, + tile.getCraftingInventory(), + InventoryGhostCrafting.SLOT_CRAFTING_1 + k + l * 3, + 67 + k * 18, + 17 + l * 18)); + } + } + } - @Override - public void onCraftMatrixChanged(IInventory iinventory, int slot) { + @Override + public void onCraftMatrixChanged(IInventory iinventory, int slot) {} - } + @Override + public void updateProgressBar(int messageId, int data) { + super.updateProgressBar(messageId, data); - @Override - public void updateProgressBar(int messageId, int data) { - super.updateProgressBar(messageId, data); + tile.getGUINetworkData(messageId, data); + } - tile.getGUINetworkData(messageId, data); - } + @Override + @SuppressWarnings("unchecked") + public void detectAndSendChanges() { + super.detectAndSendChanges(); - @Override - @SuppressWarnings("unchecked") - public void detectAndSendChanges() { - super.detectAndSendChanges(); - - for (Object crafter : crafters) { - tile.sendGUINetworkData(this, (ICrafting) crafter); - } - } + for (Object crafter : crafters) { + tile.sendGUINetworkData(this, (ICrafting) crafter); + } + } } diff --git a/src/main/java/forestry/factory/gui/ContainerFermenter.java b/src/main/java/forestry/factory/gui/ContainerFermenter.java index 98398f4f6..efcd58725 100755 --- a/src/main/java/forestry/factory/gui/ContainerFermenter.java +++ b/src/main/java/forestry/factory/gui/ContainerFermenter.java @@ -10,41 +10,40 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.ICrafting; - import forestry.core.gui.ContainerLiquidTanks; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.factory.inventory.InventoryFermenter; import forestry.factory.tiles.TileFermenter; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.ICrafting; public class ContainerFermenter extends ContainerLiquidTanks { - public ContainerFermenter(InventoryPlayer player, TileFermenter fermenter) { - super(fermenter, player, 8, 84); + public ContainerFermenter(InventoryPlayer player, TileFermenter fermenter) { + super(fermenter, player, 8, 84); - this.addSlotToContainer(new SlotFiltered(fermenter, InventoryFermenter.SLOT_RESOURCE, 85, 23)); - this.addSlotToContainer(new SlotFiltered(fermenter, InventoryFermenter.SLOT_FUEL, 75, 57)); - this.addSlotToContainer(new SlotOutput(fermenter, InventoryFermenter.SLOT_CAN_OUTPUT, 150, 58)); - this.addSlotToContainer(new SlotFiltered(fermenter, InventoryFermenter.SLOT_CAN_INPUT, 150, 22)); - this.addSlotToContainer(new SlotFiltered(fermenter, InventoryFermenter.SLOT_INPUT, 10, 40)); - } + this.addSlotToContainer(new SlotFiltered(fermenter, InventoryFermenter.SLOT_RESOURCE, 85, 23)); + this.addSlotToContainer(new SlotFiltered(fermenter, InventoryFermenter.SLOT_FUEL, 75, 57)); + this.addSlotToContainer(new SlotOutput(fermenter, InventoryFermenter.SLOT_CAN_OUTPUT, 150, 58)); + this.addSlotToContainer(new SlotFiltered(fermenter, InventoryFermenter.SLOT_CAN_INPUT, 150, 22)); + this.addSlotToContainer(new SlotFiltered(fermenter, InventoryFermenter.SLOT_INPUT, 10, 40)); + } - @Override - public void updateProgressBar(int messageId, int data) { - super.updateProgressBar(messageId, data); + @Override + public void updateProgressBar(int messageId, int data) { + super.updateProgressBar(messageId, data); - tile.getGUINetworkData(messageId, data); - } + tile.getGUINetworkData(messageId, data); + } - @Override - @SuppressWarnings("unchecked") - public void detectAndSendChanges() { - super.detectAndSendChanges(); + @Override + @SuppressWarnings("unchecked") + public void detectAndSendChanges() { + super.detectAndSendChanges(); - for (Object crafter : crafters) { - tile.sendGUINetworkData(this, (ICrafting) crafter); - } - } + for (Object crafter : crafters) { + tile.sendGUINetworkData(this, (ICrafting) crafter); + } + } } diff --git a/src/main/java/forestry/factory/gui/ContainerMoistener.java b/src/main/java/forestry/factory/gui/ContainerMoistener.java index ea9de6197..1e4fc56db 100755 --- a/src/main/java/forestry/factory/gui/ContainerMoistener.java +++ b/src/main/java/forestry/factory/gui/ContainerMoistener.java @@ -10,62 +10,61 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.ICrafting; -import net.minecraft.inventory.IInventory; - import forestry.core.gui.ContainerLiquidTanks; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotWatched; import forestry.core.gui.slots.SlotWorking; import forestry.core.inventory.watchers.ISlotChangeWatcher; import forestry.factory.tiles.TileMoistener; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.ICrafting; +import net.minecraft.inventory.IInventory; public class ContainerMoistener extends ContainerLiquidTanks implements ISlotChangeWatcher { - public ContainerMoistener(InventoryPlayer player, TileMoistener tile) { - super(tile, player, 8, 84); + public ContainerMoistener(InventoryPlayer player, TileMoistener tile) { + super(tile, player, 8, 84); - // Stash - for (int l = 0; l < 2; l++) { - for (int k1 = 0; k1 < 3; k1++) { - addSlotToContainer(new SlotFiltered(tile, k1 + l * 3, 39 + k1 * 18, 16 + l * 18)); - } - } - // Reservoir - for (int k1 = 0; k1 < 3; k1++) { - addSlotToContainer(new SlotFiltered(tile, k1 + 6, 39 + k1 * 18, 22 + 36)); - } + // Stash + for (int l = 0; l < 2; l++) { + for (int k1 = 0; k1 < 3; k1++) { + addSlotToContainer(new SlotFiltered(tile, k1 + l * 3, 39 + k1 * 18, 16 + l * 18)); + } + } + // Reservoir + for (int k1 = 0; k1 < 3; k1++) { + addSlotToContainer(new SlotFiltered(tile, k1 + 6, 39 + k1 * 18, 22 + 36)); + } - // Working slot - this.addSlotToContainer(new SlotWorking(tile, 9, 105, 37)); + // Working slot + this.addSlotToContainer(new SlotWorking(tile, 9, 105, 37)); - // Product slot - this.addSlotToContainer(new SlotFiltered(tile, 10, 143, 55)); - // Boxes - this.addSlotToContainer(new SlotWatched(tile, 11, 143, 19).setChangeWatcher(this)); - } + // Product slot + this.addSlotToContainer(new SlotFiltered(tile, 10, 143, 55)); + // Boxes + this.addSlotToContainer(new SlotWatched(tile, 11, 143, 19).setChangeWatcher(this)); + } - @Override - public void onSlotChanged(IInventory inventory, int slot) { - tile.setInventorySlotContents(slot, inventory.getStackInSlot(slot)); - tile.checkRecipe(); - } + @Override + public void onSlotChanged(IInventory inventory, int slot) { + tile.setInventorySlotContents(slot, inventory.getStackInSlot(slot)); + tile.checkRecipe(); + } - @Override - public void updateProgressBar(int messageId, int data) { - super.updateProgressBar(messageId, data); + @Override + public void updateProgressBar(int messageId, int data) { + super.updateProgressBar(messageId, data); - tile.getGUINetworkData(messageId, data); - } + tile.getGUINetworkData(messageId, data); + } - @Override - @SuppressWarnings("unchecked") - public void detectAndSendChanges() { - super.detectAndSendChanges(); + @Override + @SuppressWarnings("unchecked") + public void detectAndSendChanges() { + super.detectAndSendChanges(); - for (Object crafter : crafters) { - tile.sendGUINetworkData(this, (ICrafting) crafter); - } - } + for (Object crafter : crafters) { + tile.sendGUINetworkData(this, (ICrafting) crafter); + } + } } diff --git a/src/main/java/forestry/factory/gui/ContainerRaintank.java b/src/main/java/forestry/factory/gui/ContainerRaintank.java index 3e613fc55..2d7c76077 100755 --- a/src/main/java/forestry/factory/gui/ContainerRaintank.java +++ b/src/main/java/forestry/factory/gui/ContainerRaintank.java @@ -10,38 +10,37 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.ICrafting; - import forestry.core.gui.ContainerLiquidTanks; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.factory.inventory.InventoryRaintank; import forestry.factory.tiles.TileRaintank; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.ICrafting; public class ContainerRaintank extends ContainerLiquidTanks { - public ContainerRaintank(InventoryPlayer player, TileRaintank tile) { - super(tile, player, 8, 84); + public ContainerRaintank(InventoryPlayer player, TileRaintank tile) { + super(tile, player, 8, 84); - this.addSlotToContainer(new SlotFiltered(tile, InventoryRaintank.SLOT_RESOURCE, 116, 19)); - this.addSlotToContainer(new SlotOutput(tile, InventoryRaintank.SLOT_PRODUCT, 116, 55)); - } + this.addSlotToContainer(new SlotFiltered(tile, InventoryRaintank.SLOT_RESOURCE, 116, 19)); + this.addSlotToContainer(new SlotOutput(tile, InventoryRaintank.SLOT_PRODUCT, 116, 55)); + } - @Override - public void updateProgressBar(int messageId, int data) { - super.updateProgressBar(messageId, data); + @Override + public void updateProgressBar(int messageId, int data) { + super.updateProgressBar(messageId, data); - tile.getGUINetworkData(messageId, data); - } + tile.getGUINetworkData(messageId, data); + } - @Override - @SuppressWarnings("unchecked") - public void detectAndSendChanges() { - super.detectAndSendChanges(); + @Override + @SuppressWarnings("unchecked") + public void detectAndSendChanges() { + super.detectAndSendChanges(); - for (Object crafter : crafters) { - tile.sendGUINetworkData(this, (ICrafting) crafter); - } - } + for (Object crafter : crafters) { + tile.sendGUINetworkData(this, (ICrafting) crafter); + } + } } diff --git a/src/main/java/forestry/factory/gui/ContainerSqueezer.java b/src/main/java/forestry/factory/gui/ContainerSqueezer.java index 1ff7180e8..925dbcdbf 100755 --- a/src/main/java/forestry/factory/gui/ContainerSqueezer.java +++ b/src/main/java/forestry/factory/gui/ContainerSqueezer.java @@ -10,32 +10,31 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.gui.ContainerLiquidTanksSocketed; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.factory.inventory.InventorySqueezer; import forestry.factory.tiles.TileSqueezer; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerSqueezer extends ContainerLiquidTanksSocketed { - public ContainerSqueezer(InventoryPlayer player, TileSqueezer tile) { - super(tile, player, 8, 84); + public ContainerSqueezer(InventoryPlayer player, TileSqueezer tile) { + super(tile, player, 8, 84); - // Resource inventory - for (int row = 0; row < 3; row++) { - for (int column = 0; column < 3; column++) { - addSlotToContainer(new SlotFiltered(tile, column + row * 3, 17 + column * 18, 21 + row * 18)); - } - } + // Resource inventory + for (int row = 0; row < 3; row++) { + for (int column = 0; column < 3; column++) { + addSlotToContainer(new SlotFiltered(tile, column + row * 3, 17 + column * 18, 21 + row * 18)); + } + } - // Remnants slot - this.addSlotToContainer(new SlotOutput(tile, InventorySqueezer.SLOT_REMNANT, 97, 60)); + // Remnants slot + this.addSlotToContainer(new SlotOutput(tile, InventorySqueezer.SLOT_REMNANT, 97, 60)); - // Can slot - this.addSlotToContainer(new SlotFiltered(tile, InventorySqueezer.SLOT_CAN_INPUT, 147, 24)); - // Output slot - this.addSlotToContainer(new SlotOutput(tile, InventorySqueezer.SLOT_CAN_OUTPUT, 147, 60)); - } + // Can slot + this.addSlotToContainer(new SlotFiltered(tile, InventorySqueezer.SLOT_CAN_INPUT, 147, 24)); + // Output slot + this.addSlotToContainer(new SlotOutput(tile, InventorySqueezer.SLOT_CAN_OUTPUT, 147, 60)); + } } diff --git a/src/main/java/forestry/factory/gui/ContainerStill.java b/src/main/java/forestry/factory/gui/ContainerStill.java index 13ffb7539..025ceddf4 100755 --- a/src/main/java/forestry/factory/gui/ContainerStill.java +++ b/src/main/java/forestry/factory/gui/ContainerStill.java @@ -10,21 +10,20 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.gui.ContainerLiquidTanks; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.factory.inventory.InventoryStill; import forestry.factory.tiles.TileStill; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerStill extends ContainerLiquidTanks { - public ContainerStill(InventoryPlayer player, TileStill tile) { - super(tile, player, 8, 84); + public ContainerStill(InventoryPlayer player, TileStill tile) { + super(tile, player, 8, 84); - this.addSlotToContainer(new SlotOutput(tile, InventoryStill.SLOT_PRODUCT, 150, 54)); - this.addSlotToContainer(new SlotFiltered(tile, InventoryStill.SLOT_RESOURCE, 150, 18)); - this.addSlotToContainer(new SlotFiltered(tile, InventoryStill.SLOT_CAN, 10, 36)); - } + this.addSlotToContainer(new SlotOutput(tile, InventoryStill.SLOT_PRODUCT, 150, 54)); + this.addSlotToContainer(new SlotFiltered(tile, InventoryStill.SLOT_RESOURCE, 150, 18)); + this.addSlotToContainer(new SlotFiltered(tile, InventoryStill.SLOT_CAN, 10, 36)); + } } diff --git a/src/main/java/forestry/factory/gui/ContainerWorktable.java b/src/main/java/forestry/factory/gui/ContainerWorktable.java index cb458c9c5..108b15b12 100755 --- a/src/main/java/forestry/factory/gui/ContainerWorktable.java +++ b/src/main/java/forestry/factory/gui/ContainerWorktable.java @@ -11,13 +11,6 @@ package forestry.factory.gui; import cpw.mods.fml.common.gameevent.PlayerEvent; -import forestry.core.utils.Log; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; - import forestry.core.gui.ContainerTile; import forestry.core.gui.IContainerCrafting; import forestry.core.gui.IGuiSelectable; @@ -26,6 +19,7 @@ import forestry.core.gui.slots.SlotCrafter; import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.proxy.Proxies; import forestry.core.utils.ItemStackUtil; +import forestry.core.utils.Log; import forestry.factory.inventory.InventoryCraftingForestry; import forestry.factory.inventory.InventoryGhostCrafting; import forestry.factory.inventory.InventoryWorktable; @@ -33,174 +27,181 @@ import forestry.factory.network.packets.PacketWorktableMemoryUpdate; import forestry.factory.network.packets.PacketWorktableRecipeUpdate; import forestry.factory.recipes.RecipeMemory; import forestry.factory.tiles.TileWorktable; - import java.lang.reflect.Method; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; public class ContainerWorktable extends ContainerTile implements IContainerCrafting, IGuiSelectable { - private static final Method craftingEventHandler; - private static final Object craftingEventHandlerInstance; - static { - Object instance; - Method method; - try { - final Class clazz = Class.forName("bq_standard.handlers.EventHandler"); - method = clazz.getMethod("onItemCrafted", PlayerEvent.ItemCraftedEvent.class); - method.setAccessible(true); - instance = clazz.getConstructor().newInstance(); - } catch (ReflectiveOperationException e) { - method = null; - instance = null; - } - if (instance != null) - Log.fine("BetterQuesting 3 Standard Expansion crafting quest compat enabled."); - craftingEventHandlerInstance = instance; - craftingEventHandler = method; - } + private static final Method craftingEventHandler; + private static final Object craftingEventHandlerInstance; - private static void callBQCraftingHandler(PlayerEvent.ItemCraftedEvent event) { - if (craftingEventHandler != null) { - try { - craftingEventHandler.invoke(craftingEventHandlerInstance, event); - } catch (ReflectiveOperationException e) { - Log.logThrowable("Error calling BQ3 crafting event handler", e); - } - } - } + static { + Object instance; + Method method; + try { + final Class clazz = Class.forName("bq_standard.handlers.EventHandler"); + method = clazz.getMethod("onItemCrafted", PlayerEvent.ItemCraftedEvent.class); + method.setAccessible(true); + instance = clazz.getConstructor().newInstance(); + } catch (ReflectiveOperationException e) { + method = null; + instance = null; + } + if (instance != null) Log.fine("BetterQuesting 3 Standard Expansion crafting quest compat enabled."); + craftingEventHandlerInstance = instance; + craftingEventHandler = method; + } - private final InventoryCraftingForestry craftMatrix = new InventoryCraftingForestry(this); - private long lastMemoryUpdate; - private boolean craftMatrixChanged = false; + private static void callBQCraftingHandler(PlayerEvent.ItemCraftedEvent event) { + if (craftingEventHandler != null) { + try { + craftingEventHandler.invoke(craftingEventHandlerInstance, event); + } catch (ReflectiveOperationException e) { + Log.logThrowable("Error calling BQ3 crafting event handler", e); + } + } + } - public ContainerWorktable(EntityPlayer player, TileWorktable tile) { - super(tile, player.inventory, 8, 136); + private final InventoryCraftingForestry craftMatrix = new InventoryCraftingForestry(this); + private long lastMemoryUpdate; + private boolean craftMatrixChanged = false; - IInventory craftingDisplay = tile.getCraftingDisplay(); - IInventory internalInventory = tile.getInternalInventory(); + public ContainerWorktable(EntityPlayer player, TileWorktable tile) { + super(tile, player.inventory, 8, 136); - // Internal inventory - for (int i = 0; i < 2; i++) { - for (int k = 0; k < 9; k++) { - addSlotToContainer(new Slot(internalInventory, InventoryWorktable.SLOT_INVENTORY_1 + k + i * 9, 8 + k * 18, 90 + i * 18)); - } - } + IInventory craftingDisplay = tile.getCraftingDisplay(); + IInventory internalInventory = tile.getInternalInventory(); - // Crafting matrix - for (int l = 0; l < 3; l++) { - for (int k1 = 0; k1 < 3; k1++) { - addSlotToContainer(new SlotCraftMatrix(this, craftingDisplay, k1 + l * 3, 11 + k1 * 18, 20 + l * 18)); - } - } + // Internal inventory + for (int i = 0; i < 2; i++) { + for (int k = 0; k < 9; k++) { + addSlotToContainer(new Slot( + internalInventory, InventoryWorktable.SLOT_INVENTORY_1 + k + i * 9, 8 + k * 18, 90 + i * 18)); + } + } - // CraftResult display - addSlotToContainer(new SlotCrafter(player, craftingDisplay, tile, InventoryGhostCrafting.SLOT_CRAFTING_RESULT, 77, 38)); + // Crafting matrix + for (int l = 0; l < 3; l++) { + for (int k1 = 0; k1 < 3; k1++) { + addSlotToContainer(new SlotCraftMatrix(this, craftingDisplay, k1 + l * 3, 11 + k1 * 18, 20 + l * 18)); + } + } - for (int i = 0; i < craftMatrix.getSizeInventory(); i++) { - onCraftMatrixChanged(tile.getCraftingDisplay(), i); - } - } + // CraftResult display + addSlotToContainer( + new SlotCrafter(player, craftingDisplay, tile, InventoryGhostCrafting.SLOT_CRAFTING_RESULT, 77, 38)); - @Override - public void detectAndSendChanges() { - if (craftMatrixChanged) { - craftMatrixChanged = false; - tile.setCurrentRecipe(craftMatrix); - sendPacketToCrafters(new PacketWorktableRecipeUpdate(tile)); - } + for (int i = 0; i < craftMatrix.getSizeInventory(); i++) { + onCraftMatrixChanged(tile.getCraftingDisplay(), i); + } + } - super.detectAndSendChanges(); + @Override + public void detectAndSendChanges() { + if (craftMatrixChanged) { + craftMatrixChanged = false; + tile.setCurrentRecipe(craftMatrix); + sendPacketToCrafters(new PacketWorktableRecipeUpdate(tile)); + } - if (lastMemoryUpdate != tile.getMemory().getLastUpdate()) { - lastMemoryUpdate = tile.getMemory().getLastUpdate(); - sendPacketToCrafters(new PacketWorktableMemoryUpdate(tile)); - } - } + super.detectAndSendChanges(); - private void updateCraftMatrix() { - IInventory crafting = tile.getCraftingDisplay(); - for (int i = 0; i < crafting.getSizeInventory(); i++) { - onCraftMatrixChanged(crafting, i); - } - } + if (lastMemoryUpdate != tile.getMemory().getLastUpdate()) { + lastMemoryUpdate = tile.getMemory().getLastUpdate(); + sendPacketToCrafters(new PacketWorktableMemoryUpdate(tile)); + } + } - // Fired when SlotCraftMatrix detects a change. - // Direct changes to the underlying inventory are not detected, only slot changes. - @Override - public void onCraftMatrixChanged(IInventory iinventory, int slot) { - if (slot >= craftMatrix.getSizeInventory()) { - return; - } + private void updateCraftMatrix() { + IInventory crafting = tile.getCraftingDisplay(); + for (int i = 0; i < crafting.getSizeInventory(); i++) { + onCraftMatrixChanged(crafting, i); + } + } - ItemStack stack = iinventory.getStackInSlot(slot); - ItemStack currentStack = craftMatrix.getStackInSlot(slot); + // Fired when SlotCraftMatrix detects a change. + // Direct changes to the underlying inventory are not detected, only slot changes. + @Override + public void onCraftMatrixChanged(IInventory iinventory, int slot) { + if (slot >= craftMatrix.getSizeInventory()) { + return; + } - if (!ItemStackUtil.isIdenticalItem(stack, currentStack)) { - craftMatrix.setInventorySlotContents(slot, stack); - } - } + ItemStack stack = iinventory.getStackInSlot(slot); + ItemStack currentStack = craftMatrix.getStackInSlot(slot); - // Fired when this container's craftMatrix detects a change - @Override - public void onCraftMatrixChanged(IInventory iinventory) { - craftMatrixChanged = true; - } + if (!ItemStackUtil.isIdenticalItem(stack, currentStack)) { + craftMatrix.setInventorySlotContents(slot, stack); + } + } - /* Gui Selection Handling */ - public static void clearRecipe() { - sendRecipeClick(-1, 0); - } + // Fired when this container's craftMatrix detects a change + @Override + public void onCraftMatrixChanged(IInventory iinventory) { + craftMatrixChanged = true; + } - public static void sendRecipeClick(int mouseButton, int recipeIndex) { - Proxies.net.sendToServer(new PacketGuiSelectRequest(mouseButton, recipeIndex)); - } + /* Gui Selection Handling */ + public static void clearRecipe() { + sendRecipeClick(-1, 0); + } - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { - final ItemStack transferred = super.transferStackInSlot(player, slotIndex); - if (!player.worldObj.isRemote) { - final Object o = inventorySlots.get(slotIndex); - if (o instanceof SlotCrafter) { - // use the ghost crafting matrix instead of actual crafting matrix - // so BQ3 won't do a lookup again later on - callBQCraftingHandler(new PlayerEvent.ItemCraftedEvent(player, transferred, ((SlotCrafter) o).inventory)); - } - } - return transferred; - } + public static void sendRecipeClick(int mouseButton, int recipeIndex) { + Proxies.net.sendToServer(new PacketGuiSelectRequest(mouseButton, recipeIndex)); + } - @Override - public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { - int primary = packet.getPrimaryIndex(); - int secondary = packet.getSecondaryIndex(); + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { + final ItemStack transferred = super.transferStackInSlot(player, slotIndex); + if (!player.worldObj.isRemote) { + final Object o = inventorySlots.get(slotIndex); + if (o instanceof SlotCrafter) { + // use the ghost crafting matrix instead of actual crafting matrix + // so BQ3 won't do a lookup again later on + callBQCraftingHandler( + new PlayerEvent.ItemCraftedEvent(player, transferred, ((SlotCrafter) o).inventory)); + } + } + return transferred; + } - switch (primary) { - case -1: { // clicked clear button - tile.clearCraftMatrix(); - updateCraftMatrix(); - sendPacketToCrafters(new PacketWorktableRecipeUpdate(tile)); - break; - } - case 0: { // clicked a memorized recipe - tile.chooseRecipeMemory(secondary); - updateCraftMatrix(); - sendPacketToCrafters(new PacketWorktableRecipeUpdate(tile)); - break; - } - case 1: { // right clicked a memorized recipe - long time = player.worldObj.getTotalWorldTime(); - RecipeMemory memory = tile.getMemory(); - memory.toggleLock(time, secondary); - break; - } - case 100: { // clicked previous recipe conflict button - tile.choosePreviousConflictRecipe(); - sendPacketToCrafters(new PacketWorktableRecipeUpdate(tile)); - break; - } - case 101: { // clicked next recipe conflict button - tile.chooseNextConflictRecipe(); - sendPacketToCrafters(new PacketWorktableRecipeUpdate(tile)); - break; - } - } - } + @Override + public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { + int primary = packet.getPrimaryIndex(); + int secondary = packet.getSecondaryIndex(); + + switch (primary) { + case -1: { // clicked clear button + tile.clearCraftMatrix(); + updateCraftMatrix(); + sendPacketToCrafters(new PacketWorktableRecipeUpdate(tile)); + break; + } + case 0: { // clicked a memorized recipe + tile.chooseRecipeMemory(secondary); + updateCraftMatrix(); + sendPacketToCrafters(new PacketWorktableRecipeUpdate(tile)); + break; + } + case 1: { // right clicked a memorized recipe + long time = player.worldObj.getTotalWorldTime(); + RecipeMemory memory = tile.getMemory(); + memory.toggleLock(time, secondary); + break; + } + case 100: { // clicked previous recipe conflict button + tile.choosePreviousConflictRecipe(); + sendPacketToCrafters(new PacketWorktableRecipeUpdate(tile)); + break; + } + case 101: { // clicked next recipe conflict button + tile.chooseNextConflictRecipe(); + sendPacketToCrafters(new PacketWorktableRecipeUpdate(tile)); + break; + } + } + } } diff --git a/src/main/java/forestry/factory/gui/GuiBottler.java b/src/main/java/forestry/factory/gui/GuiBottler.java index 02eb9a9c8..aefab401c 100755 --- a/src/main/java/forestry/factory/gui/GuiBottler.java +++ b/src/main/java/forestry/factory/gui/GuiBottler.java @@ -10,26 +10,25 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; import forestry.factory.tiles.TileBottler; +import net.minecraft.entity.player.InventoryPlayer; public class GuiBottler extends GuiForestryTitled { - public GuiBottler(InventoryPlayer inventory, TileBottler processor) { - super(Constants.TEXTURE_PATH_GUI + "/bottler.png", new ContainerBottler(inventory, processor), processor); - widgetManager.add(new TankWidget(this.widgetManager, 53, 17, 0)); - } + public GuiBottler(InventoryPlayer inventory, TileBottler processor) { + super(Constants.TEXTURE_PATH_GUI + "/bottler.png", new ContainerBottler(inventory, processor), processor); + widgetManager.add(new TankWidget(this.widgetManager, 53, 17, 0)); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - TileBottler bottler = inventory; + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + TileBottler bottler = inventory; - int progress = bottler.getProgressScaled(24); - drawTexturedModalRect(guiLeft + 80, guiTop + 39, 176, 74, progress, 16); - } + int progress = bottler.getProgressScaled(24); + drawTexturedModalRect(guiLeft + 80, guiTop + 39, 176, 74, progress, 16); + } } diff --git a/src/main/java/forestry/factory/gui/GuiCarpenter.java b/src/main/java/forestry/factory/gui/GuiCarpenter.java index 02546be98..5b8217c85 100755 --- a/src/main/java/forestry/factory/gui/GuiCarpenter.java +++ b/src/main/java/forestry/factory/gui/GuiCarpenter.java @@ -10,27 +10,26 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; import forestry.factory.tiles.TileCarpenter; +import net.minecraft.entity.player.InventoryPlayer; public class GuiCarpenter extends GuiForestryTitled { - public GuiCarpenter(InventoryPlayer inventory, TileCarpenter tile) { - super(Constants.TEXTURE_PATH_GUI + "/carpenter.png", new ContainerCarpenter(inventory, tile), tile); - this.ySize = 218; + public GuiCarpenter(InventoryPlayer inventory, TileCarpenter tile) { + super(Constants.TEXTURE_PATH_GUI + "/carpenter.png", new ContainerCarpenter(inventory, tile), tile); + this.ySize = 218; - widgetManager.add(new TankWidget(this.widgetManager, 150, 17, 0)); - } - - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - int progressScaled = inventory.getProgressScaled(16); - drawTexturedModalRect(guiLeft + 98, guiTop + 51 + 16 - progressScaled, 176, 60 + 16 - progressScaled, 4, progressScaled); - } + widgetManager.add(new TankWidget(this.widgetManager, 150, 17, 0)); + } + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + int progressScaled = inventory.getProgressScaled(16); + drawTexturedModalRect( + guiLeft + 98, guiTop + 51 + 16 - progressScaled, 176, 60 + 16 - progressScaled, 4, progressScaled); + } } diff --git a/src/main/java/forestry/factory/gui/GuiCentrifuge.java b/src/main/java/forestry/factory/gui/GuiCentrifuge.java index 44ef1cd4d..64caaecac 100755 --- a/src/main/java/forestry/factory/gui/GuiCentrifuge.java +++ b/src/main/java/forestry/factory/gui/GuiCentrifuge.java @@ -10,25 +10,24 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.SocketWidget; import forestry.factory.tiles.TileCentrifuge; +import net.minecraft.entity.player.InventoryPlayer; public class GuiCentrifuge extends GuiForestryTitled { - public GuiCentrifuge(InventoryPlayer inventory, TileCentrifuge tile) { - super(Constants.TEXTURE_PATH_GUI + "/centrifugesocket.png", new ContainerCentrifuge(inventory, tile), tile); - widgetManager.add(new SocketWidget(this.widgetManager, 71, 37, tile, 0)); - } + public GuiCentrifuge(InventoryPlayer inventory, TileCentrifuge tile) { + super(Constants.TEXTURE_PATH_GUI + "/centrifugesocket.png", new ContainerCentrifuge(inventory, tile), tile); + widgetManager.add(new SocketWidget(this.widgetManager, 71, 37, tile, 0)); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - int progress = inventory.getProgressScaled(16); - drawTexturedModalRect(guiLeft + 58, guiTop + 36 + 17 - progress, 176, 17 - progress, 4, progress); - } + int progress = inventory.getProgressScaled(16); + drawTexturedModalRect(guiLeft + 58, guiTop + 36 + 17 - progress, 176, 17 - progress, 4, progress); + } } diff --git a/src/main/java/forestry/factory/gui/GuiFabricator.java b/src/main/java/forestry/factory/gui/GuiFabricator.java index d87b8b03e..e87a94433 100755 --- a/src/main/java/forestry/factory/gui/GuiFabricator.java +++ b/src/main/java/forestry/factory/gui/GuiFabricator.java @@ -10,35 +10,33 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.ReservoirWidget; import forestry.factory.tiles.TileFabricator; +import net.minecraft.entity.player.InventoryPlayer; public class GuiFabricator extends GuiForestryTitled { - public GuiFabricator(InventoryPlayer player, TileFabricator tile) { - super(Constants.TEXTURE_PATH_GUI + "/fabricator.png", new ContainerFabricator(player, tile), tile); - this.ySize = 211; - widgetManager.add(new ReservoirWidget(this.widgetManager, 26, 48, 0)); - } + public GuiFabricator(InventoryPlayer player, TileFabricator tile) { + super(Constants.TEXTURE_PATH_GUI + "/fabricator.png", new ContainerFabricator(player, tile), tile); + this.ySize = 211; + widgetManager.add(new ReservoirWidget(this.widgetManager, 26, 48, 0)); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - TileFabricator fabricator = inventory; - int heatScaled = fabricator.getHeatScaled(52); - if (heatScaled > 0) { - drawTexturedModalRect(guiLeft + 55, guiTop + 17 + 52 - heatScaled, 192, 52 - heatScaled, 4, heatScaled); - } - - int meltingPointScaled = fabricator.getMeltingPointScaled(52); - if (meltingPointScaled > 0) { - drawTexturedModalRect(guiLeft + 52, guiTop + 15 + 52 - meltingPointScaled, 196, 0, 10, 5); - } - } + TileFabricator fabricator = inventory; + int heatScaled = fabricator.getHeatScaled(52); + if (heatScaled > 0) { + drawTexturedModalRect(guiLeft + 55, guiTop + 17 + 52 - heatScaled, 192, 52 - heatScaled, 4, heatScaled); + } + int meltingPointScaled = fabricator.getMeltingPointScaled(52); + if (meltingPointScaled > 0) { + drawTexturedModalRect(guiLeft + 52, guiTop + 15 + 52 - meltingPointScaled, 196, 0, 10, 5); + } + } } diff --git a/src/main/java/forestry/factory/gui/GuiFermenter.java b/src/main/java/forestry/factory/gui/GuiFermenter.java index 8988d6ea3..e5f74dca9 100755 --- a/src/main/java/forestry/factory/gui/GuiFermenter.java +++ b/src/main/java/forestry/factory/gui/GuiFermenter.java @@ -10,36 +10,35 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; import forestry.factory.tiles.TileFermenter; +import net.minecraft.entity.player.InventoryPlayer; public class GuiFermenter extends GuiForestryTitled { - public GuiFermenter(InventoryPlayer inventory, TileFermenter tile) { - super(Constants.TEXTURE_PATH_GUI + "/fermenter.png", new ContainerFermenter(inventory, tile), tile); - widgetManager.add(new TankWidget(this.widgetManager, 35, 19, 0)); - widgetManager.add(new TankWidget(this.widgetManager, 125, 19, 1)); - } + public GuiFermenter(InventoryPlayer inventory, TileFermenter tile) { + super(Constants.TEXTURE_PATH_GUI + "/fermenter.png", new ContainerFermenter(inventory, tile), tile); + widgetManager.add(new TankWidget(this.widgetManager, 35, 19, 0)); + widgetManager.add(new TankWidget(this.widgetManager, 125, 19, 1)); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - // Fuel remaining - int fuelRemain = inventory.getBurnTimeRemainingScaled(16); - if (fuelRemain > 0) { - drawTexturedModalRect(guiLeft + 98, guiTop + 46 + 17 - fuelRemain, 176, 78 + 17 - fuelRemain, 4, fuelRemain); - } - - // Raw bio mush remaining - int bioRemain = inventory.getFermentationProgressScaled(16); - if (bioRemain > 0) { - drawTexturedModalRect(guiLeft + 74, guiTop + 32 + 17 - bioRemain, 176, 60 + 17 - bioRemain, 4, bioRemain); - } - } + // Fuel remaining + int fuelRemain = inventory.getBurnTimeRemainingScaled(16); + if (fuelRemain > 0) { + drawTexturedModalRect( + guiLeft + 98, guiTop + 46 + 17 - fuelRemain, 176, 78 + 17 - fuelRemain, 4, fuelRemain); + } + // Raw bio mush remaining + int bioRemain = inventory.getFermentationProgressScaled(16); + if (bioRemain > 0) { + drawTexturedModalRect(guiLeft + 74, guiTop + 32 + 17 - bioRemain, 176, 60 + 17 - bioRemain, 4, bioRemain); + } + } } diff --git a/src/main/java/forestry/factory/gui/GuiMoistener.java b/src/main/java/forestry/factory/gui/GuiMoistener.java index 959e54ee5..d0e40b564 100755 --- a/src/main/java/forestry/factory/gui/GuiMoistener.java +++ b/src/main/java/forestry/factory/gui/GuiMoistener.java @@ -10,35 +10,33 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; import forestry.factory.tiles.TileMoistener; +import net.minecraft.entity.player.InventoryPlayer; public class GuiMoistener extends GuiForestryTitled { - public GuiMoistener(InventoryPlayer inventory, TileMoistener tile) { - super(Constants.TEXTURE_PATH_GUI + "/moistener.png", new ContainerMoistener(inventory, tile), tile); - widgetManager.add(new TankWidget(this.widgetManager, 16, 16, 0)); - } + public GuiMoistener(InventoryPlayer inventory, TileMoistener tile) { + super(Constants.TEXTURE_PATH_GUI + "/moistener.png", new ContainerMoistener(inventory, tile), tile); + widgetManager.add(new TankWidget(this.widgetManager, 16, 16, 0)); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - // Mycelium production progress - if (inventory.isProducing()) { - int i1 = inventory.getProductionProgressScaled(16); - drawTexturedModalRect(guiLeft + 124, guiTop + 36, 176, 74, 16 - i1, 16); - } - - // Resource consumption progress - if (inventory.isWorking()) { - int i1 = inventory.getConsumptionProgressScaled(54); - drawTexturedModalRect(guiLeft + 93, guiTop + 18 + i1, 176, 92 + i1, 29, 54 - i1); - } - } + // Mycelium production progress + if (inventory.isProducing()) { + int i1 = inventory.getProductionProgressScaled(16); + drawTexturedModalRect(guiLeft + 124, guiTop + 36, 176, 74, 16 - i1, 16); + } + // Resource consumption progress + if (inventory.isWorking()) { + int i1 = inventory.getConsumptionProgressScaled(54); + drawTexturedModalRect(guiLeft + 93, guiTop + 18 + i1, 176, 92 + i1, 29, 54 - i1); + } + } } diff --git a/src/main/java/forestry/factory/gui/GuiRaintank.java b/src/main/java/forestry/factory/gui/GuiRaintank.java index f2a09240b..c6c500167 100755 --- a/src/main/java/forestry/factory/gui/GuiRaintank.java +++ b/src/main/java/forestry/factory/gui/GuiRaintank.java @@ -10,27 +10,26 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; import forestry.factory.tiles.TileRaintank; +import net.minecraft.entity.player.InventoryPlayer; public class GuiRaintank extends GuiForestryTitled { - public GuiRaintank(InventoryPlayer inventory, TileRaintank tile) { - super(Constants.TEXTURE_PATH_GUI + "/raintank.png", new ContainerRaintank(inventory, tile), tile); - widgetManager.add(new TankWidget(this.widgetManager, 53, 17, 0)); - } + public GuiRaintank(InventoryPlayer inventory, TileRaintank tile) { + super(Constants.TEXTURE_PATH_GUI + "/raintank.png", new ContainerRaintank(inventory, tile), tile); + widgetManager.add(new TankWidget(this.widgetManager, 53, 17, 0)); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - if (inventory.isFilling()) { - int progress = inventory.getFillProgressScaled(24); - drawTexturedModalRect(guiLeft + 80, guiTop + 39, 176, 74, 24 - progress, 16); - } - } + if (inventory.isFilling()) { + int progress = inventory.getFillProgressScaled(24); + drawTexturedModalRect(guiLeft + 80, guiTop + 39, 176, 74, 24 - progress, 16); + } + } } diff --git a/src/main/java/forestry/factory/gui/GuiSqueezer.java b/src/main/java/forestry/factory/gui/GuiSqueezer.java index bd6083103..fed5f432a 100755 --- a/src/main/java/forestry/factory/gui/GuiSqueezer.java +++ b/src/main/java/forestry/factory/gui/GuiSqueezer.java @@ -10,28 +10,26 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.SocketWidget; import forestry.core.gui.widgets.TankWidget; import forestry.factory.tiles.TileSqueezer; +import net.minecraft.entity.player.InventoryPlayer; public class GuiSqueezer extends GuiForestryTitled { - public GuiSqueezer(InventoryPlayer inventory, TileSqueezer tile) { - super(Constants.TEXTURE_PATH_GUI + "/squeezersocket.png", new ContainerSqueezer(inventory, tile), tile); - widgetManager.add(new TankWidget(this.widgetManager, 122, 18, 0)); - widgetManager.add(new SocketWidget(this.widgetManager, 75, 20, tile, 0)); - } + public GuiSqueezer(InventoryPlayer inventory, TileSqueezer tile) { + super(Constants.TEXTURE_PATH_GUI + "/squeezersocket.png", new ContainerSqueezer(inventory, tile), tile); + widgetManager.add(new TankWidget(this.widgetManager, 122, 18, 0)); + widgetManager.add(new SocketWidget(this.widgetManager, 75, 20, tile, 0)); + } - @Override - protected void drawWidgets() { - int progress = inventory.getProgressScaled(43); - drawTexturedModalRect(75, 41, 176, 60, progress, 18); - - super.drawWidgets(); - } + @Override + protected void drawWidgets() { + int progress = inventory.getProgressScaled(43); + drawTexturedModalRect(75, 41, 176, 60, progress, 18); + super.drawWidgets(); + } } diff --git a/src/main/java/forestry/factory/gui/GuiStill.java b/src/main/java/forestry/factory/gui/GuiStill.java index e53321745..a65b37d82 100755 --- a/src/main/java/forestry/factory/gui/GuiStill.java +++ b/src/main/java/forestry/factory/gui/GuiStill.java @@ -10,32 +10,31 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; import forestry.factory.tiles.TileStill; +import net.minecraft.entity.player.InventoryPlayer; public class GuiStill extends GuiForestryTitled { - public GuiStill(InventoryPlayer inventory, TileStill tile) { - super(Constants.TEXTURE_PATH_GUI + "/still.png", new ContainerStill(inventory, tile), tile); - widgetManager.add(new TankWidget(this.widgetManager, 35, 15, 0)); - widgetManager.add(new TankWidget(this.widgetManager, 125, 15, 1)); - } + public GuiStill(InventoryPlayer inventory, TileStill tile) { + super(Constants.TEXTURE_PATH_GUI + "/still.png", new ContainerStill(inventory, tile), tile); + widgetManager.add(new TankWidget(this.widgetManager, 35, 15, 0)); + widgetManager.add(new TankWidget(this.widgetManager, 125, 15, 1)); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - TileStill still = inventory; + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + TileStill still = inventory; - drawTexturedModalRect(guiLeft + 81, guiTop + 57, 176, 60, 14, 14); - - if (still.getWorkCounter() > 0) { - int massRemaining = still.getProgressScaled(16); - drawTexturedModalRect(guiLeft + 84, guiTop + 17 + massRemaining, 176, 74 + massRemaining, 4, 17 - massRemaining); - } - } + drawTexturedModalRect(guiLeft + 81, guiTop + 57, 176, 60, 14, 14); + if (still.getWorkCounter() > 0) { + int massRemaining = still.getProgressScaled(16); + drawTexturedModalRect( + guiLeft + 84, guiTop + 17 + massRemaining, 176, 74 + massRemaining, 4, 17 - massRemaining); + } + } } diff --git a/src/main/java/forestry/factory/gui/GuiWorktable.java b/src/main/java/forestry/factory/gui/GuiWorktable.java index e01b06df0..ad9b281c1 100755 --- a/src/main/java/forestry/factory/gui/GuiWorktable.java +++ b/src/main/java/forestry/factory/gui/GuiWorktable.java @@ -10,10 +10,6 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.buttons.GuiBetterButton; @@ -28,99 +24,97 @@ import forestry.factory.inventory.InventoryGhostCrafting; import forestry.factory.recipes.MemorizedRecipe; import forestry.factory.recipes.RecipeMemory; import forestry.factory.tiles.TileWorktable; - +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; import org.lwjgl.opengl.GL11; public class GuiWorktable extends GuiForestryTitled { - private static final int SPACING = 18; - private boolean hasRecipeConflict = false; + private static final int SPACING = 18; + private boolean hasRecipeConflict = false; - public GuiWorktable(EntityPlayer player, TileWorktable tile) { - super(Constants.TEXTURE_PATH_GUI + "/worktable2.png", new ContainerWorktable(player, tile), tile); + public GuiWorktable(EntityPlayer player, TileWorktable tile) { + super(Constants.TEXTURE_PATH_GUI + "/worktable2.png", new ContainerWorktable(player, tile), tile); - ySize = 218; + ySize = 218; - RecipeMemory recipeMemory = tile.getMemory(); + RecipeMemory recipeMemory = tile.getMemory(); - int slot = 0; - for (int y = 0; y < 3; y++) { - int yPos = 20 + (y * SPACING); - for (int x = 0; x < 3; x++) { - int xPos = 110 + (x * SPACING); - MemorizedRecipeSlot memorizedRecipeSlot = new MemorizedRecipeSlot(widgetManager, xPos, yPos, recipeMemory, slot++); - widgetManager.add(memorizedRecipeSlot); - } - } + int slot = 0; + for (int y = 0; y < 3; y++) { + int yPos = 20 + (y * SPACING); + for (int x = 0; x < 3; x++) { + int xPos = 110 + (x * SPACING); + MemorizedRecipeSlot memorizedRecipeSlot = + new MemorizedRecipeSlot(widgetManager, xPos, yPos, recipeMemory, slot++); + widgetManager.add(memorizedRecipeSlot); + } + } - widgetManager.add(new ClearWorktable(widgetManager, 66, 19)); - } - - @Override - public void updateScreen() { - super.updateScreen(); - - if (hasRecipeConflict != inventory.hasRecipeConflict()) { - hasRecipeConflict = inventory.hasRecipeConflict(); - if (hasRecipeConflict) { - addButtons(); - } else { - buttonList.clear(); - } - } - } - - @Override - public void drawScreen(int mouseX, int mouseY, float parTicks) - { - super.drawScreen(mouseX, mouseY, parTicks); - - final Slot itemSlot = (Slot) inventorySlots.inventorySlots.get(54 + InventoryGhostCrafting.SLOT_CRAFTING_RESULT); - - if ( - func_146978_c(itemSlot.xDisplayPosition, itemSlot.yDisplayPosition, 16, 16, mouseX, mouseY) && - !inventory.canTakeStack(InventoryGhostCrafting.SLOT_CRAFTING_RESULT) - ) { - final MemorizedRecipe recipe = inventory.getCurrentRecipe(); - - if (recipe != null) { - final ItemStack[] recipeItems = InventoryUtil.getStacks(recipe.getCraftMatrix()); - final ItemStack[] availableItems = InventoryUtil.getStacks(inventory); - final ItemStack[] ingregients = RecipeUtil.getCraftIngredients(recipeItems, availableItems); - - for (int slot = 0; slot < ingregients.length; slot++) { - - if (ingregients[slot] == null && recipeItems[slot] != null) { - renderSlotOverlay((Slot) inventorySlots.inventorySlots.get(54 + slot)); - } - - } - - } - - } - - } - - private void renderSlotOverlay(final Slot slot) { - final int left = guiLeft + slot.xDisplayPosition; - final int top = guiTop + slot.yDisplayPosition; - - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glTranslatef(0, 0, 150); - drawRect(left, top, left + 16, top + 16, 0x88ff0000); - GL11.glTranslatef(0, 0, -150); - GL11.glEnable(GL11.GL_LIGHTING); + widgetManager.add(new ClearWorktable(widgetManager, 66, 19)); } - @SuppressWarnings("unchecked") - private void addButtons() { - buttonList.add(new GuiBetterButton(0, guiLeft + 76, guiTop + 56, StandardButtonTextureSets.LEFT_BUTTON_SMALL)); - buttonList.add(new GuiBetterButton(1, guiLeft + 85, guiTop + 56, StandardButtonTextureSets.RIGHT_BUTTON_SMALL)); - } + @Override + public void updateScreen() { + super.updateScreen(); - @Override - protected void actionPerformed(GuiButton button) { - int id = 100 + button.id; - Proxies.net.sendToServer(new PacketGuiSelectRequest(id, 0)); - } + if (hasRecipeConflict != inventory.hasRecipeConflict()) { + hasRecipeConflict = inventory.hasRecipeConflict(); + if (hasRecipeConflict) { + addButtons(); + } else { + buttonList.clear(); + } + } + } + + @Override + public void drawScreen(int mouseX, int mouseY, float parTicks) { + super.drawScreen(mouseX, mouseY, parTicks); + + final Slot itemSlot = + (Slot) inventorySlots.inventorySlots.get(54 + InventoryGhostCrafting.SLOT_CRAFTING_RESULT); + + if (func_146978_c(itemSlot.xDisplayPosition, itemSlot.yDisplayPosition, 16, 16, mouseX, mouseY) + && !inventory.canTakeStack(InventoryGhostCrafting.SLOT_CRAFTING_RESULT)) { + final MemorizedRecipe recipe = inventory.getCurrentRecipe(); + + if (recipe != null) { + final ItemStack[] recipeItems = InventoryUtil.getStacks(recipe.getCraftMatrix()); + final ItemStack[] availableItems = InventoryUtil.getStacks(inventory); + final ItemStack[] ingregients = RecipeUtil.getCraftIngredients(recipeItems, availableItems); + + for (int slot = 0; slot < ingregients.length; slot++) { + + if (ingregients[slot] == null && recipeItems[slot] != null) { + renderSlotOverlay((Slot) inventorySlots.inventorySlots.get(54 + slot)); + } + } + } + } + } + + private void renderSlotOverlay(final Slot slot) { + final int left = guiLeft + slot.xDisplayPosition; + final int top = guiTop + slot.yDisplayPosition; + + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glTranslatef(0, 0, 150); + drawRect(left, top, left + 16, top + 16, 0x88ff0000); + GL11.glTranslatef(0, 0, -150); + GL11.glEnable(GL11.GL_LIGHTING); + } + + @SuppressWarnings("unchecked") + private void addButtons() { + buttonList.add(new GuiBetterButton(0, guiLeft + 76, guiTop + 56, StandardButtonTextureSets.LEFT_BUTTON_SMALL)); + buttonList.add(new GuiBetterButton(1, guiLeft + 85, guiTop + 56, StandardButtonTextureSets.RIGHT_BUTTON_SMALL)); + } + + @Override + protected void actionPerformed(GuiButton button) { + int id = 100 + button.id; + Proxies.net.sendToServer(new PacketGuiSelectRequest(id, 0)); + } } diff --git a/src/main/java/forestry/factory/gui/widgets/ClearWorktable.java b/src/main/java/forestry/factory/gui/widgets/ClearWorktable.java index 3ee21bf67..0fcf31958 100644 --- a/src/main/java/forestry/factory/gui/widgets/ClearWorktable.java +++ b/src/main/java/forestry/factory/gui/widgets/ClearWorktable.java @@ -1,33 +1,32 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.gui.widgets; - -import forestry.core.gui.widgets.Widget; -import forestry.core.gui.widgets.WidgetManager; -import forestry.factory.gui.ContainerWorktable; - -public class ClearWorktable extends Widget { - - public ClearWorktable(WidgetManager manager, int xPos, int yPos) { - super(manager, xPos, yPos); - width = 7; - height = 7; - } - - @Override - public void draw(int startX, int startY) { - } - - @Override - public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - ContainerWorktable.clearRecipe(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.gui.widgets; + +import forestry.core.gui.widgets.Widget; +import forestry.core.gui.widgets.WidgetManager; +import forestry.factory.gui.ContainerWorktable; + +public class ClearWorktable extends Widget { + + public ClearWorktable(WidgetManager manager, int xPos, int yPos) { + super(manager, xPos, yPos); + width = 7; + height = 7; + } + + @Override + public void draw(int startX, int startY) {} + + @Override + public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { + ContainerWorktable.clearRecipe(); + } +} diff --git a/src/main/java/forestry/factory/gui/widgets/MemorizedRecipeSlot.java b/src/main/java/forestry/factory/gui/widgets/MemorizedRecipeSlot.java index 98dd674a0..b34dd5abe 100644 --- a/src/main/java/forestry/factory/gui/widgets/MemorizedRecipeSlot.java +++ b/src/main/java/forestry/factory/gui/widgets/MemorizedRecipeSlot.java @@ -1,67 +1,65 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.gui.widgets; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; - -import org.lwjgl.opengl.GL11; - -import forestry.core.gui.widgets.ItemStackWidgetBase; -import forestry.core.gui.widgets.WidgetManager; -import forestry.core.proxy.Proxies; -import forestry.core.render.SpriteSheet; -import forestry.core.render.TextureManager; -import forestry.factory.gui.ContainerWorktable; -import forestry.factory.recipes.RecipeMemory; - -public class MemorizedRecipeSlot extends ItemStackWidgetBase { - private static final IIcon lockIcon = TextureManager.getInstance().getDefault("slots/locked"); - private final RecipeMemory recipeMemory; - private final int slotNumber; - - public MemorizedRecipeSlot(WidgetManager manager, int xPos, int yPos, RecipeMemory recipeMemory, int slot) { - super(manager, xPos, yPos); - this.recipeMemory = recipeMemory; - this.slotNumber = slot; - } - - @Override - public ItemStack getItemStack() { - return recipeMemory.getRecipeDisplayOutput(slotNumber); - } - - @Override - public void draw(int startX, int startY) { - super.draw(startX, startY); - - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - - if (recipeMemory.isLocked(slotNumber)) { - manager.gui.setZLevel(110f); - Proxies.render.bindTexture(SpriteSheet.ITEMS); - manager.gui.drawTexturedModelRectFromIcon(startX + xPos, startY + yPos, lockIcon, 16, 16); - manager.gui.setZLevel(0f); - } - - GL11.glPopAttrib(); - } - - @Override - public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - if (getItemStack() != null) { - ContainerWorktable.sendRecipeClick(mouseButton, slotNumber); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.gui.widgets; + +import forestry.core.gui.widgets.ItemStackWidgetBase; +import forestry.core.gui.widgets.WidgetManager; +import forestry.core.proxy.Proxies; +import forestry.core.render.SpriteSheet; +import forestry.core.render.TextureManager; +import forestry.factory.gui.ContainerWorktable; +import forestry.factory.recipes.RecipeMemory; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import org.lwjgl.opengl.GL11; + +public class MemorizedRecipeSlot extends ItemStackWidgetBase { + private static final IIcon lockIcon = TextureManager.getInstance().getDefault("slots/locked"); + private final RecipeMemory recipeMemory; + private final int slotNumber; + + public MemorizedRecipeSlot(WidgetManager manager, int xPos, int yPos, RecipeMemory recipeMemory, int slot) { + super(manager, xPos, yPos); + this.recipeMemory = recipeMemory; + this.slotNumber = slot; + } + + @Override + public ItemStack getItemStack() { + return recipeMemory.getRecipeDisplayOutput(slotNumber); + } + + @Override + public void draw(int startX, int startY) { + super.draw(startX, startY); + + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + if (recipeMemory.isLocked(slotNumber)) { + manager.gui.setZLevel(110f); + Proxies.render.bindTexture(SpriteSheet.ITEMS); + manager.gui.drawTexturedModelRectFromIcon(startX + xPos, startY + yPos, lockIcon, 16, 16); + manager.gui.setZLevel(0f); + } + + GL11.glPopAttrib(); + } + + @Override + public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { + if (getItemStack() != null) { + ContainerWorktable.sendRecipeClick(mouseButton, slotNumber); + } + } +} diff --git a/src/main/java/forestry/factory/inventory/InventoryBottler.java b/src/main/java/forestry/factory/inventory/InventoryBottler.java index 6540b0226..75a2bccbb 100644 --- a/src/main/java/forestry/factory/inventory/InventoryBottler.java +++ b/src/main/java/forestry/factory/inventory/InventoryBottler.java @@ -1,46 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.inventory; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - -import forestry.core.fluids.FluidHelper; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.factory.tiles.TileBottler; - -public class InventoryBottler extends InventoryAdapterTile { - public static final short SLOT_INPUT_EMPTY_CAN = 0; - public static final short SLOT_OUTPUT = 1; - public static final short SLOT_INPUT_FULL_CAN = 2; - - public InventoryBottler(TileBottler tileBottler) { - super(tileBottler, 3, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_INPUT_EMPTY_CAN) { - return FluidHelper.isFillableContainer(itemStack); - } else if (slotIndex == SLOT_INPUT_FULL_CAN) { - FluidStack fluidStack = FluidHelper.getFluidStackInContainer(itemStack); - return fluidStack != null && FluidRegistry.isFluidRegistered(fluidStack.getFluid()); - } - return false; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { - return slotIndex == SLOT_OUTPUT; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.inventory; + +import forestry.core.fluids.FluidHelper; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.factory.tiles.TileBottler; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; + +public class InventoryBottler extends InventoryAdapterTile { + public static final short SLOT_INPUT_EMPTY_CAN = 0; + public static final short SLOT_OUTPUT = 1; + public static final short SLOT_INPUT_FULL_CAN = 2; + + public InventoryBottler(TileBottler tileBottler) { + super(tileBottler, 3, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_INPUT_EMPTY_CAN) { + return FluidHelper.isFillableContainer(itemStack); + } else if (slotIndex == SLOT_INPUT_FULL_CAN) { + FluidStack fluidStack = FluidHelper.getFluidStackInContainer(itemStack); + return fluidStack != null && FluidRegistry.isFluidRegistered(fluidStack.getFluid()); + } + return false; + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { + return slotIndex == SLOT_OUTPUT; + } +} diff --git a/src/main/java/forestry/factory/inventory/InventoryCarpenter.java b/src/main/java/forestry/factory/inventory/InventoryCarpenter.java index 5c4b2f5c7..d57b78a6a 100644 --- a/src/main/java/forestry/factory/inventory/InventoryCarpenter.java +++ b/src/main/java/forestry/factory/inventory/InventoryCarpenter.java @@ -1,53 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.inventory; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.Fluid; - -import forestry.core.fluids.FluidHelper; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.utils.SlotUtil; -import forestry.factory.recipes.CarpenterRecipeManager; -import forestry.factory.tiles.TileCarpenter; - -public class InventoryCarpenter extends InventoryAdapterTile { - public final static int SLOT_BOX = 9; - public final static int SLOT_PRODUCT = 10; - public final static int SLOT_PRODUCT_COUNT = 1; - public final static int SLOT_CAN_INPUT = 11; - public final static short SLOT_INVENTORY_1 = 12; - public final static short SLOT_INVENTORY_COUNT = 18; - - public InventoryCarpenter(TileCarpenter carpenter) { - super(carpenter, 30, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_CAN_INPUT) { - Fluid fluid = FluidHelper.getFluidInContainer(itemStack); - return tile.getTankManager().accepts(fluid); - } else if (slotIndex == SLOT_BOX) { - return CarpenterRecipeManager.isBox(itemStack); - } else if (canSlotAccept(SLOT_CAN_INPUT, itemStack) || canSlotAccept(SLOT_BOX, itemStack)) { - return false; - } - - return SlotUtil.isSlotInRange(slotIndex, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT); - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { - return slotIndex == SLOT_PRODUCT; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.inventory; + +import forestry.core.fluids.FluidHelper; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.core.utils.SlotUtil; +import forestry.factory.recipes.CarpenterRecipeManager; +import forestry.factory.tiles.TileCarpenter; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; + +public class InventoryCarpenter extends InventoryAdapterTile { + public static final int SLOT_BOX = 9; + public static final int SLOT_PRODUCT = 10; + public static final int SLOT_PRODUCT_COUNT = 1; + public static final int SLOT_CAN_INPUT = 11; + public static final short SLOT_INVENTORY_1 = 12; + public static final short SLOT_INVENTORY_COUNT = 18; + + public InventoryCarpenter(TileCarpenter carpenter) { + super(carpenter, 30, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_CAN_INPUT) { + Fluid fluid = FluidHelper.getFluidInContainer(itemStack); + return tile.getTankManager().accepts(fluid); + } else if (slotIndex == SLOT_BOX) { + return CarpenterRecipeManager.isBox(itemStack); + } else if (canSlotAccept(SLOT_CAN_INPUT, itemStack) || canSlotAccept(SLOT_BOX, itemStack)) { + return false; + } + + return SlotUtil.isSlotInRange(slotIndex, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT); + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { + return slotIndex == SLOT_PRODUCT; + } +} diff --git a/src/main/java/forestry/factory/inventory/InventoryCentrifuge.java b/src/main/java/forestry/factory/inventory/InventoryCentrifuge.java index e011ecaec..74b9c1177 100644 --- a/src/main/java/forestry/factory/inventory/InventoryCentrifuge.java +++ b/src/main/java/forestry/factory/inventory/InventoryCentrifuge.java @@ -1,38 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.inventory; - -import net.minecraft.item.ItemStack; - -import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.utils.SlotUtil; -import forestry.factory.recipes.CentrifugeRecipeManager; -import forestry.factory.tiles.TileCentrifuge; - -public class InventoryCentrifuge extends InventoryAdapterTile { - public static final int SLOT_RESOURCE = 0; - public static final int SLOT_PRODUCT_1 = 1; - public static final int SLOT_PRODUCT_COUNT = 9; - - public InventoryCentrifuge(TileCentrifuge centrifuge) { - super(centrifuge, 10, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return slotIndex == SLOT_RESOURCE && CentrifugeRecipeManager.findMatchingRecipe(itemStack) != null; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { - return SlotUtil.isSlotInRange(slotIndex, SLOT_PRODUCT_1, SLOT_PRODUCT_COUNT); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.inventory; + +import forestry.core.inventory.InventoryAdapterTile; +import forestry.core.utils.SlotUtil; +import forestry.factory.recipes.CentrifugeRecipeManager; +import forestry.factory.tiles.TileCentrifuge; +import net.minecraft.item.ItemStack; + +public class InventoryCentrifuge extends InventoryAdapterTile { + public static final int SLOT_RESOURCE = 0; + public static final int SLOT_PRODUCT_1 = 1; + public static final int SLOT_PRODUCT_COUNT = 9; + + public InventoryCentrifuge(TileCentrifuge centrifuge) { + super(centrifuge, 10, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return slotIndex == SLOT_RESOURCE && CentrifugeRecipeManager.findMatchingRecipe(itemStack) != null; + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { + return SlotUtil.isSlotInRange(slotIndex, SLOT_PRODUCT_1, SLOT_PRODUCT_COUNT); + } +} diff --git a/src/main/java/forestry/factory/inventory/InventoryCraftingForestry.java b/src/main/java/forestry/factory/inventory/InventoryCraftingForestry.java index e018553e3..412dba030 100644 --- a/src/main/java/forestry/factory/inventory/InventoryCraftingForestry.java +++ b/src/main/java/forestry/factory/inventory/InventoryCraftingForestry.java @@ -1,26 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.inventory; - -import net.minecraft.inventory.InventoryCrafting; - -import forestry.core.gui.ContainerDummy; -import forestry.factory.gui.ContainerWorktable; - -public class InventoryCraftingForestry extends InventoryCrafting { - public InventoryCraftingForestry(ContainerWorktable containerWorktable) { - super(containerWorktable, 3, 3); - } - - public InventoryCraftingForestry() { - super(ContainerDummy.instance, 3, 3); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.inventory; + +import forestry.core.gui.ContainerDummy; +import forestry.factory.gui.ContainerWorktable; +import net.minecraft.inventory.InventoryCrafting; + +public class InventoryCraftingForestry extends InventoryCrafting { + public InventoryCraftingForestry(ContainerWorktable containerWorktable) { + super(containerWorktable, 3, 3); + } + + public InventoryCraftingForestry() { + super(ContainerDummy.instance, 3, 3); + } +} diff --git a/src/main/java/forestry/factory/inventory/InventoryFabricator.java b/src/main/java/forestry/factory/inventory/InventoryFabricator.java index 365d9b284..500ad44c3 100644 --- a/src/main/java/forestry/factory/inventory/InventoryFabricator.java +++ b/src/main/java/forestry/factory/inventory/InventoryFabricator.java @@ -1,57 +1,56 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.inventory; - -import net.minecraft.item.ItemStack; - -import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.utils.SlotUtil; -import forestry.factory.recipes.FabricatorRecipeManager; -import forestry.factory.recipes.FabricatorSmeltingRecipeManager; -import forestry.factory.tiles.TileFabricator; - -public class InventoryFabricator extends InventoryAdapterTile { - public static final short SLOT_METAL = 0; - public static final short SLOT_PLAN = 1; - public static final short SLOT_RESULT = 2; - // FIXME 1.8: change indexes and use correct SLOT_COUNT of 21 - // left this way for now to avoid losing items in existing fabricators - public static final short SLOT_CRAFTING_LEGACY_1 = 3; - public static final short SLOT_CRAFTING_LEGACY_COUNT = 9; - public static final short SLOT_INVENTORY_1 = 12; - public static final short SLOT_INVENTORY_COUNT = 18; - public static final short SLOT_COUNT = 30; - - public InventoryFabricator(TileFabricator fabricator) { - super(fabricator, SLOT_COUNT, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_METAL) { - return FabricatorSmeltingRecipeManager.findMatchingSmelting(itemStack) != null; - } else if (slotIndex == SLOT_PLAN) { - return FabricatorRecipeManager.isPlan(itemStack); - } else if (SlotUtil.isSlotInRange(slotIndex, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT)) { - if (FabricatorRecipeManager.isPlan(itemStack)) { - return false; - } else if (FabricatorSmeltingRecipeManager.findMatchingSmelting(itemStack) != null) { - return false; - } - } - return SlotUtil.isSlotInRange(slotIndex, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT); - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack stack, int side) { - return slotIndex == SLOT_RESULT; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.inventory; + +import forestry.core.inventory.InventoryAdapterTile; +import forestry.core.utils.SlotUtil; +import forestry.factory.recipes.FabricatorRecipeManager; +import forestry.factory.recipes.FabricatorSmeltingRecipeManager; +import forestry.factory.tiles.TileFabricator; +import net.minecraft.item.ItemStack; + +public class InventoryFabricator extends InventoryAdapterTile { + public static final short SLOT_METAL = 0; + public static final short SLOT_PLAN = 1; + public static final short SLOT_RESULT = 2; + // FIXME 1.8: change indexes and use correct SLOT_COUNT of 21 + // left this way for now to avoid losing items in existing fabricators + public static final short SLOT_CRAFTING_LEGACY_1 = 3; + public static final short SLOT_CRAFTING_LEGACY_COUNT = 9; + public static final short SLOT_INVENTORY_1 = 12; + public static final short SLOT_INVENTORY_COUNT = 18; + public static final short SLOT_COUNT = 30; + + public InventoryFabricator(TileFabricator fabricator) { + super(fabricator, SLOT_COUNT, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_METAL) { + return FabricatorSmeltingRecipeManager.findMatchingSmelting(itemStack) != null; + } else if (slotIndex == SLOT_PLAN) { + return FabricatorRecipeManager.isPlan(itemStack); + } else if (SlotUtil.isSlotInRange(slotIndex, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT)) { + if (FabricatorRecipeManager.isPlan(itemStack)) { + return false; + } else if (FabricatorSmeltingRecipeManager.findMatchingSmelting(itemStack) != null) { + return false; + } + } + return SlotUtil.isSlotInRange(slotIndex, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT); + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack stack, int side) { + return slotIndex == SLOT_RESULT; + } +} diff --git a/src/main/java/forestry/factory/inventory/InventoryFermenter.java b/src/main/java/forestry/factory/inventory/InventoryFermenter.java index 2dfeb7052..6a7cc3bad 100644 --- a/src/main/java/forestry/factory/inventory/InventoryFermenter.java +++ b/src/main/java/forestry/factory/inventory/InventoryFermenter.java @@ -1,53 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.inventory; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.Fluid; - -import forestry.api.fuels.FuelManager; -import forestry.core.fluids.FluidHelper; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.factory.recipes.FermenterRecipeManager; -import forestry.factory.tiles.TileFermenter; - -public class InventoryFermenter extends InventoryAdapterTile { - public static final short SLOT_RESOURCE = 0; - public static final short SLOT_FUEL = 1; - public static final short SLOT_CAN_OUTPUT = 2; - public static final short SLOT_CAN_INPUT = 3; - public static final short SLOT_INPUT = 4; - - public InventoryFermenter(TileFermenter fermenter) { - super(fermenter, 5, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_RESOURCE) { - return FermenterRecipeManager.isResource(itemStack); - } else if (slotIndex == SLOT_INPUT) { - Fluid fluid = FluidHelper.getFluidInContainer(itemStack); - return tile.getTankManager().accepts(fluid); - } else if (slotIndex == SLOT_CAN_INPUT) { - return FluidHelper.isFillableContainer(itemStack); - } else if (slotIndex == SLOT_FUEL) { - return FuelManager.fermenterFuel.containsKey(itemStack); - } - return false; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { - return slotIndex == SLOT_CAN_OUTPUT; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.inventory; + +import forestry.api.fuels.FuelManager; +import forestry.core.fluids.FluidHelper; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.factory.recipes.FermenterRecipeManager; +import forestry.factory.tiles.TileFermenter; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; + +public class InventoryFermenter extends InventoryAdapterTile { + public static final short SLOT_RESOURCE = 0; + public static final short SLOT_FUEL = 1; + public static final short SLOT_CAN_OUTPUT = 2; + public static final short SLOT_CAN_INPUT = 3; + public static final short SLOT_INPUT = 4; + + public InventoryFermenter(TileFermenter fermenter) { + super(fermenter, 5, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_RESOURCE) { + return FermenterRecipeManager.isResource(itemStack); + } else if (slotIndex == SLOT_INPUT) { + Fluid fluid = FluidHelper.getFluidInContainer(itemStack); + return tile.getTankManager().accepts(fluid); + } else if (slotIndex == SLOT_CAN_INPUT) { + return FluidHelper.isFillableContainer(itemStack); + } else if (slotIndex == SLOT_FUEL) { + return FuelManager.fermenterFuel.containsKey(itemStack); + } + return false; + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { + return slotIndex == SLOT_CAN_OUTPUT; + } +} diff --git a/src/main/java/forestry/factory/inventory/InventoryGhostCrafting.java b/src/main/java/forestry/factory/inventory/InventoryGhostCrafting.java index b2d2bc697..3dc515a59 100644 --- a/src/main/java/forestry/factory/inventory/InventoryGhostCrafting.java +++ b/src/main/java/forestry/factory/inventory/InventoryGhostCrafting.java @@ -1,26 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.inventory; - -import net.minecraft.tileentity.TileEntity; - -import forestry.core.access.IRestrictedAccess; -import forestry.core.inventory.InventoryAdapterTile; - -public class InventoryGhostCrafting extends InventoryAdapterTile { - public final static int SLOT_CRAFTING_1 = 0; - public final static int SLOT_CRAFTING_COUNT = 9; - public final static int SLOT_CRAFTING_RESULT = 9; - - public InventoryGhostCrafting(T tile, int size) { - super(tile, size, "CraftItems"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.inventory; + +import forestry.core.access.IRestrictedAccess; +import forestry.core.inventory.InventoryAdapterTile; +import net.minecraft.tileentity.TileEntity; + +public class InventoryGhostCrafting extends InventoryAdapterTile { + public static final int SLOT_CRAFTING_1 = 0; + public static final int SLOT_CRAFTING_COUNT = 9; + public static final int SLOT_CRAFTING_RESULT = 9; + + public InventoryGhostCrafting(T tile, int size) { + super(tile, size, "CraftItems"); + } +} diff --git a/src/main/java/forestry/factory/inventory/InventoryMoistener.java b/src/main/java/forestry/factory/inventory/InventoryMoistener.java index 238665ca3..afbaf2b8d 100644 --- a/src/main/java/forestry/factory/inventory/InventoryMoistener.java +++ b/src/main/java/forestry/factory/inventory/InventoryMoistener.java @@ -1,67 +1,65 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.inventory; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.Fluid; - -import forestry.api.fuels.FuelManager; -import forestry.core.fluids.FluidHelper; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.utils.SlotUtil; -import forestry.factory.recipes.MoistenerRecipeManager; -import forestry.factory.tiles.TileMoistener; - -public class InventoryMoistener extends InventoryAdapterTile { - public static final short SLOT_STASH_1 = 0; - public static final short SLOT_STASH_COUNT = 6; - public static final short SLOT_RESERVOIR_1 = 6; - public static final short SLOT_RESERVOIR_COUNT = 3; - public static final short SLOT_WORKING = 9; - public static final short SLOT_PRODUCT = 10; - public static final short SLOT_RESOURCE = 11; - - public InventoryMoistener(TileMoistener moistener) { - super(moistener, 12, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_RESOURCE) { - return MoistenerRecipeManager.isResource(itemStack); - } - - if (SlotUtil.isSlotInRange(slotIndex, SLOT_STASH_1, SLOT_STASH_COUNT)) { - return FuelManager.moistenerResource.containsKey(itemStack); - } - - if (slotIndex == SLOT_PRODUCT) { - Fluid fluid = FluidHelper.getFluidInContainer(itemStack); - return tile.getTankManager().accepts(fluid); - } - - return false; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { - if (slotIndex == SLOT_PRODUCT) { - return true; - } - - if (SlotUtil.isSlotInRange(slotIndex, SLOT_STASH_1, (SLOT_STASH_COUNT + SLOT_RESERVOIR_COUNT))) { - return !FuelManager.moistenerResource.containsKey(itemstack); - } - - return false; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.inventory; + +import forestry.api.fuels.FuelManager; +import forestry.core.fluids.FluidHelper; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.core.utils.SlotUtil; +import forestry.factory.recipes.MoistenerRecipeManager; +import forestry.factory.tiles.TileMoistener; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; + +public class InventoryMoistener extends InventoryAdapterTile { + public static final short SLOT_STASH_1 = 0; + public static final short SLOT_STASH_COUNT = 6; + public static final short SLOT_RESERVOIR_1 = 6; + public static final short SLOT_RESERVOIR_COUNT = 3; + public static final short SLOT_WORKING = 9; + public static final short SLOT_PRODUCT = 10; + public static final short SLOT_RESOURCE = 11; + + public InventoryMoistener(TileMoistener moistener) { + super(moistener, 12, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_RESOURCE) { + return MoistenerRecipeManager.isResource(itemStack); + } + + if (SlotUtil.isSlotInRange(slotIndex, SLOT_STASH_1, SLOT_STASH_COUNT)) { + return FuelManager.moistenerResource.containsKey(itemStack); + } + + if (slotIndex == SLOT_PRODUCT) { + Fluid fluid = FluidHelper.getFluidInContainer(itemStack); + return tile.getTankManager().accepts(fluid); + } + + return false; + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { + if (slotIndex == SLOT_PRODUCT) { + return true; + } + + if (SlotUtil.isSlotInRange(slotIndex, SLOT_STASH_1, (SLOT_STASH_COUNT + SLOT_RESERVOIR_COUNT))) { + return !FuelManager.moistenerResource.containsKey(itemstack); + } + + return false; + } +} diff --git a/src/main/java/forestry/factory/inventory/InventoryRainmaker.java b/src/main/java/forestry/factory/inventory/InventoryRainmaker.java index 40258f2d6..f03e81260 100644 --- a/src/main/java/forestry/factory/inventory/InventoryRainmaker.java +++ b/src/main/java/forestry/factory/inventory/InventoryRainmaker.java @@ -1,52 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.inventory; - -import net.minecraft.item.ItemStack; - -import forestry.api.fuels.FuelManager; -import forestry.api.fuels.RainSubstrate; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.factory.tiles.TileMillRainmaker; - -public class InventoryRainmaker extends InventoryAdapterTile { - private static final int SLOT_SUBSTRATE = 0; - - public InventoryRainmaker(TileMillRainmaker tile) { - super(tile, 1, "items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_SUBSTRATE) { - if (FuelManager.rainSubstrate.containsKey(itemStack) && tile.charge == 0 && tile.progress == 0) { - RainSubstrate substrate = FuelManager.rainSubstrate.get(itemStack); - if (tile.getWorld().isRaining() && substrate.reverse) { - return true; - } else if (!tile.getWorld().isRaining() && !substrate.reverse) { - return true; - } - } - } - - return false; - } - - @Override - public void setInventorySlotContents(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_SUBSTRATE) { - RainSubstrate substrate = FuelManager.rainSubstrate.get(itemStack); - if (substrate != null && substrate.item.isItemEqual(itemStack)) { - tile.addCharge(substrate); - } - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.inventory; + +import forestry.api.fuels.FuelManager; +import forestry.api.fuels.RainSubstrate; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.factory.tiles.TileMillRainmaker; +import net.minecraft.item.ItemStack; + +public class InventoryRainmaker extends InventoryAdapterTile { + private static final int SLOT_SUBSTRATE = 0; + + public InventoryRainmaker(TileMillRainmaker tile) { + super(tile, 1, "items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_SUBSTRATE) { + if (FuelManager.rainSubstrate.containsKey(itemStack) && tile.charge == 0 && tile.progress == 0) { + RainSubstrate substrate = FuelManager.rainSubstrate.get(itemStack); + if (tile.getWorld().isRaining() && substrate.reverse) { + return true; + } else if (!tile.getWorld().isRaining() && !substrate.reverse) { + return true; + } + } + } + + return false; + } + + @Override + public void setInventorySlotContents(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_SUBSTRATE) { + RainSubstrate substrate = FuelManager.rainSubstrate.get(itemStack); + if (substrate != null && substrate.item.isItemEqual(itemStack)) { + tile.addCharge(substrate); + } + } + } +} diff --git a/src/main/java/forestry/factory/inventory/InventoryRaintank.java b/src/main/java/forestry/factory/inventory/InventoryRaintank.java index 95cc99c55..cd371ca0c 100644 --- a/src/main/java/forestry/factory/inventory/InventoryRaintank.java +++ b/src/main/java/forestry/factory/inventory/InventoryRaintank.java @@ -1,40 +1,39 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.inventory; - -import net.minecraft.item.ItemStack; - -import forestry.core.fluids.FluidHelper; -import forestry.core.fluids.Fluids; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.factory.tiles.TileRaintank; - -public class InventoryRaintank extends InventoryAdapterTile { - public static final short SLOT_RESOURCE = 0; - public static final short SLOT_PRODUCT = 1; - - public InventoryRaintank(TileRaintank raintank) { - super(raintank, 3, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_RESOURCE) { - return FluidHelper.getFilledContainer(Fluids.WATER.getFluid(1000), itemStack) != null; - } - return false; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { - return slotIndex == SLOT_PRODUCT; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.inventory; + +import forestry.core.fluids.FluidHelper; +import forestry.core.fluids.Fluids; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.factory.tiles.TileRaintank; +import net.minecraft.item.ItemStack; + +public class InventoryRaintank extends InventoryAdapterTile { + public static final short SLOT_RESOURCE = 0; + public static final short SLOT_PRODUCT = 1; + + public InventoryRaintank(TileRaintank raintank) { + super(raintank, 3, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_RESOURCE) { + return FluidHelper.getFilledContainer(Fluids.WATER.getFluid(1000), itemStack) != null; + } + return false; + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { + return slotIndex == SLOT_PRODUCT; + } +} diff --git a/src/main/java/forestry/factory/inventory/InventorySqueezer.java b/src/main/java/forestry/factory/inventory/InventorySqueezer.java index ff704745d..a370c7088 100644 --- a/src/main/java/forestry/factory/inventory/InventorySqueezer.java +++ b/src/main/java/forestry/factory/inventory/InventorySqueezer.java @@ -1,86 +1,84 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.inventory; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.core.fluids.FluidHelper; -import forestry.core.fluids.TankManager; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.inventory.wrappers.InventoryMapper; -import forestry.core.utils.InventoryUtil; -import forestry.factory.recipes.SqueezerRecipeManager; -import forestry.factory.tiles.TileSqueezer; - -public class InventorySqueezer extends InventoryAdapterTile { - public static final short SLOT_RESOURCE_1 = 0; - public static final short SLOTS_RESOURCE_COUNT = 9; - public static final short SLOT_REMNANT = 9; - public static final short SLOT_REMNANT_COUNT = 1; - public static final short SLOT_CAN_INPUT = 10; - public static final short SLOT_CAN_OUTPUT = 11; - - public InventorySqueezer(TileSqueezer squeezer) { - super(squeezer, 12, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_CAN_INPUT) { - return FluidHelper.isEmptyContainer(itemStack); - } - - if (slotIndex >= SLOT_RESOURCE_1 && slotIndex < SLOT_RESOURCE_1 + SLOTS_RESOURCE_COUNT) { - if (FluidHelper.isEmptyContainer(itemStack)) { - return false; - } - - if (SqueezerRecipeManager.canUse(itemStack)) { - return true; - } - } - - return false; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { - return slotIndex == SLOT_REMNANT || slotIndex == SLOT_CAN_OUTPUT; - } - - public boolean hasResources() { - return !InventoryUtil.isEmpty(this, SLOT_RESOURCE_1, SLOTS_RESOURCE_COUNT); - } - - public ItemStack[] getResources() { - return InventoryUtil.getStacks(this, SLOT_RESOURCE_1, SLOTS_RESOURCE_COUNT); - } - - public boolean removeResources(ItemStack[] stacks, EntityPlayer player) { - IInventory inventory = new InventoryMapper(this, SLOT_RESOURCE_1, SLOTS_RESOURCE_COUNT); - return InventoryUtil.removeSets(inventory, 1, stacks, player, false, true, false, true); - } - - public boolean addRemnant(ItemStack remnant, boolean doAdd) { - return InventoryUtil.tryAddStack(this, remnant, SLOT_REMNANT, SLOT_REMNANT_COUNT, true, doAdd); - } - - public void fillContainers(FluidStack fluidStack, TankManager tankManager) { - if (getStackInSlot(SLOT_CAN_INPUT) == null || fluidStack == null) { - return; - } - FluidHelper.fillContainers(tankManager, this, SLOT_CAN_INPUT, SLOT_CAN_OUTPUT, fluidStack.getFluid()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.inventory; + +import forestry.core.fluids.FluidHelper; +import forestry.core.fluids.TankManager; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.core.inventory.wrappers.InventoryMapper; +import forestry.core.utils.InventoryUtil; +import forestry.factory.recipes.SqueezerRecipeManager; +import forestry.factory.tiles.TileSqueezer; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; + +public class InventorySqueezer extends InventoryAdapterTile { + public static final short SLOT_RESOURCE_1 = 0; + public static final short SLOTS_RESOURCE_COUNT = 9; + public static final short SLOT_REMNANT = 9; + public static final short SLOT_REMNANT_COUNT = 1; + public static final short SLOT_CAN_INPUT = 10; + public static final short SLOT_CAN_OUTPUT = 11; + + public InventorySqueezer(TileSqueezer squeezer) { + super(squeezer, 12, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_CAN_INPUT) { + return FluidHelper.isEmptyContainer(itemStack); + } + + if (slotIndex >= SLOT_RESOURCE_1 && slotIndex < SLOT_RESOURCE_1 + SLOTS_RESOURCE_COUNT) { + if (FluidHelper.isEmptyContainer(itemStack)) { + return false; + } + + if (SqueezerRecipeManager.canUse(itemStack)) { + return true; + } + } + + return false; + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { + return slotIndex == SLOT_REMNANT || slotIndex == SLOT_CAN_OUTPUT; + } + + public boolean hasResources() { + return !InventoryUtil.isEmpty(this, SLOT_RESOURCE_1, SLOTS_RESOURCE_COUNT); + } + + public ItemStack[] getResources() { + return InventoryUtil.getStacks(this, SLOT_RESOURCE_1, SLOTS_RESOURCE_COUNT); + } + + public boolean removeResources(ItemStack[] stacks, EntityPlayer player) { + IInventory inventory = new InventoryMapper(this, SLOT_RESOURCE_1, SLOTS_RESOURCE_COUNT); + return InventoryUtil.removeSets(inventory, 1, stacks, player, false, true, false, true); + } + + public boolean addRemnant(ItemStack remnant, boolean doAdd) { + return InventoryUtil.tryAddStack(this, remnant, SLOT_REMNANT, SLOT_REMNANT_COUNT, true, doAdd); + } + + public void fillContainers(FluidStack fluidStack, TankManager tankManager) { + if (getStackInSlot(SLOT_CAN_INPUT) == null || fluidStack == null) { + return; + } + FluidHelper.fillContainers(tankManager, this, SLOT_CAN_INPUT, SLOT_CAN_OUTPUT, fluidStack.getFluid()); + } +} diff --git a/src/main/java/forestry/factory/inventory/InventoryStill.java b/src/main/java/forestry/factory/inventory/InventoryStill.java index f3aecd28c..d4ecc687b 100644 --- a/src/main/java/forestry/factory/inventory/InventoryStill.java +++ b/src/main/java/forestry/factory/inventory/InventoryStill.java @@ -1,45 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.inventory; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.Fluid; - -import forestry.core.fluids.FluidHelper; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.factory.tiles.TileStill; - -public class InventoryStill extends InventoryAdapterTile { - public static final short SLOT_PRODUCT = 0; - public static final short SLOT_RESOURCE = 1; - public static final short SLOT_CAN = 2; - - public InventoryStill(TileStill still) { - super(still, 3, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_RESOURCE) { - return FluidHelper.isEmptyContainer(itemStack); - } else if (slotIndex == SLOT_CAN) { - Fluid fluid = FluidHelper.getFluidInContainer(itemStack); - return tile.getTankManager().accepts(fluid); - } - return false; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { - return slotIndex == SLOT_PRODUCT; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.inventory; + +import forestry.core.fluids.FluidHelper; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.factory.tiles.TileStill; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; + +public class InventoryStill extends InventoryAdapterTile { + public static final short SLOT_PRODUCT = 0; + public static final short SLOT_RESOURCE = 1; + public static final short SLOT_CAN = 2; + + public InventoryStill(TileStill still) { + super(still, 3, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == SLOT_RESOURCE) { + return FluidHelper.isEmptyContainer(itemStack); + } else if (slotIndex == SLOT_CAN) { + Fluid fluid = FluidHelper.getFluidInContainer(itemStack); + return tile.getTankManager().accepts(fluid); + } + return false; + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { + return slotIndex == SLOT_PRODUCT; + } +} diff --git a/src/main/java/forestry/factory/inventory/InventoryWorktable.java b/src/main/java/forestry/factory/inventory/InventoryWorktable.java index e4623719e..21610ae83 100644 --- a/src/main/java/forestry/factory/inventory/InventoryWorktable.java +++ b/src/main/java/forestry/factory/inventory/InventoryWorktable.java @@ -1,31 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.inventory; - -import net.minecraft.item.ItemStack; - -import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.utils.SlotUtil; -import forestry.factory.tiles.TileWorktable; - -public class InventoryWorktable extends InventoryAdapterTile { - public final static short SLOT_INVENTORY_1 = 0; - public final static short SLOT_INVENTORY_COUNT = 18; - - public InventoryWorktable(TileWorktable worktable) { - super(worktable, 18, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return SlotUtil.isSlotInRange(slotIndex, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.inventory; + +import forestry.core.inventory.InventoryAdapterTile; +import forestry.core.utils.SlotUtil; +import forestry.factory.tiles.TileWorktable; +import net.minecraft.item.ItemStack; + +public class InventoryWorktable extends InventoryAdapterTile { + public static final short SLOT_INVENTORY_1 = 0; + public static final short SLOT_INVENTORY_COUNT = 18; + + public InventoryWorktable(TileWorktable worktable) { + super(worktable, 18, "Items"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return SlotUtil.isSlotInRange(slotIndex, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT); + } +} diff --git a/src/main/java/forestry/factory/network/PacketRegistryFactory.java b/src/main/java/forestry/factory/network/PacketRegistryFactory.java index e88b97323..e75210d90 100644 --- a/src/main/java/forestry/factory/network/PacketRegistryFactory.java +++ b/src/main/java/forestry/factory/network/PacketRegistryFactory.java @@ -1,26 +1,26 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.network; - -import forestry.core.network.PacketRegistry; -import forestry.factory.network.packets.PacketWorktableMemoryUpdate; -import forestry.factory.network.packets.PacketWorktableNEISelect; -import forestry.factory.network.packets.PacketWorktableRecipeUpdate; - -public class PacketRegistryFactory extends PacketRegistry { - @Override - public void registerPackets() { - registerServerPacket(new PacketWorktableNEISelect()); - - registerClientPacket(new PacketWorktableMemoryUpdate()); - registerClientPacket(new PacketWorktableRecipeUpdate()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.network; + +import forestry.core.network.PacketRegistry; +import forestry.factory.network.packets.PacketWorktableMemoryUpdate; +import forestry.factory.network.packets.PacketWorktableNEISelect; +import forestry.factory.network.packets.PacketWorktableRecipeUpdate; + +public class PacketRegistryFactory extends PacketRegistry { + @Override + public void registerPackets() { + registerServerPacket(new PacketWorktableNEISelect()); + + registerClientPacket(new PacketWorktableMemoryUpdate()); + registerClientPacket(new PacketWorktableRecipeUpdate()); + } +} diff --git a/src/main/java/forestry/factory/network/packets/PacketWorktableMemoryUpdate.java b/src/main/java/forestry/factory/network/packets/PacketWorktableMemoryUpdate.java index c71c0ed68..1b2ff4b7c 100644 --- a/src/main/java/forestry/factory/network/packets/PacketWorktableMemoryUpdate.java +++ b/src/main/java/forestry/factory/network/packets/PacketWorktableMemoryUpdate.java @@ -1,57 +1,54 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.core.proxy.Proxies; -import forestry.factory.recipes.RecipeMemory; -import forestry.factory.tiles.TileWorktable; - -public class PacketWorktableMemoryUpdate extends PacketCoordinates implements IForestryPacketClient { - - private RecipeMemory recipeMemory; - - public PacketWorktableMemoryUpdate() { - } - - public PacketWorktableMemoryUpdate(TileWorktable worktable) { - super(worktable); - this.recipeMemory = worktable.getMemory(); - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - recipeMemory.writeData(data); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof TileWorktable) { - ((TileWorktable) tile).getMemory().readData(data); - } - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.WORKTABLE_MEMORY_UPDATE; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.network.packets.PacketCoordinates; +import forestry.core.proxy.Proxies; +import forestry.factory.recipes.RecipeMemory; +import forestry.factory.tiles.TileWorktable; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; + +public class PacketWorktableMemoryUpdate extends PacketCoordinates implements IForestryPacketClient { + + private RecipeMemory recipeMemory; + + public PacketWorktableMemoryUpdate() {} + + public PacketWorktableMemoryUpdate(TileWorktable worktable) { + super(worktable); + this.recipeMemory = worktable.getMemory(); + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + recipeMemory.writeData(data); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof TileWorktable) { + ((TileWorktable) tile).getMemory().readData(data); + } + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.WORKTABLE_MEMORY_UPDATE; + } +} diff --git a/src/main/java/forestry/factory/network/packets/PacketWorktableNEISelect.java b/src/main/java/forestry/factory/network/packets/PacketWorktableNEISelect.java index 653069e17..f46b9dee3 100644 --- a/src/main/java/forestry/factory/network/packets/PacketWorktableNEISelect.java +++ b/src/main/java/forestry/factory/network/packets/PacketWorktableNEISelect.java @@ -1,45 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.nbt.NBTTagCompound; - -import forestry.core.gui.slots.SlotCraftMatrix; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; -import forestry.core.network.packets.PacketNBT; -import forestry.core.recipes.nei.SetRecipeCommandHandler; -import forestry.factory.gui.ContainerWorktable; - -public class PacketWorktableNEISelect extends PacketNBT implements IForestryPacketServer { - private static final SetRecipeCommandHandler worktableNEISelectHandler = new SetRecipeCommandHandler(ContainerWorktable.class, SlotCraftMatrix.class); - - public PacketWorktableNEISelect() { - } - - public PacketWorktableNEISelect(NBTTagCompound nbttagcompound) { - super(nbttagcompound); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - worktableNEISelectHandler.handle(getTagCompound(), player); - } - - @Override - public PacketIdServer getPacketId() { - return PacketIdServer.WORKTABLE_NEI_SELECT; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.network.packets; + +import forestry.core.gui.slots.SlotCraftMatrix; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketIdServer; +import forestry.core.network.packets.PacketNBT; +import forestry.core.recipes.nei.SetRecipeCommandHandler; +import forestry.factory.gui.ContainerWorktable; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; + +public class PacketWorktableNEISelect extends PacketNBT implements IForestryPacketServer { + private static final SetRecipeCommandHandler worktableNEISelectHandler = + new SetRecipeCommandHandler(ContainerWorktable.class, SlotCraftMatrix.class); + + public PacketWorktableNEISelect() {} + + public PacketWorktableNEISelect(NBTTagCompound nbttagcompound) { + super(nbttagcompound); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { + worktableNEISelectHandler.handle(getTagCompound(), player); + } + + @Override + public PacketIdServer getPacketId() { + return PacketIdServer.WORKTABLE_NEI_SELECT; + } +} diff --git a/src/main/java/forestry/factory/network/packets/PacketWorktableRecipeUpdate.java b/src/main/java/forestry/factory/network/packets/PacketWorktableRecipeUpdate.java index e36437694..aee775a14 100644 --- a/src/main/java/forestry/factory/network/packets/PacketWorktableRecipeUpdate.java +++ b/src/main/java/forestry/factory/network/packets/PacketWorktableRecipeUpdate.java @@ -1,65 +1,62 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.core.proxy.Proxies; -import forestry.factory.recipes.MemorizedRecipe; -import forestry.factory.tiles.TileWorktable; - -/** - * Used to sync the worktable crafting result from Server to Client. - */ -public class PacketWorktableRecipeUpdate extends PacketCoordinates implements IForestryPacketClient { - private MemorizedRecipe recipe; - - public PacketWorktableRecipeUpdate() { - } - - public PacketWorktableRecipeUpdate(TileWorktable worktable) { - super(worktable); - this.recipe = worktable.getCurrentRecipe(); - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeStreamable(recipe); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - recipe = data.readStreamable(MemorizedRecipe.class); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof TileWorktable) { - ((TileWorktable) tile).setCurrentRecipe(recipe); - } - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.WORKTABLE_CRAFTING_UPDATE; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.network.packets.PacketCoordinates; +import forestry.core.proxy.Proxies; +import forestry.factory.recipes.MemorizedRecipe; +import forestry.factory.tiles.TileWorktable; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; + +/** + * Used to sync the worktable crafting result from Server to Client. + */ +public class PacketWorktableRecipeUpdate extends PacketCoordinates implements IForestryPacketClient { + private MemorizedRecipe recipe; + + public PacketWorktableRecipeUpdate() {} + + public PacketWorktableRecipeUpdate(TileWorktable worktable) { + super(worktable); + this.recipe = worktable.getCurrentRecipe(); + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeStreamable(recipe); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + recipe = data.readStreamable(MemorizedRecipe.class); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + TileEntity tile = getTarget(Proxies.common.getRenderWorld()); + if (tile instanceof TileWorktable) { + ((TileWorktable) tile).setCurrentRecipe(recipe); + } + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.WORKTABLE_CRAFTING_UPDATE; + } +} diff --git a/src/main/java/forestry/factory/recipes/BottlerRecipe.java b/src/main/java/forestry/factory/recipes/BottlerRecipe.java index 0a32c9e31..d02a2ba20 100644 --- a/src/main/java/forestry/factory/recipes/BottlerRecipe.java +++ b/src/main/java/forestry/factory/recipes/BottlerRecipe.java @@ -1,70 +1,68 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidContainerItem; - -import forestry.core.config.Constants; -import forestry.core.fluids.FluidHelper; - -public class BottlerRecipe { - public final FluidStack input; - public final ItemStack empty; - public final ItemStack filled; - - private BottlerRecipe(ItemStack empty, FluidStack input, ItemStack filled) { - this.input = input; - if (empty.getItem() instanceof IFluidContainerItem) { - FluidStack emptyFluid = FluidHelper.getFluidStackInContainer(empty); - if (emptyFluid != null) { - this.input.amount -= emptyFluid.amount; - } - if (this.input.amount > Constants.BUCKET_VOLUME) { - this.input.amount = Constants.BUCKET_VOLUME; - } - } - this.empty = empty; - this.filled = filled; - } - - public boolean matches(ItemStack emptyCan, FluidStack resource) { - if (emptyCan == null || resource == null || !emptyCan.isItemEqual(empty)) { - return false; - } - - if (empty.getItem() instanceof IFluidContainerItem) { - return true; - } else { - return resource.containsFluid(input); - } - } - - public static BottlerRecipe getRecipe(FluidStack res, ItemStack empty) { - if (res == null || empty == null) { - return null; - } - - ItemStack filled = FluidHelper.getFilledContainer(res.getFluid(), empty); - if (filled == null) { - return null; - } - - FluidStack input = FluidHelper.getFluidStackInContainer(filled); - if (input == null) { - return null; - } - - return new BottlerRecipe(empty, input, filled); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.core.config.Constants; +import forestry.core.fluids.FluidHelper; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.IFluidContainerItem; + +public class BottlerRecipe { + public final FluidStack input; + public final ItemStack empty; + public final ItemStack filled; + + private BottlerRecipe(ItemStack empty, FluidStack input, ItemStack filled) { + this.input = input; + if (empty.getItem() instanceof IFluidContainerItem) { + FluidStack emptyFluid = FluidHelper.getFluidStackInContainer(empty); + if (emptyFluid != null) { + this.input.amount -= emptyFluid.amount; + } + if (this.input.amount > Constants.BUCKET_VOLUME) { + this.input.amount = Constants.BUCKET_VOLUME; + } + } + this.empty = empty; + this.filled = filled; + } + + public boolean matches(ItemStack emptyCan, FluidStack resource) { + if (emptyCan == null || resource == null || !emptyCan.isItemEqual(empty)) { + return false; + } + + if (empty.getItem() instanceof IFluidContainerItem) { + return true; + } else { + return resource.containsFluid(input); + } + } + + public static BottlerRecipe getRecipe(FluidStack res, ItemStack empty) { + if (res == null || empty == null) { + return null; + } + + ItemStack filled = FluidHelper.getFilledContainer(res.getFluid(), empty); + if (filled == null) { + return null; + } + + FluidStack input = FluidHelper.getFluidStackInContainer(filled); + if (input == null) { + return null; + } + + return new BottlerRecipe(empty, input, filled); + } +} diff --git a/src/main/java/forestry/factory/recipes/CarpenterRecipe.java b/src/main/java/forestry/factory/recipes/CarpenterRecipe.java index c3d443f21..182ef1165 100644 --- a/src/main/java/forestry/factory/recipes/CarpenterRecipe.java +++ b/src/main/java/forestry/factory/recipes/CarpenterRecipe.java @@ -1,59 +1,60 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import javax.annotation.Nullable; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.ICarpenterRecipe; -import forestry.api.recipes.IDescriptiveRecipe; -import forestry.core.recipes.ShapedRecipeCustom; - -public class CarpenterRecipe implements ICarpenterRecipe { - - private final int packagingTime; - @Nullable - private final FluidStack liquid; - @Nullable - private final ItemStack box; - private final ShapedRecipeCustom internal; - - public CarpenterRecipe(int packagingTime, @Nullable FluidStack liquid, @Nullable ItemStack box, ShapedRecipeCustom internal) { - this.packagingTime = packagingTime; - this.liquid = liquid; - this.box = box; - this.internal = internal; - } - - public int getPackagingTime() { - return packagingTime; - } - - @Override - @Nullable - public ItemStack getBox() { - return box; - } - - @Override - @Nullable - public FluidStack getFluidResource() { - return liquid; - } - - @Override - public IDescriptiveRecipe getCraftingGridRecipe() { - return internal; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.ICarpenterRecipe; +import forestry.api.recipes.IDescriptiveRecipe; +import forestry.core.recipes.ShapedRecipeCustom; +import javax.annotation.Nullable; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; + +public class CarpenterRecipe implements ICarpenterRecipe { + + private final int packagingTime; + + @Nullable + private final FluidStack liquid; + + @Nullable + private final ItemStack box; + + private final ShapedRecipeCustom internal; + + public CarpenterRecipe( + int packagingTime, @Nullable FluidStack liquid, @Nullable ItemStack box, ShapedRecipeCustom internal) { + this.packagingTime = packagingTime; + this.liquid = liquid; + this.box = box; + this.internal = internal; + } + + public int getPackagingTime() { + return packagingTime; + } + + @Override + @Nullable + public ItemStack getBox() { + return box; + } + + @Override + @Nullable + public FluidStack getFluidResource() { + return liquid; + } + + @Override + public IDescriptiveRecipe getCraftingGridRecipe() { + return internal; + } +} diff --git a/src/main/java/forestry/factory/recipes/CarpenterRecipeManager.java b/src/main/java/forestry/factory/recipes/CarpenterRecipeManager.java index 54f14727f..c025c20c9 100644 --- a/src/main/java/forestry/factory/recipes/CarpenterRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/CarpenterRecipeManager.java @@ -1,140 +1,141 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.ICarpenterManager; -import forestry.api.recipes.ICarpenterRecipe; -import forestry.api.recipes.IDescriptiveRecipe; -import forestry.core.recipes.RecipeUtil; -import forestry.core.recipes.ShapedRecipeCustom; -import forestry.core.utils.ItemStackUtil; - -public class CarpenterRecipeManager implements ICarpenterManager { - - private static final Set recipes = new HashSet<>(); - private static final Set recipeFluids = new HashSet<>(); - - @Override - public void addRecipe(ItemStack box, ItemStack product, Object materials[]) { - addRecipe(5, null, box, product, materials); - } - - @Override - public void addRecipe(int packagingTime, ItemStack box, ItemStack product, Object materials[]) { - addRecipe(packagingTime, null, box, product, materials); - } - - @Override - public void addRecipe(int packagingTime, FluidStack liquid, ItemStack box, ItemStack product, Object materials[]) { - ICarpenterRecipe recipe = new CarpenterRecipe(packagingTime, liquid, box, ShapedRecipeCustom.createShapedRecipe(product, materials)); - addRecipe(recipe); - } - - public static ICarpenterRecipe findMatchingRecipe(FluidStack liquid, ItemStack item, IInventory inventorycrafting) { - for (ICarpenterRecipe recipe : recipes) { - if (matches(recipe, liquid, item, inventorycrafting)) { - return recipe; - } - } - return null; - } - - public static boolean matches(ICarpenterRecipe recipe, FluidStack resource, ItemStack item, IInventory inventoryCrafting) { - if (recipe == null) { - return false; - } - - FluidStack liquid = recipe.getFluidResource(); - if (liquid != null) { - if (resource == null || !resource.containsFluid(liquid)) { - return false; - } - } - - ItemStack box = recipe.getBox(); - if (box != null && !ItemStackUtil.isCraftingEquivalent(box, item)) { - return false; - } - - IDescriptiveRecipe internal = recipe.getCraftingGridRecipe(); - return RecipeUtil.matches(internal, inventoryCrafting); - } - - public static boolean isBox(ItemStack resource) { - if (resource == null) { - return false; - } - - for (ICarpenterRecipe recipe : recipes) { - ItemStack box = recipe.getBox(); - if (ItemStackUtil.isIdenticalItem(box, resource)) { - return true; - } - } - - return false; - } - - @Override - public boolean addRecipe(ICarpenterRecipe recipe) { - return recipes.add(recipe); - } - - @Override - public boolean removeRecipe(ICarpenterRecipe recipe) { - boolean removed = recipes.remove(recipe); - if (removed) { - recipeFluids.clear(); - } - return removed; - } - - public static Set getRecipeFluids() { - if (recipeFluids.isEmpty()) { - for (ICarpenterRecipe recipe : recipes) { - FluidStack fluidStack = recipe.getFluidResource(); - if (fluidStack != null) { - recipeFluids.add(fluidStack.getFluid()); - } - } - } - return Collections.unmodifiableSet(recipeFluids); - } - - @Override - public Set recipes() { - return Collections.unmodifiableSet(recipes); - } - - @Override - public Map getRecipes() { - - HashMap recipeList = new HashMap<>(); - - for (ICarpenterRecipe recipe : recipes) { - recipeList.put(recipe.getCraftingGridRecipe().getIngredients(), new Object[]{recipe.getCraftingGridRecipe().getRecipeOutput()}); - } - - return recipeList; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.ICarpenterManager; +import forestry.api.recipes.ICarpenterRecipe; +import forestry.api.recipes.IDescriptiveRecipe; +import forestry.core.recipes.RecipeUtil; +import forestry.core.recipes.ShapedRecipeCustom; +import forestry.core.utils.ItemStackUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +public class CarpenterRecipeManager implements ICarpenterManager { + + private static final Set recipes = new HashSet<>(); + private static final Set recipeFluids = new HashSet<>(); + + @Override + public void addRecipe(ItemStack box, ItemStack product, Object materials[]) { + addRecipe(5, null, box, product, materials); + } + + @Override + public void addRecipe(int packagingTime, ItemStack box, ItemStack product, Object materials[]) { + addRecipe(packagingTime, null, box, product, materials); + } + + @Override + public void addRecipe(int packagingTime, FluidStack liquid, ItemStack box, ItemStack product, Object materials[]) { + ICarpenterRecipe recipe = new CarpenterRecipe( + packagingTime, liquid, box, ShapedRecipeCustom.createShapedRecipe(product, materials)); + addRecipe(recipe); + } + + public static ICarpenterRecipe findMatchingRecipe(FluidStack liquid, ItemStack item, IInventory inventorycrafting) { + for (ICarpenterRecipe recipe : recipes) { + if (matches(recipe, liquid, item, inventorycrafting)) { + return recipe; + } + } + return null; + } + + public static boolean matches( + ICarpenterRecipe recipe, FluidStack resource, ItemStack item, IInventory inventoryCrafting) { + if (recipe == null) { + return false; + } + + FluidStack liquid = recipe.getFluidResource(); + if (liquid != null) { + if (resource == null || !resource.containsFluid(liquid)) { + return false; + } + } + + ItemStack box = recipe.getBox(); + if (box != null && !ItemStackUtil.isCraftingEquivalent(box, item)) { + return false; + } + + IDescriptiveRecipe internal = recipe.getCraftingGridRecipe(); + return RecipeUtil.matches(internal, inventoryCrafting); + } + + public static boolean isBox(ItemStack resource) { + if (resource == null) { + return false; + } + + for (ICarpenterRecipe recipe : recipes) { + ItemStack box = recipe.getBox(); + if (ItemStackUtil.isIdenticalItem(box, resource)) { + return true; + } + } + + return false; + } + + @Override + public boolean addRecipe(ICarpenterRecipe recipe) { + return recipes.add(recipe); + } + + @Override + public boolean removeRecipe(ICarpenterRecipe recipe) { + boolean removed = recipes.remove(recipe); + if (removed) { + recipeFluids.clear(); + } + return removed; + } + + public static Set getRecipeFluids() { + if (recipeFluids.isEmpty()) { + for (ICarpenterRecipe recipe : recipes) { + FluidStack fluidStack = recipe.getFluidResource(); + if (fluidStack != null) { + recipeFluids.add(fluidStack.getFluid()); + } + } + } + return Collections.unmodifiableSet(recipeFluids); + } + + @Override + public Set recipes() { + return Collections.unmodifiableSet(recipes); + } + + @Override + public Map getRecipes() { + + HashMap recipeList = new HashMap<>(); + + for (ICarpenterRecipe recipe : recipes) { + recipeList.put( + recipe.getCraftingGridRecipe().getIngredients(), + new Object[] {recipe.getCraftingGridRecipe().getRecipeOutput()}); + } + + return recipeList; + } +} diff --git a/src/main/java/forestry/factory/recipes/CentrifugeRecipe.java b/src/main/java/forestry/factory/recipes/CentrifugeRecipe.java index 7fdce1a73..9b321ea41 100644 --- a/src/main/java/forestry/factory/recipes/CentrifugeRecipe.java +++ b/src/main/java/forestry/factory/recipes/CentrifugeRecipe.java @@ -1,74 +1,71 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import com.google.common.collect.ImmutableMap; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import net.minecraft.item.ItemStack; - -import forestry.api.recipes.ICentrifugeRecipe; - -public class CentrifugeRecipe implements ICentrifugeRecipe { - - private final int processingTime; - private final ItemStack input; - private final Map outputs; - - public CentrifugeRecipe(int processingTime, ItemStack input, Map outputs) { - this.processingTime = processingTime; - this.input = input; - this.outputs = outputs; - - for (ItemStack item : outputs.keySet()) { - if (item == null) { - throw new IllegalArgumentException("Tried to register a null product of " + input); - } - } - } - - @Override - public ItemStack getInput() { - return input; - } - - @Override - public int getProcessingTime() { - return processingTime; - } - - @Override - public Collection getProducts(Random random) { - List products = new ArrayList<>(); - - for (Map.Entry entry : this.outputs.entrySet()) { - float probability = entry.getValue(); - - if (probability >= 1.0) { - products.add(entry.getKey().copy()); - } else if (random.nextFloat() < probability) { - products.add(entry.getKey().copy()); - } - } - - return products; - } - - @Override - public Map getAllProducts() { - return ImmutableMap.copyOf(outputs); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import com.google.common.collect.ImmutableMap; +import forestry.api.recipes.ICentrifugeRecipe; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Random; +import net.minecraft.item.ItemStack; + +public class CentrifugeRecipe implements ICentrifugeRecipe { + + private final int processingTime; + private final ItemStack input; + private final Map outputs; + + public CentrifugeRecipe(int processingTime, ItemStack input, Map outputs) { + this.processingTime = processingTime; + this.input = input; + this.outputs = outputs; + + for (ItemStack item : outputs.keySet()) { + if (item == null) { + throw new IllegalArgumentException("Tried to register a null product of " + input); + } + } + } + + @Override + public ItemStack getInput() { + return input; + } + + @Override + public int getProcessingTime() { + return processingTime; + } + + @Override + public Collection getProducts(Random random) { + List products = new ArrayList<>(); + + for (Map.Entry entry : this.outputs.entrySet()) { + float probability = entry.getValue(); + + if (probability >= 1.0) { + products.add(entry.getKey().copy()); + } else if (random.nextFloat() < probability) { + products.add(entry.getKey().copy()); + } + } + + return products; + } + + @Override + public Map getAllProducts() { + return ImmutableMap.copyOf(outputs); + } +} diff --git a/src/main/java/forestry/factory/recipes/CentrifugeRecipeManager.java b/src/main/java/forestry/factory/recipes/CentrifugeRecipeManager.java index 21bd30256..c34846b54 100644 --- a/src/main/java/forestry/factory/recipes/CentrifugeRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/CentrifugeRecipeManager.java @@ -1,76 +1,74 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import net.minecraft.item.ItemStack; - -import forestry.api.recipes.ICentrifugeManager; -import forestry.api.recipes.ICentrifugeRecipe; -import forestry.core.utils.ItemStackUtil; - -public class CentrifugeRecipeManager implements ICentrifugeManager { - - private static final Set recipes = new HashSet<>(); - - @Override - public void addRecipe(int timePerItem, ItemStack resource, Map products) { - ICentrifugeRecipe recipe = new CentrifugeRecipe(timePerItem, resource, products); - addRecipe(recipe); - } - - public static ICentrifugeRecipe findMatchingRecipe(ItemStack itemStack) { - if (itemStack == null) { - return null; - } - - for (ICentrifugeRecipe recipe : recipes) { - ItemStack recipeInput = recipe.getInput(); - if (ItemStackUtil.isCraftingEquivalent(recipeInput, itemStack)) { - return recipe; - } - } - return null; - } - - @Override - public boolean addRecipe(ICentrifugeRecipe recipe) { - return recipes.add(recipe); - } - - @Override - public boolean removeRecipe(ICentrifugeRecipe recipe) { - return recipes.remove(recipe); - } - - @Override - public Set recipes() { - return Collections.unmodifiableSet(recipes); - } - - @Override - @Deprecated - public Map getRecipes() { - HashMap recipeList = new HashMap<>(); - - for (ICentrifugeRecipe recipe : recipes) { - Set productsKeys = recipe.getAllProducts().keySet(); - recipeList.put(new Object[]{recipe.getInput()}, productsKeys.toArray(new ItemStack[productsKeys.size()])); - } - - return recipeList; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.ICentrifugeManager; +import forestry.api.recipes.ICentrifugeRecipe; +import forestry.core.utils.ItemStackUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import net.minecraft.item.ItemStack; + +public class CentrifugeRecipeManager implements ICentrifugeManager { + + private static final Set recipes = new HashSet<>(); + + @Override + public void addRecipe(int timePerItem, ItemStack resource, Map products) { + ICentrifugeRecipe recipe = new CentrifugeRecipe(timePerItem, resource, products); + addRecipe(recipe); + } + + public static ICentrifugeRecipe findMatchingRecipe(ItemStack itemStack) { + if (itemStack == null) { + return null; + } + + for (ICentrifugeRecipe recipe : recipes) { + ItemStack recipeInput = recipe.getInput(); + if (ItemStackUtil.isCraftingEquivalent(recipeInput, itemStack)) { + return recipe; + } + } + return null; + } + + @Override + public boolean addRecipe(ICentrifugeRecipe recipe) { + return recipes.add(recipe); + } + + @Override + public boolean removeRecipe(ICentrifugeRecipe recipe) { + return recipes.remove(recipe); + } + + @Override + public Set recipes() { + return Collections.unmodifiableSet(recipes); + } + + @Override + @Deprecated + public Map getRecipes() { + HashMap recipeList = new HashMap<>(); + + for (ICentrifugeRecipe recipe : recipes) { + Set productsKeys = recipe.getAllProducts().keySet(); + recipeList.put(new Object[] {recipe.getInput()}, productsKeys.toArray(new ItemStack[productsKeys.size()])); + } + + return recipeList; + } +} diff --git a/src/main/java/forestry/factory/recipes/FabricatorRecipe.java b/src/main/java/forestry/factory/recipes/FabricatorRecipe.java index 898938e3c..5414e1769 100644 --- a/src/main/java/forestry/factory/recipes/FabricatorRecipe.java +++ b/src/main/java/forestry/factory/recipes/FabricatorRecipe.java @@ -1,91 +1,88 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import javax.annotation.Nullable; - -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.IFabricatorRecipe; -import forestry.core.recipes.RecipeUtil; -import forestry.core.recipes.ShapedRecipeCustom; -import forestry.core.utils.ItemStackUtil; - -public class FabricatorRecipe implements IFabricatorRecipe { - - private final ItemStack plan; - private final FluidStack molten; - private final ShapedRecipeCustom internal; - - public FabricatorRecipe(ItemStack plan, FluidStack molten, ItemStack result, Object[] ingredients) { - this(plan, molten, ShapedRecipeCustom.createShapedRecipe(result, ingredients)); - } - - public FabricatorRecipe(ItemStack plan, FluidStack molten, ShapedRecipeCustom internal) { - this.plan = plan; - this.molten = molten; - this.internal = internal; - } - - @Override - @Deprecated - public boolean matches(@Nullable ItemStack plan, ItemStack[][] resources) { - if (this.plan != null && !ItemStackUtil.isCraftingEquivalent(this.plan, plan)) { - return false; - } - - return RecipeUtil.matches(internal.getIngredients(), internal.getWidth(), internal.getHeight(), resources); - } - - @Override - public Object[] getIngredients() { - return internal.getIngredients(); - } - - @Override - public int getWidth() { - return internal.getWidth(); - } - - @Override - public int getHeight() { - return internal.getHeight(); - } - - @Override - public boolean preservesNbt() { - return false; - } - - @Override - @Nullable - public ItemStack getPlan() { - return plan; - } - - @Override - public FluidStack getLiquid() { - return molten; - } - - @Override - public ItemStack getCraftingResult(IInventory craftingInventory) { - return internal.getRecipeOutput().copy(); - } - - @Override - public ItemStack getRecipeOutput() { - return internal.getRecipeOutput(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.IFabricatorRecipe; +import forestry.core.recipes.RecipeUtil; +import forestry.core.recipes.ShapedRecipeCustom; +import forestry.core.utils.ItemStackUtil; +import javax.annotation.Nullable; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; + +public class FabricatorRecipe implements IFabricatorRecipe { + + private final ItemStack plan; + private final FluidStack molten; + private final ShapedRecipeCustom internal; + + public FabricatorRecipe(ItemStack plan, FluidStack molten, ItemStack result, Object[] ingredients) { + this(plan, molten, ShapedRecipeCustom.createShapedRecipe(result, ingredients)); + } + + public FabricatorRecipe(ItemStack plan, FluidStack molten, ShapedRecipeCustom internal) { + this.plan = plan; + this.molten = molten; + this.internal = internal; + } + + @Override + @Deprecated + public boolean matches(@Nullable ItemStack plan, ItemStack[][] resources) { + if (this.plan != null && !ItemStackUtil.isCraftingEquivalent(this.plan, plan)) { + return false; + } + + return RecipeUtil.matches(internal.getIngredients(), internal.getWidth(), internal.getHeight(), resources); + } + + @Override + public Object[] getIngredients() { + return internal.getIngredients(); + } + + @Override + public int getWidth() { + return internal.getWidth(); + } + + @Override + public int getHeight() { + return internal.getHeight(); + } + + @Override + public boolean preservesNbt() { + return false; + } + + @Override + @Nullable + public ItemStack getPlan() { + return plan; + } + + @Override + public FluidStack getLiquid() { + return molten; + } + + @Override + public ItemStack getCraftingResult(IInventory craftingInventory) { + return internal.getRecipeOutput().copy(); + } + + @Override + public ItemStack getRecipeOutput() { + return internal.getRecipeOutput(); + } +} diff --git a/src/main/java/forestry/factory/recipes/FabricatorRecipeManager.java b/src/main/java/forestry/factory/recipes/FabricatorRecipeManager.java index 63e9f55f5..bb83b0824 100644 --- a/src/main/java/forestry/factory/recipes/FabricatorRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/FabricatorRecipeManager.java @@ -1,96 +1,94 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.IFabricatorManager; -import forestry.api.recipes.IFabricatorRecipe; -import forestry.api.recipes.RecipeManagers; -import forestry.core.recipes.RecipeUtil; -import forestry.core.recipes.ShapedRecipeCustom; -import forestry.core.utils.ItemStackUtil; - -public class FabricatorRecipeManager implements IFabricatorManager { - - private static final Set recipes = new HashSet<>(); - - @Override - public void addRecipe(ItemStack plan, FluidStack molten, ItemStack result, Object[] pattern) { - IFabricatorRecipe recipe = new FabricatorRecipe(plan, molten, ShapedRecipeCustom.createShapedRecipe(result, pattern)); - addRecipe(recipe); - } - - @Override - public void addSmelting(ItemStack resource, FluidStack molten, int meltingPoint) { - RecipeManagers.fabricatorSmeltingManager.addSmelting(resource, molten, meltingPoint); - } - - public static IFabricatorRecipe findMatchingRecipe(ItemStack plan, IInventory resources) { - ItemStack[][] gridResources = RecipeUtil.getResources(resources); - - for (IFabricatorRecipe recipe : recipes) { - if (recipe.getPlan() != null && !ItemStackUtil.isCraftingEquivalent(recipe.getPlan(), plan)) { - continue; - } - if (RecipeUtil.matches(recipe.getIngredients(), recipe.getWidth(), recipe.getHeight(), gridResources)) { - return recipe; - } - } - - return null; - } - - public static boolean isPlan(ItemStack plan) { - for (IFabricatorRecipe recipe : recipes) { - if (ItemStackUtil.isIdenticalItem(recipe.getPlan(), plan)) { - return true; - } - } - - return false; - } - - @Override - public boolean addRecipe(IFabricatorRecipe recipe) { - return recipes.add(recipe); - } - - @Override - public boolean removeRecipe(IFabricatorRecipe recipe) { - return recipes.remove(recipe); - } - - @Override - public Set recipes() { - return Collections.unmodifiableSet(recipes); - } - - @Override - public Map getRecipes() { - HashMap recipeList = new HashMap<>(); - - for (IFabricatorRecipe recipe : recipes) { - recipeList.put(recipe.getIngredients(), new Object[]{recipe.getRecipeOutput()}); - } - - return recipeList; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.IFabricatorManager; +import forestry.api.recipes.IFabricatorRecipe; +import forestry.api.recipes.RecipeManagers; +import forestry.core.recipes.RecipeUtil; +import forestry.core.recipes.ShapedRecipeCustom; +import forestry.core.utils.ItemStackUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; + +public class FabricatorRecipeManager implements IFabricatorManager { + + private static final Set recipes = new HashSet<>(); + + @Override + public void addRecipe(ItemStack plan, FluidStack molten, ItemStack result, Object[] pattern) { + IFabricatorRecipe recipe = + new FabricatorRecipe(plan, molten, ShapedRecipeCustom.createShapedRecipe(result, pattern)); + addRecipe(recipe); + } + + @Override + public void addSmelting(ItemStack resource, FluidStack molten, int meltingPoint) { + RecipeManagers.fabricatorSmeltingManager.addSmelting(resource, molten, meltingPoint); + } + + public static IFabricatorRecipe findMatchingRecipe(ItemStack plan, IInventory resources) { + ItemStack[][] gridResources = RecipeUtil.getResources(resources); + + for (IFabricatorRecipe recipe : recipes) { + if (recipe.getPlan() != null && !ItemStackUtil.isCraftingEquivalent(recipe.getPlan(), plan)) { + continue; + } + if (RecipeUtil.matches(recipe.getIngredients(), recipe.getWidth(), recipe.getHeight(), gridResources)) { + return recipe; + } + } + + return null; + } + + public static boolean isPlan(ItemStack plan) { + for (IFabricatorRecipe recipe : recipes) { + if (ItemStackUtil.isIdenticalItem(recipe.getPlan(), plan)) { + return true; + } + } + + return false; + } + + @Override + public boolean addRecipe(IFabricatorRecipe recipe) { + return recipes.add(recipe); + } + + @Override + public boolean removeRecipe(IFabricatorRecipe recipe) { + return recipes.remove(recipe); + } + + @Override + public Set recipes() { + return Collections.unmodifiableSet(recipes); + } + + @Override + public Map getRecipes() { + HashMap recipeList = new HashMap<>(); + + for (IFabricatorRecipe recipe : recipes) { + recipeList.put(recipe.getIngredients(), new Object[] {recipe.getRecipeOutput()}); + } + + return recipeList; + } +} diff --git a/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipe.java b/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipe.java index c446720c0..31ec2742b 100644 --- a/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipe.java +++ b/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipe.java @@ -1,49 +1,47 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.IFabricatorSmeltingRecipe; - -public class FabricatorSmeltingRecipe implements IFabricatorSmeltingRecipe { - - private final ItemStack resource; - private final FluidStack product; - private final int meltingPoint; - - public FabricatorSmeltingRecipe(ItemStack resource, FluidStack molten, int meltingPoint) { - if (resource == null) { - throw new IllegalArgumentException("Resource cannot be null"); - } - if (molten == null) { - throw new IllegalArgumentException("Molten cannot be null"); - } - - this.resource = resource; - this.product = molten; - this.meltingPoint = meltingPoint; - } - - public ItemStack getResource() { - return resource; - } - - public FluidStack getProduct() { - return product; - } - - public int getMeltingPoint() { - return meltingPoint; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.IFabricatorSmeltingRecipe; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; + +public class FabricatorSmeltingRecipe implements IFabricatorSmeltingRecipe { + + private final ItemStack resource; + private final FluidStack product; + private final int meltingPoint; + + public FabricatorSmeltingRecipe(ItemStack resource, FluidStack molten, int meltingPoint) { + if (resource == null) { + throw new IllegalArgumentException("Resource cannot be null"); + } + if (molten == null) { + throw new IllegalArgumentException("Molten cannot be null"); + } + + this.resource = resource; + this.product = molten; + this.meltingPoint = meltingPoint; + } + + public ItemStack getResource() { + return resource; + } + + public FluidStack getProduct() { + return product; + } + + public int getMeltingPoint() { + return meltingPoint; + } +} diff --git a/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipeManager.java b/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipeManager.java index e80b838ad..addb89212 100644 --- a/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipeManager.java @@ -1,78 +1,75 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.IFabricatorSmeltingManager; -import forestry.api.recipes.IFabricatorSmeltingRecipe; -import forestry.core.utils.ItemStackUtil; - -public class FabricatorSmeltingRecipeManager implements IFabricatorSmeltingManager { - public static final Set recipes = new HashSet<>(); - - public static IFabricatorSmeltingRecipe findMatchingSmelting(ItemStack resource) { - if (resource == null) { - return null; - } - - for (IFabricatorSmeltingRecipe smelting : recipes) { - if (ItemStackUtil.isCraftingEquivalent(smelting.getResource(), resource)) { - return smelting; - } - } - - return null; - } - - @Override - public void addSmelting(ItemStack resource, FluidStack molten, int meltingPoint) { - if (resource == null || molten == null) { - return; - } - addRecipe(new FabricatorSmeltingRecipe(resource, molten, meltingPoint)); - } - - @Override - public boolean addRecipe(IFabricatorSmeltingRecipe recipe) { - return recipes.add(recipe); - } - - @Override - public boolean removeRecipe(IFabricatorSmeltingRecipe recipe) { - return recipes.remove(recipe); - } - - @Override - public Collection recipes() { - return Collections.unmodifiableSet(recipes); - } - - @Override - public Map getRecipes() { - HashMap recipeList = new HashMap<>(); - - for (IFabricatorSmeltingRecipe recipe : recipes) { - recipeList.put(new Object[]{recipe.getResource()}, new Object[]{recipe.getProduct()}); - } - - return recipeList; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.IFabricatorSmeltingManager; +import forestry.api.recipes.IFabricatorSmeltingRecipe; +import forestry.core.utils.ItemStackUtil; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; + +public class FabricatorSmeltingRecipeManager implements IFabricatorSmeltingManager { + public static final Set recipes = new HashSet<>(); + + public static IFabricatorSmeltingRecipe findMatchingSmelting(ItemStack resource) { + if (resource == null) { + return null; + } + + for (IFabricatorSmeltingRecipe smelting : recipes) { + if (ItemStackUtil.isCraftingEquivalent(smelting.getResource(), resource)) { + return smelting; + } + } + + return null; + } + + @Override + public void addSmelting(ItemStack resource, FluidStack molten, int meltingPoint) { + if (resource == null || molten == null) { + return; + } + addRecipe(new FabricatorSmeltingRecipe(resource, molten, meltingPoint)); + } + + @Override + public boolean addRecipe(IFabricatorSmeltingRecipe recipe) { + return recipes.add(recipe); + } + + @Override + public boolean removeRecipe(IFabricatorSmeltingRecipe recipe) { + return recipes.remove(recipe); + } + + @Override + public Collection recipes() { + return Collections.unmodifiableSet(recipes); + } + + @Override + public Map getRecipes() { + HashMap recipeList = new HashMap<>(); + + for (IFabricatorSmeltingRecipe recipe : recipes) { + recipeList.put(new Object[] {recipe.getResource()}, new Object[] {recipe.getProduct()}); + } + + return recipeList; + } +} diff --git a/src/main/java/forestry/factory/recipes/FermenterRecipe.java b/src/main/java/forestry/factory/recipes/FermenterRecipe.java index fb2fa0531..10d18c6b2 100644 --- a/src/main/java/forestry/factory/recipes/FermenterRecipe.java +++ b/src/main/java/forestry/factory/recipes/FermenterRecipe.java @@ -1,78 +1,77 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.IFermenterRecipe; -import forestry.core.fluids.Fluids; - -public class FermenterRecipe implements IFermenterRecipe { - - private final ItemStack resource; - private final int fermentationValue; - private final float modifier; - private final Fluid output; - private final FluidStack fluidResource; - - public FermenterRecipe(ItemStack resource, int fermentationValue, float modifier, Fluid output, FluidStack fluidResource) { - // assume that fermenter recipes want to use Forestry's honey and not the legacy "fluid.honey" - if (Fluids.LEGACY_HONEY.is(fluidResource)) { - fluidResource = Fluids.HONEY.getFluid(fluidResource.amount); - } - - if (resource == null) { - throw new NullPointerException("Fermenter Resource cannot be null!"); - } - - if (output == null) { - throw new NullPointerException("Fermenter Output cannot be null!"); - } - - if (fluidResource == null) { - throw new NullPointerException("Fermenter Liquid cannot be null!"); - } - - this.resource = resource; - this.fermentationValue = fermentationValue; - this.modifier = modifier; - this.output = output; - this.fluidResource = fluidResource; - } - - @Override - public ItemStack getResource() { - return resource; - } - - @Override - public FluidStack getFluidResource() { - return fluidResource; - } - - @Override - public int getFermentationValue() { - return fermentationValue; - } - - @Override - public float getModifier() { - return modifier; - } - - @Override - public Fluid getOutput() { - return output; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.IFermenterRecipe; +import forestry.core.fluids.Fluids; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +public class FermenterRecipe implements IFermenterRecipe { + + private final ItemStack resource; + private final int fermentationValue; + private final float modifier; + private final Fluid output; + private final FluidStack fluidResource; + + public FermenterRecipe( + ItemStack resource, int fermentationValue, float modifier, Fluid output, FluidStack fluidResource) { + // assume that fermenter recipes want to use Forestry's honey and not the legacy "fluid.honey" + if (Fluids.LEGACY_HONEY.is(fluidResource)) { + fluidResource = Fluids.HONEY.getFluid(fluidResource.amount); + } + + if (resource == null) { + throw new NullPointerException("Fermenter Resource cannot be null!"); + } + + if (output == null) { + throw new NullPointerException("Fermenter Output cannot be null!"); + } + + if (fluidResource == null) { + throw new NullPointerException("Fermenter Liquid cannot be null!"); + } + + this.resource = resource; + this.fermentationValue = fermentationValue; + this.modifier = modifier; + this.output = output; + this.fluidResource = fluidResource; + } + + @Override + public ItemStack getResource() { + return resource; + } + + @Override + public FluidStack getFluidResource() { + return fluidResource; + } + + @Override + public int getFermentationValue() { + return fermentationValue; + } + + @Override + public float getModifier() { + return modifier; + } + + @Override + public Fluid getOutput() { + return output; + } +} diff --git a/src/main/java/forestry/factory/recipes/FermenterRecipeManager.java b/src/main/java/forestry/factory/recipes/FermenterRecipeManager.java index b979acfc8..dfa0fec8b 100644 --- a/src/main/java/forestry/factory/recipes/FermenterRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/FermenterRecipeManager.java @@ -1,115 +1,114 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.IFermenterManager; -import forestry.api.recipes.IFermenterRecipe; -import forestry.core.fluids.Fluids; -import forestry.core.utils.ItemStackUtil; - -public class FermenterRecipeManager implements IFermenterManager { - - private static final Set recipes = new HashSet<>(); - public static final Set recipeFluidInputs = new HashSet<>(); - public static final Set recipeFluidOutputs = new HashSet<>(); - - @Override - public void addRecipe(ItemStack resource, int fermentationValue, float modifier, FluidStack output, FluidStack liquid) { - IFermenterRecipe recipe = new FermenterRecipe(resource, fermentationValue, modifier, output.getFluid(), liquid); - addRecipe(recipe); - } - - @Override - public void addRecipe(ItemStack resource, int fermentationValue, float modifier, FluidStack output) { - addRecipe(resource, fermentationValue, modifier, output, Fluids.WATER.getFluid(1000)); - } - - public static IFermenterRecipe findMatchingRecipe(ItemStack res, FluidStack liqu) { - for (IFermenterRecipe recipe : recipes) { - if (matches(recipe, res, liqu)) { - return recipe; - } - } - return null; - } - - public static boolean matches(IFermenterRecipe recipe, ItemStack res, FluidStack liqu) { - ItemStack resource = recipe.getResource(); - if (!ItemStackUtil.isCraftingEquivalent(resource, res)) { - return false; - } - - FluidStack fluid = recipe.getFluidResource(); - return liqu != null && liqu.isFluidEqual(fluid); - } - - public static boolean isResource(ItemStack resource) { - if (resource == null) { - return false; - } - - for (IFermenterRecipe recipe : recipes) { - if (ItemStackUtil.isCraftingEquivalent(recipe.getResource(), resource)) { - return true; - } - } - return false; - } - - @Override - public boolean addRecipe(IFermenterRecipe recipe) { - FluidStack liquid = recipe.getFluidResource(); - recipeFluidInputs.add(liquid.getFluid()); - - Fluid output = recipe.getOutput(); - recipeFluidOutputs.add(output); - - return recipes.add(recipe); - } - - @Override - public boolean removeRecipe(IFermenterRecipe recipe) { - FluidStack liquid = recipe.getFluidResource(); - recipeFluidInputs.remove(liquid.getFluid()); - - Fluid output = recipe.getOutput(); - recipeFluidOutputs.remove(output); - - return recipes.remove(recipe); - } - - @Override - public Set recipes() { - return Collections.unmodifiableSet(recipes); - } - - @Override - public Map getRecipes() { - HashMap recipeList = new HashMap<>(); - - for (IFermenterRecipe recipe : recipes) { - recipeList.put(new Object[]{recipe.getResource(), recipe.getFluidResource()}, new Object[]{recipe.getOutput()}); - } - - return recipeList; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.IFermenterManager; +import forestry.api.recipes.IFermenterRecipe; +import forestry.core.fluids.Fluids; +import forestry.core.utils.ItemStackUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +public class FermenterRecipeManager implements IFermenterManager { + + private static final Set recipes = new HashSet<>(); + public static final Set recipeFluidInputs = new HashSet<>(); + public static final Set recipeFluidOutputs = new HashSet<>(); + + @Override + public void addRecipe( + ItemStack resource, int fermentationValue, float modifier, FluidStack output, FluidStack liquid) { + IFermenterRecipe recipe = new FermenterRecipe(resource, fermentationValue, modifier, output.getFluid(), liquid); + addRecipe(recipe); + } + + @Override + public void addRecipe(ItemStack resource, int fermentationValue, float modifier, FluidStack output) { + addRecipe(resource, fermentationValue, modifier, output, Fluids.WATER.getFluid(1000)); + } + + public static IFermenterRecipe findMatchingRecipe(ItemStack res, FluidStack liqu) { + for (IFermenterRecipe recipe : recipes) { + if (matches(recipe, res, liqu)) { + return recipe; + } + } + return null; + } + + public static boolean matches(IFermenterRecipe recipe, ItemStack res, FluidStack liqu) { + ItemStack resource = recipe.getResource(); + if (!ItemStackUtil.isCraftingEquivalent(resource, res)) { + return false; + } + + FluidStack fluid = recipe.getFluidResource(); + return liqu != null && liqu.isFluidEqual(fluid); + } + + public static boolean isResource(ItemStack resource) { + if (resource == null) { + return false; + } + + for (IFermenterRecipe recipe : recipes) { + if (ItemStackUtil.isCraftingEquivalent(recipe.getResource(), resource)) { + return true; + } + } + return false; + } + + @Override + public boolean addRecipe(IFermenterRecipe recipe) { + FluidStack liquid = recipe.getFluidResource(); + recipeFluidInputs.add(liquid.getFluid()); + + Fluid output = recipe.getOutput(); + recipeFluidOutputs.add(output); + + return recipes.add(recipe); + } + + @Override + public boolean removeRecipe(IFermenterRecipe recipe) { + FluidStack liquid = recipe.getFluidResource(); + recipeFluidInputs.remove(liquid.getFluid()); + + Fluid output = recipe.getOutput(); + recipeFluidOutputs.remove(output); + + return recipes.remove(recipe); + } + + @Override + public Set recipes() { + return Collections.unmodifiableSet(recipes); + } + + @Override + public Map getRecipes() { + HashMap recipeList = new HashMap<>(); + + for (IFermenterRecipe recipe : recipes) { + recipeList.put( + new Object[] {recipe.getResource(), recipe.getFluidResource()}, new Object[] {recipe.getOutput()}); + } + + return recipeList; + } +} diff --git a/src/main/java/forestry/factory/recipes/ISqueezerContainerRecipe.java b/src/main/java/forestry/factory/recipes/ISqueezerContainerRecipe.java index 94b7d53ff..d1ce3e80d 100644 --- a/src/main/java/forestry/factory/recipes/ISqueezerContainerRecipe.java +++ b/src/main/java/forestry/factory/recipes/ISqueezerContainerRecipe.java @@ -1,27 +1,26 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import net.minecraft.item.ItemStack; - -import forestry.api.recipes.ISqueezerRecipe; - -public interface ISqueezerContainerRecipe { - ItemStack getEmptyContainer(); - - int getProcessingTime(); - - ItemStack getRemnants(); - - float getRemnantsChance(); - - ISqueezerRecipe getSqueezerRecipe(ItemStack filledContainer); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.ISqueezerRecipe; +import net.minecraft.item.ItemStack; + +public interface ISqueezerContainerRecipe { + ItemStack getEmptyContainer(); + + int getProcessingTime(); + + ItemStack getRemnants(); + + float getRemnantsChance(); + + ISqueezerRecipe getSqueezerRecipe(ItemStack filledContainer); +} diff --git a/src/main/java/forestry/factory/recipes/MemorizedRecipe.java b/src/main/java/forestry/factory/recipes/MemorizedRecipe.java index f4c93d63e..43e904783 100644 --- a/src/main/java/forestry/factory/recipes/MemorizedRecipe.java +++ b/src/main/java/forestry/factory/recipes/MemorizedRecipe.java @@ -1,151 +1,149 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - -import forestry.api.core.INBTTagable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamable; -import forestry.core.recipes.RecipeUtil; -import forestry.core.utils.InventoryUtil; -import forestry.core.utils.ItemStackUtil; -import forestry.factory.inventory.InventoryCraftingForestry; - -public final class MemorizedRecipe implements INBTTagable, IStreamable { - private final InventoryCraftingForestry craftMatrix = new InventoryCraftingForestry(); - private final List recipeOutputs = new ArrayList<>(); - private int selectedRecipe; - private long lastUsed; - private boolean locked; - - public MemorizedRecipe() { - // required for IStreamable serialization - } - - public MemorizedRecipe(InventoryCraftingForestry craftMatrix, List recipeOutputs) { - InventoryUtil.deepCopyInventoryContents(craftMatrix, this.craftMatrix); - this.recipeOutputs.addAll(recipeOutputs); - } - - public InventoryCraftingForestry getCraftMatrix() { - return craftMatrix; - } - - public void calculateRecipeOutput(World world) { - recipeOutputs.clear(); - List matching = RecipeUtil.findMatchingRecipes(craftMatrix, world); - recipeOutputs.addAll(matching); - if (selectedRecipe >= recipeOutputs.size()) { - selectedRecipe = 0; - } - if (hasRecipeConflict()) { - removeRecipeConflicts(); - } - } - - public void incrementRecipe() { - selectedRecipe++; - if (selectedRecipe >= recipeOutputs.size()) { - selectedRecipe = 0; - } - } - - public void decrementRecipe() { - selectedRecipe--; - if (selectedRecipe < 0) { - selectedRecipe = recipeOutputs.size() - 1; - } - } - - public boolean hasRecipeConflict() { - return recipeOutputs.size() > 1; - } - - public void removeRecipeConflicts() { - ItemStack recipeOutput = getRecipeOutput(); - recipeOutputs.clear(); - recipeOutputs.add(recipeOutput); - selectedRecipe = 0; - } - - public ItemStack getRecipeOutput() { - if (recipeOutputs.size() == 0) { - return null; - } else { - return recipeOutputs.get(selectedRecipe); - } - } - - public boolean hasRecipeOutput(ItemStack output) { - return ItemStackUtil.containsItemStack(recipeOutputs, output); - } - - public void updateLastUse(long lastUsed) { - this.lastUsed = lastUsed; - } - - public long getLastUsed() { - return lastUsed; - } - - public void toggleLock() { - locked = !locked; - } - - public boolean isLocked() { - return locked; - } - - /* INBTTagable */ - @Override - public final void readFromNBT(NBTTagCompound nbttagcompound) { - InventoryUtil.readFromNBT(craftMatrix, nbttagcompound); - lastUsed = nbttagcompound.getLong("LastUsed"); - locked = nbttagcompound.getBoolean("Locked"); - - if (nbttagcompound.hasKey("SelectedRecipe")) { - selectedRecipe = nbttagcompound.getInteger("SelectedRecipe"); - } - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - InventoryUtil.writeToNBT(craftMatrix, nbttagcompound); - nbttagcompound.setLong("LastUsed", lastUsed); - nbttagcompound.setBoolean("Locked", locked); - nbttagcompound.setInteger("SelectedRecipe", selectedRecipe); - } - - /* IStreamable */ - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeInventory(craftMatrix); - data.writeBoolean(locked); - data.writeItemStacks(recipeOutputs); - data.writeVarInt(selectedRecipe); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - data.readInventory(craftMatrix); - locked = data.readBoolean(); - data.readItemStacks(recipeOutputs); - selectedRecipe = data.readVarInt(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.core.INBTTagable; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; +import forestry.core.recipes.RecipeUtil; +import forestry.core.utils.InventoryUtil; +import forestry.core.utils.ItemStackUtil; +import forestry.factory.inventory.InventoryCraftingForestry; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +public final class MemorizedRecipe implements INBTTagable, IStreamable { + private final InventoryCraftingForestry craftMatrix = new InventoryCraftingForestry(); + private final List recipeOutputs = new ArrayList<>(); + private int selectedRecipe; + private long lastUsed; + private boolean locked; + + public MemorizedRecipe() { + // required for IStreamable serialization + } + + public MemorizedRecipe(InventoryCraftingForestry craftMatrix, List recipeOutputs) { + InventoryUtil.deepCopyInventoryContents(craftMatrix, this.craftMatrix); + this.recipeOutputs.addAll(recipeOutputs); + } + + public InventoryCraftingForestry getCraftMatrix() { + return craftMatrix; + } + + public void calculateRecipeOutput(World world) { + recipeOutputs.clear(); + List matching = RecipeUtil.findMatchingRecipes(craftMatrix, world); + recipeOutputs.addAll(matching); + if (selectedRecipe >= recipeOutputs.size()) { + selectedRecipe = 0; + } + if (hasRecipeConflict()) { + removeRecipeConflicts(); + } + } + + public void incrementRecipe() { + selectedRecipe++; + if (selectedRecipe >= recipeOutputs.size()) { + selectedRecipe = 0; + } + } + + public void decrementRecipe() { + selectedRecipe--; + if (selectedRecipe < 0) { + selectedRecipe = recipeOutputs.size() - 1; + } + } + + public boolean hasRecipeConflict() { + return recipeOutputs.size() > 1; + } + + public void removeRecipeConflicts() { + ItemStack recipeOutput = getRecipeOutput(); + recipeOutputs.clear(); + recipeOutputs.add(recipeOutput); + selectedRecipe = 0; + } + + public ItemStack getRecipeOutput() { + if (recipeOutputs.size() == 0) { + return null; + } else { + return recipeOutputs.get(selectedRecipe); + } + } + + public boolean hasRecipeOutput(ItemStack output) { + return ItemStackUtil.containsItemStack(recipeOutputs, output); + } + + public void updateLastUse(long lastUsed) { + this.lastUsed = lastUsed; + } + + public long getLastUsed() { + return lastUsed; + } + + public void toggleLock() { + locked = !locked; + } + + public boolean isLocked() { + return locked; + } + + /* INBTTagable */ + @Override + public final void readFromNBT(NBTTagCompound nbttagcompound) { + InventoryUtil.readFromNBT(craftMatrix, nbttagcompound); + lastUsed = nbttagcompound.getLong("LastUsed"); + locked = nbttagcompound.getBoolean("Locked"); + + if (nbttagcompound.hasKey("SelectedRecipe")) { + selectedRecipe = nbttagcompound.getInteger("SelectedRecipe"); + } + } + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + InventoryUtil.writeToNBT(craftMatrix, nbttagcompound); + nbttagcompound.setLong("LastUsed", lastUsed); + nbttagcompound.setBoolean("Locked", locked); + nbttagcompound.setInteger("SelectedRecipe", selectedRecipe); + } + + /* IStreamable */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeInventory(craftMatrix); + data.writeBoolean(locked); + data.writeItemStacks(recipeOutputs); + data.writeVarInt(selectedRecipe); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + data.readInventory(craftMatrix); + locked = data.readBoolean(); + data.readItemStacks(recipeOutputs); + selectedRecipe = data.readVarInt(); + } +} diff --git a/src/main/java/forestry/factory/recipes/MoistenerRecipe.java b/src/main/java/forestry/factory/recipes/MoistenerRecipe.java index 21a56c14d..d1903b44c 100644 --- a/src/main/java/forestry/factory/recipes/MoistenerRecipe.java +++ b/src/main/java/forestry/factory/recipes/MoistenerRecipe.java @@ -1,40 +1,39 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import net.minecraft.item.ItemStack; - -import forestry.api.recipes.IMoistenerRecipe; - -public class MoistenerRecipe implements IMoistenerRecipe { - - private final int timePerItem; - private final ItemStack resource; - private final ItemStack product; - - public MoistenerRecipe(ItemStack resource, ItemStack product, int timePerItem) { - this.timePerItem = timePerItem; - this.resource = resource; - this.product = product; - } - - public int getTimePerItem() { - return timePerItem; - } - - public ItemStack getResource() { - return resource; - } - - public ItemStack getProduct() { - return product; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.IMoistenerRecipe; +import net.minecraft.item.ItemStack; + +public class MoistenerRecipe implements IMoistenerRecipe { + + private final int timePerItem; + private final ItemStack resource; + private final ItemStack product; + + public MoistenerRecipe(ItemStack resource, ItemStack product, int timePerItem) { + this.timePerItem = timePerItem; + this.resource = resource; + this.product = product; + } + + public int getTimePerItem() { + return timePerItem; + } + + public ItemStack getResource() { + return resource; + } + + public ItemStack getProduct() { + return product; + } +} diff --git a/src/main/java/forestry/factory/recipes/MoistenerRecipeManager.java b/src/main/java/forestry/factory/recipes/MoistenerRecipeManager.java index 8ba6fd1a0..aac66ed78 100644 --- a/src/main/java/forestry/factory/recipes/MoistenerRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/MoistenerRecipeManager.java @@ -1,83 +1,81 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import net.minecraft.item.ItemStack; - -import forestry.api.recipes.IMoistenerManager; -import forestry.api.recipes.IMoistenerRecipe; -import forestry.core.utils.ItemStackUtil; - -public class MoistenerRecipeManager implements IMoistenerManager { - - private static final Set recipes = new HashSet<>(); - - @Override - public void addRecipe(ItemStack resource, ItemStack product, int timePerItem) { - IMoistenerRecipe recipe = new MoistenerRecipe(resource, product, timePerItem); - addRecipe(recipe); - } - - public static boolean isResource(ItemStack resource) { - if (resource == null) { - return false; - } - - for (IMoistenerRecipe rec : recipes) { - if (ItemStackUtil.isIdenticalItem(resource, rec.getResource())) { - return true; - } - } - - return false; - } - - public static IMoistenerRecipe findMatchingRecipe(ItemStack item) { - for (IMoistenerRecipe recipe : recipes) { - if (ItemStackUtil.isCraftingEquivalent(recipe.getResource(), item)) { - return recipe; - } - } - return null; - } - - @Override - public boolean addRecipe(IMoistenerRecipe recipe) { - return recipes.add(recipe); - } - - @Override - public boolean removeRecipe(IMoistenerRecipe recipe) { - return recipes.remove(recipe); - } - - @Override - public Set recipes() { - return Collections.unmodifiableSet(recipes); - } - - @Override - public Map getRecipes() { - HashMap recipeList = new HashMap<>(); - - for (IMoistenerRecipe recipe : recipes) { - recipeList.put(new ItemStack[]{recipe.getResource()}, new ItemStack[]{recipe.getProduct()}); - } - - return recipeList; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.IMoistenerManager; +import forestry.api.recipes.IMoistenerRecipe; +import forestry.core.utils.ItemStackUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import net.minecraft.item.ItemStack; + +public class MoistenerRecipeManager implements IMoistenerManager { + + private static final Set recipes = new HashSet<>(); + + @Override + public void addRecipe(ItemStack resource, ItemStack product, int timePerItem) { + IMoistenerRecipe recipe = new MoistenerRecipe(resource, product, timePerItem); + addRecipe(recipe); + } + + public static boolean isResource(ItemStack resource) { + if (resource == null) { + return false; + } + + for (IMoistenerRecipe rec : recipes) { + if (ItemStackUtil.isIdenticalItem(resource, rec.getResource())) { + return true; + } + } + + return false; + } + + public static IMoistenerRecipe findMatchingRecipe(ItemStack item) { + for (IMoistenerRecipe recipe : recipes) { + if (ItemStackUtil.isCraftingEquivalent(recipe.getResource(), item)) { + return recipe; + } + } + return null; + } + + @Override + public boolean addRecipe(IMoistenerRecipe recipe) { + return recipes.add(recipe); + } + + @Override + public boolean removeRecipe(IMoistenerRecipe recipe) { + return recipes.remove(recipe); + } + + @Override + public Set recipes() { + return Collections.unmodifiableSet(recipes); + } + + @Override + public Map getRecipes() { + HashMap recipeList = new HashMap<>(); + + for (IMoistenerRecipe recipe : recipes) { + recipeList.put(new ItemStack[] {recipe.getResource()}, new ItemStack[] {recipe.getProduct()}); + } + + return recipeList; + } +} diff --git a/src/main/java/forestry/factory/recipes/RecipeMemory.java b/src/main/java/forestry/factory/recipes/RecipeMemory.java index d8c267909..f89dffffd 100644 --- a/src/main/java/forestry/factory/recipes/RecipeMemory.java +++ b/src/main/java/forestry/factory/recipes/RecipeMemory.java @@ -10,11 +10,14 @@ ******************************************************************************/ package forestry.factory.recipes; +import forestry.api.core.INBTTagable; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; - import net.minecraft.item.Item; import net.minecraft.item.ItemMap; import net.minecraft.item.ItemStack; @@ -22,182 +25,177 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; -import forestry.api.core.INBTTagable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamable; - public class RecipeMemory implements INBTTagable, IStreamable { - public static final int capacity = 9; + public static final int capacity = 9; - private static final List> memoryBlacklist = new ArrayList<>(); + private static final List> memoryBlacklist = new ArrayList<>(); - static { - memoryBlacklist.add(ItemMap.class); // almost every ItemMap is unique - } + static { + memoryBlacklist.add(ItemMap.class); // almost every ItemMap is unique + } - private LinkedList memorizedRecipes = new LinkedList<>(); - private long lastUpdate; + private LinkedList memorizedRecipes = new LinkedList<>(); + private long lastUpdate; - private static boolean isValid(MemorizedRecipe recipe) { - if (recipe == null) { - return false; - } - ItemStack recipeOutput = recipe.getRecipeOutput(); - if (recipeOutput == null) { - return false; - } - Item item = recipeOutput.getItem(); - return item != null && !memoryBlacklist.contains(item.getClass()); - } + private static boolean isValid(MemorizedRecipe recipe) { + if (recipe == null) { + return false; + } + ItemStack recipeOutput = recipe.getRecipeOutput(); + if (recipeOutput == null) { + return false; + } + Item item = recipeOutput.getItem(); + return item != null && !memoryBlacklist.contains(item.getClass()); + } - public void validate(World world) { - LinkedList validRecipes = new LinkedList<>(); - for (MemorizedRecipe recipe : memorizedRecipes) { - if (recipe != null) { - recipe.calculateRecipeOutput(world); - if (isValid(recipe)) { - validRecipes.add(recipe); - } - } - } - this.memorizedRecipes = validRecipes; - } + public void validate(World world) { + LinkedList validRecipes = new LinkedList<>(); + for (MemorizedRecipe recipe : memorizedRecipes) { + if (recipe != null) { + recipe.calculateRecipeOutput(world); + if (isValid(recipe)) { + validRecipes.add(recipe); + } + } + } + this.memorizedRecipes = validRecipes; + } - public long getLastUpdate() { - return lastUpdate; - } + public long getLastUpdate() { + return lastUpdate; + } - public void memorizeRecipe(long worldTime, MemorizedRecipe recipe) { - if (!isValid(recipe)) { - return; - } + public void memorizeRecipe(long worldTime, MemorizedRecipe recipe) { + if (!isValid(recipe)) { + return; + } - lastUpdate = worldTime; - recipe.updateLastUse(lastUpdate); + lastUpdate = worldTime; + recipe.updateLastUse(lastUpdate); - if (recipe.hasRecipeConflict()) { - recipe.removeRecipeConflicts(); - } + if (recipe.hasRecipeConflict()) { + recipe.removeRecipeConflicts(); + } - // update existing matching recipes - MemorizedRecipe memory = getExistingMemorizedRecipe(recipe.getRecipeOutput()); - if (memory != null) { - updateExistingRecipe(memory, recipe); - return; - } + // update existing matching recipes + MemorizedRecipe memory = getExistingMemorizedRecipe(recipe.getRecipeOutput()); + if (memory != null) { + updateExistingRecipe(memory, recipe); + return; + } - // add a new recipe - if (memorizedRecipes.size() < capacity) { - memorizedRecipes.add(recipe); - } else { - MemorizedRecipe oldest = getOldestUnlockedRecipe(); - if (oldest != null) { - memorizedRecipes.remove(oldest); - memorizedRecipes.add(recipe); - } - } - } + // add a new recipe + if (memorizedRecipes.size() < capacity) { + memorizedRecipes.add(recipe); + } else { + MemorizedRecipe oldest = getOldestUnlockedRecipe(); + if (oldest != null) { + memorizedRecipes.remove(oldest); + memorizedRecipes.add(recipe); + } + } + } - private void updateExistingRecipe(MemorizedRecipe existingRecipe, MemorizedRecipe updatedRecipe) { - if (existingRecipe.isLocked() != updatedRecipe.isLocked()) { - updatedRecipe.toggleLock(); - } - int index = memorizedRecipes.indexOf(existingRecipe); - memorizedRecipes.set(index, updatedRecipe); - } + private void updateExistingRecipe(MemorizedRecipe existingRecipe, MemorizedRecipe updatedRecipe) { + if (existingRecipe.isLocked() != updatedRecipe.isLocked()) { + updatedRecipe.toggleLock(); + } + int index = memorizedRecipes.indexOf(existingRecipe); + memorizedRecipes.set(index, updatedRecipe); + } - private MemorizedRecipe getOldestUnlockedRecipe() { - MemorizedRecipe oldest = null; - for (MemorizedRecipe existing : memorizedRecipes) { - if (oldest != null && oldest.getLastUsed() < existing.getLastUsed()) { - continue; - } + private MemorizedRecipe getOldestUnlockedRecipe() { + MemorizedRecipe oldest = null; + for (MemorizedRecipe existing : memorizedRecipes) { + if (oldest != null && oldest.getLastUsed() < existing.getLastUsed()) { + continue; + } - if (!existing.isLocked()) { - oldest = existing; - } - } - return oldest; - } + if (!existing.isLocked()) { + oldest = existing; + } + } + return oldest; + } - public MemorizedRecipe getRecipe(int recipeIndex) { - if (recipeIndex < 0 || recipeIndex >= memorizedRecipes.size()) { - return null; - } - return memorizedRecipes.get(recipeIndex); - } + public MemorizedRecipe getRecipe(int recipeIndex) { + if (recipeIndex < 0 || recipeIndex >= memorizedRecipes.size()) { + return null; + } + return memorizedRecipes.get(recipeIndex); + } - public ItemStack getRecipeDisplayOutput(int recipeIndex) { - MemorizedRecipe recipe = getRecipe(recipeIndex); - if (recipe == null) { - return null; - } - return recipe.getRecipeOutput(); - } + public ItemStack getRecipeDisplayOutput(int recipeIndex) { + MemorizedRecipe recipe = getRecipe(recipeIndex); + if (recipe == null) { + return null; + } + return recipe.getRecipeOutput(); + } - public boolean isLocked(int recipeIndex) { - MemorizedRecipe recipe = getRecipe(recipeIndex); - if (recipe == null) { - return false; - } - return recipe.isLocked(); - } + public boolean isLocked(int recipeIndex) { + MemorizedRecipe recipe = getRecipe(recipeIndex); + if (recipe == null) { + return false; + } + return recipe.isLocked(); + } - public void toggleLock(long worldTime, int recipeIndex) { - lastUpdate = worldTime; - if (memorizedRecipes.size() > recipeIndex) { - memorizedRecipes.get(recipeIndex).toggleLock(); - } - } + public void toggleLock(long worldTime, int recipeIndex) { + lastUpdate = worldTime; + if (memorizedRecipes.size() > recipeIndex) { + memorizedRecipes.get(recipeIndex).toggleLock(); + } + } - private MemorizedRecipe getExistingMemorizedRecipe(ItemStack craftingRecipeOutput) { - for (MemorizedRecipe memorizedRecipe : memorizedRecipes) { - if (memorizedRecipe.hasRecipeOutput(craftingRecipeOutput)) { - return memorizedRecipe; - } - } + private MemorizedRecipe getExistingMemorizedRecipe(ItemStack craftingRecipeOutput) { + for (MemorizedRecipe memorizedRecipe : memorizedRecipes) { + if (memorizedRecipe.hasRecipeOutput(craftingRecipeOutput)) { + return memorizedRecipe; + } + } - return null; - } + return null; + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - memorizedRecipes = new LinkedList<>(); - if (!nbttagcompound.hasKey("RecipeMemory")) { - return; - } + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + memorizedRecipes = new LinkedList<>(); + if (!nbttagcompound.hasKey("RecipeMemory")) { + return; + } - NBTTagList nbttaglist = nbttagcompound.getTagList("RecipeMemory", 10); - for (int j = 0; j < nbttaglist.tagCount(); ++j) { - NBTTagCompound recipeNbt = nbttaglist.getCompoundTagAt(j); - MemorizedRecipe recipe = new MemorizedRecipe(); - recipe.readFromNBT(recipeNbt); - memorizedRecipes.add(recipe); - } - } + NBTTagList nbttaglist = nbttagcompound.getTagList("RecipeMemory", 10); + for (int j = 0; j < nbttaglist.tagCount(); ++j) { + NBTTagCompound recipeNbt = nbttaglist.getCompoundTagAt(j); + MemorizedRecipe recipe = new MemorizedRecipe(); + recipe.readFromNBT(recipeNbt); + memorizedRecipes.add(recipe); + } + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - NBTTagList nbttaglist = new NBTTagList(); - for (MemorizedRecipe recipe : memorizedRecipes) { - if (recipe != null) { - NBTTagCompound recipeNbt = new NBTTagCompound(); - recipe.writeToNBT(recipeNbt); - nbttaglist.appendTag(recipeNbt); - } - } - nbttagcompound.setTag("RecipeMemory", nbttaglist); - } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + NBTTagList nbttaglist = new NBTTagList(); + for (MemorizedRecipe recipe : memorizedRecipes) { + if (recipe != null) { + NBTTagCompound recipeNbt = new NBTTagCompound(); + recipe.writeToNBT(recipeNbt); + nbttaglist.appendTag(recipeNbt); + } + } + nbttagcompound.setTag("RecipeMemory", nbttaglist); + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeStreamables(memorizedRecipes); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeStreamables(memorizedRecipes); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - data.readStreamables(memorizedRecipes, MemorizedRecipe.class); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + data.readStreamables(memorizedRecipes, MemorizedRecipe.class); + } } diff --git a/src/main/java/forestry/factory/recipes/SqueezerContainerRecipe.java b/src/main/java/forestry/factory/recipes/SqueezerContainerRecipe.java index 747c7a881..be67ade02 100644 --- a/src/main/java/forestry/factory/recipes/SqueezerContainerRecipe.java +++ b/src/main/java/forestry/factory/recipes/SqueezerContainerRecipe.java @@ -1,68 +1,67 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.ISqueezerRecipe; -import forestry.core.fluids.FluidHelper; -import forestry.core.utils.ItemStackUtil; - -public class SqueezerContainerRecipe implements ISqueezerContainerRecipe { - - private final ItemStack emptyContainer; - private final int processingTime; - private final ItemStack remnants; - private final float remnantsChance; - - public SqueezerContainerRecipe(ItemStack emptyContainer, int processingTime, ItemStack remnants, float remnantsChance) { - this.emptyContainer = emptyContainer; - this.processingTime = processingTime; - this.remnants = remnants; - this.remnantsChance = remnantsChance; - } - - @Override - public ItemStack getEmptyContainer() { - return emptyContainer; - } - - @Override - public int getProcessingTime() { - return processingTime; - } - - @Override - public ItemStack getRemnants() { - return remnants; - } - - @Override - public float getRemnantsChance() { - return remnantsChance; - } - - @Override - public ISqueezerRecipe getSqueezerRecipe(ItemStack filledContainer) { - if (filledContainer == null) { - return null; - } - FluidStack fluidOutput = FluidHelper.getFluidStackInContainer(filledContainer); - if (fluidOutput == null) { - return null; - } - ItemStack filledContainerCopy = ItemStackUtil.createSplitStack(filledContainer, 1); - return new SqueezerRecipe(processingTime, new ItemStack[]{filledContainerCopy}, fluidOutput, remnants, remnantsChance); - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.ISqueezerRecipe; +import forestry.core.fluids.FluidHelper; +import forestry.core.utils.ItemStackUtil; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; + +public class SqueezerContainerRecipe implements ISqueezerContainerRecipe { + + private final ItemStack emptyContainer; + private final int processingTime; + private final ItemStack remnants; + private final float remnantsChance; + + public SqueezerContainerRecipe( + ItemStack emptyContainer, int processingTime, ItemStack remnants, float remnantsChance) { + this.emptyContainer = emptyContainer; + this.processingTime = processingTime; + this.remnants = remnants; + this.remnantsChance = remnantsChance; + } + + @Override + public ItemStack getEmptyContainer() { + return emptyContainer; + } + + @Override + public int getProcessingTime() { + return processingTime; + } + + @Override + public ItemStack getRemnants() { + return remnants; + } + + @Override + public float getRemnantsChance() { + return remnantsChance; + } + + @Override + public ISqueezerRecipe getSqueezerRecipe(ItemStack filledContainer) { + if (filledContainer == null) { + return null; + } + FluidStack fluidOutput = FluidHelper.getFluidStackInContainer(filledContainer); + if (fluidOutput == null) { + return null; + } + ItemStack filledContainerCopy = ItemStackUtil.createSplitStack(filledContainer, 1); + return new SqueezerRecipe( + processingTime, new ItemStack[] {filledContainerCopy}, fluidOutput, remnants, remnantsChance); + } +} diff --git a/src/main/java/forestry/factory/recipes/SqueezerRecipe.java b/src/main/java/forestry/factory/recipes/SqueezerRecipe.java index e614561d4..09072f6c9 100644 --- a/src/main/java/forestry/factory/recipes/SqueezerRecipe.java +++ b/src/main/java/forestry/factory/recipes/SqueezerRecipe.java @@ -1,60 +1,62 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.ISqueezerRecipe; - -public class SqueezerRecipe implements ISqueezerRecipe { - - private final int processingTime; - private final ItemStack[] resources; - private final FluidStack fluidOutput; - private final ItemStack remnants; - private final float remnantsChance; - - public SqueezerRecipe(int processingTime, ItemStack[] resources, FluidStack fluidOutput, ItemStack remnants, float remnantsChance) { - this.processingTime = processingTime; - this.resources = resources; - this.fluidOutput = fluidOutput; - this.remnants = remnants; - this.remnantsChance = remnantsChance; - } - - @Override - public ItemStack[] getResources() { - return resources; - } - - @Override - public ItemStack getRemnants() { - return remnants; - } - - @Override - public float getRemnantsChance() { - return remnantsChance; - } - - @Override - public FluidStack getFluidOutput() { - return fluidOutput; - } - - @Override - public int getProcessingTime() { - return processingTime; - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.ISqueezerRecipe; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; + +public class SqueezerRecipe implements ISqueezerRecipe { + + private final int processingTime; + private final ItemStack[] resources; + private final FluidStack fluidOutput; + private final ItemStack remnants; + private final float remnantsChance; + + public SqueezerRecipe( + int processingTime, + ItemStack[] resources, + FluidStack fluidOutput, + ItemStack remnants, + float remnantsChance) { + this.processingTime = processingTime; + this.resources = resources; + this.fluidOutput = fluidOutput; + this.remnants = remnants; + this.remnantsChance = remnantsChance; + } + + @Override + public ItemStack[] getResources() { + return resources; + } + + @Override + public ItemStack getRemnants() { + return remnants; + } + + @Override + public float getRemnantsChance() { + return remnantsChance; + } + + @Override + public FluidStack getFluidOutput() { + return fluidOutput; + } + + @Override + public int getProcessingTime() { + return processingTime; + } +} diff --git a/src/main/java/forestry/factory/recipes/SqueezerRecipeManager.java b/src/main/java/forestry/factory/recipes/SqueezerRecipeManager.java index fb2fd01a5..e097c2626 100644 --- a/src/main/java/forestry/factory/recipes/SqueezerRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/SqueezerRecipeManager.java @@ -1,131 +1,131 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import javax.annotation.Nullable; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.ISqueezerManager; -import forestry.api.recipes.ISqueezerRecipe; -import forestry.core.fluids.FluidHelper; -import forestry.core.utils.ItemStackUtil; -import forestry.core.utils.datastructures.ItemStackMap; - -public class SqueezerRecipeManager implements ISqueezerManager { - - private static final Set recipes = new HashSet<>(); - public static final ItemStackMap containerRecipes = new ItemStackMap<>(); - - @Override - public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid, @Nullable ItemStack remnants, int chance) { - ISqueezerRecipe recipe = new SqueezerRecipe(timePerItem, resources, liquid, remnants, chance / 100.0f); - addRecipe(recipe); - } - - @Override - public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid) { - addRecipe(timePerItem, resources, liquid, null, 0); - } - - @Override - public void addContainerRecipe(int timePerItem, ItemStack emptyContainer, @Nullable ItemStack remnants, float chance) { - containerRecipes.put(emptyContainer, new SqueezerContainerRecipe(emptyContainer, timePerItem, remnants, chance)); - } - - @Nullable - public static ISqueezerContainerRecipe findMatchingContainerRecipe(ItemStack filledContainer) { - ItemStack emptyContainer = FluidHelper.getEmptyContainer(filledContainer); - if (emptyContainer == null) { - return null; - } - - return containerRecipes.get(emptyContainer); - } - - public static ISqueezerRecipe findMatchingRecipe(ItemStack[] items) { - // Find container recipes - for (ItemStack itemStack : items) { - ISqueezerContainerRecipe containerRecipe = findMatchingContainerRecipe(itemStack); - if (containerRecipe != null) { - ISqueezerRecipe recipe = containerRecipe.getSqueezerRecipe(itemStack); - if (recipe != null) { - return recipe; - } - } - } - - for (ISqueezerRecipe recipe : recipes) { - if (ItemStackUtil.containsSets(recipe.getResources(), items, false, false) > 0) { - return recipe; - } - } - - return null; - } - - public static ISqueezerRecipe findRecipeWithIngredient(ItemStack ingredient) { - for (ISqueezerRecipe recipe : recipes) { - for (ItemStack recipeIngredient : recipe.getResources()) { - if (ItemStackUtil.isCraftingEquivalent(recipeIngredient, ingredient, false, false)) { - return recipe; - } - } - } - - return null; - } - - public static boolean canUse(ItemStack itemStack) { - for (ISqueezerRecipe recipe : recipes) { - for (ItemStack recipeInput : recipe.getResources()) { - if (ItemStackUtil.isCraftingEquivalent(recipeInput, itemStack, true, false)) { - return true; - } - } - } - - return SqueezerRecipeManager.findMatchingContainerRecipe(itemStack) != null; - } - - @Override - public boolean addRecipe(ISqueezerRecipe recipe) { - return recipes.add(recipe); - } - - @Override - public boolean removeRecipe(ISqueezerRecipe recipe) { - return recipes.remove(recipe); - } - - @Override - public Set recipes() { - return Collections.unmodifiableSet(recipes); - } - - @Override - public Map getRecipes() { - HashMap recipeList = new HashMap<>(); - - for (ISqueezerRecipe recipe : recipes) { - recipeList.put(recipe.getResources(), new Object[]{recipe.getRemnants(), recipe.getFluidOutput()}); - } - - return recipeList; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.ISqueezerManager; +import forestry.api.recipes.ISqueezerRecipe; +import forestry.core.fluids.FluidHelper; +import forestry.core.utils.ItemStackUtil; +import forestry.core.utils.datastructures.ItemStackMap; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import javax.annotation.Nullable; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; + +public class SqueezerRecipeManager implements ISqueezerManager { + + private static final Set recipes = new HashSet<>(); + public static final ItemStackMap containerRecipes = new ItemStackMap<>(); + + @Override + public void addRecipe( + int timePerItem, ItemStack[] resources, FluidStack liquid, @Nullable ItemStack remnants, int chance) { + ISqueezerRecipe recipe = new SqueezerRecipe(timePerItem, resources, liquid, remnants, chance / 100.0f); + addRecipe(recipe); + } + + @Override + public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid) { + addRecipe(timePerItem, resources, liquid, null, 0); + } + + @Override + public void addContainerRecipe( + int timePerItem, ItemStack emptyContainer, @Nullable ItemStack remnants, float chance) { + containerRecipes.put( + emptyContainer, new SqueezerContainerRecipe(emptyContainer, timePerItem, remnants, chance)); + } + + @Nullable + public static ISqueezerContainerRecipe findMatchingContainerRecipe(ItemStack filledContainer) { + ItemStack emptyContainer = FluidHelper.getEmptyContainer(filledContainer); + if (emptyContainer == null) { + return null; + } + + return containerRecipes.get(emptyContainer); + } + + public static ISqueezerRecipe findMatchingRecipe(ItemStack[] items) { + // Find container recipes + for (ItemStack itemStack : items) { + ISqueezerContainerRecipe containerRecipe = findMatchingContainerRecipe(itemStack); + if (containerRecipe != null) { + ISqueezerRecipe recipe = containerRecipe.getSqueezerRecipe(itemStack); + if (recipe != null) { + return recipe; + } + } + } + + for (ISqueezerRecipe recipe : recipes) { + if (ItemStackUtil.containsSets(recipe.getResources(), items, false, false) > 0) { + return recipe; + } + } + + return null; + } + + public static ISqueezerRecipe findRecipeWithIngredient(ItemStack ingredient) { + for (ISqueezerRecipe recipe : recipes) { + for (ItemStack recipeIngredient : recipe.getResources()) { + if (ItemStackUtil.isCraftingEquivalent(recipeIngredient, ingredient, false, false)) { + return recipe; + } + } + } + + return null; + } + + public static boolean canUse(ItemStack itemStack) { + for (ISqueezerRecipe recipe : recipes) { + for (ItemStack recipeInput : recipe.getResources()) { + if (ItemStackUtil.isCraftingEquivalent(recipeInput, itemStack, true, false)) { + return true; + } + } + } + + return SqueezerRecipeManager.findMatchingContainerRecipe(itemStack) != null; + } + + @Override + public boolean addRecipe(ISqueezerRecipe recipe) { + return recipes.add(recipe); + } + + @Override + public boolean removeRecipe(ISqueezerRecipe recipe) { + return recipes.remove(recipe); + } + + @Override + public Set recipes() { + return Collections.unmodifiableSet(recipes); + } + + @Override + public Map getRecipes() { + HashMap recipeList = new HashMap<>(); + + for (ISqueezerRecipe recipe : recipes) { + recipeList.put(recipe.getResources(), new Object[] {recipe.getRemnants(), recipe.getFluidOutput()}); + } + + return recipeList; + } +} diff --git a/src/main/java/forestry/factory/recipes/StillRecipe.java b/src/main/java/forestry/factory/recipes/StillRecipe.java index 183ac6757..0e5ec0044 100644 --- a/src/main/java/forestry/factory/recipes/StillRecipe.java +++ b/src/main/java/forestry/factory/recipes/StillRecipe.java @@ -1,48 +1,47 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.IStillRecipe; - -public class StillRecipe implements IStillRecipe { - private final int timePerUnit; - private final FluidStack input; - private final FluidStack output; - - public StillRecipe(int timePerUnit, FluidStack input, FluidStack output) { - this.timePerUnit = timePerUnit; - if (input == null) { - throw new IllegalArgumentException("Still recipes need an input. Input was null."); - } - if (output == null) { - throw new IllegalArgumentException("Still recipes need an output. Output was null."); - } - this.input = input; - this.output = output; - } - - @Override - public int getCyclesPerUnit() { - return timePerUnit; - } - - @Override - public FluidStack getInput() { - return input; - } - - @Override - public FluidStack getOutput() { - return output; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.IStillRecipe; +import net.minecraftforge.fluids.FluidStack; + +public class StillRecipe implements IStillRecipe { + private final int timePerUnit; + private final FluidStack input; + private final FluidStack output; + + public StillRecipe(int timePerUnit, FluidStack input, FluidStack output) { + this.timePerUnit = timePerUnit; + if (input == null) { + throw new IllegalArgumentException("Still recipes need an input. Input was null."); + } + if (output == null) { + throw new IllegalArgumentException("Still recipes need an output. Output was null."); + } + this.input = input; + this.output = output; + } + + @Override + public int getCyclesPerUnit() { + return timePerUnit; + } + + @Override + public FluidStack getInput() { + return input; + } + + @Override + public FluidStack getOutput() { + return output; + } +} diff --git a/src/main/java/forestry/factory/recipes/StillRecipeManager.java b/src/main/java/forestry/factory/recipes/StillRecipeManager.java index 5cae7f083..8af813b70 100644 --- a/src/main/java/forestry/factory/recipes/StillRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/StillRecipeManager.java @@ -1,93 +1,91 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.recipes.IStillManager; -import forestry.api.recipes.IStillRecipe; - -public class StillRecipeManager implements IStillManager { - - private static final Set recipes = new HashSet<>(); - public static final Set recipeFluidInputs = new HashSet<>(); - public static final Set recipeFluidOutputs = new HashSet<>(); - - @Override - public void addRecipe(int timePerUnit, FluidStack input, FluidStack output) { - IStillRecipe recipe = new StillRecipe(timePerUnit, input, output); - addRecipe(recipe); - } - - public static IStillRecipe findMatchingRecipe(FluidStack item) { - if (item == null) { - return null; - } - for (IStillRecipe recipe : recipes) { - if (matches(recipe, item)) { - return recipe; - } - } - return null; - } - - public static boolean matches(IStillRecipe recipe, FluidStack item) { - if (recipe == null || item == null) { - return false; - } - return item.containsFluid(recipe.getInput()); - } - - @Override - public boolean addRecipe(IStillRecipe recipe) { - FluidStack input = recipe.getInput(); - recipeFluidInputs.add(input.getFluid()); - - FluidStack output = recipe.getOutput(); - recipeFluidOutputs.add(output.getFluid()); - - return recipes.add(recipe); - } - - @Override - public boolean removeRecipe(IStillRecipe recipe) { - FluidStack input = recipe.getInput(); - recipeFluidInputs.remove(input.getFluid()); - - FluidStack output = recipe.getOutput(); - recipeFluidOutputs.remove(output.getFluid()); - - return recipes.remove(recipe); - } - - @Override - public Set recipes() { - return Collections.unmodifiableSet(recipes); - } - - @Override - public Map getRecipes() { - HashMap recipeList = new HashMap<>(); - - for (IStillRecipe recipe : recipes) { - recipeList.put(new Object[]{recipe.getInput()}, new Object[]{recipe.getOutput()}); - } - - return recipeList; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.factory.recipes; + +import forestry.api.recipes.IStillManager; +import forestry.api.recipes.IStillRecipe; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +public class StillRecipeManager implements IStillManager { + + private static final Set recipes = new HashSet<>(); + public static final Set recipeFluidInputs = new HashSet<>(); + public static final Set recipeFluidOutputs = new HashSet<>(); + + @Override + public void addRecipe(int timePerUnit, FluidStack input, FluidStack output) { + IStillRecipe recipe = new StillRecipe(timePerUnit, input, output); + addRecipe(recipe); + } + + public static IStillRecipe findMatchingRecipe(FluidStack item) { + if (item == null) { + return null; + } + for (IStillRecipe recipe : recipes) { + if (matches(recipe, item)) { + return recipe; + } + } + return null; + } + + public static boolean matches(IStillRecipe recipe, FluidStack item) { + if (recipe == null || item == null) { + return false; + } + return item.containsFluid(recipe.getInput()); + } + + @Override + public boolean addRecipe(IStillRecipe recipe) { + FluidStack input = recipe.getInput(); + recipeFluidInputs.add(input.getFluid()); + + FluidStack output = recipe.getOutput(); + recipeFluidOutputs.add(output.getFluid()); + + return recipes.add(recipe); + } + + @Override + public boolean removeRecipe(IStillRecipe recipe) { + FluidStack input = recipe.getInput(); + recipeFluidInputs.remove(input.getFluid()); + + FluidStack output = recipe.getOutput(); + recipeFluidOutputs.remove(output.getFluid()); + + return recipes.remove(recipe); + } + + @Override + public Set recipes() { + return Collections.unmodifiableSet(recipes); + } + + @Override + public Map getRecipes() { + HashMap recipeList = new HashMap<>(); + + for (IStillRecipe recipe : recipes) { + recipeList.put(new Object[] {recipe.getInput()}, new Object[] {recipe.getOutput()}); + } + + return recipeList; + } +} diff --git a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideBottler.java b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideBottler.java index 43f305c96..b5d386fb3 100644 --- a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideBottler.java +++ b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideBottler.java @@ -10,14 +10,11 @@ ******************************************************************************/ package forestry.factory.recipes.craftguide; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidContainerRegistry; - import forestry.factory.blocks.BlockFactoryTesrType; import forestry.factory.recipes.BottlerRecipe; import forestry.plugins.PluginFactory; - +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidContainerRegistry; import uristqwerty.CraftGuide.api.ItemSlot; import uristqwerty.CraftGuide.api.LiquidSlot; import uristqwerty.CraftGuide.api.RecipeGenerator; @@ -28,35 +25,37 @@ import uristqwerty.CraftGuide.api.SlotType; public class CraftGuideBottler implements RecipeProvider { - private final Slot[] slots = new Slot[4]; + private final Slot[] slots = new Slot[4]; - public CraftGuideBottler() { - slots[0] = new ItemSlot(12, 12, 16, 16).drawOwnBackground(); - slots[1] = new LiquidSlot(12, 30); - slots[2] = new ItemSlot(50, 21, 16, 16).setSlotType(SlotType.OUTPUT_SLOT).drawOwnBackground(); - slots[3] = new ItemSlot(31, 21, 16, 16).setSlotType(SlotType.MACHINE_SLOT); - } + public CraftGuideBottler() { + slots[0] = new ItemSlot(12, 12, 16, 16).drawOwnBackground(); + slots[1] = new LiquidSlot(12, 30); + slots[2] = + new ItemSlot(50, 21, 16, 16).setSlotType(SlotType.OUTPUT_SLOT).drawOwnBackground(); + slots[3] = new ItemSlot(31, 21, 16, 16).setSlotType(SlotType.MACHINE_SLOT); + } - @Override - public void generateRecipes(RecipeGenerator generator) { - if (PluginFactory.blocks.factoryTESR == null) { - return; - } + @Override + public void generateRecipes(RecipeGenerator generator) { + if (PluginFactory.blocks.factoryTESR == null) { + return; + } - ItemStack machine = PluginFactory.blocks.factoryTESR.get(BlockFactoryTesrType.BOTTLER); - RecipeTemplate template = generator.createRecipeTemplate(slots, machine); + ItemStack machine = PluginFactory.blocks.factoryTESR.get(BlockFactoryTesrType.BOTTLER); + RecipeTemplate template = generator.createRecipeTemplate(slots, machine); - for (FluidContainerRegistry.FluidContainerData container : FluidContainerRegistry.getRegisteredFluidContainerData()) { - BottlerRecipe recipe = BottlerRecipe.getRecipe(container.fluid, container.emptyContainer); - if (recipe != null) { - Object[] array = new Object[4]; - - array[0] = recipe.empty; - array[1] = recipe.input; - array[2] = recipe.filled; - array[3] = machine; - generator.addRecipe(template, array); - } - } - } + for (FluidContainerRegistry.FluidContainerData container : + FluidContainerRegistry.getRegisteredFluidContainerData()) { + BottlerRecipe recipe = BottlerRecipe.getRecipe(container.fluid, container.emptyContainer); + if (recipe != null) { + Object[] array = new Object[4]; + + array[0] = recipe.empty; + array[1] = recipe.input; + array[2] = recipe.filled; + array[3] = machine; + generator.addRecipe(template, array); + } + } + } } diff --git a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideCarpenter.java b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideCarpenter.java index eb259cc83..d7ca376a2 100644 --- a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideCarpenter.java +++ b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideCarpenter.java @@ -10,14 +10,12 @@ ******************************************************************************/ package forestry.factory.recipes.craftguide; -import net.minecraft.item.ItemStack; - import forestry.api.recipes.ICarpenterRecipe; import forestry.api.recipes.RecipeManagers; import forestry.core.recipes.RecipeUtil; import forestry.factory.blocks.BlockFactoryTesrType; import forestry.plugins.PluginFactory; - +import net.minecraft.item.ItemStack; import uristqwerty.CraftGuide.api.ItemSlot; import uristqwerty.CraftGuide.api.LiquidSlot; import uristqwerty.CraftGuide.api.RecipeGenerator; @@ -28,45 +26,46 @@ import uristqwerty.CraftGuide.api.SlotType; public class CraftGuideCarpenter implements RecipeProvider { - private final Slot[] slots = new Slot[12]; + private final Slot[] slots = new Slot[12]; - public CraftGuideCarpenter() { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - slots[i + j * 3] = new ItemSlot(i * 18 + 3, j * 18 + 3, 16, 16).drawOwnBackground(); - } - } - slots[9] = new ItemSlot(59, 21, 16, 16, true).setSlotType(SlotType.OUTPUT_SLOT).drawOwnBackground(); - slots[10] = new LiquidSlot(59, 39); - slots[11] = new ItemSlot(59, 3, 16, 16).setSlotType(SlotType.MACHINE_SLOT); - } + public CraftGuideCarpenter() { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + slots[i + j * 3] = new ItemSlot(i * 18 + 3, j * 18 + 3, 16, 16).drawOwnBackground(); + } + } + slots[9] = new ItemSlot(59, 21, 16, 16, true) + .setSlotType(SlotType.OUTPUT_SLOT) + .drawOwnBackground(); + slots[10] = new LiquidSlot(59, 39); + slots[11] = new ItemSlot(59, 3, 16, 16).setSlotType(SlotType.MACHINE_SLOT); + } - @Override - public void generateRecipes(RecipeGenerator generator) { - if (PluginFactory.blocks.factoryTESR == null) { - return; - } + @Override + public void generateRecipes(RecipeGenerator generator) { + if (PluginFactory.blocks.factoryTESR == null) { + return; + } - ItemStack machine = PluginFactory.blocks.factoryTESR.get(BlockFactoryTesrType.CARPENTER); - RecipeTemplate template = generator.createRecipeTemplate(slots, machine); + ItemStack machine = PluginFactory.blocks.factoryTESR.get(BlockFactoryTesrType.CARPENTER); + RecipeTemplate template = generator.createRecipeTemplate(slots, machine); - for (ICarpenterRecipe recipe : RecipeManagers.carpenterManager.recipes()) { - Object[] array = new Object[12]; - - Object[] flattened = RecipeUtil.getCraftingRecipeAsArray(recipe.getCraftingGridRecipe()); - if (flattened == null) { - flattened = generator.getCraftingRecipe(recipe.getCraftingGridRecipe()); - } - if (flattened == null) { - continue; - } - System.arraycopy(flattened, 0, array, 0, flattened.length); - if (recipe.getFluidResource() != null) { - array[10] = recipe.getFluidResource(); - } - array[11] = machine; - generator.addRecipe(template, array); - } - } + for (ICarpenterRecipe recipe : RecipeManagers.carpenterManager.recipes()) { + Object[] array = new Object[12]; + Object[] flattened = RecipeUtil.getCraftingRecipeAsArray(recipe.getCraftingGridRecipe()); + if (flattened == null) { + flattened = generator.getCraftingRecipe(recipe.getCraftingGridRecipe()); + } + if (flattened == null) { + continue; + } + System.arraycopy(flattened, 0, array, 0, flattened.length); + if (recipe.getFluidResource() != null) { + array[10] = recipe.getFluidResource(); + } + array[11] = machine; + generator.addRecipe(template, array); + } + } } diff --git a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideCentrifuge.java b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideCentrifuge.java index c1b1e81dc..6f2f3f67e 100644 --- a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideCentrifuge.java +++ b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideCentrifuge.java @@ -10,17 +10,14 @@ ******************************************************************************/ package forestry.factory.recipes.craftguide; -import java.util.ArrayList; -import java.util.List; -import java.util.Map.Entry; - -import net.minecraft.item.ItemStack; - import forestry.api.recipes.ICentrifugeRecipe; import forestry.api.recipes.RecipeManagers; import forestry.factory.blocks.BlockFactoryTesrType; import forestry.plugins.PluginFactory; - +import java.util.ArrayList; +import java.util.List; +import java.util.Map.Entry; +import net.minecraft.item.ItemStack; import uristqwerty.CraftGuide.api.ChanceSlot; import uristqwerty.CraftGuide.api.ItemSlot; import uristqwerty.CraftGuide.api.RecipeGenerator; @@ -31,42 +28,46 @@ import uristqwerty.CraftGuide.api.SlotType; public class CraftGuideCentrifuge implements RecipeProvider { - private final Slot[] slots = new Slot[11]; + private final Slot[] slots = new Slot[11]; - public CraftGuideCentrifuge() { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - slots[i + j * 3] = new ChanceSlot(i * 18 + 24, j * 18 + 3, 16, 16).setRatio(100).setSlotType(SlotType.OUTPUT_SLOT).drawOwnBackground(); - } - } - slots[9] = new ItemSlot(4, 31, 16, 16, true).drawOwnBackground(); - slots[10] = new ItemSlot(4, 11, 16, 16).setSlotType(SlotType.MACHINE_SLOT); - } + public CraftGuideCentrifuge() { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + slots[i + j * 3] = new ChanceSlot(i * 18 + 24, j * 18 + 3, 16, 16) + .setRatio(100) + .setSlotType(SlotType.OUTPUT_SLOT) + .drawOwnBackground(); + } + } + slots[9] = new ItemSlot(4, 31, 16, 16, true).drawOwnBackground(); + slots[10] = new ItemSlot(4, 11, 16, 16).setSlotType(SlotType.MACHINE_SLOT); + } - @Override - public void generateRecipes(RecipeGenerator generator) { + @Override + public void generateRecipes(RecipeGenerator generator) { - if (PluginFactory.blocks.factoryTESR == null) { - return; - } + if (PluginFactory.blocks.factoryTESR == null) { + return; + } - ItemStack machine = PluginFactory.blocks.factoryTESR.get(BlockFactoryTesrType.CENTRIFUGE); - RecipeTemplate template = generator.createRecipeTemplate(slots, machine); + ItemStack machine = PluginFactory.blocks.factoryTESR.get(BlockFactoryTesrType.CENTRIFUGE); + RecipeTemplate template = generator.createRecipeTemplate(slots, machine); - for (ICentrifugeRecipe recipe : RecipeManagers.centrifugeManager.recipes()) { - Object[] array = new Object[11]; + for (ICentrifugeRecipe recipe : RecipeManagers.centrifugeManager.recipes()) { + Object[] array = new Object[11]; - List> entries = new ArrayList<>(recipe.getAllProducts().entrySet()); + List> entries = + new ArrayList<>(recipe.getAllProducts().entrySet()); - for (int i = 0; i < Math.min(entries.size(), 9); i++) { - Entry entry = entries.get(i); - array[i] = entry.getValue() > 0 ? new Object[]{entry.getKey(), entry.getValue()} : null; - } + for (int i = 0; i < Math.min(entries.size(), 9); i++) { + Entry entry = entries.get(i); + array[i] = entry.getValue() > 0 ? new Object[] {entry.getKey(), entry.getValue()} : null; + } - array[9] = recipe.getInput(); - array[10] = machine; + array[9] = recipe.getInput(); + array[10] = machine; - generator.addRecipe(template, array); - } - } + generator.addRecipe(template, array); + } + } } diff --git a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideFabricator.java b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideFabricator.java index cc07c1808..3300b0973 100644 --- a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideFabricator.java +++ b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideFabricator.java @@ -10,13 +10,11 @@ ******************************************************************************/ package forestry.factory.recipes.craftguide; -import net.minecraft.item.ItemStack; - import forestry.api.recipes.IFabricatorRecipe; import forestry.api.recipes.RecipeManagers; import forestry.factory.blocks.BlockFactoryPlainType; import forestry.plugins.PluginFactory; - +import net.minecraft.item.ItemStack; import uristqwerty.CraftGuide.api.ItemSlot; import uristqwerty.CraftGuide.api.LiquidSlot; import uristqwerty.CraftGuide.api.RecipeGenerator; @@ -27,45 +25,46 @@ import uristqwerty.CraftGuide.api.SlotType; public class CraftGuideFabricator implements RecipeProvider { - private final Slot[] slots = new Slot[12]; + private final Slot[] slots = new Slot[12]; - public CraftGuideFabricator() { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - slots[i + j * 3] = new ItemSlot(i * 18 + 3, j * 18 + 3, 16, 16).drawOwnBackground(); - } - } - slots[9] = new ItemSlot(59, 21, 16, 16, true).setSlotType(SlotType.OUTPUT_SLOT).drawOwnBackground(); - slots[10] = new LiquidSlot(59, 39); - slots[11] = new ItemSlot(59, 3, 16, 16).setSlotType(SlotType.MACHINE_SLOT); - } + public CraftGuideFabricator() { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + slots[i + j * 3] = new ItemSlot(i * 18 + 3, j * 18 + 3, 16, 16).drawOwnBackground(); + } + } + slots[9] = new ItemSlot(59, 21, 16, 16, true) + .setSlotType(SlotType.OUTPUT_SLOT) + .drawOwnBackground(); + slots[10] = new LiquidSlot(59, 39); + slots[11] = new ItemSlot(59, 3, 16, 16).setSlotType(SlotType.MACHINE_SLOT); + } - @Override - public void generateRecipes(RecipeGenerator generator) { - if (PluginFactory.blocks.factoryPlain == null) { - return; - } + @Override + public void generateRecipes(RecipeGenerator generator) { + if (PluginFactory.blocks.factoryPlain == null) { + return; + } - ItemStack machine = PluginFactory.blocks.factoryPlain.get(BlockFactoryPlainType.FABRICATOR); - RecipeTemplate template = generator.createRecipeTemplate(slots, machine); + ItemStack machine = PluginFactory.blocks.factoryPlain.get(BlockFactoryPlainType.FABRICATOR); + RecipeTemplate template = generator.createRecipeTemplate(slots, machine); - for (IFabricatorRecipe recipe : RecipeManagers.fabricatorManager.recipes()) { - Object[] array = new Object[12]; + for (IFabricatorRecipe recipe : RecipeManagers.fabricatorManager.recipes()) { + Object[] array = new Object[12]; - Object[] recipeIngredients = recipe.getIngredients(); - if (recipeIngredients == null) { - continue; - } + Object[] recipeIngredients = recipe.getIngredients(); + if (recipeIngredients == null) { + continue; + } - System.arraycopy(recipeIngredients, 0, array, 0, recipeIngredients.length); - array[9] = recipe.getRecipeOutput(); - - if (recipe.getLiquid() != null) { - array[10] = recipe.getLiquid(); - } - array[11] = machine; - generator.addRecipe(template, array); - } - } + System.arraycopy(recipeIngredients, 0, array, 0, recipeIngredients.length); + array[9] = recipe.getRecipeOutput(); + if (recipe.getLiquid() != null) { + array[10] = recipe.getLiquid(); + } + array[11] = machine; + generator.addRecipe(template, array); + } + } } diff --git a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideFermenter.java b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideFermenter.java index 63aae2acc..a79aec3b4 100644 --- a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideFermenter.java +++ b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideFermenter.java @@ -10,19 +10,15 @@ ******************************************************************************/ package forestry.factory.recipes.craftguide; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - import forestry.api.fuels.FuelManager; import forestry.api.recipes.IFermenterRecipe; import forestry.api.recipes.RecipeManagers; import forestry.factory.blocks.BlockFactoryTesrType; import forestry.plugins.PluginFactory; - +import java.util.ArrayList; +import java.util.List; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; import uristqwerty.CraftGuide.api.ItemSlot; import uristqwerty.CraftGuide.api.LiquidSlot; import uristqwerty.CraftGuide.api.RecipeGenerator; @@ -33,38 +29,38 @@ import uristqwerty.CraftGuide.api.SlotType; public class CraftGuideFermenter implements RecipeProvider { - private final Slot[] slots = new Slot[5]; + private final Slot[] slots = new Slot[5]; - public CraftGuideFermenter() { - slots[0] = new ItemSlot(3, 12, 16, 16, true); - slots[1] = new ItemSlot(3, 30, 16, 16, true); - slots[2] = new LiquidSlot(21, 21); - slots[3] = new LiquidSlot(59, 21).setSlotType(SlotType.OUTPUT_SLOT); - slots[4] = new ItemSlot(40, 21, 16, 16).setSlotType(SlotType.MACHINE_SLOT); - } + public CraftGuideFermenter() { + slots[0] = new ItemSlot(3, 12, 16, 16, true); + slots[1] = new ItemSlot(3, 30, 16, 16, true); + slots[2] = new LiquidSlot(21, 21); + slots[3] = new LiquidSlot(59, 21).setSlotType(SlotType.OUTPUT_SLOT); + slots[4] = new ItemSlot(40, 21, 16, 16).setSlotType(SlotType.MACHINE_SLOT); + } - @Override - public void generateRecipes(RecipeGenerator generator) { + @Override + public void generateRecipes(RecipeGenerator generator) { - if (PluginFactory.blocks.factoryTESR == null) { - return; - } + if (PluginFactory.blocks.factoryTESR == null) { + return; + } - ItemStack machine = PluginFactory.blocks.factoryTESR.get(BlockFactoryTesrType.FERMENTER); - RecipeTemplate template = generator.createRecipeTemplate(slots, machine); - List fuels = new ArrayList(FuelManager.fermenterFuel.keySet()); + ItemStack machine = PluginFactory.blocks.factoryTESR.get(BlockFactoryTesrType.FERMENTER); + RecipeTemplate template = generator.createRecipeTemplate(slots, machine); + List fuels = new ArrayList(FuelManager.fermenterFuel.keySet()); - for (IFermenterRecipe recipe : RecipeManagers.fermenterManager.recipes()) { - Object[] array = new Object[5]; + for (IFermenterRecipe recipe : RecipeManagers.fermenterManager.recipes()) { + Object[] array = new Object[5]; - array[0] = recipe.getResource(); - array[1] = fuels; - array[2] = recipe.getFluidResource(); - int amount = Math.round(recipe.getFermentationValue() * recipe.getModifier()); - FluidStack output = new FluidStack(recipe.getOutput(), amount); - array[3] = output; - array[4] = machine; - generator.addRecipe(template, array); - } - } + array[0] = recipe.getResource(); + array[1] = fuels; + array[2] = recipe.getFluidResource(); + int amount = Math.round(recipe.getFermentationValue() * recipe.getModifier()); + FluidStack output = new FluidStack(recipe.getOutput(), amount); + array[3] = output; + array[4] = machine; + generator.addRecipe(template, array); + } + } } diff --git a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideSqueezer.java b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideSqueezer.java index 5a38c982f..47676605b 100644 --- a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideSqueezer.java +++ b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideSqueezer.java @@ -10,13 +10,11 @@ ******************************************************************************/ package forestry.factory.recipes.craftguide; -import net.minecraft.item.ItemStack; - import forestry.api.recipes.ISqueezerRecipe; import forestry.api.recipes.RecipeManagers; import forestry.factory.blocks.BlockFactoryTesrType; import forestry.plugins.PluginFactory; - +import net.minecraft.item.ItemStack; import uristqwerty.CraftGuide.api.ChanceSlot; import uristqwerty.CraftGuide.api.ItemSlot; import uristqwerty.CraftGuide.api.LiquidSlot; @@ -28,42 +26,46 @@ import uristqwerty.CraftGuide.api.SlotType; public class CraftGuideSqueezer implements RecipeProvider { - private final Slot[] slots = new Slot[12]; + private final Slot[] slots = new Slot[12]; - public CraftGuideSqueezer() { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - slots[i + j * 3] = new ItemSlot(i * 18 + 3, j * 18 + 3, 16, 16).drawOwnBackground(); - } - } - slots[9] = new ChanceSlot(59, 39, 16, 16, true).setRatio(100).setSlotType(SlotType.OUTPUT_SLOT).drawOwnBackground(); - slots[10] = new LiquidSlot(59, 21).setSlotType(SlotType.OUTPUT_SLOT); - slots[11] = new ItemSlot(59, 3, 16, 16).setSlotType(SlotType.MACHINE_SLOT); - } + public CraftGuideSqueezer() { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + slots[i + j * 3] = new ItemSlot(i * 18 + 3, j * 18 + 3, 16, 16).drawOwnBackground(); + } + } + slots[9] = new ChanceSlot(59, 39, 16, 16, true) + .setRatio(100) + .setSlotType(SlotType.OUTPUT_SLOT) + .drawOwnBackground(); + slots[10] = new LiquidSlot(59, 21).setSlotType(SlotType.OUTPUT_SLOT); + slots[11] = new ItemSlot(59, 3, 16, 16).setSlotType(SlotType.MACHINE_SLOT); + } - @Override - public void generateRecipes(RecipeGenerator generator) { + @Override + public void generateRecipes(RecipeGenerator generator) { - if (PluginFactory.blocks.factoryTESR == null) { - return; - } + if (PluginFactory.blocks.factoryTESR == null) { + return; + } - ItemStack machine = PluginFactory.blocks.factoryTESR.get(BlockFactoryTesrType.SQUEEZER); - RecipeTemplate template = generator.createRecipeTemplate(slots, machine); + ItemStack machine = PluginFactory.blocks.factoryTESR.get(BlockFactoryTesrType.SQUEEZER); + RecipeTemplate template = generator.createRecipeTemplate(slots, machine); - for (ISqueezerRecipe recipe : RecipeManagers.squeezerManager.recipes()) { - Object[] array = new Object[12]; - - System.arraycopy(recipe.getResources(), 0, array, 0, recipe.getResources().length); - if (recipe.getRemnants() != null) { - array[9] = recipe.getRemnantsChance() > 0 ? new Object[]{recipe.getRemnants().copy(), recipe.getRemnantsChance()} : null; - } - if (recipe.getFluidOutput() != null) { - array[10] = recipe.getFluidOutput(); - } - array[11] = machine; - generator.addRecipe(template, array); - } - } + for (ISqueezerRecipe recipe : RecipeManagers.squeezerManager.recipes()) { + Object[] array = new Object[12]; + System.arraycopy(recipe.getResources(), 0, array, 0, recipe.getResources().length); + if (recipe.getRemnants() != null) { + array[9] = recipe.getRemnantsChance() > 0 + ? new Object[] {recipe.getRemnants().copy(), recipe.getRemnantsChance()} + : null; + } + if (recipe.getFluidOutput() != null) { + array[10] = recipe.getFluidOutput(); + } + array[11] = machine; + generator.addRecipe(template, array); + } + } } diff --git a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideStill.java b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideStill.java index 75375aa71..ad45c0d54 100644 --- a/src/main/java/forestry/factory/recipes/craftguide/CraftGuideStill.java +++ b/src/main/java/forestry/factory/recipes/craftguide/CraftGuideStill.java @@ -10,13 +10,11 @@ ******************************************************************************/ package forestry.factory.recipes.craftguide; -import net.minecraft.item.ItemStack; - import forestry.api.recipes.IStillRecipe; import forestry.api.recipes.RecipeManagers; import forestry.factory.blocks.BlockFactoryTesrType; import forestry.plugins.PluginFactory; - +import net.minecraft.item.ItemStack; import uristqwerty.CraftGuide.api.ItemSlot; import uristqwerty.CraftGuide.api.LiquidSlot; import uristqwerty.CraftGuide.api.RecipeGenerator; @@ -27,30 +25,30 @@ import uristqwerty.CraftGuide.api.SlotType; public class CraftGuideStill implements RecipeProvider { - private final Slot[] slots = new Slot[3]; + private final Slot[] slots = new Slot[3]; - public CraftGuideStill() { - slots[0] = new LiquidSlot(12, 21); - slots[1] = new LiquidSlot(50, 21).setSlotType(SlotType.OUTPUT_SLOT); - slots[2] = new ItemSlot(31, 21, 16, 16).setSlotType(SlotType.MACHINE_SLOT); - } + public CraftGuideStill() { + slots[0] = new LiquidSlot(12, 21); + slots[1] = new LiquidSlot(50, 21).setSlotType(SlotType.OUTPUT_SLOT); + slots[2] = new ItemSlot(31, 21, 16, 16).setSlotType(SlotType.MACHINE_SLOT); + } - @Override - public void generateRecipes(RecipeGenerator generator) { - if (PluginFactory.blocks.factoryTESR == null) { - return; - } + @Override + public void generateRecipes(RecipeGenerator generator) { + if (PluginFactory.blocks.factoryTESR == null) { + return; + } - ItemStack machine = PluginFactory.blocks.factoryTESR.get(BlockFactoryTesrType.STILL); - RecipeTemplate template = generator.createRecipeTemplate(slots, machine); + ItemStack machine = PluginFactory.blocks.factoryTESR.get(BlockFactoryTesrType.STILL); + RecipeTemplate template = generator.createRecipeTemplate(slots, machine); - for (IStillRecipe recipe : RecipeManagers.stillManager.recipes()) { - Object[] array = new Object[3]; + for (IStillRecipe recipe : RecipeManagers.stillManager.recipes()) { + Object[] array = new Object[3]; - array[0] = recipe.getInput(); - array[1] = recipe.getOutput(); - array[2] = machine; - generator.addRecipe(template, array); - } - } + array[0] = recipe.getInput(); + array[1] = recipe.getOutput(); + array[2] = machine; + generator.addRecipe(template, array); + } + } } diff --git a/src/main/java/forestry/factory/recipes/nei/NEIHandlerBottler.java b/src/main/java/forestry/factory/recipes/nei/NEIHandlerBottler.java index 3a2e69395..f8b172d27 100644 --- a/src/main/java/forestry/factory/recipes/nei/NEIHandlerBottler.java +++ b/src/main/java/forestry/factory/recipes/nei/NEIHandlerBottler.java @@ -10,146 +10,145 @@ ******************************************************************************/ package forestry.factory.recipes.nei; -import java.awt.Point; -import java.awt.Rectangle; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.StatCollector; - -import net.minecraftforge.fluids.FluidContainerRegistry; -import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; -import net.minecraftforge.fluids.FluidStack; - +import codechicken.lib.gui.GuiDraw; +import codechicken.nei.NEIServerUtils; +import codechicken.nei.PositionedStack; import forestry.core.recipes.nei.NEIUtils; import forestry.core.recipes.nei.PositionedFluidTank; import forestry.core.recipes.nei.RecipeHandlerBase; import forestry.factory.gui.GuiBottler; import forestry.factory.recipes.BottlerRecipe; - -import codechicken.lib.gui.GuiDraw; -import codechicken.nei.NEIServerUtils; -import codechicken.nei.PositionedStack; +import java.awt.Point; +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.StatCollector; +import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; +import net.minecraftforge.fluids.FluidStack; public class NEIHandlerBottler extends RecipeHandlerBase { - private static final List recipes = new ArrayList<>(); + private static final List recipes = new ArrayList<>(); - @Override - public void prepare() { - for (FluidContainerData container : FluidContainerRegistry.getRegisteredFluidContainerData()) { - BottlerRecipe recipe = BottlerRecipe.getRecipe(container.fluid, container.emptyContainer); - if (recipe != null) { - recipes.add(recipe); - } - } - } + @Override + public void prepare() { + for (FluidContainerData container : FluidContainerRegistry.getRegisteredFluidContainerData()) { + BottlerRecipe recipe = BottlerRecipe.getRecipe(container.fluid, container.emptyContainer); + if (recipe != null) { + recipes.add(recipe); + } + } + } - public class CachedBottlerRecipe extends CachedBaseRecipe { + public class CachedBottlerRecipe extends CachedBaseRecipe { - public PositionedFluidTank fluid; - public PositionedStack input; - public PositionedStack output; + public PositionedFluidTank fluid; + public PositionedStack input; + public PositionedStack output; - public CachedBottlerRecipe(BottlerRecipe recipe) { - if (recipe.input != null) { - this.fluid = new PositionedFluidTank(recipe.input, 10000, new Rectangle(48, 6, 16, 58), NEIHandlerBottler.this.getGuiTexture(), new Point(176, 0)); - } - if (recipe.empty != null) { - this.input = new PositionedStack(recipe.empty, 111, 8); - } - if (recipe.filled != null) { - this.output = new PositionedStack(recipe.filled, 111, 44); - } - } + public CachedBottlerRecipe(BottlerRecipe recipe) { + if (recipe.input != null) { + this.fluid = new PositionedFluidTank( + recipe.input, + 10000, + new Rectangle(48, 6, 16, 58), + NEIHandlerBottler.this.getGuiTexture(), + new Point(176, 0)); + } + if (recipe.empty != null) { + this.input = new PositionedStack(recipe.empty, 111, 8); + } + if (recipe.filled != null) { + this.output = new PositionedStack(recipe.filled, 111, 44); + } + } - @Override - public PositionedStack getIngredient() { - return this.input; - } + @Override + public PositionedStack getIngredient() { + return this.input; + } - @Override - public PositionedStack getResult() { - return this.output; - } + @Override + public PositionedStack getResult() { + return this.output; + } - @Override - public PositionedFluidTank getFluidTank() { - return this.fluid; - } + @Override + public PositionedFluidTank getFluidTank() { + return this.fluid; + } + } - } + @Override + public String getRecipeID() { + return "forestry.bottler"; + } - @Override - public String getRecipeID() { - return "forestry.bottler"; - } + @Override + public String getRecipeName() { + return StatCollector.translateToLocal("tile.for.factory.0.name"); + } - @Override - public String getRecipeName() { - return StatCollector.translateToLocal("tile.for.factory.0.name"); - } + @Override + public String getGuiTexture() { + return "forestry:textures/gui/bottler.png"; + } - @Override - public String getGuiTexture() { - return "forestry:textures/gui/bottler.png"; - } + @Override + public void loadTransferRects() { + this.addTransferRect(75, 27, 24, 17); + } - @Override - public void loadTransferRects() { - this.addTransferRect(75, 27, 24, 17); - } + @Override + public Class getGuiClass() { + return GuiBottler.class; + } - @Override - public Class getGuiClass() { - return GuiBottler.class; - } + @Override + public void drawBackground(int recipe) { + this.changeToGuiTexture(); + GuiDraw.drawTexturedModalRect(43, 0, 48, 11, 123, 65); + } - @Override - public void drawBackground(int recipe) { - this.changeToGuiTexture(); - GuiDraw.drawTexturedModalRect(43, 0, 48, 11, 123, 65); - } + @Override + public void drawExtras(int recipe) { + this.drawProgressBar(75, 27, 176, 74, 24, 17, 40, 0); + } - @Override - public void drawExtras(int recipe) { - this.drawProgressBar(75, 27, 176, 74, 24, 17, 40, 0); - } + @Override + public void loadAllRecipes() { + for (BottlerRecipe recipe : recipes) { + this.arecipes.add(new CachedBottlerRecipe(recipe)); + } + } - @Override - public void loadAllRecipes() { - for (BottlerRecipe recipe : recipes) { - this.arecipes.add(new CachedBottlerRecipe(recipe)); - } - } + @Override + public void loadCraftingRecipes(ItemStack result) { + for (BottlerRecipe recipe : recipes) { + if (NEIServerUtils.areStacksSameTypeCrafting(recipe.filled, result)) { + this.arecipes.add(new CachedBottlerRecipe(recipe)); + } + } + } - @Override - public void loadCraftingRecipes(ItemStack result) { - for (BottlerRecipe recipe : recipes) { - if (NEIServerUtils.areStacksSameTypeCrafting(recipe.filled, result)) { - this.arecipes.add(new CachedBottlerRecipe(recipe)); - } - } - } - - @Override - public void loadUsageRecipes(ItemStack ingred) { - for (BottlerRecipe recipe : recipes) { - if (NEIServerUtils.areStacksSameTypeCrafting(recipe.empty, ingred)) { - this.arecipes.add(new CachedBottlerRecipe(recipe)); - } - } - } - - @Override - public void loadUsageRecipes(FluidStack ingred) { - for (BottlerRecipe recipe : recipes) { - if (NEIUtils.areFluidsSameType(recipe.input, ingred)) { - this.arecipes.add(new CachedBottlerRecipe(recipe)); - } - } - } + @Override + public void loadUsageRecipes(ItemStack ingred) { + for (BottlerRecipe recipe : recipes) { + if (NEIServerUtils.areStacksSameTypeCrafting(recipe.empty, ingred)) { + this.arecipes.add(new CachedBottlerRecipe(recipe)); + } + } + } + @Override + public void loadUsageRecipes(FluidStack ingred) { + for (BottlerRecipe recipe : recipes) { + if (NEIUtils.areFluidsSameType(recipe.input, ingred)) { + this.arecipes.add(new CachedBottlerRecipe(recipe)); + } + } + } } diff --git a/src/main/java/forestry/factory/recipes/nei/NEIHandlerCarpenter.java b/src/main/java/forestry/factory/recipes/nei/NEIHandlerCarpenter.java index b81cbe505..de7189975 100644 --- a/src/main/java/forestry/factory/recipes/nei/NEIHandlerCarpenter.java +++ b/src/main/java/forestry/factory/recipes/nei/NEIHandlerCarpenter.java @@ -10,17 +10,10 @@ ******************************************************************************/ package forestry.factory.recipes.nei; -import java.awt.Point; -import java.awt.Rectangle; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.StatCollector; - -import net.minecraftforge.fluids.FluidStack; - +import codechicken.lib.gui.GuiDraw; +import codechicken.nei.NEIServerUtils; +import codechicken.nei.PositionedStack; +import codechicken.nei.api.API; import forestry.api.recipes.ICarpenterRecipe; import forestry.api.recipes.IDescriptiveRecipe; import forestry.api.recipes.RecipeManagers; @@ -28,168 +21,176 @@ import forestry.core.recipes.nei.NEIUtils; import forestry.core.recipes.nei.PositionedFluidTank; import forestry.core.recipes.nei.RecipeHandlerBase; import forestry.factory.gui.GuiCarpenter; - -import codechicken.lib.gui.GuiDraw; -import codechicken.nei.NEIServerUtils; -import codechicken.nei.PositionedStack; -import codechicken.nei.api.API; +import java.awt.Point; +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.StatCollector; +import net.minecraftforge.fluids.FluidStack; public class NEIHandlerCarpenter extends RecipeHandlerBase { - private static Class guiClass; + private static Class guiClass; - @Override - public void prepare() { - guiClass = GuiCarpenter.class; - API.setGuiOffset(guiClass, 5, 14); - } + @Override + public void prepare() { + guiClass = GuiCarpenter.class; + API.setGuiOffset(guiClass, 5, 14); + } - public class CachedCarpenterRecipe extends CachedBaseRecipe { + public class CachedCarpenterRecipe extends CachedBaseRecipe { - public List inputs = new ArrayList<>(); - public PositionedFluidTank tank; - public PositionedStack output; + public List inputs = new ArrayList<>(); + public PositionedFluidTank tank; + public PositionedStack output; - public CachedCarpenterRecipe(ICarpenterRecipe recipe, boolean genPerms) { - IDescriptiveRecipe irecipe = recipe.getCraftingGridRecipe(); - if (irecipe != null) { - if (irecipe.getIngredients() != null) { - this.setIngredients(irecipe.getWidth(), irecipe.getHeight(), irecipe.getIngredients()); - } - if (recipe.getBox() != null) { - this.inputs.add(new PositionedStack(recipe.getBox(), 78, 6)); - } - if (recipe.getFluidResource() != null) { - this.tank = new PositionedFluidTank(recipe.getFluidResource(), 10000, new Rectangle(145, 3, 16, 58), NEIHandlerCarpenter.this.getGuiTexture(), new Point(176, 0)); - } - if (recipe.getCraftingGridRecipe().getRecipeOutput() != null) { - this.output = new PositionedStack(recipe.getCraftingGridRecipe().getRecipeOutput(), 75, 37); - } - } + public CachedCarpenterRecipe(ICarpenterRecipe recipe, boolean genPerms) { + IDescriptiveRecipe irecipe = recipe.getCraftingGridRecipe(); + if (irecipe != null) { + if (irecipe.getIngredients() != null) { + this.setIngredients(irecipe.getWidth(), irecipe.getHeight(), irecipe.getIngredients()); + } + if (recipe.getBox() != null) { + this.inputs.add(new PositionedStack(recipe.getBox(), 78, 6)); + } + if (recipe.getFluidResource() != null) { + this.tank = new PositionedFluidTank( + recipe.getFluidResource(), + 10000, + new Rectangle(145, 3, 16, 58), + NEIHandlerCarpenter.this.getGuiTexture(), + new Point(176, 0)); + } + if (recipe.getCraftingGridRecipe().getRecipeOutput() != null) { + this.output = + new PositionedStack(recipe.getCraftingGridRecipe().getRecipeOutput(), 75, 37); + } + } - if (genPerms) { - this.generatePermutations(); - } - } + if (genPerms) { + this.generatePermutations(); + } + } - public CachedCarpenterRecipe(ICarpenterRecipe recipe) { - this(recipe, false); - } + public CachedCarpenterRecipe(ICarpenterRecipe recipe) { + this(recipe, false); + } - public void setIngredients(int width, int height, Object[] items) { - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - Object item = items[y * width + x]; - if (item == null) { - continue; - } else if (item instanceof ItemStack[] && ((ItemStack[]) item).length == 0) { - continue; - } else if (item instanceof List && ((List) item).size() == 0) { - continue; - } + public void setIngredients(int width, int height, Object[] items) { + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + Object item = items[y * width + x]; + if (item == null) { + continue; + } else if (item instanceof ItemStack[] && ((ItemStack[]) item).length == 0) { + continue; + } else if (item instanceof List && ((List) item).size() == 0) { + continue; + } - PositionedStack stack = new PositionedStack(item, 5 + x * 18, 6 + y * 18, false); - stack.setMaxSize(1); - this.inputs.add(stack); - } - } - } + PositionedStack stack = new PositionedStack(item, 5 + x * 18, 6 + y * 18, false); + stack.setMaxSize(1); + this.inputs.add(stack); + } + } + } - @Override - public List getIngredients() { - return this.getCycledIngredients(NEIHandlerCarpenter.this.cycleticks / 20, this.inputs); - } + @Override + public List getIngredients() { + return this.getCycledIngredients(NEIHandlerCarpenter.this.cycleticks / 20, this.inputs); + } - @Override - public PositionedFluidTank getFluidTank() { - return this.tank; - } + @Override + public PositionedFluidTank getFluidTank() { + return this.tank; + } - @Override - public PositionedStack getResult() { - return this.output; - } + @Override + public PositionedStack getResult() { + return this.output; + } - public void generatePermutations() { - for (PositionedStack p : this.inputs) { - p.generatePermutations(); - } - } + public void generatePermutations() { + for (PositionedStack p : this.inputs) { + p.generatePermutations(); + } + } + } - } + @Override + public String getRecipeID() { + return "forestry.carpenter"; + } - @Override - public String getRecipeID() { - return "forestry.carpenter"; - } + @Override + public String getRecipeName() { + return StatCollector.translateToLocal("tile.for.factory.1.name"); + } - @Override - public String getRecipeName() { - return StatCollector.translateToLocal("tile.for.factory.1.name"); - } + @Override + public String getGuiTexture() { + return "forestry:textures/gui/carpenter.png"; + } - @Override - public String getGuiTexture() { - return "forestry:textures/gui/carpenter.png"; - } + @Override + public void loadTransferRects() { + this.addTransferRect(93, 36, 4, 18); + } - @Override - public void loadTransferRects() { - this.addTransferRect(93, 36, 4, 18); - } + @Override + public Class getGuiClass() { + return guiClass; + } - @Override - public Class getGuiClass() { - return guiClass; - } + @Override + public void drawBackground(int recipe) { + this.changeToGuiTexture(); + GuiDraw.drawTexturedModalRect(0, 0, 5, 14, 166, 65); + } - @Override - public void drawBackground(int recipe) { - this.changeToGuiTexture(); - GuiDraw.drawTexturedModalRect(0, 0, 5, 14, 166, 65); - } + @Override + public void drawExtras(int recipe) { + this.drawProgressBar(93, 36, 176, 59, 4, 17, 80, 3); + } - @Override - public void drawExtras(int recipe) { - this.drawProgressBar(93, 36, 176, 59, 4, 17, 80, 3); - } + @Override + public void loadAllRecipes() { + for (ICarpenterRecipe recipe : RecipeManagers.carpenterManager.recipes()) { + this.arecipes.add(new CachedCarpenterRecipe(recipe, true)); + } + } - @Override - public void loadAllRecipes() { - for (ICarpenterRecipe recipe : RecipeManagers.carpenterManager.recipes()) { - this.arecipes.add(new CachedCarpenterRecipe(recipe, true)); - } - } + @Override + public void loadCraftingRecipes(ItemStack result) { + for (ICarpenterRecipe recipe : RecipeManagers.carpenterManager.recipes()) { + if (NEIServerUtils.areStacksSameTypeCrafting( + recipe.getCraftingGridRecipe().getRecipeOutput(), result)) { + this.arecipes.add(new CachedCarpenterRecipe(recipe, true)); + } + } + } - @Override - public void loadCraftingRecipes(ItemStack result) { - for (ICarpenterRecipe recipe : RecipeManagers.carpenterManager.recipes()) { - if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getCraftingGridRecipe().getRecipeOutput(), result)) { - this.arecipes.add(new CachedCarpenterRecipe(recipe, true)); - } - } - } - - @Override - public void loadUsageRecipes(ItemStack ingred) { - super.loadUsageRecipes(ingred); - for (ICarpenterRecipe recipe : RecipeManagers.carpenterManager.recipes()) { - CachedCarpenterRecipe crecipe = new CachedCarpenterRecipe(recipe); - if (crecipe.inputs != null && crecipe.contains(crecipe.inputs, ingred)) { - crecipe.generatePermutations(); - crecipe.setIngredientPermutation(crecipe.inputs, ingred); - this.arecipes.add(crecipe); - } - } - } - - @Override - public void loadUsageRecipes(FluidStack ingredient) { - for (ICarpenterRecipe recipe : RecipeManagers.carpenterManager.recipes()) { - if (NEIUtils.areFluidsSameType(recipe.getFluidResource(), ingredient)) { - this.arecipes.add(new CachedCarpenterRecipe(recipe, true)); - } - } - } + @Override + public void loadUsageRecipes(ItemStack ingred) { + super.loadUsageRecipes(ingred); + for (ICarpenterRecipe recipe : RecipeManagers.carpenterManager.recipes()) { + CachedCarpenterRecipe crecipe = new CachedCarpenterRecipe(recipe); + if (crecipe.inputs != null && crecipe.contains(crecipe.inputs, ingred)) { + crecipe.generatePermutations(); + crecipe.setIngredientPermutation(crecipe.inputs, ingred); + this.arecipes.add(crecipe); + } + } + } + @Override + public void loadUsageRecipes(FluidStack ingredient) { + for (ICarpenterRecipe recipe : RecipeManagers.carpenterManager.recipes()) { + if (NEIUtils.areFluidsSameType(recipe.getFluidResource(), ingredient)) { + this.arecipes.add(new CachedCarpenterRecipe(recipe, true)); + } + } + } } diff --git a/src/main/java/forestry/factory/recipes/nei/NEIHandlerCentrifuge.java b/src/main/java/forestry/factory/recipes/nei/NEIHandlerCentrifuge.java index 0701a41ff..2bbde9368 100644 --- a/src/main/java/forestry/factory/recipes/nei/NEIHandlerCentrifuge.java +++ b/src/main/java/forestry/factory/recipes/nei/NEIHandlerCentrifuge.java @@ -10,6 +10,13 @@ ******************************************************************************/ package forestry.factory.recipes.nei; +import codechicken.nei.NEIServerUtils; +import codechicken.nei.PositionedStack; +import forestry.api.recipes.ICentrifugeRecipe; +import forestry.api.recipes.RecipeManagers; +import forestry.core.recipes.nei.PositionedStackAdv; +import forestry.core.recipes.nei.RecipeHandlerBase; +import forestry.factory.gui.GuiCentrifuge; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -17,144 +24,136 @@ import java.util.Map; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Set; - import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; -import forestry.api.recipes.ICentrifugeRecipe; -import forestry.api.recipes.RecipeManagers; -import forestry.core.recipes.nei.PositionedStackAdv; -import forestry.core.recipes.nei.RecipeHandlerBase; -import forestry.factory.gui.GuiCentrifuge; - -import codechicken.nei.NEIServerUtils; -import codechicken.nei.PositionedStack; - public class NEIHandlerCentrifuge extends RecipeHandlerBase { - private static final int[][] OUTPUTS = new int[][]{{0, 0}, {1, 0}, {2, 0}, {0, 1}, {1, 1}, {2, 1}, {0, 2}, {1, 2}, {2, 2}}; + private static final int[][] OUTPUTS = + new int[][] {{0, 0}, {1, 0}, {2, 0}, {0, 1}, {1, 1}, {2, 1}, {0, 2}, {1, 2}, {2, 2}}; - private static final Comparator> highestChanceComparator = new Comparator>() { - @Override - public int compare(Entry o1, Entry o2) { - return o2.getValue().compareTo(o1.getValue()); - } - }; + private static final Comparator> highestChanceComparator = + new Comparator>() { + @Override + public int compare(Entry o1, Entry o2) { + return o2.getValue().compareTo(o1.getValue()); + } + }; - public class CachedCentrifugeRecipe extends CachedBaseRecipe { + public class CachedCentrifugeRecipe extends CachedBaseRecipe { - public PositionedStack inputs; - public List outputs = new ArrayList<>(); + public PositionedStack inputs; + public List outputs = new ArrayList<>(); - public CachedCentrifugeRecipe(ICentrifugeRecipe recipe, boolean genPerms) { - if (recipe.getInput() != null) { - this.inputs = new PositionedStack(recipe.getInput(), 25, 26); - } - if (recipe.getAllProducts() != null) { - this.setResults(recipe.getAllProducts()); - } - } + public CachedCentrifugeRecipe(ICentrifugeRecipe recipe, boolean genPerms) { + if (recipe.getInput() != null) { + this.inputs = new PositionedStack(recipe.getInput(), 25, 26); + } + if (recipe.getAllProducts() != null) { + this.setResults(recipe.getAllProducts()); + } + } - public CachedCentrifugeRecipe(ICentrifugeRecipe recipe) { - this(recipe, false); - } + public CachedCentrifugeRecipe(ICentrifugeRecipe recipe) { + this(recipe, false); + } - public void setResults(Map outputs) { - Set> entrySet = outputs.entrySet(); - if (entrySet.size() == 0) { - return; - } - PriorityQueue> sortByChance = new PriorityQueue<>(entrySet.size(), highestChanceComparator); - sortByChance.addAll(entrySet); + public void setResults(Map outputs) { + Set> entrySet = outputs.entrySet(); + if (entrySet.size() == 0) { + return; + } + PriorityQueue> sortByChance = + new PriorityQueue<>(entrySet.size(), highestChanceComparator); + sortByChance.addAll(entrySet); - int i = 0; - while (!sortByChance.isEmpty()) { - Entry stack = sortByChance.poll(); - if (i >= OUTPUTS.length) { - return; - } - PositionedStackAdv output = new PositionedStackAdv(stack.getKey(), 93 + OUTPUTS[i][0] * 18, 8 + OUTPUTS[i][1] * 18); - output.setChance(stack.getValue()); - this.outputs.add(output); - i++; - } - } + int i = 0; + while (!sortByChance.isEmpty()) { + Entry stack = sortByChance.poll(); + if (i >= OUTPUTS.length) { + return; + } + PositionedStackAdv output = + new PositionedStackAdv(stack.getKey(), 93 + OUTPUTS[i][0] * 18, 8 + OUTPUTS[i][1] * 18); + output.setChance(stack.getValue()); + this.outputs.add(output); + i++; + } + } - @Override - public PositionedStack getIngredient() { - this.randomRenderPermutation(this.inputs, NEIHandlerCentrifuge.this.cycleticks / 20); - return this.inputs; - } + @Override + public PositionedStack getIngredient() { + this.randomRenderPermutation(this.inputs, NEIHandlerCentrifuge.this.cycleticks / 20); + return this.inputs; + } - @Override - public List getOtherStacks() { - return this.outputs; - } + @Override + public List getOtherStacks() { + return this.outputs; + } - @Override - public PositionedStack getResult() { - return null; - } + @Override + public PositionedStack getResult() { + return null; + } + } - } + @Override + public String getRecipeID() { + return "forestry.centrifuge"; + } - @Override - public String getRecipeID() { - return "forestry.centrifuge"; - } + @Override + public String getRecipeName() { + return StatCollector.translateToLocal("tile.for.factory.2.name"); + } - @Override - public String getRecipeName() { - return StatCollector.translateToLocal("tile.for.factory.2.name"); - } + @Override + public String getGuiTexture() { + return "forestry:textures/gui/centrifugesocket.png"; + } - @Override - public String getGuiTexture() { - return "forestry:textures/gui/centrifugesocket.png"; - } + @Override + public void loadTransferRects() { + this.addTransferRect(57 - 12, 26 - 8, 16, 24 + 6 + 6); + } - @Override - public void loadTransferRects() { - this.addTransferRect(57 - 12, 26 - 8, 16, 24 + 6 + 6); - } + @Override + public Class getGuiClass() { + return GuiCentrifuge.class; + } - @Override - public Class getGuiClass() { - return GuiCentrifuge.class; - } + @Override + public void drawExtras(int recipe) { + this.drawProgressBar(57 - 4, 25, 176, 0, 4, 17, 80, 3); + } - @Override - public void drawExtras(int recipe) { - this.drawProgressBar(57 - 4, 25, 176, 0, 4, 17, 80, 3); - } + @Override + public void loadAllRecipes() { + for (ICentrifugeRecipe recipe : RecipeManagers.centrifugeManager.recipes()) { + this.arecipes.add(new CachedCentrifugeRecipe(recipe, true)); + } + } - @Override - public void loadAllRecipes() { - for (ICentrifugeRecipe recipe : RecipeManagers.centrifugeManager.recipes()) { - this.arecipes.add(new CachedCentrifugeRecipe(recipe, true)); - } - } - - @Override - public void loadCraftingRecipes(ItemStack result) { - for (ICentrifugeRecipe recipe : RecipeManagers.centrifugeManager.recipes()) { - CachedCentrifugeRecipe crecipe = new CachedCentrifugeRecipe(recipe); - if (crecipe.outputs != null && crecipe.contains(crecipe.outputs, result)) { - crecipe.setIngredientPermutation(crecipe.outputs, result); - this.arecipes.add(crecipe); - } - } - } - - @Override - public void loadUsageRecipes(ItemStack ingred) { - super.loadCraftingRecipes(ingred); - for (ICentrifugeRecipe recipe : RecipeManagers.centrifugeManager.recipes()) { - if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getInput(), ingred)) { - this.arecipes.add(new CachedCentrifugeRecipe(recipe, true)); - } - } - } + @Override + public void loadCraftingRecipes(ItemStack result) { + for (ICentrifugeRecipe recipe : RecipeManagers.centrifugeManager.recipes()) { + CachedCentrifugeRecipe crecipe = new CachedCentrifugeRecipe(recipe); + if (crecipe.outputs != null && crecipe.contains(crecipe.outputs, result)) { + crecipe.setIngredientPermutation(crecipe.outputs, result); + this.arecipes.add(crecipe); + } + } + } + @Override + public void loadUsageRecipes(ItemStack ingred) { + super.loadCraftingRecipes(ingred); + for (ICentrifugeRecipe recipe : RecipeManagers.centrifugeManager.recipes()) { + if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getInput(), ingred)) { + this.arecipes.add(new CachedCentrifugeRecipe(recipe, true)); + } + } + } } diff --git a/src/main/java/forestry/factory/recipes/nei/NEIHandlerFabricator.java b/src/main/java/forestry/factory/recipes/nei/NEIHandlerFabricator.java index 0c2e5c877..65ca03a7f 100644 --- a/src/main/java/forestry/factory/recipes/nei/NEIHandlerFabricator.java +++ b/src/main/java/forestry/factory/recipes/nei/NEIHandlerFabricator.java @@ -10,21 +10,9 @@ ******************************************************************************/ package forestry.factory.recipes.nei; -import java.awt.Point; -import java.awt.Rectangle; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.StatCollector; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; - +import codechicken.nei.NEIServerUtils; +import codechicken.nei.PositionedStack; +import codechicken.nei.recipe.GuiRecipe; import forestry.api.recipes.IFabricatorRecipe; import forestry.api.recipes.IFabricatorSmeltingRecipe; import forestry.api.recipes.RecipeManagers; @@ -33,199 +21,214 @@ import forestry.core.recipes.nei.PositionedFluidTank; import forestry.core.recipes.nei.RecipeHandlerBase; import forestry.factory.gui.GuiFabricator; import forestry.factory.recipes.FabricatorSmeltingRecipeManager; - -import codechicken.nei.NEIServerUtils; -import codechicken.nei.PositionedStack; -import codechicken.nei.recipe.GuiRecipe; +import java.awt.Point; +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.StatCollector; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; public class NEIHandlerFabricator extends RecipeHandlerBase { - public class CachedFabricatorRecipe extends CachedBaseRecipe { - public List smeltingInput = new ArrayList<>(); - public PositionedFluidTank tank; - public List inputs = new ArrayList<>(); - public PositionedStack output; + public class CachedFabricatorRecipe extends CachedBaseRecipe { + public List smeltingInput = new ArrayList<>(); + public PositionedFluidTank tank; + public List inputs = new ArrayList<>(); + public PositionedStack output; - public CachedFabricatorRecipe(IFabricatorRecipe recipe, boolean genPerms) { - if (recipe.getLiquid() != null) { - this.tank = new PositionedFluidTank(recipe.getLiquid(), 2000, new Rectangle(21, 37, 16, 16)); - List smeltingInput = new ArrayList<>(); - for (IFabricatorSmeltingRecipe s : getSmeltingInputs().get(recipe.getLiquid().getFluid())) { - smeltingInput.add(s.getResource()); - } - if (!smeltingInput.isEmpty()) { - this.smeltingInput.add(new PositionedStack(smeltingInput, 21, 10)); - } - } + public CachedFabricatorRecipe(IFabricatorRecipe recipe, boolean genPerms) { + if (recipe.getLiquid() != null) { + this.tank = new PositionedFluidTank(recipe.getLiquid(), 2000, new Rectangle(21, 37, 16, 16)); + List smeltingInput = new ArrayList<>(); + for (IFabricatorSmeltingRecipe s : + getSmeltingInputs().get(recipe.getLiquid().getFluid())) { + smeltingInput.add(s.getResource()); + } + if (!smeltingInput.isEmpty()) { + this.smeltingInput.add(new PositionedStack(smeltingInput, 21, 10)); + } + } - if (recipe != null) { - if (recipe.getIngredients() != null) { - this.setIngredients(recipe.getWidth(), recipe.getHeight(), recipe.getIngredients()); - } - if (recipe.getPlan() != null) { - this.inputs.add(new PositionedStack(recipe.getPlan(), 134, 6)); - } + if (recipe != null) { + if (recipe.getIngredients() != null) { + this.setIngredients(recipe.getWidth(), recipe.getHeight(), recipe.getIngredients()); + } + if (recipe.getPlan() != null) { + this.inputs.add(new PositionedStack(recipe.getPlan(), 134, 6)); + } - if (recipe.getRecipeOutput() != null) { - this.output = new PositionedStack(recipe.getRecipeOutput(), 134, 42); - } - } + if (recipe.getRecipeOutput() != null) { + this.output = new PositionedStack(recipe.getRecipeOutput(), 134, 42); + } + } - if (genPerms) { - this.generatePermutations(); - } - } + if (genPerms) { + this.generatePermutations(); + } + } - public CachedFabricatorRecipe(IFabricatorRecipe recipe) { - this(recipe, false); - } + public CachedFabricatorRecipe(IFabricatorRecipe recipe) { + this(recipe, false); + } - public void setIngredients(int width, int height, Object[] items) { - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - Object item = items[y * width + x]; - if (item == null) { - continue; - } else if (item instanceof ItemStack[] && ((ItemStack[]) item).length == 0) { - continue; - } else if (item instanceof List && ((List) item).size() == 0) { - continue; - } + public void setIngredients(int width, int height, Object[] items) { + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + Object item = items[y * width + x]; + if (item == null) { + continue; + } else if (item instanceof ItemStack[] && ((ItemStack[]) item).length == 0) { + continue; + } else if (item instanceof List && ((List) item).size() == 0) { + continue; + } - PositionedStack stack = new PositionedStack(item, 62 + x * 18, 6 + y * 18, false); - stack.setMaxSize(1); - this.inputs.add(stack); - } - } - } + PositionedStack stack = new PositionedStack(item, 62 + x * 18, 6 + y * 18, false); + stack.setMaxSize(1); + this.inputs.add(stack); + } + } + } - @Override - public PositionedStack getResult() { - return this.output; - } + @Override + public PositionedStack getResult() { + return this.output; + } - @Override - public List getOtherStacks() { - return super.getCycledIngredients(NEIHandlerFabricator.this.cycleticks / 40, this.smeltingInput); - } + @Override + public List getOtherStacks() { + return super.getCycledIngredients(NEIHandlerFabricator.this.cycleticks / 40, this.smeltingInput); + } - @Override - public List getIngredients() { - return getCycledIngredients(NEIHandlerFabricator.this.cycleticks / 20, this.inputs); - } + @Override + public List getIngredients() { + return getCycledIngredients(NEIHandlerFabricator.this.cycleticks / 20, this.inputs); + } - @Override - public PositionedFluidTank getFluidTank() { - return this.tank; - } + @Override + public PositionedFluidTank getFluidTank() { + return this.tank; + } - public void generatePermutations() { - for (PositionedStack p : this.inputs) { - p.generatePermutations(); - } - } + public void generatePermutations() { + for (PositionedStack p : this.inputs) { + p.generatePermutations(); + } + } + } - } + @Override + public List getIngredientStacks(int recipe) { + return arecipes.get(recipe).getIngredients(); + } - @Override - public List getIngredientStacks(int recipe) { - return arecipes.get(recipe).getIngredients(); - } + @Override + public PositionedStack getResultStack(int recipe) { + return arecipes.get(recipe).getResult(); + } - @Override - public PositionedStack getResultStack(int recipe) { - return arecipes.get(recipe).getResult(); - } + @Override + public String getRecipeID() { + return "forestry.fabricator"; + } - @Override - public String getRecipeID() { - return "forestry.fabricator"; - } + @Override + public String getRecipeName() { + return StatCollector.translateToLocal("tile.for.factory2.0.name"); + } - @Override - public String getRecipeName() { - return StatCollector.translateToLocal("tile.for.factory2.0.name"); - } + @Override + public String getGuiTexture() { + return "forestry:textures/gui/fabricator.png"; + } - @Override - public String getGuiTexture() { - return "forestry:textures/gui/fabricator.png"; - } + @Override + public void loadTransferRects() { + this.addTransferRect(117, 44, 14, 13); + } - @Override - public void loadTransferRects() { - this.addTransferRect(117, 44, 14, 13); - } + @Override + public Class getGuiClass() { + return GuiFabricator.class; + } - @Override - public Class getGuiClass() { - return GuiFabricator.class; - } + @Override + public void loadAllRecipes() { + for (IFabricatorRecipe recipe : RecipeManagers.fabricatorManager.recipes()) { + this.arecipes.add(new CachedFabricatorRecipe(recipe, true)); + } + } - @Override - public void loadAllRecipes() { - for (IFabricatorRecipe recipe : RecipeManagers.fabricatorManager.recipes()) { - this.arecipes.add(new CachedFabricatorRecipe(recipe, true)); - } - } + @Override + public void loadCraftingRecipes(ItemStack result) { + for (IFabricatorRecipe recipe : RecipeManagers.fabricatorManager.recipes()) { + if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getRecipeOutput(), result)) { + CachedFabricatorRecipe crecipe = new CachedFabricatorRecipe(recipe, true); + this.arecipes.add(crecipe); + } + } + } - @Override - public void loadCraftingRecipes(ItemStack result) { - for (IFabricatorRecipe recipe : RecipeManagers.fabricatorManager.recipes()) { - if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getRecipeOutput(), result)) { - CachedFabricatorRecipe crecipe = new CachedFabricatorRecipe(recipe, true); - this.arecipes.add(crecipe); - } - } - } + @Override + public void loadUsageRecipes(ItemStack ingred) { + super.loadUsageRecipes(ingred); + for (IFabricatorRecipe recipe : RecipeManagers.fabricatorManager.recipes()) { + CachedFabricatorRecipe crecipe = new CachedFabricatorRecipe(recipe); + if (crecipe.inputs != null && crecipe.contains(crecipe.inputs, ingred) + || crecipe.smeltingInput != null && crecipe.contains(crecipe.smeltingInput, ingred)) { + crecipe.generatePermutations(); + crecipe.setIngredientPermutation(crecipe.smeltingInput, ingred); + this.arecipes.add(crecipe); + } + } + } - @Override - public void loadUsageRecipes(ItemStack ingred) { - super.loadUsageRecipes(ingred); - for (IFabricatorRecipe recipe : RecipeManagers.fabricatorManager.recipes()) { - CachedFabricatorRecipe crecipe = new CachedFabricatorRecipe(recipe); - if (crecipe.inputs != null && crecipe.contains(crecipe.inputs, ingred) || crecipe.smeltingInput != null && crecipe.contains(crecipe.smeltingInput, ingred)) { - crecipe.generatePermutations(); - crecipe.setIngredientPermutation(crecipe.smeltingInput, ingred); - this.arecipes.add(crecipe); - } - } - } + @Override + public void loadUsageRecipes(FluidStack ingredient) { + for (IFabricatorRecipe recipe : RecipeManagers.fabricatorManager.recipes()) { + if (NEIUtils.areFluidsSameType(recipe.getLiquid(), ingredient)) { + this.arecipes.add(new CachedFabricatorRecipe(recipe, true)); + } + } + } - @Override - public void loadUsageRecipes(FluidStack ingredient) { - for (IFabricatorRecipe recipe : RecipeManagers.fabricatorManager.recipes()) { - if (NEIUtils.areFluidsSameType(recipe.getLiquid(), ingredient)) { - this.arecipes.add(new CachedFabricatorRecipe(recipe, true)); - } - } - } + @Override + public List provideItemTooltip( + GuiRecipe guiRecipe, + ItemStack itemStack, + List currenttip, + CachedBaseRecipe crecipe, + Point relMouse) { + super.provideItemTooltip(guiRecipe, itemStack, currenttip, crecipe, relMouse); - @Override - public List provideItemTooltip(GuiRecipe guiRecipe, ItemStack itemStack, List currenttip, CachedBaseRecipe crecipe, Point relMouse) { - super.provideItemTooltip(guiRecipe, itemStack, currenttip, crecipe, relMouse); + if (new Rectangle(20, 9, 18, 18).contains(relMouse)) { + for (IFabricatorSmeltingRecipe smelting : FabricatorSmeltingRecipeManager.recipes) { + if (NEIServerUtils.areStacksSameTypeCrafting(smelting.getResource(), itemStack) + && smelting.getProduct() != null) { + currenttip.add(EnumChatFormatting.GRAY + NEIUtils.translate("handler.forestry.fabricator.worth") + + " " + smelting.getProduct().amount + " mB"); + } + } + } - if (new Rectangle(20, 9, 18, 18).contains(relMouse)) { - for (IFabricatorSmeltingRecipe smelting : FabricatorSmeltingRecipeManager.recipes) { - if (NEIServerUtils.areStacksSameTypeCrafting(smelting.getResource(), itemStack) && smelting.getProduct() != null) { - currenttip.add(EnumChatFormatting.GRAY + NEIUtils.translate("handler.forestry.fabricator.worth") + " " + smelting.getProduct().amount + " mB"); - } - } - } - - return currenttip; - } - - private static Map> getSmeltingInputs() { - Map> smeltingInputs = new HashMap<>(); - for (IFabricatorSmeltingRecipe smelting : FabricatorSmeltingRecipeManager.recipes) { - Fluid fluid = smelting.getProduct().getFluid(); - if (!smeltingInputs.containsKey(fluid)) { - smeltingInputs.put(fluid, new ArrayList()); - } - smeltingInputs.get(fluid).add(smelting); - } - return smeltingInputs; - } + return currenttip; + } + private static Map> getSmeltingInputs() { + Map> smeltingInputs = new HashMap<>(); + for (IFabricatorSmeltingRecipe smelting : FabricatorSmeltingRecipeManager.recipes) { + Fluid fluid = smelting.getProduct().getFluid(); + if (!smeltingInputs.containsKey(fluid)) { + smeltingInputs.put(fluid, new ArrayList()); + } + smeltingInputs.get(fluid).add(smelting); + } + return smeltingInputs; + } } diff --git a/src/main/java/forestry/factory/recipes/nei/NEIHandlerFermenter.java b/src/main/java/forestry/factory/recipes/nei/NEIHandlerFermenter.java index 9c93073a9..a7cb3319b 100644 --- a/src/main/java/forestry/factory/recipes/nei/NEIHandlerFermenter.java +++ b/src/main/java/forestry/factory/recipes/nei/NEIHandlerFermenter.java @@ -10,18 +10,10 @@ ******************************************************************************/ package forestry.factory.recipes.nei; -import java.awt.Point; -import java.awt.Rectangle; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.StatCollector; - -import net.minecraftforge.fluids.FluidStack; - +import codechicken.lib.gui.GuiDraw; +import codechicken.nei.NEIServerUtils; +import codechicken.nei.PositionedStack; +import codechicken.nei.api.API; import forestry.api.fuels.FermenterFuel; import forestry.api.fuels.FuelManager; import forestry.api.recipes.IFermenterRecipe; @@ -32,173 +24,186 @@ import forestry.core.recipes.nei.NEIUtils; import forestry.core.recipes.nei.PositionedFluidTank; import forestry.core.recipes.nei.RecipeHandlerBase; import forestry.factory.gui.GuiFermenter; - -import codechicken.lib.gui.GuiDraw; -import codechicken.nei.NEIServerUtils; -import codechicken.nei.PositionedStack; -import codechicken.nei.api.API; +import java.awt.Point; +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.StatCollector; +import net.minecraftforge.fluids.FluidStack; public class NEIHandlerFermenter extends RecipeHandlerBase { - private static Class guiClass; + private static Class guiClass; - @Override - public void prepare() { - guiClass = GuiFermenter.class; - API.setGuiOffset(guiClass, 5, 15); - } + @Override + public void prepare() { + guiClass = GuiFermenter.class; + API.setGuiOffset(guiClass, 5, 15); + } - public class CachedFermenterRecipe extends CachedBaseRecipe { + public class CachedFermenterRecipe extends CachedBaseRecipe { - public List tanks = new ArrayList<>(); - public PositionedStack resource; - public List inputItems = new ArrayList<>(); + public List tanks = new ArrayList<>(); + public PositionedStack resource; + public List inputItems = new ArrayList<>(); - public CachedFermenterRecipe(IFermenterRecipe recipe, ItemStack fermentable, boolean genPerms) { - if (recipe.getFluidResource() != null) { - FluidStack input = recipe.getFluidResource().copy(); - input.amount = recipe.getFermentationValue(); - this.tanks.add(new PositionedFluidTank(input, 10000, new Rectangle(30, 4, 16, 58), NEIHandlerFermenter.this.getGuiTexture(), new Point(176, 0))); - } - if (recipe.getOutput() != null) { - int amount = Math.round(recipe.getFermentationValue() * recipe.getModifier()); - if (fermentable.getItem() instanceof IVariableFermentable) { - amount *= ((IVariableFermentable) fermentable.getItem()).getFermentationModifier(fermentable); - } - FluidStack output = new FluidStack(recipe.getOutput(), amount); - this.tanks.add(new PositionedFluidTank(output, 10000, new Rectangle(120, 4, 16, 58), NEIHandlerFermenter.this.getGuiTexture(), new Point(176, 0))); - } + public CachedFermenterRecipe(IFermenterRecipe recipe, ItemStack fermentable, boolean genPerms) { + if (recipe.getFluidResource() != null) { + FluidStack input = recipe.getFluidResource().copy(); + input.amount = recipe.getFermentationValue(); + this.tanks.add(new PositionedFluidTank( + input, + 10000, + new Rectangle(30, 4, 16, 58), + NEIHandlerFermenter.this.getGuiTexture(), + new Point(176, 0))); + } + if (recipe.getOutput() != null) { + int amount = Math.round(recipe.getFermentationValue() * recipe.getModifier()); + if (fermentable.getItem() instanceof IVariableFermentable) { + amount *= ((IVariableFermentable) fermentable.getItem()).getFermentationModifier(fermentable); + } + FluidStack output = new FluidStack(recipe.getOutput(), amount); + this.tanks.add(new PositionedFluidTank( + output, + 10000, + new Rectangle(120, 4, 16, 58), + NEIHandlerFermenter.this.getGuiTexture(), + new Point(176, 0))); + } - this.inputItems.add(new PositionedStack(fermentable, 80, 8)); - List fuels = new ArrayList<>(); - for (FermenterFuel fuel : FuelManager.fermenterFuel.values()) { - fuels.add(fuel.item); - } - this.inputItems.add(new PositionedStack(fuels, 70, 42)); + this.inputItems.add(new PositionedStack(fermentable, 80, 8)); + List fuels = new ArrayList<>(); + for (FermenterFuel fuel : FuelManager.fermenterFuel.values()) { + fuels.add(fuel.item); + } + this.inputItems.add(new PositionedStack(fuels, 70, 42)); - if (genPerms) { - this.generatePermutations(); - } - } + if (genPerms) { + this.generatePermutations(); + } + } - @Override - public List getIngredients() { - return this.getCycledIngredients(NEIHandlerFermenter.this.cycleticks / 40, this.inputItems); - } + @Override + public List getIngredients() { + return this.getCycledIngredients(NEIHandlerFermenter.this.cycleticks / 40, this.inputItems); + } - @Override - public PositionedStack getResult() { - return null; - } + @Override + public PositionedStack getResult() { + return null; + } - @Override - public List getFluidTanks() { - return this.tanks; - } + @Override + public List getFluidTanks() { + return this.tanks; + } - public void generatePermutations() { - for (PositionedStack p : this.inputItems) { - p.generatePermutations(); - } - } + public void generatePermutations() { + for (PositionedStack p : this.inputItems) { + p.generatePermutations(); + } + } + } - } + @Override + public String getRecipeID() { + return "forestry.fermenter"; + } - @Override - public String getRecipeID() { - return "forestry.fermenter"; - } + @Override + public String getRecipeName() { + return StatCollector.translateToLocal("tile.for.factory.3.name"); + } - @Override - public String getRecipeName() { - return StatCollector.translateToLocal("tile.for.factory.3.name"); - } + @Override + public String getGuiTexture() { + return "forestry:textures/gui/fermenter.png"; + } - @Override - public String getGuiTexture() { - return "forestry:textures/gui/fermenter.png"; - } + @Override + public void loadTransferRects() { + this.addTransferRect(76, 27, 14, 12); + } - @Override - public void loadTransferRects() { - this.addTransferRect(76, 27, 14, 12); - } + @Override + public Class getGuiClass() { + return guiClass; + } - @Override - public Class getGuiClass() { - return guiClass; - } + @Override + public void drawBackground(int recipe) { + this.changeToGuiTexture(); + GuiDraw.drawTexturedModalRect(25, 0, 30, 15, 116, 65); + } - @Override - public void drawBackground(int recipe) { - this.changeToGuiTexture(); - GuiDraw.drawTexturedModalRect(25, 0, 30, 15, 116, 65); - } + @Override + public void drawExtras(int recipe) { + this.drawProgressBar(69, 17, 176, 60, 4, 18, 40, 11); + this.drawProgressBar(93, 31, 176, 78, 4, 18, 80, 11); + } - @Override - public void drawExtras(int recipe) { - this.drawProgressBar(69, 17, 176, 60, 4, 18, 40, 11); - this.drawProgressBar(93, 31, 176, 78, 4, 18, 80, 11); - } + private List getCachedRecipes(IFermenterRecipe recipe, boolean generatePermutations) { + if (recipe.getResource() != null && recipe.getResource().getItem() instanceof IVariableFermentable) { + List crecipes = new ArrayList<>(); + for (ItemStack stack : NEIUtils.getItemVariations(recipe.getResource())) { + crecipes.add(new CachedFermenterRecipe(recipe, stack, generatePermutations)); + } + return crecipes; + } + return Collections.singletonList(new CachedFermenterRecipe(recipe, recipe.getResource(), generatePermutations)); + } - private List getCachedRecipes(IFermenterRecipe recipe, boolean generatePermutations) { - if (recipe.getResource() != null && recipe.getResource().getItem() instanceof IVariableFermentable) { - List crecipes = new ArrayList<>(); - for (ItemStack stack : NEIUtils.getItemVariations(recipe.getResource())) { - crecipes.add(new CachedFermenterRecipe(recipe, stack, generatePermutations)); - } - return crecipes; - } - return Collections.singletonList(new CachedFermenterRecipe(recipe, recipe.getResource(), generatePermutations)); - } + @Override + public void loadAllRecipes() { + for (IFermenterRecipe recipe : RecipeManagers.fermenterManager.recipes()) { + this.arecipes.addAll(this.getCachedRecipes(recipe, true)); + } + } - @Override - public void loadAllRecipes() { - for (IFermenterRecipe recipe : RecipeManagers.fermenterManager.recipes()) { - this.arecipes.addAll(this.getCachedRecipes(recipe, true)); - } - } + @Override + public void loadCraftingRecipes(FluidStack result) { + for (IFermenterRecipe recipe : RecipeManagers.fermenterManager.recipes()) { + FluidStack output = new FluidStack(recipe.getOutput(), Constants.BUCKET_VOLUME); + if (NEIUtils.areFluidsSameType(output, result)) { + this.arecipes.addAll(this.getCachedRecipes(recipe, true)); + } + } + } - @Override - public void loadCraftingRecipes(FluidStack result) { - for (IFermenterRecipe recipe : RecipeManagers.fermenterManager.recipes()) { - FluidStack output = new FluidStack(recipe.getOutput(), Constants.BUCKET_VOLUME); - if (NEIUtils.areFluidsSameType(output, result)) { - this.arecipes.addAll(this.getCachedRecipes(recipe, true)); - } - } - } - - @Override - public void loadUsageRecipes(ItemStack ingred) { - super.loadUsageRecipes(ingred); - for (IFermenterRecipe recipe : RecipeManagers.fermenterManager.recipes()) { - if (recipe.getResource() != null) { - for (ItemStack stack : NEIUtils.getItemVariations(recipe.getResource())) { - if (stack.hasTagCompound() && NEIServerUtils.areStacksSameType(stack, ingred) || !stack.hasTagCompound() && NEIServerUtils.areStacksSameTypeCrafting(stack, ingred)) { - CachedFermenterRecipe crecipe = new CachedFermenterRecipe(recipe, stack, true); - this.arecipes.add(crecipe); - } - } - } - for (FermenterFuel fuel : FuelManager.fermenterFuel.values()) { - if (NEIServerUtils.areStacksSameTypeCrafting(fuel.item, ingred)) { - for (CachedFermenterRecipe crecipe : this.getCachedRecipes(recipe, true)) { - crecipe.setIngredientPermutation(crecipe.inputItems, ingred); - this.arecipes.add(crecipe); - } - } - } - } - } - - @Override - public void loadUsageRecipes(FluidStack ingred) { - for (IFermenterRecipe recipe : RecipeManagers.fermenterManager.recipes()) { - if (NEIUtils.areFluidsSameType(recipe.getFluidResource(), ingred)) { - this.arecipes.addAll(this.getCachedRecipes(recipe, true)); - } - } - } + @Override + public void loadUsageRecipes(ItemStack ingred) { + super.loadUsageRecipes(ingred); + for (IFermenterRecipe recipe : RecipeManagers.fermenterManager.recipes()) { + if (recipe.getResource() != null) { + for (ItemStack stack : NEIUtils.getItemVariations(recipe.getResource())) { + if (stack.hasTagCompound() && NEIServerUtils.areStacksSameType(stack, ingred) + || !stack.hasTagCompound() && NEIServerUtils.areStacksSameTypeCrafting(stack, ingred)) { + CachedFermenterRecipe crecipe = new CachedFermenterRecipe(recipe, stack, true); + this.arecipes.add(crecipe); + } + } + } + for (FermenterFuel fuel : FuelManager.fermenterFuel.values()) { + if (NEIServerUtils.areStacksSameTypeCrafting(fuel.item, ingred)) { + for (CachedFermenterRecipe crecipe : this.getCachedRecipes(recipe, true)) { + crecipe.setIngredientPermutation(crecipe.inputItems, ingred); + this.arecipes.add(crecipe); + } + } + } + } + } + @Override + public void loadUsageRecipes(FluidStack ingred) { + for (IFermenterRecipe recipe : RecipeManagers.fermenterManager.recipes()) { + if (NEIUtils.areFluidsSameType(recipe.getFluidResource(), ingred)) { + this.arecipes.addAll(this.getCachedRecipes(recipe, true)); + } + } + } } diff --git a/src/main/java/forestry/factory/recipes/nei/NEIHandlerMoistener.java b/src/main/java/forestry/factory/recipes/nei/NEIHandlerMoistener.java index 63fb90b52..106427a5c 100644 --- a/src/main/java/forestry/factory/recipes/nei/NEIHandlerMoistener.java +++ b/src/main/java/forestry/factory/recipes/nei/NEIHandlerMoistener.java @@ -10,18 +10,8 @@ ******************************************************************************/ package forestry.factory.recipes.nei; -import java.awt.Point; -import java.awt.Rectangle; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.StatCollector; - -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - +import codechicken.nei.NEIServerUtils; +import codechicken.nei.PositionedStack; import forestry.api.fuels.FuelManager; import forestry.api.fuels.MoistenerFuel; import forestry.api.recipes.IMoistenerRecipe; @@ -29,131 +19,142 @@ import forestry.api.recipes.RecipeManagers; import forestry.core.recipes.nei.PositionedFluidTank; import forestry.core.recipes.nei.RecipeHandlerBase; import forestry.factory.gui.GuiMoistener; - -import codechicken.nei.NEIServerUtils; -import codechicken.nei.PositionedStack; +import java.awt.Point; +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.StatCollector; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; public class NEIHandlerMoistener extends RecipeHandlerBase { - public class CachedMoistenerRecipe extends CachedBaseRecipe { + public class CachedMoistenerRecipe extends CachedBaseRecipe { - public PositionedFluidTank tank; - public List fuels = new ArrayList<>(); - public PositionedStack input; - public PositionedStack output; + public PositionedFluidTank tank; + public List fuels = new ArrayList<>(); + public PositionedStack input; + public PositionedStack output; - public CachedMoistenerRecipe(IMoistenerRecipe recipe, MoistenerFuel fuel) { - this.tank = new PositionedFluidTank(FluidRegistry.getFluidStack("water", 10000), 10000, new Rectangle(11, 5, 16, 58), NEIHandlerMoistener.this.getGuiTexture(), new Point(176, 0)); - this.tank.showAmount = false; - if (fuel.item != null) { - this.fuels.add(new PositionedStack(fuel.item, 34, 47)); - } - if (fuel.product != null) { - this.fuels.add(new PositionedStack(fuel.product, 100, 26)); - } - if (recipe.getResource() != null) { - this.input = new PositionedStack(recipe.getResource(), 138, 8); - } - if (recipe.getProduct() != null) { - this.output = new PositionedStack(recipe.getProduct(), 138, 44); - } - } + public CachedMoistenerRecipe(IMoistenerRecipe recipe, MoistenerFuel fuel) { + this.tank = new PositionedFluidTank( + FluidRegistry.getFluidStack("water", 10000), + 10000, + new Rectangle(11, 5, 16, 58), + NEIHandlerMoistener.this.getGuiTexture(), + new Point(176, 0)); + this.tank.showAmount = false; + if (fuel.item != null) { + this.fuels.add(new PositionedStack(fuel.item, 34, 47)); + } + if (fuel.product != null) { + this.fuels.add(new PositionedStack(fuel.product, 100, 26)); + } + if (recipe.getResource() != null) { + this.input = new PositionedStack(recipe.getResource(), 138, 8); + } + if (recipe.getProduct() != null) { + this.output = new PositionedStack(recipe.getProduct(), 138, 44); + } + } - @Override - public List getOtherStacks() { - return this.fuels; - } + @Override + public List getOtherStacks() { + return this.fuels; + } - @Override - public PositionedStack getIngredient() { - return this.input; - } + @Override + public PositionedStack getIngredient() { + return this.input; + } - @Override - public PositionedStack getResult() { - return this.output; - } + @Override + public PositionedStack getResult() { + return this.output; + } - @Override - public PositionedFluidTank getFluidTank() { - return this.tank; - } + @Override + public PositionedFluidTank getFluidTank() { + return this.tank; + } + } - } + @Override + public String getRecipeID() { + return "forestry.moistener"; + } - @Override - public String getRecipeID() { - return "forestry.moistener"; - } + @Override + public String getRecipeName() { + return StatCollector.translateToLocal("tile.for.factory.4.name"); + } - @Override - public String getRecipeName() { - return StatCollector.translateToLocal("tile.for.factory.4.name"); - } + @Override + public String getGuiTexture() { + return "forestry:textures/gui/moistener.png"; + } - @Override - public String getGuiTexture() { - return "forestry:textures/gui/moistener.png"; - } + @Override + public void loadTransferRects() { + this.addTransferRect(138, 27, 16, 14); + } - @Override - public void loadTransferRects() { - this.addTransferRect(138, 27, 16, 14); - } + @Override + public Class getGuiClass() { + return GuiMoistener.class; + } - @Override - public Class getGuiClass() { - return GuiMoistener.class; - } + @Override + public void drawBackground(int recipe) { + super.drawBackground(recipe); + this.drawProgressBar(88, 6, 176, 91, 29, 55, 80, 3); + } - @Override - public void drawBackground(int recipe) { - super.drawBackground(recipe); - this.drawProgressBar(88, 6, 176, 91, 29, 55, 80, 3); - } + @Override + public void drawExtras(int recipe) { + this.drawProgressBar(119, 25, 176, 74, 16, 15, 160, 0); + } - @Override - public void drawExtras(int recipe) { - this.drawProgressBar(119, 25, 176, 74, 16, 15, 160, 0); - } + @Override + public void loadAllRecipes() { + for (IMoistenerRecipe recipe : RecipeManagers.moistenerManager.recipes()) { + for (MoistenerFuel fuel : FuelManager.moistenerResource.values()) { + this.arecipes.add(new CachedMoistenerRecipe(recipe, fuel)); + } + } + } - @Override - public void loadAllRecipes() { - for (IMoistenerRecipe recipe : RecipeManagers.moistenerManager.recipes()) { - for (MoistenerFuel fuel : FuelManager.moistenerResource.values()) { - this.arecipes.add(new CachedMoistenerRecipe(recipe, fuel)); - } - } - } + @Override + public void loadCraftingRecipes(ItemStack result) { + for (IMoistenerRecipe recipe : RecipeManagers.moistenerManager.recipes()) { + for (MoistenerFuel fuel : FuelManager.moistenerResource.values()) { + if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getProduct(), result) + || NEIServerUtils.areStacksSameTypeCrafting(fuel.product, result)) { + this.arecipes.add(new CachedMoistenerRecipe(recipe, fuel)); + } + } + } + } - @Override - public void loadCraftingRecipes(ItemStack result) { - for (IMoistenerRecipe recipe : RecipeManagers.moistenerManager.recipes()) { - for (MoistenerFuel fuel : FuelManager.moistenerResource.values()) { - if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getProduct(), result) || NEIServerUtils.areStacksSameTypeCrafting(fuel.product, result)) { - this.arecipes.add(new CachedMoistenerRecipe(recipe, fuel)); - } - } - } - } - - @Override - public void loadUsageRecipes(ItemStack ingred) { - super.loadUsageRecipes(ingred); - for (IMoistenerRecipe recipe : RecipeManagers.moistenerManager.recipes()) { - for (MoistenerFuel fuel : FuelManager.moistenerResource.values()) { - if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getResource(), ingred) || NEIServerUtils.areStacksSameTypeCrafting(fuel.item, ingred)) { - this.arecipes.add(new CachedMoistenerRecipe(recipe, fuel)); - } - } - } - } - - @Override - public void loadUsageRecipes(FluidStack ingredient) { - if (ingredient.getFluid() == FluidRegistry.WATER) { - this.loadAllRecipes(); - } - } + @Override + public void loadUsageRecipes(ItemStack ingred) { + super.loadUsageRecipes(ingred); + for (IMoistenerRecipe recipe : RecipeManagers.moistenerManager.recipes()) { + for (MoistenerFuel fuel : FuelManager.moistenerResource.values()) { + if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getResource(), ingred) + || NEIServerUtils.areStacksSameTypeCrafting(fuel.item, ingred)) { + this.arecipes.add(new CachedMoistenerRecipe(recipe, fuel)); + } + } + } + } + @Override + public void loadUsageRecipes(FluidStack ingredient) { + if (ingredient.getFluid() == FluidRegistry.WATER) { + this.loadAllRecipes(); + } + } } diff --git a/src/main/java/forestry/factory/recipes/nei/NEIHandlerSqueezer.java b/src/main/java/forestry/factory/recipes/nei/NEIHandlerSqueezer.java index d33e0b846..ee18b8c10 100644 --- a/src/main/java/forestry/factory/recipes/nei/NEIHandlerSqueezer.java +++ b/src/main/java/forestry/factory/recipes/nei/NEIHandlerSqueezer.java @@ -10,20 +10,8 @@ ******************************************************************************/ package forestry.factory.recipes.nei; -import java.awt.Point; -import java.awt.Rectangle; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Random; - -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.StatCollector; - -import net.minecraftforge.fluids.FluidStack; - +import codechicken.nei.NEIServerUtils; +import codechicken.nei.PositionedStack; import forestry.api.recipes.ISqueezerRecipe; import forestry.api.recipes.RecipeManagers; import forestry.core.fluids.FluidHelper; @@ -34,223 +22,237 @@ import forestry.core.recipes.nei.RecipeHandlerBase; import forestry.factory.gui.GuiSqueezer; import forestry.factory.recipes.ISqueezerContainerRecipe; import forestry.factory.recipes.SqueezerRecipeManager; - -import codechicken.nei.NEIServerUtils; -import codechicken.nei.PositionedStack; +import java.awt.Point; +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Random; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.StatCollector; +import net.minecraftforge.fluids.FluidStack; public class NEIHandlerSqueezer extends RecipeHandlerBase { - private static final int[][] INPUTS = new int[][]{{0, 0}, {1, 0}, {2, 0}, {0, 1}, {1, 1}, {2, 1}, {0, 2}, {1, 2}, {2, 2}}; + private static final int[][] INPUTS = + new int[][] {{0, 0}, {1, 0}, {2, 0}, {0, 1}, {1, 1}, {2, 1}, {0, 2}, {1, 2}, {2, 2}}; - public class CachedSqueezerRecipe extends CachedBaseRecipe { + public class CachedSqueezerRecipe extends CachedBaseRecipe { - public List inputs = new ArrayList<>(); - public PositionedFluidTank tank; - public PositionedStackAdv remnants = null; - public int processingTime; - public boolean containerRecipe = false; + public List inputs = new ArrayList<>(); + public PositionedFluidTank tank; + public PositionedStackAdv remnants = null; + public int processingTime; + public boolean containerRecipe = false; - public CachedSqueezerRecipe(ISqueezerRecipe recipe, boolean genPerms) { - if (recipe.getResources() != null) { - this.setIngredients(recipe.getResources()); - } - if (recipe.getFluidOutput() != null) { - setTankFluid(recipe.getFluidOutput()); - } - if (recipe.getRemnants() != null) { - this.remnants = new PositionedStackAdv(recipe.getRemnants(), 92, 49).setChance(recipe.getRemnantsChance()); - } + public CachedSqueezerRecipe(ISqueezerRecipe recipe, boolean genPerms) { + if (recipe.getResources() != null) { + this.setIngredients(recipe.getResources()); + } + if (recipe.getFluidOutput() != null) { + setTankFluid(recipe.getFluidOutput()); + } + if (recipe.getRemnants() != null) { + this.remnants = + new PositionedStackAdv(recipe.getRemnants(), 92, 49).setChance(recipe.getRemnantsChance()); + } - this.processingTime = recipe.getProcessingTime(); + this.processingTime = recipe.getProcessingTime(); - if (genPerms) { - this.generatePermutations(); - } - } + if (genPerms) { + this.generatePermutations(); + } + } - public CachedSqueezerRecipe(ISqueezerRecipe recipe) { - this(recipe, false); - } + public CachedSqueezerRecipe(ISqueezerRecipe recipe) { + this(recipe, false); + } - public CachedSqueezerRecipe(ISqueezerContainerRecipe recipe, boolean genPerms) { - this.containerRecipe = true; + public CachedSqueezerRecipe(ISqueezerContainerRecipe recipe, boolean genPerms) { + this.containerRecipe = true; - ItemStack emptyContainer = recipe.getEmptyContainer(); - List ingredients = FluidHelper.getAllFilledContainers(emptyContainer); - setIngredients(new Object[]{ingredients}); - List fluids = new ArrayList<>(); - for (ItemStack ingredient : ingredients) { - FluidStack fluidStack = FluidHelper.getFluidStackInContainer(ingredient); - fluids.add(fluidStack); - } - setTankFluid(fluids); + ItemStack emptyContainer = recipe.getEmptyContainer(); + List ingredients = FluidHelper.getAllFilledContainers(emptyContainer); + setIngredients(new Object[] {ingredients}); + List fluids = new ArrayList<>(); + for (ItemStack ingredient : ingredients) { + FluidStack fluidStack = FluidHelper.getFluidStackInContainer(ingredient); + fluids.add(fluidStack); + } + setTankFluid(fluids); - if (recipe.getRemnants() != null) { - this.remnants = new PositionedStackAdv(recipe.getRemnants(), 92, 49).setChance(recipe.getRemnantsChance()); - } + if (recipe.getRemnants() != null) { + this.remnants = + new PositionedStackAdv(recipe.getRemnants(), 92, 49).setChance(recipe.getRemnantsChance()); + } - this.processingTime = recipe.getProcessingTime(); + this.processingTime = recipe.getProcessingTime(); - if (genPerms) { - this.generatePermutations(); - } - } + if (genPerms) { + this.generatePermutations(); + } + } - public void setIngredients(Object[] inputs) { - this.inputs.clear(); - int i = 0; - for (Object stack : inputs) { - if (i >= INPUTS.length) { - return; - } - this.inputs.add(new PositionedStack(stack, 12 + INPUTS[i][0] * 18, 10 + INPUTS[i][1] * 18, false)); - i++; - } - } + public void setIngredients(Object[] inputs) { + this.inputs.clear(); + int i = 0; + for (Object stack : inputs) { + if (i >= INPUTS.length) { + return; + } + this.inputs.add(new PositionedStack(stack, 12 + INPUTS[i][0] * 18, 10 + INPUTS[i][1] * 18, false)); + i++; + } + } - public void setTankFluid(FluidStack... fluidStack) { - setTankFluid(Arrays.asList(fluidStack)); - } + public void setTankFluid(FluidStack... fluidStack) { + setTankFluid(Arrays.asList(fluidStack)); + } - public void setTankFluid(Collection fluidStacks) { - this.tank = new PositionedFluidTank(fluidStacks, 10000, new Rectangle(117, 7, 16, 58), NEIHandlerSqueezer.this.getGuiTexture(), new Point(176, 0)); - } + public void setTankFluid(Collection fluidStacks) { + this.tank = new PositionedFluidTank( + fluidStacks, + 10000, + new Rectangle(117, 7, 16, 58), + NEIHandlerSqueezer.this.getGuiTexture(), + new Point(176, 0)); + } - @Override - public List getIngredients() { - return this.getCycledIngredients(NEIHandlerSqueezer.this.cycleticks / 20, this.inputs); - } + @Override + public List getIngredients() { + return this.getCycledIngredients(NEIHandlerSqueezer.this.cycleticks / 20, this.inputs); + } - @Override - public List getCycledIngredients(int cycle, List ingredients) { - if (containerRecipe) { - // cycle ingredients and output together - Random random = new Random(cycle); - cycle = Math.abs(random.nextInt()); - for (PositionedStack ingredient : ingredients) { - ingredient.setPermutationToRender(cycle % ingredient.items.length); - } - tank.setPermutationToRender(cycle % tank.getPermutationCount()); - return ingredients; - } else { - return super.getCycledIngredients(cycle, ingredients); - } - } + @Override + public List getCycledIngredients(int cycle, List ingredients) { + if (containerRecipe) { + // cycle ingredients and output together + Random random = new Random(cycle); + cycle = Math.abs(random.nextInt()); + for (PositionedStack ingredient : ingredients) { + ingredient.setPermutationToRender(cycle % ingredient.items.length); + } + tank.setPermutationToRender(cycle % tank.getPermutationCount()); + return ingredients; + } else { + return super.getCycledIngredients(cycle, ingredients); + } + } - @Override - public PositionedFluidTank getFluidTank() { - return this.tank; - } + @Override + public PositionedFluidTank getFluidTank() { + return this.tank; + } - @Override - public PositionedStack getResult() { - return this.remnants; - } + @Override + public PositionedStack getResult() { + return this.remnants; + } - public void generatePermutations() { - for (PositionedStack p : this.inputs) { - p.generatePermutations(); - } - } + public void generatePermutations() { + for (PositionedStack p : this.inputs) { + p.generatePermutations(); + } + } + } - } + @Override + public String getRecipeID() { + return "forestry.squeezer"; + } - @Override - public String getRecipeID() { - return "forestry.squeezer"; - } + @Override + public String getRecipeName() { + return StatCollector.translateToLocal("tile.for.factory.5.name"); + } - @Override - public String getRecipeName() { - return StatCollector.translateToLocal("tile.for.factory.5.name"); - } + @Override + public String getGuiTexture() { + return "forestry:textures/gui/squeezersocket.png"; + } - @Override - public String getGuiTexture() { - return "forestry:textures/gui/squeezersocket.png"; - } + @Override + public void loadTransferRects() { + this.addTransferRect(98 - 16 - 6 - 4, 9 + 8 + 8 + 4, 15 + 16 + 6 + 4, 18); + } - @Override - public void loadTransferRects() { - this.addTransferRect(98 - 16 - 6 - 4, 9 + 8 + 8 + 4, 15 + 16 + 6 + 4, 18); - } + @Override + public void drawExtras(int recipeIndex) { + CachedRecipe recipe = arecipes.get(recipeIndex); + if (recipe instanceof CachedSqueezerRecipe) { + int processingTime = ((CachedSqueezerRecipe) recipe).processingTime; + this.drawProgressBar(70, 30, 176, 60, 43, 18, processingTime * 5, 0); + } + } - @Override - public void drawExtras(int recipeIndex) { - CachedRecipe recipe = arecipes.get(recipeIndex); - if (recipe instanceof CachedSqueezerRecipe) { - int processingTime = ((CachedSqueezerRecipe) recipe).processingTime; - this.drawProgressBar(70, 30, 176, 60, 43, 18, processingTime * 5, 0); - } - } + @Override + public Class getGuiClass() { + return GuiSqueezer.class; + } - @Override - public Class getGuiClass() { - return GuiSqueezer.class; - } + @Override + public void loadAllRecipes() { + for (ISqueezerRecipe recipe : RecipeManagers.squeezerManager.recipes()) { + this.arecipes.add(new CachedSqueezerRecipe(recipe, true)); + } + for (ISqueezerContainerRecipe containerRecipe : SqueezerRecipeManager.containerRecipes.values()) { + this.arecipes.add(new CachedSqueezerRecipe(containerRecipe, true)); + } + } - @Override - public void loadAllRecipes() { - for (ISqueezerRecipe recipe : RecipeManagers.squeezerManager.recipes()) { - this.arecipes.add(new CachedSqueezerRecipe(recipe, true)); - } - for (ISqueezerContainerRecipe containerRecipe : SqueezerRecipeManager.containerRecipes.values()) { - this.arecipes.add(new CachedSqueezerRecipe(containerRecipe, true)); - } - } + @Override + public void loadCraftingRecipes(ItemStack result) { + for (ISqueezerRecipe recipe : RecipeManagers.squeezerManager.recipes()) { + if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getRemnants(), result)) { + this.arecipes.add(new CachedSqueezerRecipe(recipe, true)); + } + } + for (ISqueezerContainerRecipe containerRecipe : SqueezerRecipeManager.containerRecipes.values()) { + if (NEIServerUtils.areStacksSameTypeCrafting(containerRecipe.getRemnants(), result)) { + this.arecipes.add(new CachedSqueezerRecipe(containerRecipe, true)); + } + } + } - @Override - public void loadCraftingRecipes(ItemStack result) { - for (ISqueezerRecipe recipe : RecipeManagers.squeezerManager.recipes()) { - if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getRemnants(), result)) { - this.arecipes.add(new CachedSqueezerRecipe(recipe, true)); - } - } - for (ISqueezerContainerRecipe containerRecipe : SqueezerRecipeManager.containerRecipes.values()) { - if (NEIServerUtils.areStacksSameTypeCrafting(containerRecipe.getRemnants(), result)) { - this.arecipes.add(new CachedSqueezerRecipe(containerRecipe, true)); - } - } - } + @Override + public void loadCraftingRecipes(FluidStack result) { + for (ISqueezerRecipe recipe : RecipeManagers.squeezerManager.recipes()) { + if (NEIUtils.areFluidsSameType(recipe.getFluidOutput(), result)) { + this.arecipes.add(new CachedSqueezerRecipe(recipe, true)); + } + } + for (ISqueezerContainerRecipe containerRecipe : SqueezerRecipeManager.containerRecipes.values()) { + ItemStack emptyContainer = containerRecipe.getEmptyContainer(); + ItemStack filledContainer = FluidHelper.getFilledContainer(result, emptyContainer); + if (filledContainer != null) { + ISqueezerRecipe recipe = containerRecipe.getSqueezerRecipe(filledContainer); + if (recipe != null) { + this.arecipes.add(new CachedSqueezerRecipe(recipe, true)); + } + } + } + } - @Override - public void loadCraftingRecipes(FluidStack result) { - for (ISqueezerRecipe recipe : RecipeManagers.squeezerManager.recipes()) { - if (NEIUtils.areFluidsSameType(recipe.getFluidOutput(), result)) { - this.arecipes.add(new CachedSqueezerRecipe(recipe, true)); - } - } - for (ISqueezerContainerRecipe containerRecipe : SqueezerRecipeManager.containerRecipes.values()) { - ItemStack emptyContainer = containerRecipe.getEmptyContainer(); - ItemStack filledContainer = FluidHelper.getFilledContainer(result, emptyContainer); - if (filledContainer != null) { - ISqueezerRecipe recipe = containerRecipe.getSqueezerRecipe(filledContainer); - if (recipe != null) { - this.arecipes.add(new CachedSqueezerRecipe(recipe, true)); - } - } - } - } + @Override + public void loadUsageRecipes(ItemStack ingred) { + ingred.stackSize = 1; - @Override - public void loadUsageRecipes(ItemStack ingred) { - ingred.stackSize = 1; - - ISqueezerContainerRecipe containerRecipe = SqueezerRecipeManager.findMatchingContainerRecipe(ingred); - if (containerRecipe != null) { - CachedSqueezerRecipe crecipe = new CachedSqueezerRecipe(containerRecipe, true); - crecipe.setIngredients(new ItemStack[]{ingred}); - FluidStack fluidStack = FluidHelper.getFluidStackInContainer(ingred); - crecipe.setTankFluid(fluidStack); - this.arecipes.add(crecipe); - return; - } - - ISqueezerRecipe recipe = SqueezerRecipeManager.findRecipeWithIngredient(ingred); - if (recipe != null) { - CachedSqueezerRecipe crecipe = new CachedSqueezerRecipe(recipe); - this.arecipes.add(crecipe); - } - } + ISqueezerContainerRecipe containerRecipe = SqueezerRecipeManager.findMatchingContainerRecipe(ingred); + if (containerRecipe != null) { + CachedSqueezerRecipe crecipe = new CachedSqueezerRecipe(containerRecipe, true); + crecipe.setIngredients(new ItemStack[] {ingred}); + FluidStack fluidStack = FluidHelper.getFluidStackInContainer(ingred); + crecipe.setTankFluid(fluidStack); + this.arecipes.add(crecipe); + return; + } + ISqueezerRecipe recipe = SqueezerRecipeManager.findRecipeWithIngredient(ingred); + if (recipe != null) { + CachedSqueezerRecipe crecipe = new CachedSqueezerRecipe(recipe); + this.arecipes.add(crecipe); + } + } } diff --git a/src/main/java/forestry/factory/recipes/nei/NEIHandlerStill.java b/src/main/java/forestry/factory/recipes/nei/NEIHandlerStill.java index 14b5fe310..283cf1d0c 100644 --- a/src/main/java/forestry/factory/recipes/nei/NEIHandlerStill.java +++ b/src/main/java/forestry/factory/recipes/nei/NEIHandlerStill.java @@ -10,113 +10,117 @@ ******************************************************************************/ package forestry.factory.recipes.nei; -import java.awt.Point; -import java.awt.Rectangle; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.util.StatCollector; - -import net.minecraftforge.fluids.FluidStack; - +import codechicken.lib.gui.GuiDraw; +import codechicken.nei.PositionedStack; import forestry.api.recipes.IStillRecipe; import forestry.api.recipes.RecipeManagers; import forestry.core.recipes.nei.NEIUtils; import forestry.core.recipes.nei.PositionedFluidTank; import forestry.core.recipes.nei.RecipeHandlerBase; import forestry.factory.gui.GuiStill; - -import codechicken.lib.gui.GuiDraw; -import codechicken.nei.PositionedStack; +import java.awt.Point; +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.util.StatCollector; +import net.minecraftforge.fluids.FluidStack; public class NEIHandlerStill extends RecipeHandlerBase { - public class CachedStillRecipe extends CachedBaseRecipe { + public class CachedStillRecipe extends CachedBaseRecipe { - public List tanks = new ArrayList<>(); + public List tanks = new ArrayList<>(); - public CachedStillRecipe(IStillRecipe recipe) { - if (recipe.getInput() != null) { - this.tanks.add(new PositionedFluidTank(recipe.getInput(), 10000, new Rectangle(30, 4, 16, 58), NEIHandlerStill.this.getGuiTexture(), new Point(176, 0))); - } - if (recipe.getOutput() != null) { - this.tanks.add(new PositionedFluidTank(recipe.getOutput(), 10000, new Rectangle(120, 4, 16, 58), NEIHandlerStill.this.getGuiTexture(), new Point(176, 0))); - } - } + public CachedStillRecipe(IStillRecipe recipe) { + if (recipe.getInput() != null) { + this.tanks.add(new PositionedFluidTank( + recipe.getInput(), + 10000, + new Rectangle(30, 4, 16, 58), + NEIHandlerStill.this.getGuiTexture(), + new Point(176, 0))); + } + if (recipe.getOutput() != null) { + this.tanks.add(new PositionedFluidTank( + recipe.getOutput(), + 10000, + new Rectangle(120, 4, 16, 58), + NEIHandlerStill.this.getGuiTexture(), + new Point(176, 0))); + } + } - @Override - public PositionedStack getResult() { - return null; - } + @Override + public PositionedStack getResult() { + return null; + } - @Override - public List getFluidTanks() { - return this.tanks; - } + @Override + public List getFluidTanks() { + return this.tanks; + } + } - } + @Override + public String getRecipeID() { + return "forestry.still"; + } - @Override - public String getRecipeID() { - return "forestry.still"; - } + @Override + public String getRecipeName() { + return StatCollector.translateToLocal("tile.for.factory.6.name"); + } - @Override - public String getRecipeName() { - return StatCollector.translateToLocal("tile.for.factory.6.name"); - } + @Override + public String getGuiTexture() { + return "forestry:textures/gui/still.png"; + } - @Override - public String getGuiTexture() { - return "forestry:textures/gui/still.png"; - } + @Override + public void loadTransferRects() { + this.addTransferRect(76, 27, 14, 12); + } - @Override - public void loadTransferRects() { - this.addTransferRect(76, 27, 14, 12); - } + @Override + public Class getGuiClass() { + return GuiStill.class; + } - @Override - public Class getGuiClass() { - return GuiStill.class; - } + @Override + public void drawBackground(int recipe) { + this.changeToGuiTexture(); + GuiDraw.drawTexturedModalRect(25, 0, 30, 11, 116, 65); + } - @Override - public void drawBackground(int recipe) { - this.changeToGuiTexture(); - GuiDraw.drawTexturedModalRect(25, 0, 30, 11, 116, 65); - } + @Override + public void drawExtras(int recipe) { + this.drawProgressBar(79, 6, 176, 74, 4, 18, 80, 11); + GuiDraw.drawTexturedModalRect(77, 46, 176, 60, 14, 14); + } - @Override - public void drawExtras(int recipe) { - this.drawProgressBar(79, 6, 176, 74, 4, 18, 80, 11); - GuiDraw.drawTexturedModalRect(77, 46, 176, 60, 14, 14); - } + @Override + public void loadAllRecipes() { + for (IStillRecipe recipe : RecipeManagers.stillManager.recipes()) { + this.arecipes.add(new CachedStillRecipe(recipe)); + } + } - @Override - public void loadAllRecipes() { - for (IStillRecipe recipe : RecipeManagers.stillManager.recipes()) { - this.arecipes.add(new CachedStillRecipe(recipe)); - } - } - - @Override - public void loadCraftingRecipes(FluidStack result) { - for (IStillRecipe recipe : RecipeManagers.stillManager.recipes()) { - if (NEIUtils.areFluidsSameType(recipe.getOutput(), result)) { - this.arecipes.add(new CachedStillRecipe(recipe)); - } - } - } - - @Override - public void loadUsageRecipes(FluidStack ingred) { - for (IStillRecipe recipe : RecipeManagers.stillManager.recipes()) { - if (NEIUtils.areFluidsSameType(recipe.getInput(), ingred)) { - this.arecipes.add(new CachedStillRecipe(recipe)); - } - } - } + @Override + public void loadCraftingRecipes(FluidStack result) { + for (IStillRecipe recipe : RecipeManagers.stillManager.recipes()) { + if (NEIUtils.areFluidsSameType(recipe.getOutput(), result)) { + this.arecipes.add(new CachedStillRecipe(recipe)); + } + } + } + @Override + public void loadUsageRecipes(FluidStack ingred) { + for (IStillRecipe recipe : RecipeManagers.stillManager.recipes()) { + if (NEIUtils.areFluidsSameType(recipe.getInput(), ingred)) { + this.arecipes.add(new CachedStillRecipe(recipe)); + } + } + } } diff --git a/src/main/java/forestry/factory/tiles/ICrafterWorktable.java b/src/main/java/forestry/factory/tiles/ICrafterWorktable.java index 69b7ed277..5422dbf7c 100644 --- a/src/main/java/forestry/factory/tiles/ICrafterWorktable.java +++ b/src/main/java/forestry/factory/tiles/ICrafterWorktable.java @@ -1,14 +1,14 @@ -package forestry.factory.tiles; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -public interface ICrafterWorktable { - ItemStack getResult(); - - boolean canTakeStack(int slotIndex); - - boolean onCraftingStart(EntityPlayer player); - - void onCraftingComplete(EntityPlayer player); -} +package forestry.factory.tiles; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public interface ICrafterWorktable { + ItemStack getResult(); + + boolean canTakeStack(int slotIndex); + + boolean onCraftingStart(EntityPlayer player); + + void onCraftingComplete(EntityPlayer player); +} diff --git a/src/main/java/forestry/factory/tiles/TileBottler.java b/src/main/java/forestry/factory/tiles/TileBottler.java index ec36601ef..842fbffcc 100644 --- a/src/main/java/forestry/factory/tiles/TileBottler.java +++ b/src/main/java/forestry/factory/tiles/TileBottler.java @@ -10,24 +10,8 @@ ******************************************************************************/ package forestry.factory.tiles; -import java.io.IOException; -import java.util.Collection; -import java.util.LinkedList; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; - +import buildcraft.api.statements.ITriggerExternal; import cpw.mods.fml.common.Optional; - import forestry.api.core.IErrorLogic; import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; @@ -45,175 +29,201 @@ import forestry.factory.gui.GuiBottler; import forestry.factory.inventory.InventoryBottler; import forestry.factory.recipes.BottlerRecipe; import forestry.factory.triggers.FactoryTriggers; - -import buildcraft.api.statements.ITriggerExternal; +import java.io.IOException; +import java.util.Collection; +import java.util.LinkedList; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; public class TileBottler extends TilePowered implements ISidedInventory, ILiquidTankTile, IFluidHandler { - private static final int TICKS_PER_RECIPE_TIME = 5; - private static final int ENERGY_PER_RECIPE_TIME = 1000; + private static final int TICKS_PER_RECIPE_TIME = 5; + private static final int ENERGY_PER_RECIPE_TIME = 1000; - private final StandardTank resourceTank; - private final TankManager tankManager; + private final StandardTank resourceTank; + private final TankManager tankManager; - private BottlerRecipe currentRecipe; + private BottlerRecipe currentRecipe; - public TileBottler() { - super("bottler", 1100, 4000); + public TileBottler() { + super("bottler", 1100, 4000); - setInternalInventory(new InventoryBottler(this)); + setInternalInventory(new InventoryBottler(this)); - resourceTank = new StandardTank(Constants.PROCESSOR_TANK_CAPACITY); - tankManager = new TankManager(this, resourceTank); - } + resourceTank = new StandardTank(Constants.PROCESSOR_TANK_CAPACITY); + tankManager = new TankManager(this, resourceTank); + } - /* SAVING & LOADING */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - tankManager.writeToNBT(nbttagcompound); - } + /* SAVING & LOADING */ + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + tankManager.writeToNBT(nbttagcompound); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - tankManager.readFromNBT(nbttagcompound); - checkRecipe(); - } + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + tankManager.readFromNBT(nbttagcompound); + checkRecipe(); + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - tankManager.writeData(data); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + tankManager.writeData(data); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - tankManager.readData(data); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + tankManager.readData(data); + } - @Override - public void updateServerSide() { - super.updateServerSide(); + @Override + public void updateServerSide() { + super.updateServerSide(); - if (updateOnInterval(20)) { - FluidHelper.drainContainers(tankManager, this, InventoryBottler.SLOT_INPUT_FULL_CAN); - } - } + if (updateOnInterval(20)) { + FluidHelper.drainContainers(tankManager, this, InventoryBottler.SLOT_INPUT_FULL_CAN); + } + } - @Override - public boolean workCycle() { - FluidHelper.FillStatus status = FluidHelper.fillContainers(tankManager, this, InventoryBottler.SLOT_INPUT_EMPTY_CAN, InventoryBottler.SLOT_OUTPUT, currentRecipe.input.getFluid()); - return status == FluidHelper.FillStatus.SUCCESS; - } + @Override + public boolean workCycle() { + FluidHelper.FillStatus status = FluidHelper.fillContainers( + tankManager, + this, + InventoryBottler.SLOT_INPUT_EMPTY_CAN, + InventoryBottler.SLOT_OUTPUT, + currentRecipe.input.getFluid()); + return status == FluidHelper.FillStatus.SUCCESS; + } - private void checkRecipe() { - ItemStack emptyCan = getStackInSlot(InventoryBottler.SLOT_INPUT_EMPTY_CAN); - FluidStack resource = resourceTank.getFluid(); + private void checkRecipe() { + ItemStack emptyCan = getStackInSlot(InventoryBottler.SLOT_INPUT_EMPTY_CAN); + FluidStack resource = resourceTank.getFluid(); - if (currentRecipe == null || !currentRecipe.matches(emptyCan, resource)) { - currentRecipe = BottlerRecipe.getRecipe(resource, emptyCan); - if (currentRecipe != null) { - float viscosityMultiplier = resource.getFluid().getViscosity(resource) / 1000.0f; - viscosityMultiplier = ((viscosityMultiplier - 1f) / 20f) + 1f; // scale down the effect + if (currentRecipe == null || !currentRecipe.matches(emptyCan, resource)) { + currentRecipe = BottlerRecipe.getRecipe(resource, emptyCan); + if (currentRecipe != null) { + float viscosityMultiplier = resource.getFluid().getViscosity(resource) / 1000.0f; + viscosityMultiplier = ((viscosityMultiplier - 1f) / 20f) + 1f; // scale down the effect - int fillAmount = Math.min(currentRecipe.input.amount, resource.amount); - float fillTime = fillAmount / (float) Constants.BUCKET_VOLUME; - fillTime *= viscosityMultiplier; + int fillAmount = Math.min(currentRecipe.input.amount, resource.amount); + float fillTime = fillAmount / (float) Constants.BUCKET_VOLUME; + fillTime *= viscosityMultiplier; - setTicksPerWorkCycle(Math.round(fillTime * TICKS_PER_RECIPE_TIME)); - setEnergyPerWorkCycle(Math.round(fillTime * ENERGY_PER_RECIPE_TIME)); - } - } - } + setTicksPerWorkCycle(Math.round(fillTime * TICKS_PER_RECIPE_TIME)); + setEnergyPerWorkCycle(Math.round(fillTime * ENERGY_PER_RECIPE_TIME)); + } + } + } - @Override - public boolean hasResourcesMin(float percentage) { - IInventoryAdapter inventory = getInternalInventory(); - if (inventory.getStackInSlot(InventoryBottler.SLOT_INPUT_EMPTY_CAN) == null) { - return false; - } + @Override + public boolean hasResourcesMin(float percentage) { + IInventoryAdapter inventory = getInternalInventory(); + if (inventory.getStackInSlot(InventoryBottler.SLOT_INPUT_EMPTY_CAN) == null) { + return false; + } - return ((float) inventory.getStackInSlot(InventoryBottler.SLOT_INPUT_EMPTY_CAN).stackSize / (float) inventory.getStackInSlot(InventoryBottler.SLOT_INPUT_EMPTY_CAN).getMaxStackSize()) > percentage; - } + return ((float) inventory.getStackInSlot(InventoryBottler.SLOT_INPUT_EMPTY_CAN).stackSize + / (float) inventory + .getStackInSlot(InventoryBottler.SLOT_INPUT_EMPTY_CAN) + .getMaxStackSize()) + > percentage; + } - @Override - public boolean hasWork() { - checkRecipe(); + @Override + public boolean hasWork() { + checkRecipe(); - IErrorLogic errorLogic = getErrorLogic(); + IErrorLogic errorLogic = getErrorLogic(); - FluidHelper.FillStatus status; + FluidHelper.FillStatus status; - if (currentRecipe == null) { - status = FluidHelper.FillStatus.NO_FLUID; - } else { - status = FluidHelper.fillContainers(tankManager, this, InventoryBottler.SLOT_INPUT_EMPTY_CAN, InventoryBottler.SLOT_OUTPUT, currentRecipe.input.getFluid(), false); - } + if (currentRecipe == null) { + status = FluidHelper.FillStatus.NO_FLUID; + } else { + status = FluidHelper.fillContainers( + tankManager, + this, + InventoryBottler.SLOT_INPUT_EMPTY_CAN, + InventoryBottler.SLOT_OUTPUT, + currentRecipe.input.getFluid(), + false); + } - errorLogic.setCondition(status == FluidHelper.FillStatus.NO_FLUID, EnumErrorCode.NO_RESOURCE_LIQUID); - errorLogic.setCondition(status == FluidHelper.FillStatus.NO_SPACE, EnumErrorCode.NO_SPACE_INVENTORY); - return status == FluidHelper.FillStatus.SUCCESS; - } + errorLogic.setCondition(status == FluidHelper.FillStatus.NO_FLUID, EnumErrorCode.NO_RESOURCE_LIQUID); + errorLogic.setCondition(status == FluidHelper.FillStatus.NO_SPACE, EnumErrorCode.NO_SPACE_INVENTORY); + return status == FluidHelper.FillStatus.SUCCESS; + } - @Override - public TankRenderInfo getResourceTankInfo() { - return new TankRenderInfo(resourceTank); - } + @Override + public TankRenderInfo getResourceTankInfo() { + return new TankRenderInfo(resourceTank); + } - /* ILIQUIDCONTAINER */ - @Override - public TankManager getTankManager() { - return tankManager; - } + /* ILIQUIDCONTAINER */ + @Override + public TankManager getTankManager() { + return tankManager; + } - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return tankManager.fill(from, resource, doFill); - } + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return tankManager.drain(from, resource, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return tankManager.drain(from, maxDrain, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return tankManager.canFill(from, fluid); - } + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return tankManager.canDrain(from, fluid); - } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return tankManager.getTankInfo(from); - } + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } - /* ITRIGGERPROVIDER */ - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { - LinkedList res = new LinkedList<>(); - res.add(FactoryTriggers.lowResource25); - res.add(FactoryTriggers.lowResource10); - return res; - } + /* ITRIGGERPROVIDER */ + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { + LinkedList res = new LinkedList<>(); + res.add(FactoryTriggers.lowResource25); + res.add(FactoryTriggers.lowResource10); + return res; + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiBottler(player.inventory, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiBottler(player.inventory, this); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerBottler(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerBottler(player.inventory, this); + } } diff --git a/src/main/java/forestry/factory/tiles/TileCarpenter.java b/src/main/java/forestry/factory/tiles/TileCarpenter.java index ef2bf9b20..48f49941d 100644 --- a/src/main/java/forestry/factory/tiles/TileCarpenter.java +++ b/src/main/java/forestry/factory/tiles/TileCarpenter.java @@ -10,22 +10,6 @@ ******************************************************************************/ package forestry.factory.tiles; -import javax.annotation.Nullable; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.inventory.InventoryCraftResult; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; - import forestry.api.core.IErrorLogic; import forestry.api.recipes.ICarpenterRecipe; import forestry.core.config.Constants; @@ -48,241 +32,265 @@ import forestry.factory.gui.GuiCarpenter; import forestry.factory.inventory.InventoryCarpenter; import forestry.factory.inventory.InventoryGhostCrafting; import forestry.factory.recipes.CarpenterRecipeManager; +import java.io.IOException; +import javax.annotation.Nullable; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.inventory.InventoryCraftResult; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; -public class TileCarpenter extends TilePowered implements ISidedInventory, ILiquidTankTile, IFluidHandler, IItemStackDisplay { - private static final int TICKS_PER_RECIPE_TIME = 1; - private static final int ENERGY_PER_WORK_CYCLE = 2040; - private static final int ENERGY_PER_RECIPE_TIME = ENERGY_PER_WORK_CYCLE / 10; +public class TileCarpenter extends TilePowered + implements ISidedInventory, ILiquidTankTile, IFluidHandler, IItemStackDisplay { + private static final int TICKS_PER_RECIPE_TIME = 1; + private static final int ENERGY_PER_WORK_CYCLE = 2040; + private static final int ENERGY_PER_RECIPE_TIME = ENERGY_PER_WORK_CYCLE / 10; - private final FilteredTank resourceTank; - private final TankManager tankManager; - private final InventoryAdapterTile craftingInventory; - private final InventoryCraftResult craftPreviewInventory; + private final FilteredTank resourceTank; + private final TankManager tankManager; + private final InventoryAdapterTile craftingInventory; + private final InventoryCraftResult craftPreviewInventory; - @Nullable - private ICarpenterRecipe currentRecipe; + @Nullable + private ICarpenterRecipe currentRecipe; - private ItemStack getBoxStack() { - return getInternalInventory().getStackInSlot(InventoryCarpenter.SLOT_BOX); - } + private ItemStack getBoxStack() { + return getInternalInventory().getStackInSlot(InventoryCarpenter.SLOT_BOX); + } - public TileCarpenter() { - super("carpenter", 1100, 4000); - setEnergyPerWorkCycle(ENERGY_PER_WORK_CYCLE); - resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, CarpenterRecipeManager.getRecipeFluids()); + public TileCarpenter() { + super("carpenter", 1100, 4000); + setEnergyPerWorkCycle(ENERGY_PER_WORK_CYCLE); + resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, CarpenterRecipeManager.getRecipeFluids()); - craftingInventory = new InventoryGhostCrafting<>(this, 10); - craftPreviewInventory = new InventoryCraftResult(); - setInternalInventory(new InventoryCarpenter(this)); + craftingInventory = new InventoryGhostCrafting<>(this, 10); + craftPreviewInventory = new InventoryCraftResult(); + setInternalInventory(new InventoryCarpenter(this)); - tankManager = new TankManager(this, resourceTank); - } + tankManager = new TankManager(this, resourceTank); + } - /* LOADING & SAVING */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + /* LOADING & SAVING */ + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - tankManager.writeToNBT(nbttagcompound); - craftingInventory.writeToNBT(nbttagcompound); - } + tankManager.writeToNBT(nbttagcompound); + craftingInventory.writeToNBT(nbttagcompound); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - tankManager.readFromNBT(nbttagcompound); - craftingInventory.readFromNBT(nbttagcompound); - } + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + tankManager.readFromNBT(nbttagcompound); + craftingInventory.readFromNBT(nbttagcompound); + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - tankManager.writeData(data); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + tankManager.writeData(data); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - tankManager.readData(data); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + tankManager.readData(data); + } - public void checkRecipe() { - if (worldObj.isRemote) { - return; - } + public void checkRecipe() { + if (worldObj.isRemote) { + return; + } - if (!CarpenterRecipeManager.matches(currentRecipe, resourceTank.getFluid(), getBoxStack(), craftingInventory)) { - currentRecipe = CarpenterRecipeManager.findMatchingRecipe(resourceTank.getFluid(), getBoxStack(), craftingInventory); + if (!CarpenterRecipeManager.matches(currentRecipe, resourceTank.getFluid(), getBoxStack(), craftingInventory)) { + currentRecipe = CarpenterRecipeManager.findMatchingRecipe( + resourceTank.getFluid(), getBoxStack(), craftingInventory); - if (currentRecipe != null) { - int recipeTime = currentRecipe.getPackagingTime(); - setTicksPerWorkCycle(recipeTime * TICKS_PER_RECIPE_TIME); - setEnergyPerWorkCycle(recipeTime * ENERGY_PER_RECIPE_TIME); + if (currentRecipe != null) { + int recipeTime = currentRecipe.getPackagingTime(); + setTicksPerWorkCycle(recipeTime * TICKS_PER_RECIPE_TIME); + setEnergyPerWorkCycle(recipeTime * ENERGY_PER_RECIPE_TIME); - ItemStack craftingResult = currentRecipe.getCraftingGridRecipe().getRecipeOutput(); - craftPreviewInventory.setInventorySlotContents(0, craftingResult); - } else { - craftPreviewInventory.setInventorySlotContents(0, null); - } - } - } + ItemStack craftingResult = currentRecipe.getCraftingGridRecipe().getRecipeOutput(); + craftPreviewInventory.setInventorySlotContents(0, craftingResult); + } else { + craftPreviewInventory.setInventorySlotContents(0, null); + } + } + } - @Override - public void updateServerSide() { - super.updateServerSide(); + @Override + public void updateServerSide() { + super.updateServerSide(); - if (updateOnInterval(20)) { - FluidHelper.drainContainers(tankManager, this, InventoryCarpenter.SLOT_CAN_INPUT); - } - } + if (updateOnInterval(20)) { + FluidHelper.drainContainers(tankManager, this, InventoryCarpenter.SLOT_CAN_INPUT); + } + } - @Override - public boolean workCycle() { - if (!removeLiquidResources(true)) { - return false; - } - if (!removeItemResources(true)) { - return false; - } + @Override + public boolean workCycle() { + if (!removeLiquidResources(true)) { + return false; + } + if (!removeItemResources(true)) { + return false; + } - ItemStack pendingProduct = currentRecipe.getCraftingGridRecipe().getRecipeOutput(); - InventoryUtil.tryAddStack(this, pendingProduct, InventoryCarpenter.SLOT_PRODUCT, InventoryCarpenter.SLOT_PRODUCT_COUNT, true); + ItemStack pendingProduct = currentRecipe.getCraftingGridRecipe().getRecipeOutput(); + InventoryUtil.tryAddStack( + this, pendingProduct, InventoryCarpenter.SLOT_PRODUCT, InventoryCarpenter.SLOT_PRODUCT_COUNT, true); - return true; - } + return true; + } - private boolean removeLiquidResources(boolean doRemove) { - if (currentRecipe == null) { - return true; - } + private boolean removeLiquidResources(boolean doRemove) { + if (currentRecipe == null) { + return true; + } - FluidStack fluid = currentRecipe.getFluidResource(); - if (fluid != null) { - if (!resourceTank.canDrain(fluid)) { - return false; - } - if (doRemove) { - resourceTank.drain(fluid.amount, true); - } - } + FluidStack fluid = currentRecipe.getFluidResource(); + if (fluid != null) { + if (!resourceTank.canDrain(fluid)) { + return false; + } + if (doRemove) { + resourceTank.drain(fluid.amount, true); + } + } - return true; - } + return true; + } - private boolean removeItemResources(boolean doRemove) { - if (currentRecipe == null) { - return true; - } + private boolean removeItemResources(boolean doRemove) { + if (currentRecipe == null) { + return true; + } - if (currentRecipe.getBox() != null) { - ItemStack box = getStackInSlot(InventoryCarpenter.SLOT_BOX); - if (box == null || box.stackSize == 0) { - return false; - } - if (doRemove) { - decrStackSize(InventoryCarpenter.SLOT_BOX, 1); - } - } + if (currentRecipe.getBox() != null) { + ItemStack box = getStackInSlot(InventoryCarpenter.SLOT_BOX); + if (box == null || box.stackSize == 0) { + return false; + } + if (doRemove) { + decrStackSize(InventoryCarpenter.SLOT_BOX, 1); + } + } - EntityPlayer player = PlayerUtil.getPlayer(worldObj, getAccessHandler().getOwner()); - ItemStack[] craftingSets = InventoryUtil.getStacks(craftingInventory, InventoryGhostCrafting.SLOT_CRAFTING_1, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); - IInventory inventory = new InventoryMapper(getInternalInventory(), InventoryCarpenter.SLOT_INVENTORY_1, InventoryCarpenter.SLOT_INVENTORY_COUNT); - return InventoryUtil.removeSets(inventory, 1, craftingSets, player, true, true, false, doRemove); - } + EntityPlayer player = PlayerUtil.getPlayer(worldObj, getAccessHandler().getOwner()); + ItemStack[] craftingSets = InventoryUtil.getStacks( + craftingInventory, InventoryGhostCrafting.SLOT_CRAFTING_1, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); + IInventory inventory = new InventoryMapper( + getInternalInventory(), InventoryCarpenter.SLOT_INVENTORY_1, InventoryCarpenter.SLOT_INVENTORY_COUNT); + return InventoryUtil.removeSets(inventory, 1, craftingSets, player, true, true, false, doRemove); + } - /* STATE INFORMATION */ - @Override - public boolean hasWork() { - if (updateOnInterval(20)) { - checkRecipe(); - } + /* STATE INFORMATION */ + @Override + public boolean hasWork() { + if (updateOnInterval(20)) { + checkRecipe(); + } - boolean hasRecipe = (currentRecipe != null); - boolean hasLiquidResources = true; - boolean hasItemResources = true; - boolean canAdd = true; + boolean hasRecipe = (currentRecipe != null); + boolean hasLiquidResources = true; + boolean hasItemResources = true; + boolean canAdd = true; - if (hasRecipe) { - hasLiquidResources = removeLiquidResources(false); - hasItemResources = removeItemResources(false); + if (hasRecipe) { + hasLiquidResources = removeLiquidResources(false); + hasItemResources = removeItemResources(false); - ItemStack pendingProduct = currentRecipe.getCraftingGridRecipe().getRecipeOutput(); - canAdd = InventoryUtil.tryAddStack(this, pendingProduct, InventoryCarpenter.SLOT_PRODUCT, InventoryCarpenter.SLOT_PRODUCT_COUNT, true, false); - } + ItemStack pendingProduct = currentRecipe.getCraftingGridRecipe().getRecipeOutput(); + canAdd = InventoryUtil.tryAddStack( + this, + pendingProduct, + InventoryCarpenter.SLOT_PRODUCT, + InventoryCarpenter.SLOT_PRODUCT_COUNT, + true, + false); + } - IErrorLogic errorLogic = getErrorLogic(); - errorLogic.setCondition(!hasRecipe, EnumErrorCode.NO_RECIPE); - errorLogic.setCondition(!hasLiquidResources, EnumErrorCode.NO_RESOURCE_LIQUID); - errorLogic.setCondition(!hasItemResources, EnumErrorCode.NO_RESOURCE_INVENTORY); - errorLogic.setCondition(!canAdd, EnumErrorCode.NO_SPACE_INVENTORY); + IErrorLogic errorLogic = getErrorLogic(); + errorLogic.setCondition(!hasRecipe, EnumErrorCode.NO_RECIPE); + errorLogic.setCondition(!hasLiquidResources, EnumErrorCode.NO_RESOURCE_LIQUID); + errorLogic.setCondition(!hasItemResources, EnumErrorCode.NO_RESOURCE_INVENTORY); + errorLogic.setCondition(!canAdd, EnumErrorCode.NO_SPACE_INVENTORY); - return hasRecipe && hasItemResources && hasLiquidResources && canAdd; - } + return hasRecipe && hasItemResources && hasLiquidResources && canAdd; + } - @Override - public TankRenderInfo getResourceTankInfo() { - return new TankRenderInfo(resourceTank); - } + @Override + public TankRenderInfo getResourceTankInfo() { + return new TankRenderInfo(resourceTank); + } - /** - * @return Inaccessible crafting inventory for the craft grid. - */ - public IInventory getCraftingInventory() { - return craftingInventory; - } + /** + * @return Inaccessible crafting inventory for the craft grid. + */ + public IInventory getCraftingInventory() { + return craftingInventory; + } - public IInventory getCraftPreviewInventory() { - return craftPreviewInventory; - } + public IInventory getCraftPreviewInventory() { + return craftPreviewInventory; + } - @Override - public void handleItemStackForDisplay(ItemStack itemStack) { - craftPreviewInventory.setInventorySlotContents(0, itemStack); - } + @Override + public void handleItemStackForDisplay(ItemStack itemStack) { + craftPreviewInventory.setInventorySlotContents(0, itemStack); + } - // IFLUIDCONTAINER IMPLEMENTATION - @Override - public int fill(ForgeDirection direction, FluidStack resource, boolean doFill) { - return tankManager.fill(direction, resource, doFill); - } + // IFLUIDCONTAINER IMPLEMENTATION + @Override + public int fill(ForgeDirection direction, FluidStack resource, boolean doFill) { + return tankManager.fill(direction, resource, doFill); + } - @Override - public TankManager getTankManager() { - return tankManager; - } + @Override + public TankManager getTankManager() { + return tankManager; + } - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return tankManager.drain(from, resource, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return tankManager.drain(from, maxDrain, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return tankManager.canFill(from, fluid); - } + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return tankManager.canDrain(from, fluid); - } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return tankManager.getTankInfo(from); - } + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiCarpenter(player.inventory, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiCarpenter(player.inventory, this); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerCarpenter(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerCarpenter(player.inventory, this); + } } diff --git a/src/main/java/forestry/factory/tiles/TileCentrifuge.java b/src/main/java/forestry/factory/tiles/TileCentrifuge.java index c023301cb..65f81840c 100644 --- a/src/main/java/forestry/factory/tiles/TileCentrifuge.java +++ b/src/main/java/forestry/factory/tiles/TileCentrifuge.java @@ -10,22 +10,8 @@ ******************************************************************************/ package forestry.factory.tiles; -import java.io.IOException; -import java.util.Collection; -import java.util.LinkedList; -import java.util.Stack; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.statements.ITriggerExternal; import cpw.mods.fml.common.Optional; - import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.CircuitSocketType; import forestry.api.circuits.ICircuitBoard; @@ -46,217 +32,231 @@ import forestry.factory.gui.GuiCentrifuge; import forestry.factory.inventory.InventoryCentrifuge; import forestry.factory.recipes.CentrifugeRecipeManager; import forestry.factory.triggers.FactoryTriggers; - -import buildcraft.api.statements.ITriggerExternal; +import java.io.IOException; +import java.util.Collection; +import java.util.LinkedList; +import java.util.Stack; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TileCentrifuge extends TilePowered implements ISocketable, ISidedInventory { - private static final int TICKS_PER_RECIPE_TIME = 1; - private static final int ENERGY_PER_WORK_CYCLE = 3200; - private static final int ENERGY_PER_RECIPE_TIME = ENERGY_PER_WORK_CYCLE / 20; + private static final int TICKS_PER_RECIPE_TIME = 1; + private static final int ENERGY_PER_WORK_CYCLE = 3200; + private static final int ENERGY_PER_RECIPE_TIME = ENERGY_PER_WORK_CYCLE / 20; - private final InventoryAdapter sockets = new InventoryAdapter(1, "sockets"); + private final InventoryAdapter sockets = new InventoryAdapter(1, "sockets"); - private ICentrifugeRecipe currentRecipe; + private ICentrifugeRecipe currentRecipe; - private final Stack pendingProducts = new Stack<>(); + private final Stack pendingProducts = new Stack<>(); - public TileCentrifuge() { - super("centrifuge", 800, Constants.MACHINE_MAX_ENERGY); - setInternalInventory(new InventoryCentrifuge(this)); - } + public TileCentrifuge() { + super("centrifuge", 800, Constants.MACHINE_MAX_ENERGY); + setInternalInventory(new InventoryCentrifuge(this)); + } - /* LOADING & SAVING */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + /* LOADING & SAVING */ + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - sockets.writeToNBT(nbttagcompound); + sockets.writeToNBT(nbttagcompound); - NBTTagList nbttaglist = new NBTTagList(); - ItemStack[] offspring = pendingProducts.toArray(new ItemStack[pendingProducts.size()]); - for (int i = 0; i < offspring.length; i++) { - if (offspring[i] != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte("Slot", (byte) i); - offspring[i].writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); - } - } - nbttagcompound.setTag("PendingProducts", nbttaglist); - } + NBTTagList nbttaglist = new NBTTagList(); + ItemStack[] offspring = pendingProducts.toArray(new ItemStack[pendingProducts.size()]); + for (int i = 0; i < offspring.length; i++) { + if (offspring[i] != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setByte("Slot", (byte) i); + offspring[i].writeToNBT(nbttagcompound1); + nbttaglist.appendTag(nbttagcompound1); + } + } + nbttagcompound.setTag("PendingProducts", nbttaglist); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); - NBTTagList nbttaglist = nbttagcompound.getTagList("PendingProducts", 10); - for (int i = 0; i < nbttaglist.tagCount(); i++) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - pendingProducts.add(ItemStack.loadItemStackFromNBT(nbttagcompound1)); - } - sockets.readFromNBT(nbttagcompound); + NBTTagList nbttaglist = nbttagcompound.getTagList("PendingProducts", 10); + for (int i = 0; i < nbttaglist.tagCount(); i++) { + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + pendingProducts.add(ItemStack.loadItemStackFromNBT(nbttagcompound1)); + } + sockets.readFromNBT(nbttagcompound); - ItemStack chip = sockets.getStackInSlot(0); - if (chip != null) { - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(chip); - if (chipset != null) { - chipset.onLoad(this); - } - } - } + ItemStack chip = sockets.getStackInSlot(0); + if (chip != null) { + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(chip); + if (chipset != null) { + chipset.onLoad(this); + } + } + } - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - super.writeGuiData(data); - sockets.writeData(data); - } + @Override + public void writeGuiData(DataOutputStreamForestry data) throws IOException { + super.writeGuiData(data); + sockets.writeData(data); + } - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - super.readGuiData(data); - sockets.readData(data); - } + @Override + public void readGuiData(DataInputStreamForestry data) throws IOException { + super.readGuiData(data); + sockets.readData(data); + } - @Override - public boolean workCycle() { + @Override + public boolean workCycle() { - // If we add pending products, we skip to the next work cycle. - if (tryAddPending()) { - return false; - } + // If we add pending products, we skip to the next work cycle. + if (tryAddPending()) { + return false; + } - if (!pendingProducts.isEmpty()) { - return false; - } + if (!pendingProducts.isEmpty()) { + return false; + } - if (currentRecipe == null) { - return false; - } + if (currentRecipe == null) { + return false; + } - // We are done, add products to queue - Collection products = currentRecipe.getProducts(worldObj.rand); - pendingProducts.addAll(products); + // We are done, add products to queue + Collection products = currentRecipe.getProducts(worldObj.rand); + pendingProducts.addAll(products); - getInternalInventory().decrStackSize(InventoryCentrifuge.SLOT_RESOURCE, 1); + getInternalInventory().decrStackSize(InventoryCentrifuge.SLOT_RESOURCE, 1); - tryAddPending(); - return true; - } + tryAddPending(); + return true; + } - private void checkRecipe() { - ItemStack resource = getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE); - ICentrifugeRecipe matchingRecipe = CentrifugeRecipeManager.findMatchingRecipe(resource); + private void checkRecipe() { + ItemStack resource = getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE); + ICentrifugeRecipe matchingRecipe = CentrifugeRecipeManager.findMatchingRecipe(resource); - if (currentRecipe != matchingRecipe) { - currentRecipe = matchingRecipe; - if (currentRecipe != null) { - int recipeTime = currentRecipe.getProcessingTime(); - setTicksPerWorkCycle(recipeTime * TICKS_PER_RECIPE_TIME); - setEnergyPerWorkCycle(recipeTime * ENERGY_PER_RECIPE_TIME); - } - } - } + if (currentRecipe != matchingRecipe) { + currentRecipe = matchingRecipe; + if (currentRecipe != null) { + int recipeTime = currentRecipe.getProcessingTime(); + setTicksPerWorkCycle(recipeTime * TICKS_PER_RECIPE_TIME); + setEnergyPerWorkCycle(recipeTime * ENERGY_PER_RECIPE_TIME); + } + } + } - private boolean tryAddPending() { - if (pendingProducts.isEmpty()) { - return false; - } + private boolean tryAddPending() { + if (pendingProducts.isEmpty()) { + return false; + } - ItemStack next = pendingProducts.peek(); + ItemStack next = pendingProducts.peek(); - boolean added = InventoryUtil.tryAddStack(this, next, InventoryCentrifuge.SLOT_PRODUCT_1, InventoryCentrifuge.SLOT_PRODUCT_COUNT, true); + boolean added = InventoryUtil.tryAddStack( + this, next, InventoryCentrifuge.SLOT_PRODUCT_1, InventoryCentrifuge.SLOT_PRODUCT_COUNT, true); - if (added) { - pendingProducts.pop(); - } + if (added) { + pendingProducts.pop(); + } - getErrorLogic().setCondition(!added, EnumErrorCode.NO_SPACE_INVENTORY); - return added; - } + getErrorLogic().setCondition(!added, EnumErrorCode.NO_SPACE_INVENTORY); + return added; + } - @Override - public boolean hasResourcesMin(float percentage) { - IInventoryAdapter inventory = getInternalInventory(); - if (inventory.getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE) == null) { - return false; - } + @Override + public boolean hasResourcesMin(float percentage) { + IInventoryAdapter inventory = getInternalInventory(); + if (inventory.getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE) == null) { + return false; + } - return ((float) inventory.getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE).stackSize / (float) inventory.getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE).getMaxStackSize()) > percentage; - } + return ((float) inventory.getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE).stackSize + / (float) inventory + .getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE) + .getMaxStackSize()) + > percentage; + } - @Override - public boolean hasWork() { - checkRecipe(); + @Override + public boolean hasWork() { + checkRecipe(); - boolean hasResource = getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE) != null; + boolean hasResource = getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE) != null; - IErrorLogic errorLogic = getErrorLogic(); - errorLogic.setCondition(!hasResource, EnumErrorCode.NO_RESOURCE); + IErrorLogic errorLogic = getErrorLogic(); + errorLogic.setCondition(!hasResource, EnumErrorCode.NO_RESOURCE); - return hasResource; - } + return hasResource; + } - /* ITRIGGERPROVIDER */ - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { - LinkedList res = new LinkedList<>(); - res.add(FactoryTriggers.lowResource25); - res.add(FactoryTriggers.lowResource10); - return res; - } + /* ITRIGGERPROVIDER */ + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { + LinkedList res = new LinkedList<>(); + res.add(FactoryTriggers.lowResource25); + res.add(FactoryTriggers.lowResource10); + return res; + } - /* ISocketable */ - @Override - public int getSocketCount() { - return sockets.getSizeInventory(); - } + /* ISocketable */ + @Override + public int getSocketCount() { + return sockets.getSizeInventory(); + } - @Override - public ItemStack getSocket(int slot) { - return sockets.getStackInSlot(slot); - } + @Override + public ItemStack getSocket(int slot) { + return sockets.getStackInSlot(slot); + } - @Override - public void setSocket(int slot, ItemStack stack) { + @Override + public void setSocket(int slot, ItemStack stack) { - if (stack != null && !ChipsetManager.circuitRegistry.isChipset(stack)) { - return; - } + if (stack != null && !ChipsetManager.circuitRegistry.isChipset(stack)) { + return; + } - // Dispose correctly of old chipsets - if (sockets.getStackInSlot(slot) != null) { - if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(sockets.getStackInSlot(slot)); - if (chipset != null) { - chipset.onRemoval(this); - } - } - } + // Dispose correctly of old chipsets + if (sockets.getStackInSlot(slot) != null) { + if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(sockets.getStackInSlot(slot)); + if (chipset != null) { + chipset.onRemoval(this); + } + } + } - sockets.setInventorySlotContents(slot, stack); - if (stack == null) { - return; - } + sockets.setInventorySlotContents(slot, stack); + if (stack == null) { + return; + } - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(stack); - if (chipset != null) { - chipset.onInsertion(this); - } - } + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(stack); + if (chipset != null) { + chipset.onInsertion(this); + } + } - @Override - public ICircuitSocketType getSocketType() { - return CircuitSocketType.MACHINE; - } + @Override + public ICircuitSocketType getSocketType() { + return CircuitSocketType.MACHINE; + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiCentrifuge(player.inventory, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiCentrifuge(player.inventory, this); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerCentrifuge(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerCentrifuge(player.inventory, this); + } } diff --git a/src/main/java/forestry/factory/tiles/TileFabricator.java b/src/main/java/forestry/factory/tiles/TileFabricator.java index da16b8ed3..500e15eb8 100644 --- a/src/main/java/forestry/factory/tiles/TileFabricator.java +++ b/src/main/java/forestry/factory/tiles/TileFabricator.java @@ -10,23 +10,6 @@ ******************************************************************************/ package forestry.factory.tiles; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.ICrafting; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; - import forestry.api.core.IErrorLogic; import forestry.api.recipes.IFabricatorRecipe; import forestry.api.recipes.IFabricatorSmeltingRecipe; @@ -53,316 +36,341 @@ import forestry.factory.inventory.InventoryFabricator; import forestry.factory.inventory.InventoryGhostCrafting; import forestry.factory.recipes.FabricatorRecipeManager; import forestry.factory.recipes.FabricatorSmeltingRecipeManager; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; -public class TileFabricator extends TilePowered implements ISlotPickupWatcher, ILiquidTankTile, IFluidHandler, ISidedInventory { - private static final int MAX_HEAT = 5000; +public class TileFabricator extends TilePowered + implements ISlotPickupWatcher, ILiquidTankTile, IFluidHandler, ISidedInventory { + private static final int MAX_HEAT = 5000; - private final InventoryAdapterTile craftingInventory; - private final TankManager tankManager; - private final FilteredTank moltenTank; - private int heat = 0; - private int meltingPoint = 0; + private final InventoryAdapterTile craftingInventory; + private final TankManager tankManager; + private final FilteredTank moltenTank; + private int heat = 0; + private int meltingPoint = 0; - public TileFabricator() { - super("fabricator", 1100, 3300); - setEnergyPerWorkCycle(200); - craftingInventory = new InventoryGhostCrafting<>(this, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); - setInternalInventory(new InventoryFabricator(this)); - moltenTank = new FilteredTank(8 * Constants.BUCKET_VOLUME, Fluids.GLASS.getFluid()); - moltenTank.tankMode = StandardTank.TankMode.INTERNAL; - tankManager = new TankManager(this, moltenTank); - } + public TileFabricator() { + super("fabricator", 1100, 3300); + setEnergyPerWorkCycle(200); + craftingInventory = new InventoryGhostCrafting<>(this, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); + setInternalInventory(new InventoryFabricator(this)); + moltenTank = new FilteredTank(8 * Constants.BUCKET_VOLUME, Fluids.GLASS.getFluid()); + moltenTank.tankMode = StandardTank.TankMode.INTERNAL; + tankManager = new TankManager(this, moltenTank); + } - /* SAVING & LOADING */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + /* SAVING & LOADING */ + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - nbttagcompound.setInteger("Heat", heat); - tankManager.writeToNBT(nbttagcompound); - craftingInventory.writeToNBT(nbttagcompound); - } + nbttagcompound.setInteger("Heat", heat); + tankManager.writeToNBT(nbttagcompound); + craftingInventory.writeToNBT(nbttagcompound); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); - heat = nbttagcompound.getInteger("Heat"); - tankManager.readFromNBT(nbttagcompound); - craftingInventory.readFromNBT(nbttagcompound); + heat = nbttagcompound.getInteger("Heat"); + tankManager.readFromNBT(nbttagcompound); + craftingInventory.readFromNBT(nbttagcompound); - // FIXME 1.8: wont need this - // move items from legacy crafting area to the new one - IInventory inventory = getInternalInventory(); - for (int slot = InventoryFabricator.SLOT_CRAFTING_LEGACY_1; slot < InventoryFabricator.SLOT_CRAFTING_LEGACY_1 + InventoryFabricator.SLOT_CRAFTING_LEGACY_COUNT; slot++) { - ItemStack stack = inventory.getStackInSlot(slot); - if (stack != null) { - inventory.setInventorySlotContents(slot, null); + // FIXME 1.8: wont need this + // move items from legacy crafting area to the new one + IInventory inventory = getInternalInventory(); + for (int slot = InventoryFabricator.SLOT_CRAFTING_LEGACY_1; + slot < InventoryFabricator.SLOT_CRAFTING_LEGACY_1 + InventoryFabricator.SLOT_CRAFTING_LEGACY_COUNT; + slot++) { + ItemStack stack = inventory.getStackInSlot(slot); + if (stack != null) { + inventory.setInventorySlotContents(slot, null); - int newSlot = slot - InventoryFabricator.SLOT_CRAFTING_LEGACY_1; - craftingInventory.setInventorySlotContents(newSlot, stack); - } - } - } + int newSlot = slot - InventoryFabricator.SLOT_CRAFTING_LEGACY_1; + craftingInventory.setInventorySlotContents(newSlot, stack); + } + } + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - tankManager.writeData(data); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + tankManager.writeData(data); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - tankManager.readData(data); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + tankManager.readData(data); + } - /* UPDATING */ - @Override - public void updateServerSide() { - super.updateServerSide(); + /* UPDATING */ + @Override + public void updateServerSide() { + super.updateServerSide(); - if (!moltenTank.isFull()) { - trySmelting(); - } + if (!moltenTank.isFull()) { + trySmelting(); + } - if (!moltenTank.isEmpty()) { - // Remove smelt if we have gone below melting point - if (heat < (getMeltingPoint() - 100)) { - moltenTank.drain(5, true); - } - } + if (!moltenTank.isEmpty()) { + // Remove smelt if we have gone below melting point + if (heat < (getMeltingPoint() - 100)) { + moltenTank.drain(5, true); + } + } - if (heat > 2500) { - this.heat -= 2; - } else if (heat > 0) { - this.heat--; - } - } + if (heat > 2500) { + this.heat -= 2; + } else if (heat > 0) { + this.heat--; + } + } - private void trySmelting() { - IInventoryAdapter inventory = getInternalInventory(); + private void trySmelting() { + IInventoryAdapter inventory = getInternalInventory(); - ItemStack smeltResource = inventory.getStackInSlot(InventoryFabricator.SLOT_METAL); - if (smeltResource == null) { - return; - } + ItemStack smeltResource = inventory.getStackInSlot(InventoryFabricator.SLOT_METAL); + if (smeltResource == null) { + return; + } - IFabricatorSmeltingRecipe smelt = FabricatorSmeltingRecipeManager.findMatchingSmelting(smeltResource); - if (smelt == null || smelt.getMeltingPoint() > heat) { - return; - } + IFabricatorSmeltingRecipe smelt = FabricatorSmeltingRecipeManager.findMatchingSmelting(smeltResource); + if (smelt == null || smelt.getMeltingPoint() > heat) { + return; + } - FluidStack smeltFluid = smelt.getProduct(); - if (moltenTank.canFill(smeltFluid)) { - this.decrStackSize(InventoryFabricator.SLOT_METAL, 1); - moltenTank.fill(smeltFluid, true); - meltingPoint = smelt.getMeltingPoint(); - } - } + FluidStack smeltFluid = smelt.getProduct(); + if (moltenTank.canFill(smeltFluid)) { + this.decrStackSize(InventoryFabricator.SLOT_METAL, 1); + moltenTank.fill(smeltFluid, true); + meltingPoint = smelt.getMeltingPoint(); + } + } - @Override - public boolean workCycle() { - this.heat += 100; - if (this.heat > MAX_HEAT) { - this.heat = MAX_HEAT; - } + @Override + public boolean workCycle() { + this.heat += 100; + if (this.heat > MAX_HEAT) { + this.heat = MAX_HEAT; + } - craftResult(); + craftResult(); - return true; - } + return true; + } - private IFabricatorRecipe getRecipe() { - IInventoryAdapter inventory = getInternalInventory(); - ItemStack plan = inventory.getStackInSlot(InventoryFabricator.SLOT_PLAN); - FluidStack liquid = moltenTank.getFluid(); - IFabricatorRecipe recipe = FabricatorRecipeManager.findMatchingRecipe(plan, craftingInventory); - if (liquid != null && !liquid.containsFluid(recipe.getLiquid())) { - return null; - } - return recipe; - } + private IFabricatorRecipe getRecipe() { + IInventoryAdapter inventory = getInternalInventory(); + ItemStack plan = inventory.getStackInSlot(InventoryFabricator.SLOT_PLAN); + FluidStack liquid = moltenTank.getFluid(); + IFabricatorRecipe recipe = FabricatorRecipeManager.findMatchingRecipe(plan, craftingInventory); + if (liquid != null && !liquid.containsFluid(recipe.getLiquid())) { + return null; + } + return recipe; + } - public ItemStack getResult() { - IFabricatorRecipe myRecipe = getRecipe(); + public ItemStack getResult() { + IFabricatorRecipe myRecipe = getRecipe(); - if (myRecipe == null) { - return null; - } + if (myRecipe == null) { + return null; + } - return myRecipe.getRecipeOutput().copy(); - } + return myRecipe.getRecipeOutput().copy(); + } - /* ISlotPickupWatcher */ - @Override - public void onPickupFromSlot(int slotIndex, EntityPlayer player) { - if (slotIndex == InventoryFabricator.SLOT_RESULT) { - decrStackSize(InventoryFabricator.SLOT_RESULT, 1); - } - } + /* ISlotPickupWatcher */ + @Override + public void onPickupFromSlot(int slotIndex, EntityPlayer player) { + if (slotIndex == InventoryFabricator.SLOT_RESULT) { + decrStackSize(InventoryFabricator.SLOT_RESULT, 1); + } + } - private void craftResult() { - IFabricatorRecipe myRecipe = getRecipe(); - if (myRecipe == null) { - return; - } + private void craftResult() { + IFabricatorRecipe myRecipe = getRecipe(); + if (myRecipe == null) { + return; + } - ItemStack result = getResult(); - if (result == null) { - return; - } + ItemStack result = getResult(); + if (result == null) { + return; + } - if (getStackInSlot(InventoryFabricator.SLOT_RESULT) != null) { - return; - } + if (getStackInSlot(InventoryFabricator.SLOT_RESULT) != null) { + return; + } - FluidStack liquid = myRecipe.getLiquid(); + FluidStack liquid = myRecipe.getLiquid(); - // Remove resources - ItemStack[] crafting = InventoryUtil.getStacks(craftingInventory, InventoryGhostCrafting.SLOT_CRAFTING_1, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); - if (!removeFromInventory(crafting, null, false)) { - return; - } + // Remove resources + ItemStack[] crafting = InventoryUtil.getStacks( + craftingInventory, InventoryGhostCrafting.SLOT_CRAFTING_1, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); + if (!removeFromInventory(crafting, null, false)) { + return; + } - if (!moltenTank.canDrain(liquid)) { - return; - } + if (!moltenTank.canDrain(liquid)) { + return; + } - removeFromInventory(crafting, null, true); - moltenTank.drain(liquid.amount, true); + removeFromInventory(crafting, null, true); + moltenTank.drain(liquid.amount, true); - // Damage plan - if (getStackInSlot(InventoryFabricator.SLOT_PLAN) != null) { - Item planItem = getStackInSlot(InventoryFabricator.SLOT_PLAN).getItem(); - if (planItem instanceof ICraftingPlan) { - setInventorySlotContents(InventoryFabricator.SLOT_PLAN, ((ICraftingPlan) planItem).planUsed(getStackInSlot(InventoryFabricator.SLOT_PLAN), result)); - } - } + // Damage plan + if (getStackInSlot(InventoryFabricator.SLOT_PLAN) != null) { + Item planItem = getStackInSlot(InventoryFabricator.SLOT_PLAN).getItem(); + if (planItem instanceof ICraftingPlan) { + setInventorySlotContents( + InventoryFabricator.SLOT_PLAN, + ((ICraftingPlan) planItem).planUsed(getStackInSlot(InventoryFabricator.SLOT_PLAN), result)); + } + } - setInventorySlotContents(InventoryFabricator.SLOT_RESULT, result); - } + setInventorySlotContents(InventoryFabricator.SLOT_RESULT, result); + } - private boolean removeFromInventory(ItemStack[] set, EntityPlayer player, boolean doRemove) { - IInventory inventory = new InventoryMapper(this, InventoryFabricator.SLOT_INVENTORY_1, InventoryFabricator.SLOT_INVENTORY_COUNT); - return InventoryUtil.removeSets(inventory, 1, set, player, true, true, false, doRemove); - } + private boolean removeFromInventory(ItemStack[] set, EntityPlayer player, boolean doRemove) { + IInventory inventory = new InventoryMapper( + this, InventoryFabricator.SLOT_INVENTORY_1, InventoryFabricator.SLOT_INVENTORY_COUNT); + return InventoryUtil.removeSets(inventory, 1, set, player, true, true, false, doRemove); + } - @Override - public boolean hasWork() { - boolean hasRecipe = true; - boolean hasLiquidResources = true; - boolean hasResources = true; + @Override + public boolean hasWork() { + boolean hasRecipe = true; + boolean hasLiquidResources = true; + boolean hasResources = true; - ItemStack plan = getStackInSlot(InventoryFabricator.SLOT_PLAN); - IFabricatorRecipe recipe = FabricatorRecipeManager.findMatchingRecipe(plan, craftingInventory); - if (recipe != null) { - ItemStack[] crafting = InventoryUtil.getStacks(craftingInventory, InventoryGhostCrafting.SLOT_CRAFTING_1, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); - hasResources = removeFromInventory(crafting, null, false); - hasLiquidResources = moltenTank.canDrain(recipe.getLiquid()); - } else { - hasRecipe = false; - } + ItemStack plan = getStackInSlot(InventoryFabricator.SLOT_PLAN); + IFabricatorRecipe recipe = FabricatorRecipeManager.findMatchingRecipe(plan, craftingInventory); + if (recipe != null) { + ItemStack[] crafting = InventoryUtil.getStacks( + craftingInventory, + InventoryGhostCrafting.SLOT_CRAFTING_1, + InventoryGhostCrafting.SLOT_CRAFTING_COUNT); + hasResources = removeFromInventory(crafting, null, false); + hasLiquidResources = moltenTank.canDrain(recipe.getLiquid()); + } else { + hasRecipe = false; + } - IErrorLogic errorLogic = getErrorLogic(); - errorLogic.setCondition(!hasRecipe, EnumErrorCode.NO_RECIPE); - errorLogic.setCondition(!hasLiquidResources, EnumErrorCode.NO_RESOURCE_LIQUID); - errorLogic.setCondition(!hasResources, EnumErrorCode.NO_RESOURCE_INVENTORY); + IErrorLogic errorLogic = getErrorLogic(); + errorLogic.setCondition(!hasRecipe, EnumErrorCode.NO_RECIPE); + errorLogic.setCondition(!hasLiquidResources, EnumErrorCode.NO_RESOURCE_LIQUID); + errorLogic.setCondition(!hasResources, EnumErrorCode.NO_RESOURCE_INVENTORY); - return hasRecipe; - } + return hasRecipe; + } - public int getHeatScaled(int i) { - return (heat * i) / MAX_HEAT; - } + public int getHeatScaled(int i) { + return (heat * i) / MAX_HEAT; + } - private int getMeltingPoint() { - if (this.getStackInSlot(InventoryFabricator.SLOT_METAL) != null) { - IFabricatorSmeltingRecipe smelt = FabricatorSmeltingRecipeManager.findMatchingSmelting(this.getStackInSlot(InventoryFabricator.SLOT_METAL)); - if (smelt != null) { - return smelt.getMeltingPoint(); - } - } else if (moltenTank.getFluidAmount() > 0) { - return meltingPoint; - } + private int getMeltingPoint() { + if (this.getStackInSlot(InventoryFabricator.SLOT_METAL) != null) { + IFabricatorSmeltingRecipe smelt = FabricatorSmeltingRecipeManager.findMatchingSmelting( + this.getStackInSlot(InventoryFabricator.SLOT_METAL)); + if (smelt != null) { + return smelt.getMeltingPoint(); + } + } else if (moltenTank.getFluidAmount() > 0) { + return meltingPoint; + } - return 0; - } + return 0; + } - public int getMeltingPointScaled(int i) { - int meltingPoint = getMeltingPoint(); + public int getMeltingPointScaled(int i) { + int meltingPoint = getMeltingPoint(); - if (meltingPoint <= 0) { - return 0; - } else { - return (meltingPoint * i) / MAX_HEAT; - } - } + if (meltingPoint <= 0) { + return 0; + } else { + return (meltingPoint * i) / MAX_HEAT; + } + } - /* SMP */ - public void getGUINetworkData(int i, int j) { - if (i == 0) { - heat = j; - } else if (i == 1) { - meltingPoint = j; - } - } + /* SMP */ + public void getGUINetworkData(int i, int j) { + if (i == 0) { + heat = j; + } else if (i == 1) { + meltingPoint = j; + } + } - public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, heat); - iCrafting.sendProgressBarUpdate(container, 1, getMeltingPoint()); - } + public void sendGUINetworkData(Container container, ICrafting iCrafting) { + iCrafting.sendProgressBarUpdate(container, 0, heat); + iCrafting.sendProgressBarUpdate(container, 1, getMeltingPoint()); + } - /** - * @return Inaccessible crafting inventory for the craft grid. - */ - public InventoryAdapter getCraftingInventory() { - return craftingInventory; - } + /** + * @return Inaccessible crafting inventory for the craft grid. + */ + public InventoryAdapter getCraftingInventory() { + return craftingInventory; + } - /* ILIQUIDCONTAINER */ - @Override - public TankManager getTankManager() { - return tankManager; - } + /* ILIQUIDCONTAINER */ + @Override + public TankManager getTankManager() { + return tankManager; + } - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return tankManager.fill(from, resource, doFill); - } + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return tankManager.drain(from, resource, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return tankManager.drain(from, maxDrain, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return tankManager.canFill(from, fluid); - } + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return tankManager.canDrain(from, fluid); - } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return tankManager.getTankInfo(from); - } + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiFabricator(player.inventory, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiFabricator(player.inventory, this); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerFabricator(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerFabricator(player.inventory, this); + } } diff --git a/src/main/java/forestry/factory/tiles/TileFermenter.java b/src/main/java/forestry/factory/tiles/TileFermenter.java index 2b6d8960e..175a688c5 100644 --- a/src/main/java/forestry/factory/tiles/TileFermenter.java +++ b/src/main/java/forestry/factory/tiles/TileFermenter.java @@ -10,26 +10,8 @@ ******************************************************************************/ package forestry.factory.tiles; -import java.io.IOException; -import java.util.Collection; -import java.util.LinkedList; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.ICrafting; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; - +import buildcraft.api.statements.ITriggerExternal; import cpw.mods.fml.common.Optional; - import forestry.api.core.IErrorLogic; import forestry.api.fuels.FermenterFuel; import forestry.api.fuels.FuelManager; @@ -51,303 +33,320 @@ import forestry.factory.gui.GuiFermenter; import forestry.factory.inventory.InventoryFermenter; import forestry.factory.recipes.FermenterRecipeManager; import forestry.factory.triggers.FactoryTriggers; - -import buildcraft.api.statements.ITriggerExternal; +import java.io.IOException; +import java.util.Collection; +import java.util.LinkedList; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; public class TileFermenter extends TilePowered implements ISidedInventory, ILiquidTankTile, IFluidHandler { - private final FilteredTank resourceTank; - private final FilteredTank productTank; - private final TankManager tankManager; + private final FilteredTank resourceTank; + private final FilteredTank productTank; + private final TankManager tankManager; - private IFermenterRecipe currentRecipe; - private float currentResourceModifier; - private int fermentationTime = 0; - private int fermentationTotalTime = 0; - private int fuelBurnTime = 0; - private int fuelTotalTime = 0; - private int fuelCurrentFerment = 0; + private IFermenterRecipe currentRecipe; + private float currentResourceModifier; + private int fermentationTime = 0; + private int fermentationTotalTime = 0; + private int fuelBurnTime = 0; + private int fuelTotalTime = 0; + private int fuelCurrentFerment = 0; - public TileFermenter() { - super("fermenter", 2000, 8000); - setEnergyPerWorkCycle(4200); - setInternalInventory(new InventoryFermenter(this)); - resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, FermenterRecipeManager.recipeFluidInputs); - resourceTank.tankMode = StandardTank.TankMode.INPUT; - productTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, FermenterRecipeManager.recipeFluidOutputs); - productTank.tankMode = StandardTank.TankMode.OUTPUT; - tankManager = new TankManager(this, resourceTank, productTank); - } + public TileFermenter() { + super("fermenter", 2000, 8000); + setEnergyPerWorkCycle(4200); + setInternalInventory(new InventoryFermenter(this)); + resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, FermenterRecipeManager.recipeFluidInputs); + resourceTank.tankMode = StandardTank.TankMode.INPUT; + productTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, FermenterRecipeManager.recipeFluidOutputs); + productTank.tankMode = StandardTank.TankMode.OUTPUT; + tankManager = new TankManager(this, resourceTank, productTank); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - nbttagcompound.setInteger("FermentationTime", fermentationTime); - nbttagcompound.setInteger("FermentationTotalTime", fermentationTotalTime); - nbttagcompound.setInteger("FuelBurnTime", fuelBurnTime); - nbttagcompound.setInteger("FuelTotalTime", fuelTotalTime); - nbttagcompound.setInteger("FuelCurrentFerment", fuelCurrentFerment); + nbttagcompound.setInteger("FermentationTime", fermentationTime); + nbttagcompound.setInteger("FermentationTotalTime", fermentationTotalTime); + nbttagcompound.setInteger("FuelBurnTime", fuelBurnTime); + nbttagcompound.setInteger("FuelTotalTime", fuelTotalTime); + nbttagcompound.setInteger("FuelCurrentFerment", fuelCurrentFerment); - tankManager.writeToNBT(nbttagcompound); - } + tankManager.writeToNBT(nbttagcompound); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); - fermentationTime = nbttagcompound.getInteger("FermentationTime"); - fermentationTotalTime = nbttagcompound.getInteger("FermentationTotalTime"); - fuelBurnTime = nbttagcompound.getInteger("FuelBurnTime"); - fuelTotalTime = nbttagcompound.getInteger("FuelTotalTime"); - fuelCurrentFerment = nbttagcompound.getInteger("FuelCurrentFerment"); + fermentationTime = nbttagcompound.getInteger("FermentationTime"); + fermentationTotalTime = nbttagcompound.getInteger("FermentationTotalTime"); + fuelBurnTime = nbttagcompound.getInteger("FuelBurnTime"); + fuelTotalTime = nbttagcompound.getInteger("FuelTotalTime"); + fuelCurrentFerment = nbttagcompound.getInteger("FuelCurrentFerment"); - tankManager.readFromNBT(nbttagcompound); - } + tankManager.readFromNBT(nbttagcompound); + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - tankManager.writeData(data); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + tankManager.writeData(data); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - tankManager.readData(data); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + tankManager.readData(data); + } - @Override - public void updateServerSide() { - super.updateServerSide(); + @Override + public void updateServerSide() { + super.updateServerSide(); - if (updateOnInterval(20)) { - FluidHelper.drainContainers(tankManager, this, InventoryFermenter.SLOT_INPUT); + if (updateOnInterval(20)) { + FluidHelper.drainContainers(tankManager, this, InventoryFermenter.SLOT_INPUT); - FluidStack fluidStack = productTank.getFluid(); - if (fluidStack != null) { - FluidHelper.fillContainers(tankManager, this, InventoryFermenter.SLOT_CAN_INPUT, InventoryFermenter.SLOT_CAN_OUTPUT, fluidStack.getFluid()); - } - } - } + FluidStack fluidStack = productTank.getFluid(); + if (fluidStack != null) { + FluidHelper.fillContainers( + tankManager, + this, + InventoryFermenter.SLOT_CAN_INPUT, + InventoryFermenter.SLOT_CAN_OUTPUT, + fluidStack.getFluid()); + } + } + } - @Override - public boolean workCycle() { - int fermented = Math.min(fermentationTime, fuelCurrentFerment); - int productAmount = Math.round(fermented * currentRecipe.getModifier() * currentResourceModifier); - productTank.fill(new FluidStack(currentRecipe.getOutput(), productAmount), true); + @Override + public boolean workCycle() { + int fermented = Math.min(fermentationTime, fuelCurrentFerment); + int productAmount = Math.round(fermented * currentRecipe.getModifier() * currentResourceModifier); + productTank.fill(new FluidStack(currentRecipe.getOutput(), productAmount), true); - fuelBurnTime--; - resourceTank.drain(fuelCurrentFerment, true); - fermentationTime -= this.fuelCurrentFerment; + fuelBurnTime--; + resourceTank.drain(fuelCurrentFerment, true); + fermentationTime -= this.fuelCurrentFerment; - // Not done yet - if (fermentationTime > 0) { - return false; - } + // Not done yet + if (fermentationTime > 0) { + return false; + } - currentRecipe = null; - return true; - } + currentRecipe = null; + return true; + } - private void checkRecipe() { - if (currentRecipe != null) { - return; - } + private void checkRecipe() { + if (currentRecipe != null) { + return; + } - ItemStack resource = getStackInSlot(InventoryFermenter.SLOT_RESOURCE); - FluidStack fluid = resourceTank.getFluid(); + ItemStack resource = getStackInSlot(InventoryFermenter.SLOT_RESOURCE); + FluidStack fluid = resourceTank.getFluid(); - currentRecipe = FermenterRecipeManager.findMatchingRecipe(resource, fluid); + currentRecipe = FermenterRecipeManager.findMatchingRecipe(resource, fluid); - fermentationTotalTime = fermentationTime = (currentRecipe == null) ? 0 : currentRecipe.getFermentationValue(); + fermentationTotalTime = fermentationTime = (currentRecipe == null) ? 0 : currentRecipe.getFermentationValue(); - if (currentRecipe != null) { - currentResourceModifier = determineResourceMod(resource); - decrStackSize(InventoryFermenter.SLOT_RESOURCE, 1); - } - } + if (currentRecipe != null) { + currentResourceModifier = determineResourceMod(resource); + decrStackSize(InventoryFermenter.SLOT_RESOURCE, 1); + } + } - private void checkFuel() { - if (fuelBurnTime > 0) { - return; - } + private void checkFuel() { + if (fuelBurnTime > 0) { + return; + } - ItemStack fuel = getStackInSlot(InventoryFermenter.SLOT_FUEL); - if (fuel == null) { - return; - } + ItemStack fuel = getStackInSlot(InventoryFermenter.SLOT_FUEL); + if (fuel == null) { + return; + } - FermenterFuel fermenterFuel = FuelManager.fermenterFuel.get(fuel); - if (fermenterFuel == null) { - return; - } + FermenterFuel fermenterFuel = FuelManager.fermenterFuel.get(fuel); + if (fermenterFuel == null) { + return; + } - fuelBurnTime = fuelTotalTime = fermenterFuel.burnDuration; - fuelCurrentFerment = fermenterFuel.fermentPerCycle; + fuelBurnTime = fuelTotalTime = fermenterFuel.burnDuration; + fuelCurrentFerment = fermenterFuel.fermentPerCycle; - decrStackSize(InventoryFermenter.SLOT_FUEL, 1); - } + decrStackSize(InventoryFermenter.SLOT_FUEL, 1); + } - private static float determineResourceMod(ItemStack itemstack) { - if (!(itemstack.getItem() instanceof IVariableFermentable)) { - return 1.0f; - } + private static float determineResourceMod(ItemStack itemstack) { + if (!(itemstack.getItem() instanceof IVariableFermentable)) { + return 1.0f; + } - return ((IVariableFermentable) itemstack.getItem()).getFermentationModifier(itemstack); - } + return ((IVariableFermentable) itemstack.getItem()).getFermentationModifier(itemstack); + } + @Override + public boolean hasResourcesMin(float percentage) { + ItemStack fermentationStack = getStackInSlot(InventoryFermenter.SLOT_RESOURCE); + if (fermentationStack == null) { + return false; + } - @Override - public boolean hasResourcesMin(float percentage) { - ItemStack fermentationStack = getStackInSlot(InventoryFermenter.SLOT_RESOURCE); - if (fermentationStack == null) { - return false; - } + return ((float) fermentationStack.stackSize / (float) fermentationStack.getMaxStackSize()) > percentage; + } - return ((float) fermentationStack.stackSize / (float) fermentationStack.getMaxStackSize()) > percentage; - } + @Override + public boolean hasFuelMin(float percentage) { + ItemStack fuelStack = getStackInSlot(InventoryFermenter.SLOT_FUEL); + if (fuelStack == null) { + return false; + } - @Override - public boolean hasFuelMin(float percentage) { - ItemStack fuelStack = getStackInSlot(InventoryFermenter.SLOT_FUEL); - if (fuelStack == null) { - return false; - } + return ((float) fuelStack.stackSize / (float) fuelStack.getMaxStackSize()) > percentage; + } - return ((float) fuelStack.stackSize / (float) fuelStack.getMaxStackSize()) > percentage; - } + @Override + public boolean hasWork() { + checkRecipe(); + checkFuel(); - @Override - public boolean hasWork() { - checkRecipe(); - checkFuel(); + boolean hasRecipe = (currentRecipe != null); + boolean hasFuel = fuelBurnTime > 0; + boolean hasResource = fermentationTime > 0 || getStackInSlot(InventoryFermenter.SLOT_RESOURCE) != null; + boolean hasFluidResource = resourceTank.canDrain(fuelCurrentFerment); + boolean hasFluidSpace = true; - boolean hasRecipe = (currentRecipe != null); - boolean hasFuel = fuelBurnTime > 0; - boolean hasResource = fermentationTime > 0 || getStackInSlot(InventoryFermenter.SLOT_RESOURCE) != null; - boolean hasFluidResource = resourceTank.canDrain(fuelCurrentFerment); - boolean hasFluidSpace = true; + if (hasRecipe) { + int fermented = Math.min(fermentationTime, fuelCurrentFerment); + int productAmount = Math.round(fermented * currentRecipe.getModifier() * currentResourceModifier); + hasFluidSpace = productTank.canFill(currentRecipe.getOutput(), productAmount); + } - if (hasRecipe) { - int fermented = Math.min(fermentationTime, fuelCurrentFerment); - int productAmount = Math.round(fermented * currentRecipe.getModifier() * currentResourceModifier); - hasFluidSpace = productTank.canFill(currentRecipe.getOutput(), productAmount); - } + IErrorLogic errorLogic = getErrorLogic(); + errorLogic.setCondition(!hasRecipe, EnumErrorCode.NO_RECIPE); + errorLogic.setCondition(!hasFuel, EnumErrorCode.NO_FUEL); + errorLogic.setCondition(!hasResource, EnumErrorCode.NO_RESOURCE); + errorLogic.setCondition(!hasFluidResource, EnumErrorCode.NO_RESOURCE_LIQUID); + errorLogic.setCondition(!hasFluidSpace, EnumErrorCode.NO_SPACE_TANK); - IErrorLogic errorLogic = getErrorLogic(); - errorLogic.setCondition(!hasRecipe, EnumErrorCode.NO_RECIPE); - errorLogic.setCondition(!hasFuel, EnumErrorCode.NO_FUEL); - errorLogic.setCondition(!hasResource, EnumErrorCode.NO_RESOURCE); - errorLogic.setCondition(!hasFluidResource, EnumErrorCode.NO_RESOURCE_LIQUID); - errorLogic.setCondition(!hasFluidSpace, EnumErrorCode.NO_SPACE_TANK); + return hasRecipe && hasFuel && hasResource && hasFluidResource && hasFluidSpace; + } - return hasRecipe && hasFuel && hasResource && hasFluidResource && hasFluidSpace; - } + public int getBurnTimeRemainingScaled(int i) { + if (fuelTotalTime == 0) { + return 0; + } - public int getBurnTimeRemainingScaled(int i) { - if (fuelTotalTime == 0) { - return 0; - } + return (fuelBurnTime * i) / fuelTotalTime; + } - return (fuelBurnTime * i) / fuelTotalTime; - } + public int getFermentationProgressScaled(int i) { + if (fermentationTotalTime == 0) { + return 0; + } - public int getFermentationProgressScaled(int i) { - if (fermentationTotalTime == 0) { - return 0; - } + return (fermentationTime * i) / fermentationTotalTime; + } - return (fermentationTime * i) / fermentationTotalTime; - } + @Override + public TankRenderInfo getResourceTankInfo() { + return new TankRenderInfo(resourceTank); + } - @Override - public TankRenderInfo getResourceTankInfo() { - return new TankRenderInfo(resourceTank); - } + @Override + public TankRenderInfo getProductTankInfo() { + return new TankRenderInfo(productTank); + } - @Override - public TankRenderInfo getProductTankInfo() { - return new TankRenderInfo(productTank); - } + /* SMP GUI */ + public void getGUINetworkData(int i, int j) { + switch (i) { + case 0: + fuelBurnTime = j; + break; + case 1: + fuelTotalTime = j; + break; + case 2: + fermentationTime = j; + break; + case 3: + fermentationTotalTime = j; + break; + } + } - /* SMP GUI */ - public void getGUINetworkData(int i, int j) { - switch (i) { - case 0: - fuelBurnTime = j; - break; - case 1: - fuelTotalTime = j; - break; - case 2: - fermentationTime = j; - break; - case 3: - fermentationTotalTime = j; - break; - } - } + public void sendGUINetworkData(Container container, ICrafting iCrafting) { + iCrafting.sendProgressBarUpdate(container, 0, fuelBurnTime); + iCrafting.sendProgressBarUpdate(container, 1, fuelTotalTime); + iCrafting.sendProgressBarUpdate(container, 2, fermentationTime); + iCrafting.sendProgressBarUpdate(container, 3, fermentationTotalTime); + } - public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, fuelBurnTime); - iCrafting.sendProgressBarUpdate(container, 1, fuelTotalTime); - iCrafting.sendProgressBarUpdate(container, 2, fermentationTime); - iCrafting.sendProgressBarUpdate(container, 3, fermentationTotalTime); - } + /* ILiquidTankTile */ + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return resourceTank.fill(resource, doFill); + } - /* ILiquidTankTile */ - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return resourceTank.fill(resource, doFill); - } + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return tankManager.drain(from, resource, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, int quantityMax, boolean doEmpty) { + return tankManager.drain(from, quantityMax, doEmpty); + } - @Override - public FluidStack drain(ForgeDirection from, int quantityMax, boolean doEmpty) { - return tankManager.drain(from, quantityMax, doEmpty); - } + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return tankManager.canFill(from, fluid); - } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return tankManager.canDrain(from, fluid); - } + @Override + public TankManager getTankManager() { + return tankManager; + } - @Override - public TankManager getTankManager() { - return tankManager; - } + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return tankManager.getTankInfo(from); - } + /* ITRIGGERPROVIDER */ + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { + LinkedList res = new LinkedList<>(); + res.add(FactoryTriggers.lowResource25); + res.add(FactoryTriggers.lowResource10); + return res; + } - /* ITRIGGERPROVIDER */ - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { - LinkedList res = new LinkedList<>(); - res.add(FactoryTriggers.lowResource25); - res.add(FactoryTriggers.lowResource10); - return res; - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiFermenter(player.inventory, this); + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiFermenter(player.inventory, this); - } - - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerFermenter(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerFermenter(player.inventory, this); + } } diff --git a/src/main/java/forestry/factory/tiles/TileMillRainmaker.java b/src/main/java/forestry/factory/tiles/TileMillRainmaker.java index fa89768b8..27d6d8cfc 100644 --- a/src/main/java/forestry/factory/tiles/TileMillRainmaker.java +++ b/src/main/java/forestry/factory/tiles/TileMillRainmaker.java @@ -10,115 +10,119 @@ ******************************************************************************/ package forestry.factory.tiles; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; - import forestry.api.fuels.FuelManager; import forestry.api.fuels.RainSubstrate; import forestry.core.proxy.Proxies; import forestry.core.tiles.TileMill; import forestry.factory.inventory.InventoryRainmaker; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; public class TileMillRainmaker extends TileMill { - private int duration; - private boolean reverse; + private int duration; + private boolean reverse; - public TileMillRainmaker() { - super(null); - speed = 0.01f; - setInternalInventory(new InventoryRainmaker(this)); - } + public TileMillRainmaker() { + super(null); + speed = 0.01f; + setInternalInventory(new InventoryRainmaker(this)); + } - @Override - public void openGui(EntityPlayer player) { - if (player.worldObj.isRemote) { - return; - } + @Override + public void openGui(EntityPlayer player) { + if (player.worldObj.isRemote) { + return; + } - if (player.inventory.getCurrentItem() == null) { - return; - } + if (player.inventory.getCurrentItem() == null) { + return; + } - // We don't have a gui, but we can be activated - if (FuelManager.rainSubstrate.containsKey(player.inventory.getCurrentItem()) && charge == 0) { - RainSubstrate substrate = FuelManager.rainSubstrate.get(player.inventory.getCurrentItem()); - if (substrate.item.isItemEqual(player.inventory.getCurrentItem())) { - addCharge(substrate); - player.inventory.getCurrentItem().stackSize--; - } - } - sendNetworkUpdate(); - } + // We don't have a gui, but we can be activated + if (FuelManager.rainSubstrate.containsKey(player.inventory.getCurrentItem()) && charge == 0) { + RainSubstrate substrate = FuelManager.rainSubstrate.get(player.inventory.getCurrentItem()); + if (substrate.item.isItemEqual(player.inventory.getCurrentItem())) { + addCharge(substrate); + player.inventory.getCurrentItem().stackSize--; + } + } + sendNetworkUpdate(); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); - charge = nbttagcompound.getInteger("Charge"); - progress = nbttagcompound.getFloat("Progress"); - stage = nbttagcompound.getInteger("Stage"); - duration = nbttagcompound.getInteger("Duration"); - reverse = nbttagcompound.getBoolean("Reverse"); - } + charge = nbttagcompound.getInteger("Charge"); + progress = nbttagcompound.getFloat("Progress"); + stage = nbttagcompound.getInteger("Stage"); + duration = nbttagcompound.getInteger("Duration"); + reverse = nbttagcompound.getBoolean("Reverse"); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - nbttagcompound.setInteger("Charge", charge); - nbttagcompound.setFloat("Progress", progress); - nbttagcompound.setInteger("Stage", stage); - nbttagcompound.setInteger("Duration", duration); - nbttagcompound.setBoolean("Reverse", reverse); - } + nbttagcompound.setInteger("Charge", charge); + nbttagcompound.setFloat("Progress", progress); + nbttagcompound.setInteger("Stage", stage); + nbttagcompound.setInteger("Duration", duration); + nbttagcompound.setBoolean("Reverse", reverse); + } - public void addCharge(RainSubstrate substrate) { - charge = 1; - speed = substrate.speed; - duration = substrate.duration; - reverse = substrate.reverse; - sendNetworkUpdate(); - } + public void addCharge(RainSubstrate substrate) { + charge = 1; + speed = substrate.speed; + duration = substrate.duration; + reverse = substrate.reverse; + sendNetworkUpdate(); + } - @Override - public void activate() { - if (Proxies.render.hasRendering()) { - worldObj.playSoundEffect(xCoord, yCoord, zCoord, "ambient.weather.thunder", 4F, - (1.0F + (worldObj.rand.nextFloat() - worldObj.rand.nextFloat()) * 0.2F) * 0.7F); + @Override + public void activate() { + if (Proxies.render.hasRendering()) { + worldObj.playSoundEffect( + xCoord, + yCoord, + zCoord, + "ambient.weather.thunder", + 4F, + (1.0F + (worldObj.rand.nextFloat() - worldObj.rand.nextFloat()) * 0.2F) * 0.7F); - float f = xCoord + 0.5F; - float f1 = yCoord + 0.0F + (worldObj.rand.nextFloat() * 6F) / 16F; - float f2 = zCoord + 0.5F; - float f3 = 0.52F; - float f4 = worldObj.rand.nextFloat() * 0.6F - 0.3F; + float f = xCoord + 0.5F; + float f1 = yCoord + 0.0F + (worldObj.rand.nextFloat() * 6F) / 16F; + float f2 = zCoord + 0.5F; + float f3 = 0.52F; + float f4 = worldObj.rand.nextFloat() * 0.6F - 0.3F; - Proxies.render.addEntityExplodeFX(worldObj, (f - f3), f1, (f2 + f4)); - Proxies.render.addEntityExplodeFX(worldObj, (f + f3), f1, (f2 + f4)); - Proxies.render.addEntityExplodeFX(worldObj, (f + f4), f1, (f2 - f3)); - Proxies.render.addEntityExplodeFX(worldObj, (f + f4), f1, (f2 + f3)); - } + Proxies.render.addEntityExplodeFX(worldObj, (f - f3), f1, (f2 + f4)); + Proxies.render.addEntityExplodeFX(worldObj, (f + f3), f1, (f2 + f4)); + Proxies.render.addEntityExplodeFX(worldObj, (f + f4), f1, (f2 - f3)); + Proxies.render.addEntityExplodeFX(worldObj, (f + f4), f1, (f2 + f3)); + } - if (!worldObj.isRemote) { - if (reverse) { - worldObj.getWorldInfo().setRaining(false); - } else { - worldObj.getWorldInfo().setRaining(true); - worldObj.getWorldInfo().setRainTime(duration); - } - charge = 0; - duration = 0; - reverse = false; - sendNetworkUpdate(); - } - } + if (!worldObj.isRemote) { + if (reverse) { + worldObj.getWorldInfo().setRaining(false); + } else { + worldObj.getWorldInfo().setRaining(true); + worldObj.getWorldInfo().setRainTime(duration); + } + charge = 0; + duration = 0; + reverse = false; + sendNetworkUpdate(); + } + } - @Override - public Object getGui(EntityPlayer player, int data) { - return null; - } + @Override + public Object getGui(EntityPlayer player, int data) { + return null; + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return null; - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return null; + } } diff --git a/src/main/java/forestry/factory/tiles/TileMoistener.java b/src/main/java/forestry/factory/tiles/TileMoistener.java index 28fae034b..76f10d776 100644 --- a/src/main/java/forestry/factory/tiles/TileMoistener.java +++ b/src/main/java/forestry/factory/tiles/TileMoistener.java @@ -10,23 +10,6 @@ ******************************************************************************/ package forestry.factory.tiles; -import java.io.IOException; -import java.util.ArrayList; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.ICrafting; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; - import forestry.api.core.IErrorLogic; import forestry.api.fuels.FuelManager; import forestry.api.fuels.MoistenerFuel; @@ -49,502 +32,528 @@ import forestry.factory.gui.ContainerMoistener; import forestry.factory.gui.GuiMoistener; import forestry.factory.inventory.InventoryMoistener; import forestry.factory.recipes.MoistenerRecipeManager; - -public class TileMoistener extends TileBase implements ISidedInventory, ILiquidTankTile, IFluidHandler, IRenderableTile { - private final FilteredTank resourceTank; - private final TankManager tankManager; - private IMoistenerRecipe currentRecipe; - - private int burnTime = 0; - private int totalTime = 0; - private int productionTime = 0; - private int timePerItem = 0; - private ItemStack currentProduct; - private ItemStack pendingProduct; - - public TileMoistener() { - super("moistener"); - setInternalInventory(new InventoryMoistener(this)); - resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, FluidRegistry.WATER); - tankManager = new TankManager(this, resourceTank); - } - - /* LOADING & SAVING */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - - nbttagcompound.setInteger("BurnTime", burnTime); - nbttagcompound.setInteger("TotalTime", totalTime); - nbttagcompound.setInteger("ProductionTime", productionTime); - - tankManager.writeToNBT(nbttagcompound); - - // Write pending product - if (pendingProduct != null) { - NBTTagCompound nbttagcompoundP = new NBTTagCompound(); - pendingProduct.writeToNBT(nbttagcompoundP); - nbttagcompound.setTag("PendingProduct", nbttagcompoundP); - } - if (currentProduct != null) { - NBTTagCompound nbttagcompoundP = new NBTTagCompound(); - currentProduct.writeToNBT(nbttagcompoundP); - nbttagcompound.setTag("CurrentProduct", nbttagcompoundP); - } - } - - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - - burnTime = nbttagcompound.getInteger("BurnTime"); - totalTime = nbttagcompound.getInteger("TotalTime"); - productionTime = nbttagcompound.getInteger("ProductionTime"); - - tankManager.readFromNBT(nbttagcompound); - - // Load pending product - if (nbttagcompound.hasKey("PendingProduct")) { - NBTTagCompound nbttagcompoundP = nbttagcompound.getCompoundTag("PendingProduct"); - pendingProduct = ItemStack.loadItemStackFromNBT(nbttagcompoundP); - } - if (nbttagcompound.hasKey("CurrentProduct")) { - NBTTagCompound nbttagcompoundP = nbttagcompound.getCompoundTag("CurrentProduct"); - currentProduct = ItemStack.loadItemStackFromNBT(nbttagcompoundP); - } - - checkRecipe(); - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - tankManager.writeData(data); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - tankManager.readData(data); - } - - @Override - public void updateServerSide() { - - if (updateOnInterval(20)) { - // Check if we have suitable water container waiting in the item slot - FluidHelper.drainContainers(tankManager, this, InventoryMoistener.SLOT_PRODUCT); - } - - // Let's get to work - int lightvalue = worldObj.getBlockLightValue(xCoord, yCoord + 1, zCoord); - - IErrorLogic errorLogic = getErrorLogic(); - - // Not working in broad daylight - boolean gloomy = lightvalue <= 11; - if (errorLogic.setCondition(!gloomy, EnumErrorCode.NOT_DARK)) { - return; - } - - // The darker, the better - int speed; - if (lightvalue >= 9) { - speed = 1; - } else if (lightvalue >= 7) { - speed = 2; - } else if (lightvalue >= 5) { - speed = 3; - } else { - speed = 4; - } - - // Already running - if (burnTime > 0 && pendingProduct == null) { - // Not working if there is no water available. - boolean hasLiquid = resourceTank.getFluidAmount() > 0; - if (errorLogic.setCondition(!hasLiquid, EnumErrorCode.NO_RESOURCE_LIQUID)) { - return; - } - - checkRecipe(); - - if (currentRecipe == null) { - return; - } - - resourceTank.drain(1, true); - burnTime -= speed; - productionTime -= speed; - - if (productionTime <= 0) { - pendingProduct = currentProduct; - decrStackSize(InventoryMoistener.SLOT_RESOURCE, 1); - resetRecipe(); - tryAddPending(); - } - - } else if (pendingProduct != null) { - tryAddPending(); - } - // Try to start process - else { // Make sure we have a new item in the working slot. - if (rotateWorkingSlot()) { - checkRecipe(); - - // Let's see if we have a valid resource in the working slot - if (getStackInSlot(InventoryMoistener.SLOT_WORKING) == null) { - return; - } - - if (FuelManager.moistenerResource.containsKey(getStackInSlot(InventoryMoistener.SLOT_WORKING))) { - MoistenerFuel res = FuelManager.moistenerResource.get(getStackInSlot(InventoryMoistener.SLOT_WORKING)); - burnTime = totalTime = res.moistenerValue; - } - } else { - rotateReservoir(); - } - } - - errorLogic.setCondition(currentRecipe == null, EnumErrorCode.NO_RECIPE); - } - - private boolean tryAddPending() { - if (pendingProduct == null) { - return false; - } - - boolean added = InventoryUtil.tryAddStack(this, pendingProduct, InventoryMoistener.SLOT_PRODUCT, 1, true); - getErrorLogic().setCondition(!added, EnumErrorCode.NO_SPACE_INVENTORY); - - if (added) { - pendingProduct = null; - } - - return added; - } - - public void checkRecipe() { - IMoistenerRecipe sameRec = MoistenerRecipeManager.findMatchingRecipe(getInternalInventory().getStackInSlot(InventoryMoistener.SLOT_RESOURCE)); - if (currentRecipe != sameRec) { - currentRecipe = sameRec; - resetRecipe(); - } - - getErrorLogic().setCondition(currentRecipe == null, EnumErrorCode.NO_RECIPE); - } - - private void resetRecipe() { - if (currentRecipe == null) { - currentProduct = null; - productionTime = 0; - timePerItem = 0; - } else { - currentProduct = currentRecipe.getProduct(); - productionTime = currentRecipe.getTimePerItem(); - timePerItem = currentRecipe.getTimePerItem(); - } - } - - private int getFreeSlot(ItemStack deposit, int startSlot, int endSlot, boolean emptyOnly) { - int slot = -1; - - for (int i = startSlot; i < endSlot; i++) { - ItemStack slotStack = getStackInSlot(i); - // Empty slots are okay. - if (slotStack == null) { - if (slot < 0) { - slot = i; - } - continue; - } - - if (emptyOnly) { - continue; - } - - // Wrong item or full - if (!slotStack.isItemEqual(deposit) || slotStack.stackSize >= slotStack.getMaxStackSize()) { - continue; - } - - slot = i; - } - - return slot; - } - - private int getFreeStashSlot(ItemStack deposit, boolean emptyOnly) { - return getFreeSlot(deposit, 0, InventoryMoistener.SLOT_RESERVOIR_1, emptyOnly); - } - - private int getFreeReservoirSlot(ItemStack deposit) { - return getFreeSlot(deposit, InventoryMoistener.SLOT_RESERVOIR_1, InventoryMoistener.SLOT_RESERVOIR_1 + InventoryMoistener.SLOT_RESERVOIR_COUNT, false); - - } - - private int getNextResourceSlot(int startSlot, int endSlot) { - // Let's look for a new resource to put into the working slot. - int stage = -1; - int resourceSlot = -1; - - IInventoryAdapter inventory = getInternalInventory(); - for (int i = startSlot; i < endSlot; i++) { - ItemStack slotStack = inventory.getStackInSlot(i); - if (slotStack == null) { - continue; - } - - if (!FuelManager.moistenerResource.containsKey(slotStack)) { - continue; - } - - MoistenerFuel res = FuelManager.moistenerResource.get(slotStack); - if (stage < 0 || res.stage < stage) { - stage = res.stage; - resourceSlot = i; - } - } - - return resourceSlot; - } - - private boolean rotateWorkingSlot() { - IErrorLogic errorLogic = getErrorLogic(); - - // Put working slot contents into inventory if space is available - if (getStackInSlot(InventoryMoistener.SLOT_WORKING) != null) { - // Get the result of the consumed item in the working slot - ItemStack deposit; - if (FuelManager.moistenerResource.containsKey(getStackInSlot(InventoryMoistener.SLOT_WORKING))) { - MoistenerFuel res = FuelManager.moistenerResource.get(getStackInSlot(InventoryMoistener.SLOT_WORKING)); - deposit = res.product.copy(); - } else { - deposit = getStackInSlot(InventoryMoistener.SLOT_WORKING).copy(); - } - - int targetSlot = getFreeReservoirSlot(deposit); - // We stop the whole thing, if we don't have any room anymore. - if (errorLogic.setCondition(targetSlot < 0, EnumErrorCode.NO_SPACE_INVENTORY)) { - return false; - } - - if (getStackInSlot(targetSlot) == null) { - setInventorySlotContents(targetSlot, deposit); - } else { - getStackInSlot(targetSlot).stackSize++; - } - - decrStackSize(InventoryMoistener.SLOT_WORKING, 1); - } - - if (getStackInSlot(InventoryMoistener.SLOT_WORKING) != null) { - return true; - } - - // Let's look for a new resource to put into the working slot. - int resourceSlot = getNextResourceSlot(InventoryMoistener.SLOT_RESERVOIR_1, InventoryMoistener.SLOT_RESERVOIR_1 + InventoryMoistener.SLOT_RESERVOIR_COUNT); - // Nothing found, stop. - if (errorLogic.setCondition(resourceSlot < 0, EnumErrorCode.NO_RESOURCE)) { - return false; - } - - setInventorySlotContents(InventoryMoistener.SLOT_WORKING, decrStackSize(resourceSlot, 1)); - return true; - } - - private void rotateReservoir() { - ArrayList slotsToShift = new ArrayList<>(); - - for (int i = InventoryMoistener.SLOT_RESERVOIR_1; i < InventoryMoistener.SLOT_RESERVOIR_1 + InventoryMoistener.SLOT_RESERVOIR_COUNT; i++) { - if (getStackInSlot(i) == null) { - continue; - } - - if (!FuelManager.moistenerResource.containsKey(getStackInSlot(i))) { - slotsToShift.add(i); - } - } - - // Move consumed items back to stash - int shiftedSlots = 0; - for (int slot : slotsToShift) { - ItemStack slotStack = getStackInSlot(slot); - int targetSlot = getFreeStashSlot(slotStack, true); - if (targetSlot < 0) { - continue; - } - - setInventorySlotContents(targetSlot, slotStack); - setInventorySlotContents(slot, null); - shiftedSlots++; - } - - // Grab new items from stash - for (int i = 0; i < (slotsToShift.size() > 0 ? shiftedSlots : 2); i++) { - int resourceSlot = getNextResourceSlot(0, InventoryMoistener.SLOT_RESERVOIR_1); - // Stop if no resources are available - if (resourceSlot < 0) { - break; - } - int targetSlot = getFreeReservoirSlot(getStackInSlot(resourceSlot)); - // No free target slot, stop - if (targetSlot < 0) { - break; - } - // Else shift - if (getStackInSlot(targetSlot) == null) { - setInventorySlotContents(targetSlot, getStackInSlot(resourceSlot)); - setInventorySlotContents(resourceSlot, null); - } else { - ItemStackUtil.mergeStacks(getStackInSlot(resourceSlot), getStackInSlot(targetSlot)); - if (getStackInSlot(resourceSlot) != null && getStackInSlot(resourceSlot).stackSize <= 0) { - setInventorySlotContents(resourceSlot, null); - } - } - } - } - - public boolean isWorking() { - return burnTime > 0 && resourceTank.getFluidAmount() > 0; - } - - public boolean hasFuelMin(float percentage) { - int max = 0; - int avail = 0; - IInventoryAdapter inventory = getInternalInventory(); - - for (int i = InventoryMoistener.SLOT_STASH_1; i < InventoryMoistener.SLOT_RESERVOIR_1; i++) { - if (inventory.getStackInSlot(i) == null) { - max += 64; - continue; - } - if (FuelManager.moistenerResource.containsKey(inventory.getStackInSlot(i))) { - MoistenerFuel res = FuelManager.moistenerResource.get(inventory.getStackInSlot(i)); - if (res.item.isItemEqual(inventory.getStackInSlot(i))) { - max += 64; - avail += inventory.getStackInSlot(i).stackSize; - } - } - } - - return ((float) avail / (float) max) > percentage; - } - - public boolean hasResourcesMin(float percentage) { - IInventoryAdapter inventory = getInternalInventory(); - if (inventory.getStackInSlot(InventoryMoistener.SLOT_RESOURCE) == null) { - return false; - } - - return ((float) inventory.getStackInSlot(InventoryMoistener.SLOT_RESOURCE).stackSize / (float) inventory.getStackInSlot(InventoryMoistener.SLOT_RESOURCE).getMaxStackSize()) > percentage; - } - - public boolean isProducing() { - return productionTime > 0; - } - - public int getProductionProgressScaled(int i) { - if (timePerItem == 0) { - return 0; - } - - return (productionTime * i) / timePerItem; - - } - - public int getConsumptionProgressScaled(int i) { - if (totalTime == 0) { - return 0; - } - - return (burnTime * i) / totalTime; - - } - - public int getResourceScaled(int i) { - return (resourceTank.getFluidAmount() * i) / Constants.PROCESSOR_TANK_CAPACITY; - } - - /* IRenderableTile */ - @Override - public TankRenderInfo getResourceTankInfo() { - return new TankRenderInfo(resourceTank); - } - - @Override - public TankRenderInfo getProductTankInfo() { - return TankRenderInfo.EMPTY; - } - - /* ILiquidTankTile */ - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return tankManager.fill(from, resource, doFill); - } - - @Override - public TankManager getTankManager() { - return tankManager; - } - - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return tankManager.drain(from, resource, doDrain); - } - - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return tankManager.drain(from, maxDrain, doDrain); - } - - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return tankManager.canFill(from, fluid); - } - - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return tankManager.canDrain(from, fluid); - } - - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return tankManager.getTankInfo(from); - } - - /* SMP GUI */ - public void getGUINetworkData(int i, int j) { - switch (i) { - case 0: - burnTime = j; - break; - case 1: - totalTime = j; - break; - case 2: - productionTime = j; - break; - case 3: - timePerItem = j; - break; - } - } - - public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, burnTime); - iCrafting.sendProgressBarUpdate(container, 1, totalTime); - iCrafting.sendProgressBarUpdate(container, 2, productionTime); - iCrafting.sendProgressBarUpdate(container, 3, timePerItem); - } - - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiMoistener(player.inventory, this); - } - - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerMoistener(player.inventory, this); - } +import java.io.IOException; +import java.util.ArrayList; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; + +public class TileMoistener extends TileBase + implements ISidedInventory, ILiquidTankTile, IFluidHandler, IRenderableTile { + private final FilteredTank resourceTank; + private final TankManager tankManager; + private IMoistenerRecipe currentRecipe; + + private int burnTime = 0; + private int totalTime = 0; + private int productionTime = 0; + private int timePerItem = 0; + private ItemStack currentProduct; + private ItemStack pendingProduct; + + public TileMoistener() { + super("moistener"); + setInternalInventory(new InventoryMoistener(this)); + resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, FluidRegistry.WATER); + tankManager = new TankManager(this, resourceTank); + } + + /* LOADING & SAVING */ + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + + nbttagcompound.setInteger("BurnTime", burnTime); + nbttagcompound.setInteger("TotalTime", totalTime); + nbttagcompound.setInteger("ProductionTime", productionTime); + + tankManager.writeToNBT(nbttagcompound); + + // Write pending product + if (pendingProduct != null) { + NBTTagCompound nbttagcompoundP = new NBTTagCompound(); + pendingProduct.writeToNBT(nbttagcompoundP); + nbttagcompound.setTag("PendingProduct", nbttagcompoundP); + } + if (currentProduct != null) { + NBTTagCompound nbttagcompoundP = new NBTTagCompound(); + currentProduct.writeToNBT(nbttagcompoundP); + nbttagcompound.setTag("CurrentProduct", nbttagcompoundP); + } + } + + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + + burnTime = nbttagcompound.getInteger("BurnTime"); + totalTime = nbttagcompound.getInteger("TotalTime"); + productionTime = nbttagcompound.getInteger("ProductionTime"); + + tankManager.readFromNBT(nbttagcompound); + + // Load pending product + if (nbttagcompound.hasKey("PendingProduct")) { + NBTTagCompound nbttagcompoundP = nbttagcompound.getCompoundTag("PendingProduct"); + pendingProduct = ItemStack.loadItemStackFromNBT(nbttagcompoundP); + } + if (nbttagcompound.hasKey("CurrentProduct")) { + NBTTagCompound nbttagcompoundP = nbttagcompound.getCompoundTag("CurrentProduct"); + currentProduct = ItemStack.loadItemStackFromNBT(nbttagcompoundP); + } + + checkRecipe(); + } + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + tankManager.writeData(data); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + tankManager.readData(data); + } + + @Override + public void updateServerSide() { + + if (updateOnInterval(20)) { + // Check if we have suitable water container waiting in the item slot + FluidHelper.drainContainers(tankManager, this, InventoryMoistener.SLOT_PRODUCT); + } + + // Let's get to work + int lightvalue = worldObj.getBlockLightValue(xCoord, yCoord + 1, zCoord); + + IErrorLogic errorLogic = getErrorLogic(); + + // Not working in broad daylight + boolean gloomy = lightvalue <= 11; + if (errorLogic.setCondition(!gloomy, EnumErrorCode.NOT_DARK)) { + return; + } + + // The darker, the better + int speed; + if (lightvalue >= 9) { + speed = 1; + } else if (lightvalue >= 7) { + speed = 2; + } else if (lightvalue >= 5) { + speed = 3; + } else { + speed = 4; + } + + // Already running + if (burnTime > 0 && pendingProduct == null) { + // Not working if there is no water available. + boolean hasLiquid = resourceTank.getFluidAmount() > 0; + if (errorLogic.setCondition(!hasLiquid, EnumErrorCode.NO_RESOURCE_LIQUID)) { + return; + } + + checkRecipe(); + + if (currentRecipe == null) { + return; + } + + resourceTank.drain(1, true); + burnTime -= speed; + productionTime -= speed; + + if (productionTime <= 0) { + pendingProduct = currentProduct; + decrStackSize(InventoryMoistener.SLOT_RESOURCE, 1); + resetRecipe(); + tryAddPending(); + } + + } else if (pendingProduct != null) { + tryAddPending(); + } + // Try to start process + else { // Make sure we have a new item in the working slot. + if (rotateWorkingSlot()) { + checkRecipe(); + + // Let's see if we have a valid resource in the working slot + if (getStackInSlot(InventoryMoistener.SLOT_WORKING) == null) { + return; + } + + if (FuelManager.moistenerResource.containsKey(getStackInSlot(InventoryMoistener.SLOT_WORKING))) { + MoistenerFuel res = + FuelManager.moistenerResource.get(getStackInSlot(InventoryMoistener.SLOT_WORKING)); + burnTime = totalTime = res.moistenerValue; + } + } else { + rotateReservoir(); + } + } + + errorLogic.setCondition(currentRecipe == null, EnumErrorCode.NO_RECIPE); + } + + private boolean tryAddPending() { + if (pendingProduct == null) { + return false; + } + + boolean added = InventoryUtil.tryAddStack(this, pendingProduct, InventoryMoistener.SLOT_PRODUCT, 1, true); + getErrorLogic().setCondition(!added, EnumErrorCode.NO_SPACE_INVENTORY); + + if (added) { + pendingProduct = null; + } + + return added; + } + + public void checkRecipe() { + IMoistenerRecipe sameRec = MoistenerRecipeManager.findMatchingRecipe( + getInternalInventory().getStackInSlot(InventoryMoistener.SLOT_RESOURCE)); + if (currentRecipe != sameRec) { + currentRecipe = sameRec; + resetRecipe(); + } + + getErrorLogic().setCondition(currentRecipe == null, EnumErrorCode.NO_RECIPE); + } + + private void resetRecipe() { + if (currentRecipe == null) { + currentProduct = null; + productionTime = 0; + timePerItem = 0; + } else { + currentProduct = currentRecipe.getProduct(); + productionTime = currentRecipe.getTimePerItem(); + timePerItem = currentRecipe.getTimePerItem(); + } + } + + private int getFreeSlot(ItemStack deposit, int startSlot, int endSlot, boolean emptyOnly) { + int slot = -1; + + for (int i = startSlot; i < endSlot; i++) { + ItemStack slotStack = getStackInSlot(i); + // Empty slots are okay. + if (slotStack == null) { + if (slot < 0) { + slot = i; + } + continue; + } + + if (emptyOnly) { + continue; + } + + // Wrong item or full + if (!slotStack.isItemEqual(deposit) || slotStack.stackSize >= slotStack.getMaxStackSize()) { + continue; + } + + slot = i; + } + + return slot; + } + + private int getFreeStashSlot(ItemStack deposit, boolean emptyOnly) { + return getFreeSlot(deposit, 0, InventoryMoistener.SLOT_RESERVOIR_1, emptyOnly); + } + + private int getFreeReservoirSlot(ItemStack deposit) { + return getFreeSlot( + deposit, + InventoryMoistener.SLOT_RESERVOIR_1, + InventoryMoistener.SLOT_RESERVOIR_1 + InventoryMoistener.SLOT_RESERVOIR_COUNT, + false); + } + + private int getNextResourceSlot(int startSlot, int endSlot) { + // Let's look for a new resource to put into the working slot. + int stage = -1; + int resourceSlot = -1; + + IInventoryAdapter inventory = getInternalInventory(); + for (int i = startSlot; i < endSlot; i++) { + ItemStack slotStack = inventory.getStackInSlot(i); + if (slotStack == null) { + continue; + } + + if (!FuelManager.moistenerResource.containsKey(slotStack)) { + continue; + } + + MoistenerFuel res = FuelManager.moistenerResource.get(slotStack); + if (stage < 0 || res.stage < stage) { + stage = res.stage; + resourceSlot = i; + } + } + + return resourceSlot; + } + + private boolean rotateWorkingSlot() { + IErrorLogic errorLogic = getErrorLogic(); + + // Put working slot contents into inventory if space is available + if (getStackInSlot(InventoryMoistener.SLOT_WORKING) != null) { + // Get the result of the consumed item in the working slot + ItemStack deposit; + if (FuelManager.moistenerResource.containsKey(getStackInSlot(InventoryMoistener.SLOT_WORKING))) { + MoistenerFuel res = FuelManager.moistenerResource.get(getStackInSlot(InventoryMoistener.SLOT_WORKING)); + deposit = res.product.copy(); + } else { + deposit = getStackInSlot(InventoryMoistener.SLOT_WORKING).copy(); + } + + int targetSlot = getFreeReservoirSlot(deposit); + // We stop the whole thing, if we don't have any room anymore. + if (errorLogic.setCondition(targetSlot < 0, EnumErrorCode.NO_SPACE_INVENTORY)) { + return false; + } + + if (getStackInSlot(targetSlot) == null) { + setInventorySlotContents(targetSlot, deposit); + } else { + getStackInSlot(targetSlot).stackSize++; + } + + decrStackSize(InventoryMoistener.SLOT_WORKING, 1); + } + + if (getStackInSlot(InventoryMoistener.SLOT_WORKING) != null) { + return true; + } + + // Let's look for a new resource to put into the working slot. + int resourceSlot = getNextResourceSlot( + InventoryMoistener.SLOT_RESERVOIR_1, + InventoryMoistener.SLOT_RESERVOIR_1 + InventoryMoistener.SLOT_RESERVOIR_COUNT); + // Nothing found, stop. + if (errorLogic.setCondition(resourceSlot < 0, EnumErrorCode.NO_RESOURCE)) { + return false; + } + + setInventorySlotContents(InventoryMoistener.SLOT_WORKING, decrStackSize(resourceSlot, 1)); + return true; + } + + private void rotateReservoir() { + ArrayList slotsToShift = new ArrayList<>(); + + for (int i = InventoryMoistener.SLOT_RESERVOIR_1; + i < InventoryMoistener.SLOT_RESERVOIR_1 + InventoryMoistener.SLOT_RESERVOIR_COUNT; + i++) { + if (getStackInSlot(i) == null) { + continue; + } + + if (!FuelManager.moistenerResource.containsKey(getStackInSlot(i))) { + slotsToShift.add(i); + } + } + + // Move consumed items back to stash + int shiftedSlots = 0; + for (int slot : slotsToShift) { + ItemStack slotStack = getStackInSlot(slot); + int targetSlot = getFreeStashSlot(slotStack, true); + if (targetSlot < 0) { + continue; + } + + setInventorySlotContents(targetSlot, slotStack); + setInventorySlotContents(slot, null); + shiftedSlots++; + } + + // Grab new items from stash + for (int i = 0; i < (slotsToShift.size() > 0 ? shiftedSlots : 2); i++) { + int resourceSlot = getNextResourceSlot(0, InventoryMoistener.SLOT_RESERVOIR_1); + // Stop if no resources are available + if (resourceSlot < 0) { + break; + } + int targetSlot = getFreeReservoirSlot(getStackInSlot(resourceSlot)); + // No free target slot, stop + if (targetSlot < 0) { + break; + } + // Else shift + if (getStackInSlot(targetSlot) == null) { + setInventorySlotContents(targetSlot, getStackInSlot(resourceSlot)); + setInventorySlotContents(resourceSlot, null); + } else { + ItemStackUtil.mergeStacks(getStackInSlot(resourceSlot), getStackInSlot(targetSlot)); + if (getStackInSlot(resourceSlot) != null && getStackInSlot(resourceSlot).stackSize <= 0) { + setInventorySlotContents(resourceSlot, null); + } + } + } + } + + public boolean isWorking() { + return burnTime > 0 && resourceTank.getFluidAmount() > 0; + } + + public boolean hasFuelMin(float percentage) { + int max = 0; + int avail = 0; + IInventoryAdapter inventory = getInternalInventory(); + + for (int i = InventoryMoistener.SLOT_STASH_1; i < InventoryMoistener.SLOT_RESERVOIR_1; i++) { + if (inventory.getStackInSlot(i) == null) { + max += 64; + continue; + } + if (FuelManager.moistenerResource.containsKey(inventory.getStackInSlot(i))) { + MoistenerFuel res = FuelManager.moistenerResource.get(inventory.getStackInSlot(i)); + if (res.item.isItemEqual(inventory.getStackInSlot(i))) { + max += 64; + avail += inventory.getStackInSlot(i).stackSize; + } + } + } + + return ((float) avail / (float) max) > percentage; + } + + public boolean hasResourcesMin(float percentage) { + IInventoryAdapter inventory = getInternalInventory(); + if (inventory.getStackInSlot(InventoryMoistener.SLOT_RESOURCE) == null) { + return false; + } + + return ((float) inventory.getStackInSlot(InventoryMoistener.SLOT_RESOURCE).stackSize + / (float) inventory + .getStackInSlot(InventoryMoistener.SLOT_RESOURCE) + .getMaxStackSize()) + > percentage; + } + + public boolean isProducing() { + return productionTime > 0; + } + + public int getProductionProgressScaled(int i) { + if (timePerItem == 0) { + return 0; + } + + return (productionTime * i) / timePerItem; + } + + public int getConsumptionProgressScaled(int i) { + if (totalTime == 0) { + return 0; + } + + return (burnTime * i) / totalTime; + } + + public int getResourceScaled(int i) { + return (resourceTank.getFluidAmount() * i) / Constants.PROCESSOR_TANK_CAPACITY; + } + + /* IRenderableTile */ + @Override + public TankRenderInfo getResourceTankInfo() { + return new TankRenderInfo(resourceTank); + } + + @Override + public TankRenderInfo getProductTankInfo() { + return TankRenderInfo.EMPTY; + } + + /* ILiquidTankTile */ + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } + + @Override + public TankManager getTankManager() { + return tankManager; + } + + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } + + /* SMP GUI */ + public void getGUINetworkData(int i, int j) { + switch (i) { + case 0: + burnTime = j; + break; + case 1: + totalTime = j; + break; + case 2: + productionTime = j; + break; + case 3: + timePerItem = j; + break; + } + } + + public void sendGUINetworkData(Container container, ICrafting iCrafting) { + iCrafting.sendProgressBarUpdate(container, 0, burnTime); + iCrafting.sendProgressBarUpdate(container, 1, totalTime); + iCrafting.sendProgressBarUpdate(container, 2, productionTime); + iCrafting.sendProgressBarUpdate(container, 3, timePerItem); + } + + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiMoistener(player.inventory, this); + } + + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerMoistener(player.inventory, this); + } } diff --git a/src/main/java/forestry/factory/tiles/TileRaintank.java b/src/main/java/forestry/factory/tiles/TileRaintank.java index 56df61d71..57c8de931 100644 --- a/src/main/java/forestry/factory/tiles/TileRaintank.java +++ b/src/main/java/forestry/factory/tiles/TileRaintank.java @@ -10,23 +10,6 @@ ******************************************************************************/ package forestry.factory.tiles; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.ICrafting; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.biome.BiomeGenBase; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; - import forestry.api.core.BiomeHelper; import forestry.api.core.IErrorLogic; import forestry.core.config.Constants; @@ -43,175 +26,200 @@ import forestry.core.utils.ItemStackUtil; import forestry.factory.gui.ContainerRaintank; import forestry.factory.gui.GuiRaintank; import forestry.factory.inventory.InventoryRaintank; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.biome.BiomeGenBase; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; public class TileRaintank extends TileBase implements ISidedInventory, ILiquidTankTile, IFluidHandler { - private static final FluidStack STACK_WATER = Fluids.WATER.getFluid(Constants.RAINTANK_AMOUNT_PER_UPDATE); + private static final FluidStack STACK_WATER = Fluids.WATER.getFluid(Constants.RAINTANK_AMOUNT_PER_UPDATE); - private final FilteredTank resourceTank; - private final TankManager tankManager; - private boolean isValidBiome = true; - private int fillingTime; - private ItemStack usedEmpty; + private final FilteredTank resourceTank; + private final TankManager tankManager; + private boolean isValidBiome = true; + private int fillingTime; + private ItemStack usedEmpty; - public TileRaintank() { - super("raintank"); - setInternalInventory(new InventoryRaintank(this)); + public TileRaintank() { + super("raintank"); + setInternalInventory(new InventoryRaintank(this)); - resourceTank = new FilteredTank(Constants.RAINTANK_TANK_CAPACITY, FluidRegistry.WATER); - tankManager = new TankManager(this, resourceTank); - } + resourceTank = new FilteredTank(Constants.RAINTANK_TANK_CAPACITY, FluidRegistry.WATER); + tankManager = new TankManager(this, resourceTank); + } - @Override - public void validate() { - // Raintanks in desert biomes are useless - if (worldObj != null) { - BiomeGenBase biome = worldObj.getBiomeGenForCoordsBody(xCoord, zCoord); - isValidBiome = BiomeHelper.canRainOrSnow(biome); - getErrorLogic().setCondition(!isValidBiome, EnumErrorCode.NO_RAIN_BIOME); - } + @Override + public void validate() { + // Raintanks in desert biomes are useless + if (worldObj != null) { + BiomeGenBase biome = worldObj.getBiomeGenForCoordsBody(xCoord, zCoord); + isValidBiome = BiomeHelper.canRainOrSnow(biome); + getErrorLogic().setCondition(!isValidBiome, EnumErrorCode.NO_RAIN_BIOME); + } - super.validate(); - } + super.validate(); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - nbttagcompound.setBoolean("IsValidBiome", isValidBiome); + nbttagcompound.setBoolean("IsValidBiome", isValidBiome); - tankManager.writeToNBT(nbttagcompound); - } + tankManager.writeToNBT(nbttagcompound); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); - isValidBiome = nbttagcompound.getBoolean("IsValidBiome"); + isValidBiome = nbttagcompound.getBoolean("IsValidBiome"); - tankManager.readFromNBT(nbttagcompound); - } + tankManager.readFromNBT(nbttagcompound); + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - tankManager.writeData(data); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + tankManager.writeData(data); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - tankManager.readData(data); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + tankManager.readData(data); + } - @Override - public void updateServerSide() { + @Override + public void updateServerSide() { - if (!updateOnInterval(20)) { - return; - } + if (!updateOnInterval(20)) { + return; + } - IErrorLogic errorLogic = getErrorLogic(); + IErrorLogic errorLogic = getErrorLogic(); - errorLogic.setCondition(!isValidBiome, EnumErrorCode.NO_RAIN_BIOME); + errorLogic.setCondition(!isValidBiome, EnumErrorCode.NO_RAIN_BIOME); - boolean hasSky = worldObj.canBlockSeeTheSky(xCoord, yCoord + 1, zCoord); - errorLogic.setCondition(!hasSky, EnumErrorCode.NO_SKY_RAIN_TANK); + boolean hasSky = worldObj.canBlockSeeTheSky(xCoord, yCoord + 1, zCoord); + errorLogic.setCondition(!hasSky, EnumErrorCode.NO_SKY_RAIN_TANK); - errorLogic.setCondition(!worldObj.isRaining(), EnumErrorCode.NOT_RAINING); + errorLogic.setCondition(!worldObj.isRaining(), EnumErrorCode.NOT_RAINING); - if (!errorLogic.hasErrors()) { - resourceTank.fill(STACK_WATER, true); - } - - if (!ItemStackUtil.isIdenticalItem(usedEmpty, getStackInSlot(InventoryRaintank.SLOT_RESOURCE))) { - fillingTime = 0; - usedEmpty = null; - } + if (!errorLogic.hasErrors()) { + resourceTank.fill(STACK_WATER, true); + } - if (usedEmpty == null) { - usedEmpty = getStackInSlot(InventoryRaintank.SLOT_RESOURCE); - } + if (!ItemStackUtil.isIdenticalItem(usedEmpty, getStackInSlot(InventoryRaintank.SLOT_RESOURCE))) { + fillingTime = 0; + usedEmpty = null; + } - if (!isFilling()) { - FluidHelper.FillStatus canFill = FluidHelper.fillContainers(tankManager, this, InventoryRaintank.SLOT_RESOURCE, InventoryRaintank.SLOT_PRODUCT, Fluids.WATER.getFluid(), false); - if (canFill == FluidHelper.FillStatus.SUCCESS) { - fillingTime = Constants.RAINTANK_FILLING_TIME; - } - } else { - fillingTime--; - if (fillingTime <= 0) { - FluidHelper.FillStatus filled = FluidHelper.fillContainers(tankManager, this, InventoryRaintank.SLOT_RESOURCE, InventoryRaintank.SLOT_PRODUCT, Fluids.WATER.getFluid()); - if (filled == FluidHelper.FillStatus.SUCCESS) { - fillingTime = 0; - } - } - } - } + if (usedEmpty == null) { + usedEmpty = getStackInSlot(InventoryRaintank.SLOT_RESOURCE); + } - public boolean isFilling() { - return fillingTime > 0; - } + if (!isFilling()) { + FluidHelper.FillStatus canFill = FluidHelper.fillContainers( + tankManager, + this, + InventoryRaintank.SLOT_RESOURCE, + InventoryRaintank.SLOT_PRODUCT, + Fluids.WATER.getFluid(), + false); + if (canFill == FluidHelper.FillStatus.SUCCESS) { + fillingTime = Constants.RAINTANK_FILLING_TIME; + } + } else { + fillingTime--; + if (fillingTime <= 0) { + FluidHelper.FillStatus filled = FluidHelper.fillContainers( + tankManager, + this, + InventoryRaintank.SLOT_RESOURCE, + InventoryRaintank.SLOT_PRODUCT, + Fluids.WATER.getFluid()); + if (filled == FluidHelper.FillStatus.SUCCESS) { + fillingTime = 0; + } + } + } + } - public int getFillProgressScaled(int i) { - return (fillingTime * i) / Constants.RAINTANK_FILLING_TIME; - } + public boolean isFilling() { + return fillingTime > 0; + } - /* SMP GUI */ - public void getGUINetworkData(int i, int j) { - switch (i) { - case 0: - fillingTime = j; - break; - } - } + public int getFillProgressScaled(int i) { + return (fillingTime * i) / Constants.RAINTANK_FILLING_TIME; + } - public void sendGUINetworkData(Container container, ICrafting iCrafting) { - iCrafting.sendProgressBarUpdate(container, 0, fillingTime); - } + /* SMP GUI */ + public void getGUINetworkData(int i, int j) { + switch (i) { + case 0: + fillingTime = j; + break; + } + } - // / ILIQUIDCONTAINER IMPLEMENTATION - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return tankManager.fill(from, resource, doFill); - } + public void sendGUINetworkData(Container container, ICrafting iCrafting) { + iCrafting.sendProgressBarUpdate(container, 0, fillingTime); + } - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return tankManager.drain(from, resource, doDrain); - } + // / ILIQUIDCONTAINER IMPLEMENTATION + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return tankManager.drain(from, maxDrain, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return tankManager.canFill(from, fluid); - } + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return tankManager.canDrain(from, fluid); - } + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } - @Override - public TankManager getTankManager() { - return tankManager; - } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return tankManager.getTankInfo(from); - } + @Override + public TankManager getTankManager() { + return tankManager; + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiRaintank(player.inventory, this); - } + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerRaintank(player.inventory, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiRaintank(player.inventory, this); + } + + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerRaintank(player.inventory, this); + } } diff --git a/src/main/java/forestry/factory/tiles/TileSqueezer.java b/src/main/java/forestry/factory/tiles/TileSqueezer.java index f978a98d3..6bda009d7 100644 --- a/src/main/java/forestry/factory/tiles/TileSqueezer.java +++ b/src/main/java/forestry/factory/tiles/TileSqueezer.java @@ -10,19 +10,6 @@ ******************************************************************************/ package forestry.factory.tiles; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; - import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.CircuitSocketType; import forestry.api.circuits.ICircuitBoard; @@ -47,251 +34,263 @@ import forestry.factory.gui.ContainerSqueezer; import forestry.factory.gui.GuiSqueezer; import forestry.factory.inventory.InventorySqueezer; import forestry.factory.recipes.SqueezerRecipeManager; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; -public class TileSqueezer extends TilePowered implements ISocketable, ISidedInventory, ILiquidTankTile, IFluidHandler, ISpeedUpgradable { - private static final int TICKS_PER_RECIPE_TIME = 1; - private static final int ENERGY_PER_WORK_CYCLE = 2000; - private static final int ENERGY_PER_RECIPE_TIME = ENERGY_PER_WORK_CYCLE / 10; +public class TileSqueezer extends TilePowered + implements ISocketable, ISidedInventory, ILiquidTankTile, IFluidHandler, ISpeedUpgradable { + private static final int TICKS_PER_RECIPE_TIME = 1; + private static final int ENERGY_PER_WORK_CYCLE = 2000; + private static final int ENERGY_PER_RECIPE_TIME = ENERGY_PER_WORK_CYCLE / 10; - private final InventoryAdapter sockets = new InventoryAdapter(1, "sockets"); + private final InventoryAdapter sockets = new InventoryAdapter(1, "sockets"); - private final TankManager tankManager; - private final StandardTank productTank; - private final InventorySqueezer inventory; + private final TankManager tankManager; + private final StandardTank productTank; + private final InventorySqueezer inventory; - private ISqueezerRecipe currentRecipe; + private ISqueezerRecipe currentRecipe; - public TileSqueezer() { - super("squeezer", 1100, Constants.MACHINE_MAX_ENERGY); - this.inventory = new InventorySqueezer(this); - setInternalInventory(this.inventory); - this.productTank = new StandardTank(Constants.PROCESSOR_TANK_CAPACITY); - this.productTank.tankMode = StandardTank.TankMode.OUTPUT; - this.tankManager = new TankManager(this, productTank); - } + public TileSqueezer() { + super("squeezer", 1100, Constants.MACHINE_MAX_ENERGY); + this.inventory = new InventorySqueezer(this); + setInternalInventory(this.inventory); + this.productTank = new StandardTank(Constants.PROCESSOR_TANK_CAPACITY); + this.productTank.tankMode = StandardTank.TankMode.OUTPUT; + this.tankManager = new TankManager(this, productTank); + } - /* LOADING & SAVING */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - tankManager.writeToNBT(nbttagcompound); - sockets.writeToNBT(nbttagcompound); - } + /* LOADING & SAVING */ + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + tankManager.writeToNBT(nbttagcompound); + sockets.writeToNBT(nbttagcompound); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - tankManager.readFromNBT(nbttagcompound); - sockets.readFromNBT(nbttagcompound); + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + tankManager.readFromNBT(nbttagcompound); + sockets.readFromNBT(nbttagcompound); - ItemStack chip = sockets.getStackInSlot(0); - if (chip != null) { - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(chip); - if (chipset != null) { - chipset.onLoad(this); - } - } - } + ItemStack chip = sockets.getStackInSlot(0); + if (chip != null) { + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(chip); + if (chipset != null) { + chipset.onLoad(this); + } + } + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - tankManager.writeData(data); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + tankManager.writeData(data); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - tankManager.readData(data); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + tankManager.readData(data); + } - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - super.writeGuiData(data); - sockets.writeData(data); - } + @Override + public void writeGuiData(DataOutputStreamForestry data) throws IOException { + super.writeGuiData(data); + sockets.writeData(data); + } - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - super.readGuiData(data); - sockets.readData(data); - } + @Override + public void readGuiData(DataInputStreamForestry data) throws IOException { + super.readGuiData(data); + sockets.readData(data); + } - // / WORKING - @Override - public void updateServerSide() { - super.updateServerSide(); + // / WORKING + @Override + public void updateServerSide() { + super.updateServerSide(); - if (updateOnInterval(20)) { - inventory.fillContainers(productTank.getFluid(), tankManager); - } - } + if (updateOnInterval(20)) { + inventory.fillContainers(productTank.getFluid(), tankManager); + } + } - @Override - public boolean workCycle() { - EntityPlayer player = PlayerUtil.getPlayer(worldObj, getAccessHandler().getOwner()); - if (!inventory.removeResources(currentRecipe.getResources(), player)) { - return false; - } + @Override + public boolean workCycle() { + EntityPlayer player = PlayerUtil.getPlayer(worldObj, getAccessHandler().getOwner()); + if (!inventory.removeResources(currentRecipe.getResources(), player)) { + return false; + } - FluidStack resultFluid = currentRecipe.getFluidOutput(); - productTank.fill(resultFluid, true); + FluidStack resultFluid = currentRecipe.getFluidOutput(); + productTank.fill(resultFluid, true); - if (currentRecipe.getRemnants() != null && (worldObj.rand.nextFloat() < currentRecipe.getRemnantsChance())) { - ItemStack remnant = currentRecipe.getRemnants().copy(); - inventory.addRemnant(remnant, true); - } + if (currentRecipe.getRemnants() != null && (worldObj.rand.nextFloat() < currentRecipe.getRemnantsChance())) { + ItemStack remnant = currentRecipe.getRemnants().copy(); + inventory.addRemnant(remnant, true); + } - return true; - } + return true; + } - private boolean checkRecipe() { - ISqueezerRecipe matchingRecipe = null; - if (inventory.hasResources()) { - ItemStack[] resources = inventory.getResources(); + private boolean checkRecipe() { + ISqueezerRecipe matchingRecipe = null; + if (inventory.hasResources()) { + ItemStack[] resources = inventory.getResources(); - if (currentRecipe != null && ItemStackUtil.containsSets(currentRecipe.getResources(), resources, true, false) > 0) { - matchingRecipe = currentRecipe; - } else { - matchingRecipe = SqueezerRecipeManager.findMatchingRecipe(resources); - } - } + if (currentRecipe != null + && ItemStackUtil.containsSets(currentRecipe.getResources(), resources, true, false) > 0) { + matchingRecipe = currentRecipe; + } else { + matchingRecipe = SqueezerRecipeManager.findMatchingRecipe(resources); + } + } - if (currentRecipe != matchingRecipe) { - currentRecipe = matchingRecipe; - if (currentRecipe != null) { - int recipeTime = currentRecipe.getProcessingTime(); - setTicksPerWorkCycle(recipeTime * TICKS_PER_RECIPE_TIME); - setEnergyPerWorkCycle(recipeTime * ENERGY_PER_RECIPE_TIME); - } - } + if (currentRecipe != matchingRecipe) { + currentRecipe = matchingRecipe; + if (currentRecipe != null) { + int recipeTime = currentRecipe.getProcessingTime(); + setTicksPerWorkCycle(recipeTime * TICKS_PER_RECIPE_TIME); + setEnergyPerWorkCycle(recipeTime * ENERGY_PER_RECIPE_TIME); + } + } - getErrorLogic().setCondition(currentRecipe == null, EnumErrorCode.NO_RECIPE); - return currentRecipe != null; - } + getErrorLogic().setCondition(currentRecipe == null, EnumErrorCode.NO_RECIPE); + return currentRecipe != null; + } - @Override - public boolean hasWork() { - checkRecipe(); + @Override + public boolean hasWork() { + checkRecipe(); - boolean hasResources = inventory.hasResources(); - boolean hasRecipe = true; - boolean canFill = true; - boolean canAdd = true; + boolean hasResources = inventory.hasResources(); + boolean hasRecipe = true; + boolean canFill = true; + boolean canAdd = true; - if (hasResources) { - hasRecipe = (currentRecipe != null); - if (hasRecipe) { - FluidStack resultFluid = currentRecipe.getFluidOutput(); - canFill = productTank.canFill(resultFluid); + if (hasResources) { + hasRecipe = (currentRecipe != null); + if (hasRecipe) { + FluidStack resultFluid = currentRecipe.getFluidOutput(); + canFill = productTank.canFill(resultFluid); - if (currentRecipe.getRemnants() != null) { - canAdd = inventory.addRemnant(currentRecipe.getRemnants(), false); - } - } - } + if (currentRecipe.getRemnants() != null) { + canAdd = inventory.addRemnant(currentRecipe.getRemnants(), false); + } + } + } - IErrorLogic errorLogic = getErrorLogic(); - errorLogic.setCondition(!hasResources, EnumErrorCode.NO_RESOURCE); - errorLogic.setCondition(!hasRecipe, EnumErrorCode.NO_RECIPE); - errorLogic.setCondition(!canFill, EnumErrorCode.NO_SPACE_TANK); - errorLogic.setCondition(!canAdd, EnumErrorCode.NO_SPACE_INVENTORY); + IErrorLogic errorLogic = getErrorLogic(); + errorLogic.setCondition(!hasResources, EnumErrorCode.NO_RESOURCE); + errorLogic.setCondition(!hasRecipe, EnumErrorCode.NO_RECIPE); + errorLogic.setCondition(!canFill, EnumErrorCode.NO_SPACE_TANK); + errorLogic.setCondition(!canAdd, EnumErrorCode.NO_SPACE_INVENTORY); - return hasResources && hasRecipe && canFill && canAdd; - } + return hasResources && hasRecipe && canFill && canAdd; + } - @Override - public TankRenderInfo getProductTankInfo() { - return new TankRenderInfo(productTank); - } + @Override + public TankRenderInfo getProductTankInfo() { + return new TankRenderInfo(productTank); + } - /* ILIQUIDCONTAINER IMPLEMENTATION */ - @Override - public TankManager getTankManager() { - return tankManager; - } + /* ILIQUIDCONTAINER IMPLEMENTATION */ + @Override + public TankManager getTankManager() { + return tankManager; + } - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return tankManager.fill(from, resource, doFill); - } + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return tankManager.drain(from, resource, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return tankManager.drain(from, maxDrain, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return tankManager.drain(from, maxDrain, doDrain); + } - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return tankManager.canFill(from, fluid); - } + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return tankManager.canDrain(from, fluid); - } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return tankManager.getTankInfo(from); - } + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } - /* ISocketable */ - @Override - public int getSocketCount() { - return sockets.getSizeInventory(); - } + /* ISocketable */ + @Override + public int getSocketCount() { + return sockets.getSizeInventory(); + } - @Override - public ItemStack getSocket(int slot) { - return sockets.getStackInSlot(slot); - } + @Override + public ItemStack getSocket(int slot) { + return sockets.getStackInSlot(slot); + } - @Override - public void setSocket(int slot, ItemStack stack) { + @Override + public void setSocket(int slot, ItemStack stack) { - if (stack != null && !ChipsetManager.circuitRegistry.isChipset(stack)) { - return; - } + if (stack != null && !ChipsetManager.circuitRegistry.isChipset(stack)) { + return; + } - // Dispose correctly of old chipsets - if (sockets.getStackInSlot(slot) != null) { - if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(sockets.getStackInSlot(slot)); - if (chipset != null) { - chipset.onRemoval(this); - } - } - } + // Dispose correctly of old chipsets + if (sockets.getStackInSlot(slot) != null) { + if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(sockets.getStackInSlot(slot)); + if (chipset != null) { + chipset.onRemoval(this); + } + } + } - sockets.setInventorySlotContents(slot, stack); - if (stack == null) { - return; - } + sockets.setInventorySlotContents(slot, stack); + if (stack == null) { + return; + } - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(stack); - if (chipset != null) { - chipset.onInsertion(this); - } - } + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(stack); + if (chipset != null) { + chipset.onInsertion(this); + } + } - @Override - public ICircuitSocketType getSocketType() { - return CircuitSocketType.MACHINE; - } + @Override + public ICircuitSocketType getSocketType() { + return CircuitSocketType.MACHINE; + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiSqueezer(player.inventory, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiSqueezer(player.inventory, this); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerSqueezer(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerSqueezer(player.inventory, this); + } } diff --git a/src/main/java/forestry/factory/tiles/TileStill.java b/src/main/java/forestry/factory/tiles/TileStill.java index 18a4e1f30..2cb2dd923 100644 --- a/src/main/java/forestry/factory/tiles/TileStill.java +++ b/src/main/java/forestry/factory/tiles/TileStill.java @@ -10,18 +10,6 @@ ******************************************************************************/ package forestry.factory.tiles; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; - import forestry.api.core.IErrorLogic; import forestry.api.recipes.IStillRecipe; import forestry.core.config.Constants; @@ -39,186 +27,199 @@ import forestry.factory.gui.ContainerStill; import forestry.factory.gui.GuiStill; import forestry.factory.inventory.InventoryStill; import forestry.factory.recipes.StillRecipeManager; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; public class TileStill extends TilePowered implements ISidedInventory, ILiquidTankTile, IFluidHandler { - private static final int ENERGY_PER_RECIPE_TIME = 200; + private static final int ENERGY_PER_RECIPE_TIME = 200; - private final FilteredTank resourceTank; - private final FilteredTank productTank; - private final TankManager tankManager; + private final FilteredTank resourceTank; + private final FilteredTank productTank; + private final TankManager tankManager; - private IStillRecipe currentRecipe; - private FluidStack bufferedLiquid; + private IStillRecipe currentRecipe; + private FluidStack bufferedLiquid; - public TileStill() { - super("still", 1100, 8000); - setInternalInventory(new InventoryStill(this)); - resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, StillRecipeManager.recipeFluidInputs); - resourceTank.tankMode = StandardTank.TankMode.INPUT; - productTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, StillRecipeManager.recipeFluidOutputs); - productTank.tankMode = StandardTank.TankMode.OUTPUT; - tankManager = new TankManager(this, resourceTank, productTank); - } + public TileStill() { + super("still", 1100, 8000); + setInternalInventory(new InventoryStill(this)); + resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, StillRecipeManager.recipeFluidInputs); + resourceTank.tankMode = StandardTank.TankMode.INPUT; + productTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, StillRecipeManager.recipeFluidOutputs); + productTank.tankMode = StandardTank.TankMode.OUTPUT; + tankManager = new TankManager(this, resourceTank, productTank); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - tankManager.writeToNBT(nbttagcompound); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + tankManager.writeToNBT(nbttagcompound); - if (bufferedLiquid != null) { - NBTTagCompound buffer = new NBTTagCompound(); - bufferedLiquid.writeToNBT(buffer); - nbttagcompound.setTag("Buffer", buffer); - } + if (bufferedLiquid != null) { + NBTTagCompound buffer = new NBTTagCompound(); + bufferedLiquid.writeToNBT(buffer); + nbttagcompound.setTag("Buffer", buffer); + } + } - } + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + tankManager.readFromNBT(nbttagcompound); - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - tankManager.readFromNBT(nbttagcompound); + if (nbttagcompound.hasKey("Buffer")) { + NBTTagCompound buffer = nbttagcompound.getCompoundTag("Buffer"); + bufferedLiquid = FluidStack.loadFluidStackFromNBT(buffer); + } + } - if (nbttagcompound.hasKey("Buffer")) { - NBTTagCompound buffer = nbttagcompound.getCompoundTag("Buffer"); - bufferedLiquid = FluidStack.loadFluidStackFromNBT(buffer); - } - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + tankManager.writeData(data); + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - tankManager.writeData(data); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + tankManager.readData(data); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - tankManager.readData(data); - } + @Override + public void updateServerSide() { + super.updateServerSide(); - @Override - public void updateServerSide() { - super.updateServerSide(); + if (updateOnInterval(20)) { + FluidHelper.drainContainers(tankManager, this, InventoryStill.SLOT_CAN); - if (updateOnInterval(20)) { - FluidHelper.drainContainers(tankManager, this, InventoryStill.SLOT_CAN); + FluidStack fluidStack = productTank.getFluid(); + if (fluidStack != null) { + FluidHelper.fillContainers( + tankManager, + this, + InventoryStill.SLOT_RESOURCE, + InventoryStill.SLOT_PRODUCT, + fluidStack.getFluid()); + } + } + } - FluidStack fluidStack = productTank.getFluid(); - if (fluidStack != null) { - FluidHelper.fillContainers(tankManager, this, InventoryStill.SLOT_RESOURCE, InventoryStill.SLOT_PRODUCT, fluidStack.getFluid()); - } - } - } + @Override + public boolean workCycle() { - @Override - public boolean workCycle() { + int cycles = currentRecipe.getCyclesPerUnit(); + FluidStack output = currentRecipe.getOutput(); - int cycles = currentRecipe.getCyclesPerUnit(); - FluidStack output = currentRecipe.getOutput(); + FluidStack product = new FluidStack(output, output.amount * cycles); + productTank.fill(product, true); - FluidStack product = new FluidStack(output, output.amount * cycles); - productTank.fill(product, true); + bufferedLiquid = null; - bufferedLiquid = null; + return true; + } - return true; - } + private void checkRecipe() { + FluidStack recipeLiquid = bufferedLiquid != null ? bufferedLiquid : resourceTank.getFluid(); - private void checkRecipe() { - FluidStack recipeLiquid = bufferedLiquid != null ? bufferedLiquid : resourceTank.getFluid(); + if (!StillRecipeManager.matches(currentRecipe, recipeLiquid)) { + currentRecipe = StillRecipeManager.findMatchingRecipe(recipeLiquid); - if (!StillRecipeManager.matches(currentRecipe, recipeLiquid)) { - currentRecipe = StillRecipeManager.findMatchingRecipe(recipeLiquid); + int recipeTime = currentRecipe == null ? 0 : currentRecipe.getCyclesPerUnit(); + setEnergyPerWorkCycle(ENERGY_PER_RECIPE_TIME * recipeTime); + setTicksPerWorkCycle(recipeTime); + } + } - int recipeTime = currentRecipe == null ? 0 : currentRecipe.getCyclesPerUnit(); - setEnergyPerWorkCycle(ENERGY_PER_RECIPE_TIME * recipeTime); - setTicksPerWorkCycle(recipeTime); - } - } + @Override + public boolean hasWork() { + checkRecipe(); - @Override - public boolean hasWork() { - checkRecipe(); + boolean hasRecipe = (currentRecipe != null); + boolean hasTankSpace = true; + boolean hasLiquidResource = true; - boolean hasRecipe = (currentRecipe != null); - boolean hasTankSpace = true; - boolean hasLiquidResource = true; + if (hasRecipe) { + hasTankSpace = productTank.canFill(currentRecipe.getOutput()); + if (bufferedLiquid == null) { + int cycles = currentRecipe.getCyclesPerUnit(); + FluidStack input = currentRecipe.getInput(); + int drainAmount = cycles * input.amount; + hasLiquidResource = resourceTank.canDrain(drainAmount); + if (hasLiquidResource) { + bufferedLiquid = new FluidStack(input, drainAmount); + resourceTank.drain(drainAmount, true); + } + } + } - if (hasRecipe) { - hasTankSpace = productTank.canFill(currentRecipe.getOutput()); - if (bufferedLiquid == null) { - int cycles = currentRecipe.getCyclesPerUnit(); - FluidStack input = currentRecipe.getInput(); - int drainAmount = cycles * input.amount; - hasLiquidResource = resourceTank.canDrain(drainAmount); - if (hasLiquidResource) { - bufferedLiquid = new FluidStack(input, drainAmount); - resourceTank.drain(drainAmount, true); - } - } - } + IErrorLogic errorLogic = getErrorLogic(); + errorLogic.setCondition(!hasRecipe, EnumErrorCode.NO_RECIPE); + errorLogic.setCondition(!hasTankSpace, EnumErrorCode.NO_SPACE_TANK); + errorLogic.setCondition(!hasLiquidResource, EnumErrorCode.NO_RESOURCE_LIQUID); - IErrorLogic errorLogic = getErrorLogic(); - errorLogic.setCondition(!hasRecipe, EnumErrorCode.NO_RECIPE); - errorLogic.setCondition(!hasTankSpace, EnumErrorCode.NO_SPACE_TANK); - errorLogic.setCondition(!hasLiquidResource, EnumErrorCode.NO_RESOURCE_LIQUID); + return hasRecipe && hasLiquidResource && hasTankSpace; + } - return hasRecipe && hasLiquidResource && hasTankSpace; - } + @Override + public TankRenderInfo getResourceTankInfo() { + return new TankRenderInfo(resourceTank); + } - @Override - public TankRenderInfo getResourceTankInfo() { - return new TankRenderInfo(resourceTank); - } + @Override + public TankRenderInfo getProductTankInfo() { + return new TankRenderInfo(productTank); + } - @Override - public TankRenderInfo getProductTankInfo() { - return new TankRenderInfo(productTank); - } + /* IFluidHandler */ + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return tankManager.fill(from, resource, doFill); + } - /* IFluidHandler */ - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return tankManager.fill(from, resource, doFill); - } + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return tankManager.drain(from, resource, doDrain); + } - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return tankManager.drain(from, resource, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, int quantityMax, boolean doEmpty) { + return tankManager.drain(from, quantityMax, doEmpty); + } - @Override - public FluidStack drain(ForgeDirection from, int quantityMax, boolean doEmpty) { - return tankManager.drain(from, quantityMax, doEmpty); - } + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return tankManager.canFill(from, fluid); + } - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return tankManager.canFill(from, fluid); - } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return tankManager.canDrain(from, fluid); + } - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return tankManager.canDrain(from, fluid); - } + @Override + public TankManager getTankManager() { + return tankManager; + } - @Override - public TankManager getTankManager() { - return tankManager; - } + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return tankManager.getTankInfo(from); + } - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return tankManager.getTankInfo(from); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiStill(player.inventory, this); + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiStill(player.inventory, this); - } - - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerStill(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerStill(player.inventory, this); + } } diff --git a/src/main/java/forestry/factory/tiles/TileWorktable.java b/src/main/java/forestry/factory/tiles/TileWorktable.java index 644e7fb90..d30aa8c28 100644 --- a/src/main/java/forestry/factory/tiles/TileWorktable.java +++ b/src/main/java/forestry/factory/tiles/TileWorktable.java @@ -10,17 +10,6 @@ ******************************************************************************/ package forestry.factory.tiles; -import java.io.IOException; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; - import forestry.core.config.Config; import forestry.core.inventory.InventoryAdapterTile; import forestry.core.inventory.wrappers.InventoryMapper; @@ -37,259 +26,272 @@ import forestry.factory.inventory.InventoryGhostCrafting; import forestry.factory.inventory.InventoryWorktable; import forestry.factory.recipes.MemorizedRecipe; import forestry.factory.recipes.RecipeMemory; +import java.io.IOException; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; public class TileWorktable extends TileBase implements ICrafterWorktable { - private final RecipeMemory recipeMemory; - private final InventoryAdapterTile craftingDisplay; - private MemorizedRecipe currentRecipe; + private final RecipeMemory recipeMemory; + private final InventoryAdapterTile craftingDisplay; + private MemorizedRecipe currentRecipe; private long savedTick = 0; private long savedSystemTimeExpiration = 0; - - public TileWorktable() { - super("worktable"); - setInternalInventory(new InventoryWorktable(this)); - craftingDisplay = new InventoryGhostCrafting<>(this, 10); - recipeMemory = new RecipeMemory(); - } + public TileWorktable() { + super("worktable"); + setInternalInventory(new InventoryWorktable(this)); - /* LOADING & SAVING */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + craftingDisplay = new InventoryGhostCrafting<>(this, 10); + recipeMemory = new RecipeMemory(); + } - craftingDisplay.writeToNBT(nbttagcompound); - recipeMemory.writeToNBT(nbttagcompound); - } + /* LOADING & SAVING */ + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); + craftingDisplay.writeToNBT(nbttagcompound); + recipeMemory.writeToNBT(nbttagcompound); + } - craftingDisplay.readFromNBT(nbttagcompound); - recipeMemory.readFromNBT(nbttagcompound); - } + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); - /* NETWORK */ - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); + craftingDisplay.readFromNBT(nbttagcompound); + recipeMemory.readFromNBT(nbttagcompound); + } - craftingDisplay.writeData(data); - recipeMemory.writeData(data); - } + /* NETWORK */ + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); + craftingDisplay.writeData(data); + recipeMemory.writeData(data); + } - craftingDisplay.readData(data); - recipeMemory.readData(data); - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); - @Override - public void validate() { - super.validate(); - recipeMemory.validate(worldObj); - } + craftingDisplay.readData(data); + recipeMemory.readData(data); + } - /* Recipe Conflicts */ - public boolean hasRecipeConflict() { - return currentRecipe != null && currentRecipe.hasRecipeConflict(); - } + @Override + public void validate() { + super.validate(); + recipeMemory.validate(worldObj); + } - public void chooseNextConflictRecipe() { - if (currentRecipe != null) { - currentRecipe.incrementRecipe(); - } - } + /* Recipe Conflicts */ + public boolean hasRecipeConflict() { + return currentRecipe != null && currentRecipe.hasRecipeConflict(); + } - public void choosePreviousConflictRecipe() { - if (currentRecipe != null) { - currentRecipe.decrementRecipe(); - } - } + public void chooseNextConflictRecipe() { + if (currentRecipe != null) { + currentRecipe.incrementRecipe(); + } + } - /* ICrafterWorktable */ - @Override - public boolean canTakeStack(int craftingSlotIndex) { - if (craftingSlotIndex == InventoryGhostCrafting.SLOT_CRAFTING_RESULT) { - return canCraftCurrentRecipe(); - } - return true; - } + public void choosePreviousConflictRecipe() { + if (currentRecipe != null) { + currentRecipe.decrementRecipe(); + } + } - private boolean canCraftCurrentRecipe() { - if (currentRecipe == null) { - return false; - } + /* ICrafterWorktable */ + @Override + public boolean canTakeStack(int craftingSlotIndex) { + if (craftingSlotIndex == InventoryGhostCrafting.SLOT_CRAFTING_RESULT) { + return canCraftCurrentRecipe(); + } + return true; + } - if( Config.enableCraftingTimeout ) { + private boolean canCraftCurrentRecipe() { + if (currentRecipe == null) { + return false; + } + + if (Config.enableCraftingTimeout) { long currentTick = worldObj.getTotalWorldTime(); - if (currentTick == savedTick){ + if (currentTick == savedTick) { // Processing in the same tick, second call, check expiration timer long currentTime = System.nanoTime(); - if(currentTime > savedSystemTimeExpiration) { + if (currentTime > savedSystemTimeExpiration) { // Time to craft has expired, stop crafting loop return false; } } else { // New tick has arrived, so reset timer data - savedTick=currentTick; + savedTick = currentTick; savedSystemTimeExpiration = System.nanoTime() + Config.craftingTimeout * 1000000; } } - ItemStack[] recipeItems = InventoryUtil.getStacks(currentRecipe.getCraftMatrix()); - ItemStack[] inventory = InventoryUtil.getStacks(this); - InventoryCraftingForestry crafting = RecipeUtil.getCraftRecipe(recipeItems, inventory, worldObj, currentRecipe.getRecipeOutput()); + ItemStack[] recipeItems = InventoryUtil.getStacks(currentRecipe.getCraftMatrix()); + ItemStack[] inventory = InventoryUtil.getStacks(this); + InventoryCraftingForestry crafting = + RecipeUtil.getCraftRecipe(recipeItems, inventory, worldObj, currentRecipe.getRecipeOutput()); return crafting != null; - } + } - @Override - public boolean onCraftingStart(EntityPlayer player) { - if (currentRecipe == null) { - return false; - } + @Override + public boolean onCraftingStart(EntityPlayer player) { + if (currentRecipe == null) { + return false; + } - ItemStack[] recipeItems = InventoryUtil.getStacks(currentRecipe.getCraftMatrix()); - ItemStack[] inventory = InventoryUtil.getStacks(this); - InventoryCraftingForestry crafting = RecipeUtil.getCraftRecipe(recipeItems, inventory, worldObj, currentRecipe.getRecipeOutput()); - if (crafting == null) { - return false; - } + ItemStack[] recipeItems = InventoryUtil.getStacks(currentRecipe.getCraftMatrix()); + ItemStack[] inventory = InventoryUtil.getStacks(this); + InventoryCraftingForestry crafting = + RecipeUtil.getCraftRecipe(recipeItems, inventory, worldObj, currentRecipe.getRecipeOutput()); + if (crafting == null) { + return false; + } - recipeItems = InventoryUtil.getStacks(crafting); + recipeItems = InventoryUtil.getStacks(crafting); - // craft recipe should exactly match ingredients here, so no oreDict or tool matching - ItemStack[] removed = InventoryUtil.removeSets(this, 1, recipeItems, player, false, false, false); - if (removed == null) { - return false; - } - // update crafting display to match the ingredients that were actually used - setCraftingDisplay(crafting); - return true; - } + // craft recipe should exactly match ingredients here, so no oreDict or tool matching + ItemStack[] removed = InventoryUtil.removeSets(this, 1, recipeItems, player, false, false, false); + if (removed == null) { + return false; + } + // update crafting display to match the ingredients that were actually used + setCraftingDisplay(crafting); + return true; + } - @Override - public void onCraftingComplete(EntityPlayer player) { - IInventory craftingInventory = getCraftingDisplay(); - for (int i = 0; i < craftingInventory.getSizeInventory(); ++i) { - ItemStack itemStack = craftingInventory.getStackInSlot(i); - if (itemStack == null) { - continue; - } + @Override + public void onCraftingComplete(EntityPlayer player) { + IInventory craftingInventory = getCraftingDisplay(); + for (int i = 0; i < craftingInventory.getSizeInventory(); ++i) { + ItemStack itemStack = craftingInventory.getStackInSlot(i); + if (itemStack == null) { + continue; + } - ItemStack container = null; + ItemStack container = null; - if (itemStack.getItem().hasContainerItem(itemStack)) { - container = itemStack.getItem().getContainerItem(itemStack); - } else if (itemStack.stackSize > 1) { - // TerraFirmaCraft's crafting event handler does some tricky stuff with its tools. - // It sets the tool's stack size to 2 instead of using a container. - container = ItemStackUtil.createSplitStack(itemStack, itemStack.stackSize - 1); - itemStack.stackSize = 1; - } + if (itemStack.getItem().hasContainerItem(itemStack)) { + container = itemStack.getItem().getContainerItem(itemStack); + } else if (itemStack.stackSize > 1) { + // TerraFirmaCraft's crafting event handler does some tricky stuff with its tools. + // It sets the tool's stack size to 2 instead of using a container. + container = ItemStackUtil.createSplitStack(itemStack, itemStack.stackSize - 1); + itemStack.stackSize = 1; + } - if (container == null) { - continue; - } + if (container == null) { + continue; + } - if (container != null && container.isItemStackDamageable() && container.getItemDamage() > container.getMaxDamage()) { - MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, container)); - continue; - } + if (container != null + && container.isItemStackDamageable() + && container.getItemDamage() > container.getMaxDamage()) { + MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, container)); + continue; + } - if (!InventoryUtil.tryAddStack(this, container, true)) { - player.dropPlayerItemWithRandomChoice(container, false); - } - } - - if (!worldObj.isRemote) { - recipeMemory.memorizeRecipe(worldObj.getTotalWorldTime(), currentRecipe); - } - } + if (!InventoryUtil.tryAddStack(this, container, true)) { + player.dropPlayerItemWithRandomChoice(container, false); + } + } - @Override - public ItemStack getResult() { - if (currentRecipe == null) { - return null; - } + if (!worldObj.isRemote) { + recipeMemory.memorizeRecipe(worldObj.getTotalWorldTime(), currentRecipe); + } + } - ItemStack result = currentRecipe.getRecipeOutput(); - if (result != null) { - result = result.copy(); - } - return result; - } + @Override + public ItemStack getResult() { + if (currentRecipe == null) { + return null; + } - /* Crafting Container methods */ - public RecipeMemory getMemory() { - return recipeMemory; - } + ItemStack result = currentRecipe.getRecipeOutput(); + if (result != null) { + result = result.copy(); + } + return result; + } - public void chooseRecipeMemory(int recipeIndex) { - MemorizedRecipe recipe = recipeMemory.getRecipe(recipeIndex); - setCurrentRecipe(recipe); - } + /* Crafting Container methods */ + public RecipeMemory getMemory() { + return recipeMemory; + } - private void setCraftingDisplay(IInventory craftMatrix) { - if (craftMatrix == null) { - return; - } + public void chooseRecipeMemory(int recipeIndex) { + MemorizedRecipe recipe = recipeMemory.getRecipe(recipeIndex); + setCurrentRecipe(recipe); + } - for (int slot = 0; slot < craftMatrix.getSizeInventory(); slot++) { - craftingDisplay.setInventorySlotContents(slot, craftMatrix.getStackInSlot(slot)); - } - } + private void setCraftingDisplay(IInventory craftMatrix) { + if (craftMatrix == null) { + return; + } - public IInventory getCraftingDisplay() { - return new InventoryMapper(craftingDisplay, InventoryGhostCrafting.SLOT_CRAFTING_1, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); - } + for (int slot = 0; slot < craftMatrix.getSizeInventory(); slot++) { + craftingDisplay.setInventorySlotContents(slot, craftMatrix.getStackInSlot(slot)); + } + } - public void clearCraftMatrix() { - for (int slot = 0; slot < craftingDisplay.getSizeInventory(); slot++) { - craftingDisplay.setInventorySlotContents(slot, null); - } - } + public IInventory getCraftingDisplay() { + return new InventoryMapper( + craftingDisplay, InventoryGhostCrafting.SLOT_CRAFTING_1, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); + } - public void setCurrentRecipe(InventoryCraftingForestry crafting) { - List recipeOutputs = RecipeUtil.findMatchingRecipes(crafting, worldObj); - MemorizedRecipe recipe = recipeOutputs.size() == 0 ? null : new MemorizedRecipe(crafting, recipeOutputs); + public void clearCraftMatrix() { + for (int slot = 0; slot < craftingDisplay.getSizeInventory(); slot++) { + craftingDisplay.setInventorySlotContents(slot, null); + } + } - if (currentRecipe != null && recipe != null) { - if (recipe.hasRecipeOutput(currentRecipe.getRecipeOutput())) { - ItemStack[] stacks = InventoryUtil.getStacks(crafting); - ItemStack[] currentStacks = InventoryUtil.getStacks(currentRecipe.getCraftMatrix()); - if (ItemStackUtil.equalSets(stacks, currentStacks)) { - return; - } - } - } + public void setCurrentRecipe(InventoryCraftingForestry crafting) { + List recipeOutputs = RecipeUtil.findMatchingRecipes(crafting, worldObj); + MemorizedRecipe recipe = recipeOutputs.size() == 0 ? null : new MemorizedRecipe(crafting, recipeOutputs); - setCurrentRecipe(recipe); - } + if (currentRecipe != null && recipe != null) { + if (recipe.hasRecipeOutput(currentRecipe.getRecipeOutput())) { + ItemStack[] stacks = InventoryUtil.getStacks(crafting); + ItemStack[] currentStacks = InventoryUtil.getStacks(currentRecipe.getCraftMatrix()); + if (ItemStackUtil.equalSets(stacks, currentStacks)) { + return; + } + } + } - /* Network Sync with PacketWorktableRecipeUpdate */ - public MemorizedRecipe getCurrentRecipe() { - return currentRecipe; - } + setCurrentRecipe(recipe); + } - public void setCurrentRecipe(MemorizedRecipe recipe) { - this.currentRecipe = recipe; - if (currentRecipe != null) { - setCraftingDisplay(currentRecipe.getCraftMatrix()); - } - } + /* Network Sync with PacketWorktableRecipeUpdate */ + public MemorizedRecipe getCurrentRecipe() { + return currentRecipe; + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiWorktable(player, this); - } + public void setCurrentRecipe(MemorizedRecipe recipe) { + this.currentRecipe = recipe; + if (currentRecipe != null) { + setCraftingDisplay(currentRecipe.getCraftMatrix()); + } + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerWorktable(player, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiWorktable(player, this); + } + + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerWorktable(player, this); + } } diff --git a/src/main/java/forestry/factory/triggers/FactoryTriggers.java b/src/main/java/forestry/factory/triggers/FactoryTriggers.java index d6c90c5cd..fb358869c 100644 --- a/src/main/java/forestry/factory/triggers/FactoryTriggers.java +++ b/src/main/java/forestry/factory/triggers/FactoryTriggers.java @@ -13,15 +13,15 @@ package forestry.factory.triggers; import forestry.core.triggers.Trigger; public class FactoryTriggers { - public static Trigger lowResource25; - public static Trigger lowResource10; - public static Trigger lowFuel25; - public static Trigger lowFuel10; + public static Trigger lowResource25; + public static Trigger lowResource10; + public static Trigger lowFuel25; + public static Trigger lowFuel10; - public static void initialize() { - lowResource25 = new TriggerLowResource("lowResources.25", 0.25f); - lowResource10 = new TriggerLowResource("lowResources.10", 0.1f); - lowFuel25 = new TriggerLowFuel("lowFuel.25", 0.25f); - lowFuel10 = new TriggerLowFuel("lowFuel.10", 0.1f); - } + public static void initialize() { + lowResource25 = new TriggerLowResource("lowResources.25", 0.25f); + lowResource10 = new TriggerLowResource("lowResources.10", 0.1f); + lowFuel25 = new TriggerLowFuel("lowFuel.25", 0.25f); + lowFuel10 = new TriggerLowFuel("lowFuel.10", 0.1f); + } } diff --git a/src/main/java/forestry/factory/triggers/TriggerLowFuel.java b/src/main/java/forestry/factory/triggers/TriggerLowFuel.java index 77da0a62c..20f35c97a 100644 --- a/src/main/java/forestry/factory/triggers/TriggerLowFuel.java +++ b/src/main/java/forestry/factory/triggers/TriggerLowFuel.java @@ -10,47 +10,44 @@ ******************************************************************************/ package forestry.factory.triggers; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.statements.IStatementContainer; +import buildcraft.api.statements.IStatementParameter; import forestry.core.tiles.TileEngine; import forestry.core.tiles.TilePowered; import forestry.core.triggers.Trigger; - -import buildcraft.api.statements.IStatementContainer; -import buildcraft.api.statements.IStatementParameter; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TriggerLowFuel extends Trigger { - private float threshold = 0.25F; + private float threshold = 0.25F; - public TriggerLowFuel(String tag, float threshold) { - super(tag, "lowFuel"); - this.threshold = threshold; - } + public TriggerLowFuel(String tag, float threshold) { + super(tag, "lowFuel"); + this.threshold = threshold; + } - @Override - public String getDescription() { - return super.getDescription() + " < " + threshold * 100 + "%"; - } + @Override + public String getDescription() { + return super.getDescription() + " < " + threshold * 100 + "%"; + } - /** - * Return true if the tile given in parameter activates the trigger, given the parameters. - */ - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + /** + * Return true if the tile given in parameter activates the trigger, given the parameters. + */ + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - if (tile instanceof TilePowered) { - return !((TilePowered) tile).hasFuelMin(threshold); - } + if (tile instanceof TilePowered) { + return !((TilePowered) tile).hasFuelMin(threshold); + } - if (tile instanceof TileEngine) { - TileEngine tileEngine = (TileEngine) tile; - return !tileEngine.hasFuelMin(threshold); - } - - return false; - } + if (tile instanceof TileEngine) { + TileEngine tileEngine = (TileEngine) tile; + return !tileEngine.hasFuelMin(threshold); + } + return false; + } } diff --git a/src/main/java/forestry/factory/triggers/TriggerLowResource.java b/src/main/java/forestry/factory/triggers/TriggerLowResource.java index e652bfe37..0c4a96620 100644 --- a/src/main/java/forestry/factory/triggers/TriggerLowResource.java +++ b/src/main/java/forestry/factory/triggers/TriggerLowResource.java @@ -10,40 +10,37 @@ ******************************************************************************/ package forestry.factory.triggers; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.core.tiles.TilePowered; -import forestry.core.triggers.Trigger; - import buildcraft.api.statements.IStatementContainer; import buildcraft.api.statements.IStatementParameter; +import forestry.core.tiles.TilePowered; +import forestry.core.triggers.Trigger; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TriggerLowResource extends Trigger { - private float threshold = 0.25F; + private float threshold = 0.25F; - public TriggerLowResource(String tag, float threshold) { - super(tag, "lowResources"); - this.threshold = threshold; - } + public TriggerLowResource(String tag, float threshold) { + super(tag, "lowResources"); + this.threshold = threshold; + } - @Override - public String getDescription() { - return super.getDescription() + " < " + threshold * 100 + "%"; - } + @Override + public String getDescription() { + return super.getDescription() + " < " + threshold * 100 + "%"; + } - /** - * Return true if the tile given in parameter activates the trigger, given the parameters. - */ - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - if (!(tile instanceof TilePowered)) { - return false; - } - - return !((TilePowered) tile).hasResourcesMin(threshold); - } + /** + * Return true if the tile given in parameter activates the trigger, given the parameters. + */ + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + if (!(tile instanceof TilePowered)) { + return false; + } + return !((TilePowered) tile).hasResourcesMin(threshold); + } } diff --git a/src/main/java/forestry/farming/FarmHelper.java b/src/main/java/forestry/farming/FarmHelper.java index aad125448..194775be2 100755 --- a/src/main/java/forestry/farming/FarmHelper.java +++ b/src/main/java/forestry/farming/FarmHelper.java @@ -1,59 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming; - -import com.google.common.collect.ImmutableSet; - -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.api.farming.FarmDirection; -import forestry.api.multiblock.IFarmComponent; -import forestry.core.utils.vect.MutableVect; -import forestry.core.utils.vect.Vect; -import forestry.core.utils.vect.VectUtil; - -public class FarmHelper { - - public static final ImmutableSet bricks = ImmutableSet.of( - Blocks.brick_block, - Blocks.stonebrick, - Blocks.sandstone, - Blocks.nether_brick, - Blocks.quartz_block - ); - - private static FarmDirection getOpposite(FarmDirection farmDirection) { - ForgeDirection forgeDirection = farmDirection.getForgeDirection(); - ForgeDirection forgeDirectionOpposite = forgeDirection.getOpposite(); - return FarmDirection.getFarmDirection(forgeDirectionOpposite); - } - - public static Vect getFarmMultiblockCorner(World world, Vect start, FarmDirection farmSide, FarmDirection layoutDirection) { - Vect edge = getFarmMultiblockEdge(world, start, farmSide); - return getFarmMultiblockEdge(world, edge, getOpposite(layoutDirection)); - } - - private static Vect getFarmMultiblockEdge(World world, Vect start, FarmDirection direction) { - MutableVect edge = new MutableVect(start); - - while (VectUtil.getTile(world, edge) instanceof IFarmComponent) { - edge.add(direction); - } - - edge.add(getOpposite(direction)); - return new Vect(edge); - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming; + +import com.google.common.collect.ImmutableSet; +import forestry.api.farming.FarmDirection; +import forestry.api.multiblock.IFarmComponent; +import forestry.core.utils.vect.MutableVect; +import forestry.core.utils.vect.Vect; +import forestry.core.utils.vect.VectUtil; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +public class FarmHelper { + + public static final ImmutableSet bricks = ImmutableSet.of( + Blocks.brick_block, Blocks.stonebrick, Blocks.sandstone, Blocks.nether_brick, Blocks.quartz_block); + + private static FarmDirection getOpposite(FarmDirection farmDirection) { + ForgeDirection forgeDirection = farmDirection.getForgeDirection(); + ForgeDirection forgeDirectionOpposite = forgeDirection.getOpposite(); + return FarmDirection.getFarmDirection(forgeDirectionOpposite); + } + + public static Vect getFarmMultiblockCorner( + World world, Vect start, FarmDirection farmSide, FarmDirection layoutDirection) { + Vect edge = getFarmMultiblockEdge(world, start, farmSide); + return getFarmMultiblockEdge(world, edge, getOpposite(layoutDirection)); + } + + private static Vect getFarmMultiblockEdge(World world, Vect start, FarmDirection direction) { + MutableVect edge = new MutableVect(start); + + while (VectUtil.getTile(world, edge) instanceof IFarmComponent) { + edge.add(direction); + } + + edge.add(getOpposite(direction)); + return new Vect(edge); + } +} diff --git a/src/main/java/forestry/farming/FarmTarget.java b/src/main/java/forestry/farming/FarmTarget.java index a276bc708..aeb83c1dd 100755 --- a/src/main/java/forestry/farming/FarmTarget.java +++ b/src/main/java/forestry/farming/FarmTarget.java @@ -1,69 +1,68 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming; - -import net.minecraft.block.Block; -import net.minecraft.world.World; - -import forestry.api.farming.FarmDirection; -import forestry.core.utils.vect.MutableVect; -import forestry.core.utils.vect.Vect; -import forestry.core.utils.vect.VectUtil; - -public class FarmTarget { - - private final Vect start; - private final FarmDirection direction; - private final int limit; - - private int yOffset; - private int extent; - - public FarmTarget(Vect start, FarmDirection direction, int limit) { - this.start = start; - this.direction = direction; - this.limit = limit; - } - - public Vect getStart() { - return start; - } - - public int getYOffset() { - return this.yOffset; - } - - public int getExtent() { - return extent; - } - - public FarmDirection getDirection() { - return direction; - } - - public void setExtentAndYOffset(World world, Vect platformPosition) { - if (platformPosition == null) { - extent = 0; - return; - } - - MutableVect position = new MutableVect(platformPosition); - for (extent = 0; extent < limit; extent++) { - Block platform = VectUtil.getBlock(world, position); - if (!FarmHelper.bricks.contains(platform)) { - break; - } - position.add(getDirection().getForgeDirection()); - } - - yOffset = platformPosition.getY() + 1 - getStart().getY(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming; + +import forestry.api.farming.FarmDirection; +import forestry.core.utils.vect.MutableVect; +import forestry.core.utils.vect.Vect; +import forestry.core.utils.vect.VectUtil; +import net.minecraft.block.Block; +import net.minecraft.world.World; + +public class FarmTarget { + + private final Vect start; + private final FarmDirection direction; + private final int limit; + + private int yOffset; + private int extent; + + public FarmTarget(Vect start, FarmDirection direction, int limit) { + this.start = start; + this.direction = direction; + this.limit = limit; + } + + public Vect getStart() { + return start; + } + + public int getYOffset() { + return this.yOffset; + } + + public int getExtent() { + return extent; + } + + public FarmDirection getDirection() { + return direction; + } + + public void setExtentAndYOffset(World world, Vect platformPosition) { + if (platformPosition == null) { + extent = 0; + return; + } + + MutableVect position = new MutableVect(platformPosition); + for (extent = 0; extent < limit; extent++) { + Block platform = VectUtil.getBlock(world, position); + if (!FarmHelper.bricks.contains(platform)) { + break; + } + position.add(getDirection().getForgeDirection()); + } + + yOffset = platformPosition.getY() + 1 - getStart().getY(); + } +} diff --git a/src/main/java/forestry/farming/blocks/BlockFarm.java b/src/main/java/forestry/farming/blocks/BlockFarm.java index 750a0fb6b..6270399ed 100644 --- a/src/main/java/forestry/farming/blocks/BlockFarm.java +++ b/src/main/java/forestry/farming/blocks/BlockFarm.java @@ -10,9 +10,21 @@ ******************************************************************************/ package forestry.farming.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.blocks.BlockStructure; +import forestry.core.render.ParticleHelper; +import forestry.core.utils.ItemStackUtil; +import forestry.farming.render.EnumFarmBlockTexture; +import forestry.farming.tiles.TileFarm; +import forestry.farming.tiles.TileFarmControl; +import forestry.farming.tiles.TileFarmGearbox; +import forestry.farming.tiles.TileFarmHatch; +import forestry.farming.tiles.TileFarmPlain; +import forestry.farming.tiles.TileFarmValve; +import forestry.plugins.PluginFarming; import java.util.ArrayList; import java.util.List; - import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.particle.EffectRenderer; @@ -29,198 +41,183 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.blocks.BlockStructure; -import forestry.core.render.ParticleHelper; -import forestry.core.utils.ItemStackUtil; -import forestry.farming.render.EnumFarmBlockTexture; -import forestry.farming.tiles.TileFarm; -import forestry.farming.tiles.TileFarmControl; -import forestry.farming.tiles.TileFarmGearbox; -import forestry.farming.tiles.TileFarmHatch; -import forestry.farming.tiles.TileFarmPlain; -import forestry.farming.tiles.TileFarmValve; -import forestry.plugins.PluginFarming; - public class BlockFarm extends BlockStructure { - private final ParticleHelper.Callback particleCallback; + private final ParticleHelper.Callback particleCallback; - public BlockFarm() { - super(Material.rock); - setHardness(1.0f); - setHarvestLevel("pickaxe", 0); - this.particleCallback = new ParticleHelper.DefaultCallback(this); - } + public BlockFarm() { + super(Material.rock); + setHardness(1.0f); + setHarvestLevel("pickaxe", 0); + this.particleCallback = new ParticleHelper.DefaultCallback(this); + } - @Override - @SuppressWarnings({"rawtypes", "unchecked"}) - @SideOnly(Side.CLIENT) - public void getSubBlocks(Item item, CreativeTabs tab, List list) { - for (int i = 0; i < 6; i++) { - if (i == 1) { - continue; - } + @Override + @SuppressWarnings({"rawtypes", "unchecked"}) + @SideOnly(Side.CLIENT) + public void getSubBlocks(Item item, CreativeTabs tab, List list) { + for (int i = 0; i < 6; i++) { + if (i == 1) { + continue; + } - for (EnumFarmBlockTexture block : EnumFarmBlockTexture.values()) { - ItemStack stack = new ItemStack(item, 1, i); - NBTTagCompound compound = new NBTTagCompound(); - block.saveToCompound(compound); - stack.setTagCompound(compound); - list.add(stack); - } - } - } + for (EnumFarmBlockTexture block : EnumFarmBlockTexture.values()) { + ItemStack stack = new ItemStack(item, 1, i); + NBTTagCompound compound = new NBTTagCompound(); + block.saveToCompound(compound); + stack.setTagCompound(compound); + list.add(stack); + } + } + } - @Override - public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { - ArrayList drops = getDrops(world, x, y, z, 0, 0); - if (drops.isEmpty()) { - return super.getPickBlock(target, world, x, y, z); - } - return drops.get(0); - } + @Override + public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { + ArrayList drops = getDrops(world, x, y, z, 0, 0); + if (drops.isEmpty()) { + return super.getPickBlock(target, world, x, y, z); + } + return drops.get(0); + } - @Override - public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityLiving, ItemStack stack) { - super.onBlockPlacedBy(world, x, y, z, entityLiving, stack); - if (!stack.hasTagCompound()) { - return; - } + @Override + public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityLiving, ItemStack stack) { + super.onBlockPlacedBy(world, x, y, z, entityLiving, stack); + if (!stack.hasTagCompound()) { + return; + } - TileFarm tile = (TileFarm) world.getTileEntity(x, y, z); - tile.setFarmBlockTexture(EnumFarmBlockTexture.getFromCompound(stack.getTagCompound())); - } + TileFarm tile = (TileFarm) world.getTileEntity(x, y, z); + tile.setFarmBlockTexture(EnumFarmBlockTexture.getFromCompound(stack.getTagCompound())); + } - @Override - public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) { - int meta = world.getBlockMetadata(x, y, z); - if (!world.isRemote && canHarvestBlock(player, meta)) { - List drops = getDrops(world, x, y, z, 0, 0); - for (ItemStack drop : drops) { - ItemStackUtil.dropItemStackAsEntity(drop, world, x, y, z); - } - } - return world.setBlockToAir(x, y, z); - } + @Override + public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) { + int meta = world.getBlockMetadata(x, y, z); + if (!world.isRemote && canHarvestBlock(player, meta)) { + List drops = getDrops(world, x, y, z, 0, 0); + for (ItemStack drop : drops) { + ItemStackUtil.dropItemStackAsEntity(drop, world, x, y, z); + } + } + return world.setBlockToAir(x, y, z); + } - @Override - public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { - ArrayList drops = new ArrayList<>(); - int meta = world.getBlockMetadata(x, y, z); - TileEntity tile = world.getTileEntity(x, y, z); - if (tile instanceof TileFarm) { - TileFarm farm = (TileFarm) tile; + @Override + public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { + ArrayList drops = new ArrayList<>(); + int meta = world.getBlockMetadata(x, y, z); + TileEntity tile = world.getTileEntity(x, y, z); + if (tile instanceof TileFarm) { + TileFarm farm = (TileFarm) tile; - ItemStack stack = new ItemStack(this, 1, meta != 1 ? meta : 0); - NBTTagCompound compound = new NBTTagCompound(); - farm.getFarmBlockTexture().saveToCompound(compound); - stack.setTagCompound(compound); - drops.add(stack); - } - return drops; - } + ItemStack stack = new ItemStack(this, 1, meta != 1 ? meta : 0); + NBTTagCompound compound = new NBTTagCompound(); + farm.getFarmBlockTexture().saveToCompound(compound); + stack.setTagCompound(compound); + drops.add(stack); + } + return drops; + } - @Override - public int getDamageValue(World world, int x, int y, int z) { - int meta = world.getBlockMetadata(x, y, z); - return meta != 1 ? meta : 0; - } + @Override + public int getDamageValue(World world, int x, int y, int z) { + int meta = world.getBlockMetadata(x, y, z); + return meta != 1 ? meta : 0; + } - @Override - public TileEntity createTileEntity(World world, int metadata) { - switch (metadata) { - case 2: - return new TileFarmGearbox(); - case 3: - return new TileFarmHatch(); - case 4: - return new TileFarmValve(); - case 5: - return new TileFarmControl(); - default: - return new TileFarmPlain(); - } - } + @Override + public TileEntity createTileEntity(World world, int metadata) { + switch (metadata) { + case 2: + return new TileFarmGearbox(); + case 3: + return new TileFarmHatch(); + case 4: + return new TileFarmValve(); + case 5: + return new TileFarmControl(); + default: + return new TileFarmPlain(); + } + } - @Override - public TileEntity createNewTileEntity(World world, int meta) { - return createTileEntity(world, meta); - } + @Override + public TileEntity createNewTileEntity(World world, int meta) { + return createTileEntity(world, meta); + } - /* ICONS */ - @Override - public int getRenderType() { - return PluginFarming.modelIdFarmBlock; - } + /* ICONS */ + @Override + public int getRenderType() { + return PluginFarming.modelIdFarmBlock; + } - @SideOnly(Side.CLIENT) - @Override - public void registerBlockIcons(IIconRegister register) { - EnumFarmBlockTexture.registerIcons(register); - } + @SideOnly(Side.CLIENT) + @Override + public void registerBlockIcons(IIconRegister register) { + EnumFarmBlockTexture.registerIcons(register); + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(int side, int metadata) { - return getBlockTextureForSide(EnumFarmBlockTexture.BRICK, side); - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(int side, int metadata) { + return getBlockTextureForSide(EnumFarmBlockTexture.BRICK, side); + } - @SideOnly(Side.CLIENT) - public static IIcon getBlockTextureForSide(EnumFarmBlockTexture type, int side) { - Block block = ItemStackUtil.getBlock(type.getBase()); - if (block == null) { - return null; - } - int damage = type.getBase().getItemDamage(); - return block.getIcon(side, damage); - } + @SideOnly(Side.CLIENT) + public static IIcon getBlockTextureForSide(EnumFarmBlockTexture type, int side) { + Block block = ItemStackUtil.getBlock(type.getBase()); + if (block == null) { + return null; + } + int damage = type.getBase().getItemDamage(); + return block.getIcon(side, damage); + } - @SideOnly(Side.CLIENT) - public static IIcon getOverlayTextureForBlock(int side, int metadata) { - BlockFarmType type = BlockFarmType.VALUES[metadata]; - return EnumFarmBlockTexture.getIcon(type, side); - } + @SideOnly(Side.CLIENT) + public static IIcon getOverlayTextureForBlock(int side, int metadata) { + BlockFarmType type = BlockFarmType.VALUES[metadata]; + return EnumFarmBlockTexture.getIcon(type, side); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { - TileEntity tile = world.getTileEntity(x, y, z); - ItemStack base = EnumFarmBlockTexture.BRICK_STONE.getBase(); + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { + TileEntity tile = world.getTileEntity(x, y, z); + ItemStack base = EnumFarmBlockTexture.BRICK_STONE.getBase(); - if (tile instanceof TileFarm) { - base = ((TileFarm) tile).getFarmBlockTexture().getBase(); - } + if (tile instanceof TileFarm) { + base = ((TileFarm) tile).getFarmBlockTexture().getBase(); + } - Block block = ItemStackUtil.getBlock(base); - if (block == null) { - return null; - } + Block block = ItemStackUtil.getBlock(base); + if (block == null) { + return null; + } - return block.getIcon(side, base.getItemDamage()); - } + return block.getIcon(side, base.getItemDamage()); + } - /* Particles */ - @SideOnly(Side.CLIENT) - @Override - public boolean addHitEffects(World worldObj, MovingObjectPosition target, EffectRenderer effectRenderer) { - return ParticleHelper.addHitEffects(worldObj, this, target, effectRenderer, particleCallback); - } + /* Particles */ + @SideOnly(Side.CLIENT) + @Override + public boolean addHitEffects(World worldObj, MovingObjectPosition target, EffectRenderer effectRenderer) { + return ParticleHelper.addHitEffects(worldObj, this, target, effectRenderer, particleCallback); + } - @SideOnly(Side.CLIENT) - @Override - public boolean addDestroyEffects(World worldObj, int x, int y, int z, int meta, EffectRenderer effectRenderer) { - return ParticleHelper.addDestroyEffects(worldObj, this, x, y, z, meta, effectRenderer, particleCallback); - } + @SideOnly(Side.CLIENT) + @Override + public boolean addDestroyEffects(World worldObj, int x, int y, int z, int meta, EffectRenderer effectRenderer) { + return ParticleHelper.addDestroyEffects(worldObj, this, x, y, z, meta, effectRenderer, particleCallback); + } - @Override - public boolean canConnectRedstone(IBlockAccess world, int x, int y, int z, int side) { - return world.getBlockMetadata(x, y, z) == 5; - } + @Override + public boolean canConnectRedstone(IBlockAccess world, int x, int y, int z, int side) { + return world.getBlockMetadata(x, y, z) == 5; + } - public ItemStack get(BlockFarmType type, int amount) { - return new ItemStack(this, amount, type.ordinal()); - } + public ItemStack get(BlockFarmType type, int amount) { + return new ItemStack(this, amount, type.ordinal()); + } } diff --git a/src/main/java/forestry/farming/blocks/BlockFarmType.java b/src/main/java/forestry/farming/blocks/BlockFarmType.java index 9b01f5605..5e0c0d049 100644 --- a/src/main/java/forestry/farming/blocks/BlockFarmType.java +++ b/src/main/java/forestry/farming/blocks/BlockFarmType.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.blocks; - -public enum BlockFarmType { - BASIC, - BAND, - GEARBOX, - HATCH, - VALVE, - CONTROL; - - public static final BlockFarmType[] VALUES = values(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.blocks; + +public enum BlockFarmType { + BASIC, + BAND, + GEARBOX, + HATCH, + VALVE, + CONTROL; + + public static final BlockFarmType[] VALUES = values(); +} diff --git a/src/main/java/forestry/farming/blocks/BlockMushroom.java b/src/main/java/forestry/farming/blocks/BlockMushroom.java index c9ac110cd..cb7972934 100644 --- a/src/main/java/forestry/farming/blocks/BlockMushroom.java +++ b/src/main/java/forestry/farming/blocks/BlockMushroom.java @@ -10,10 +10,13 @@ ******************************************************************************/ package forestry.farming.blocks; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.blocks.IItemTyped; +import forestry.core.config.Constants; import java.util.ArrayList; import java.util.List; import java.util.Random; - import net.minecraft.block.Block; import net.minecraft.block.BlockSapling; import net.minecraft.client.renderer.texture.IIconRegister; @@ -26,127 +29,122 @@ import net.minecraft.world.World; import net.minecraft.world.gen.feature.WorldGenBigMushroom; import net.minecraft.world.gen.feature.WorldGenerator; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.blocks.IItemTyped; -import forestry.core.config.Constants; - public class BlockMushroom extends BlockSapling implements IItemTyped { - public enum MushroomType { - BROWN, RED - } + public enum MushroomType { + BROWN, + RED + } - private final WorldGenerator[] generators; - private final ItemStack[] drops; + private final WorldGenerator[] generators; + private final ItemStack[] drops; - public BlockMushroom() { - super(); - setHardness(0.0f); - this.generators = new WorldGenerator[]{new WorldGenBigMushroom(MushroomType.BROWN.ordinal()), new WorldGenBigMushroom(MushroomType.RED.ordinal())}; - this.drops = new ItemStack[]{new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.red_mushroom)}; - setCreativeTab(null); - setTickRandomly(true); - } + public BlockMushroom() { + super(); + setHardness(0.0f); + this.generators = new WorldGenerator[] { + new WorldGenBigMushroom(MushroomType.BROWN.ordinal()), new WorldGenBigMushroom(MushroomType.RED.ordinal()) + }; + this.drops = new ItemStack[] {new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.red_mushroom)}; + setCreativeTab(null); + setTickRandomly(true); + } - @Override - public boolean getTickRandomly() { - return true; - } + @Override + public boolean getTickRandomly() { + return true; + } - // / DROPS - @Override - public ArrayList getDrops(World world, int X, int Y, int Z, int metadata, int fortune) { - ArrayList ret = new ArrayList<>(); + // / DROPS + @Override + public ArrayList getDrops(World world, int X, int Y, int Z, int metadata, int fortune) { + ArrayList ret = new ArrayList<>(); - MushroomType type = getTypeFromMeta(metadata); + MushroomType type = getTypeFromMeta(metadata); - ret.add(drops[type.ordinal()]); + ret.add(drops[type.ordinal()]); - return ret; - } + return ret; + } - @Override - protected boolean canPlaceBlockOn(Block block) { - return block == Blocks.mycelium; - } + @Override + protected boolean canPlaceBlockOn(Block block) { + return block == Blocks.mycelium; + } - @Override - public void updateTick(World world, int i, int j, int k, Random random) { + @Override + public void updateTick(World world, int i, int j, int k, Random random) { - if (world.isRemote) { - return; - } + if (world.isRemote) { + return; + } - int meta = world.getBlockMetadata(i, j, k); - MushroomType type = getTypeFromMeta(meta); - int maturity = meta >> 2; + int meta = world.getBlockMetadata(i, j, k); + MushroomType type = getTypeFromMeta(meta); + int maturity = meta >> 2; - tickGermling(world, i, j, k, random, type, maturity); - } + tickGermling(world, i, j, k, random, type, maturity); + } - private void tickGermling(World world, int i, int j, int k, Random random, MushroomType type, int maturity) { + private void tickGermling(World world, int i, int j, int k, Random random, MushroomType type, int maturity) { - int lightvalue = world.getBlockLightValue(i, j + 1, k); + int lightvalue = world.getBlockLightValue(i, j + 1, k); - if (random.nextInt(2) != 0) { - return; - } + if (random.nextInt(2) != 0) { + return; + } - if (maturity != 3) { - maturity = 3; - int matX = maturity << 2; - int meta = (matX | type.ordinal()); - world.setBlockMetadataWithNotify(i, j, k, meta, Constants.FLAG_BLOCK_SYNCH); - } else if (lightvalue <= 7) { - func_149878_d(world, i, j, k, random); - } - } + if (maturity != 3) { + maturity = 3; + int matX = maturity << 2; + int meta = (matX | type.ordinal()); + world.setBlockMetadataWithNotify(i, j, k, meta, Constants.FLAG_BLOCK_SYNCH); + } else if (lightvalue <= 7) { + func_149878_d(world, i, j, k, random); + } + } - @Override - public void func_149878_d(World world, int i, int j, int k, Random random) { - MushroomType type = getTypeFromMeta(world.getBlockMetadata(i, j, k)); + @Override + public void func_149878_d(World world, int i, int j, int k, Random random) { + MushroomType type = getTypeFromMeta(world.getBlockMetadata(i, j, k)); - world.setBlockToAir(i, j, k); - if (!generators[type.ordinal()].generate(world, random, i, j, k)) { - world.setBlock(i, j, k, this, type.ordinal(), 0); - } - } + world.setBlockToAir(i, j, k); + if (!generators[type.ordinal()].generate(world, random, i, j, k)) { + world.setBlock(i, j, k, this, type.ordinal(), 0); + } + } - @Override - public MushroomType getTypeFromMeta(int meta) { - meta %= MushroomType.values().length; - return MushroomType.values()[meta]; - } + @Override + public MushroomType getTypeFromMeta(int meta) { + meta %= MushroomType.values().length; + return MushroomType.values()[meta]; + } - /* ICONS */ - @SuppressWarnings({"unchecked", "rawtypes"}) - @SideOnly(Side.CLIENT) - @Override - public void getSubBlocks(Item item, CreativeTabs tab, List list) { - list.add(new ItemStack(item, 1, 0)); - list.add(new ItemStack(item, 1, 1)); - } + /* ICONS */ + @SuppressWarnings({"unchecked", "rawtypes"}) + @SideOnly(Side.CLIENT) + @Override + public void getSubBlocks(Item item, CreativeTabs tab, List list) { + list.add(new ItemStack(item, 1, 0)); + list.add(new ItemStack(item, 1, 1)); + } - @SideOnly(Side.CLIENT) - @Override - public void registerBlockIcons(IIconRegister register) { - } + @SideOnly(Side.CLIENT) + @Override + public void registerBlockIcons(IIconRegister register) {} - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon(int side, int meta) { - MushroomType type = getTypeFromMeta(meta); - - switch (type) { - case BROWN: - return Blocks.brown_mushroom.getIcon(side, meta); - case RED: - return Blocks.red_mushroom.getIcon(side, meta); - default: - return null; - } - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(int side, int meta) { + MushroomType type = getTypeFromMeta(meta); + switch (type) { + case BROWN: + return Blocks.brown_mushroom.getIcon(side, meta); + case RED: + return Blocks.red_mushroom.getIcon(side, meta); + default: + return null; + } + } } diff --git a/src/main/java/forestry/farming/blocks/BlockRegistryFarming.java b/src/main/java/forestry/farming/blocks/BlockRegistryFarming.java index 7f8fcaa80..2fedacd09 100644 --- a/src/main/java/forestry/farming/blocks/BlockRegistryFarming.java +++ b/src/main/java/forestry/farming/blocks/BlockRegistryFarming.java @@ -1,25 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.blocks; - -import forestry.core.blocks.BlockRegistry; -import forestry.core.items.ItemBlockTyped; -import forestry.farming.items.ItemBlockFarm; - -public class BlockRegistryFarming extends BlockRegistry { - public final BlockMushroom mushroom; - public final BlockFarm farm; - - public BlockRegistryFarming() { - mushroom = registerBlock(new BlockMushroom(), ItemBlockTyped.class, "mushroom"); - farm = registerBlock(new BlockFarm(), ItemBlockFarm.class, "ffarm"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.blocks; + +import forestry.core.blocks.BlockRegistry; +import forestry.core.items.ItemBlockTyped; +import forestry.farming.items.ItemBlockFarm; + +public class BlockRegistryFarming extends BlockRegistry { + public final BlockMushroom mushroom; + public final BlockFarm farm; + + public BlockRegistryFarming() { + mushroom = registerBlock(new BlockMushroom(), ItemBlockTyped.class, "mushroom"); + farm = registerBlock(new BlockFarm(), ItemBlockFarm.class, "ffarm"); + } +} diff --git a/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java b/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java index cc402c35a..a4ec8b23d 100755 --- a/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java +++ b/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java @@ -17,72 +17,71 @@ import forestry.core.circuits.Circuit; public class CircuitFarmLogic extends Circuit { - private final Class logicClass; - private boolean isManual = false; + private final Class logicClass; + private boolean isManual = false; - public CircuitFarmLogic(String uid, Class logicClass) { - super(uid, false); - this.logicClass = logicClass; - setLimit(4); - } + public CircuitFarmLogic(String uid, Class logicClass) { + super(uid, false); + this.logicClass = logicClass; + setLimit(4); + } - public CircuitFarmLogic setManual() { - isManual = true; - return this; - } + public CircuitFarmLogic setManual() { + isManual = true; + return this; + } - @Override - public boolean isCircuitable(Object tile) { - return tile instanceof IFarmHousing; - } + @Override + public boolean isCircuitable(Object tile) { + return tile instanceof IFarmHousing; + } - private IFarmHousing getCircuitable(Object tile) { - if (!isCircuitable(tile)) { - return null; - } - return (IFarmHousing) tile; - } + private IFarmHousing getCircuitable(Object tile) { + if (!isCircuitable(tile)) { + return null; + } + return (IFarmHousing) tile; + } - @Override - @SuppressWarnings("rawtypes") - public void onInsertion(int slot, Object tile) { - IFarmHousing housing = getCircuitable(tile); - if (housing == null) { - return; - } + @Override + @SuppressWarnings("rawtypes") + public void onInsertion(int slot, Object tile) { + IFarmHousing housing = getCircuitable(tile); + if (housing == null) { + return; + } - IFarmLogic logic; - try { - logic = logicClass.getConstructor(IFarmHousing.class).newInstance(housing); - } catch (Exception ex) { - throw new RuntimeException("Failed to instantiate logic of class " + logicClass.getName() + ": " + ex.getMessage()); - } + IFarmLogic logic; + try { + logic = logicClass.getConstructor(IFarmHousing.class).newInstance(housing); + } catch (Exception ex) { + throw new RuntimeException( + "Failed to instantiate logic of class " + logicClass.getName() + ": " + ex.getMessage()); + } - try { - logic.setManual(isManual); - } catch (Throwable e) { - // uses older version of the API that doesn't implement setManual - } - housing.setFarmLogic(FarmDirection.values()[slot], logic); - } + try { + logic.setManual(isManual); + } catch (Throwable e) { + // uses older version of the API that doesn't implement setManual + } + housing.setFarmLogic(FarmDirection.values()[slot], logic); + } - @Override - public void onLoad(int slot, Object tile) { - onInsertion(slot, tile); - } + @Override + public void onLoad(int slot, Object tile) { + onInsertion(slot, tile); + } - @Override - public void onRemoval(int slot, Object tile) { - IFarmHousing farmHousing = getCircuitable(tile); - if (farmHousing == null) { - return; - } + @Override + public void onRemoval(int slot, Object tile) { + IFarmHousing farmHousing = getCircuitable(tile); + if (farmHousing == null) { + return; + } - farmHousing.resetFarmLogic(FarmDirection.values()[slot]); - } - - @Override - public void onTick(int slot, Object tile) { - } + farmHousing.resetFarmLogic(FarmDirection.values()[slot]); + } + @Override + public void onTick(int slot, Object tile) {} } diff --git a/src/main/java/forestry/farming/gui/ContainerFarm.java b/src/main/java/forestry/farming/gui/ContainerFarm.java index fcdd49851..f12275442 100755 --- a/src/main/java/forestry/farming/gui/ContainerFarm.java +++ b/src/main/java/forestry/farming/gui/ContainerFarm.java @@ -10,65 +10,66 @@ ******************************************************************************/ package forestry.farming.gui; -import net.minecraft.entity.player.InventoryPlayer; - -import net.minecraftforge.fluids.IFluidTank; - import forestry.core.gui.ContainerSocketed; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.core.network.packets.PacketGuiUpdate; import forestry.farming.multiblock.InventoryFarm; import forestry.farming.tiles.TileFarm; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraftforge.fluids.IFluidTank; public class ContainerFarm extends ContainerSocketed { - public ContainerFarm(InventoryPlayer playerInventory, TileFarm tile) { - super(tile, playerInventory, 28, 138); + public ContainerFarm(InventoryPlayer playerInventory, TileFarm tile) { + super(tile, playerInventory, 28, 138); - // Resources - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 2; j++) { - addSlotToContainer(new SlotFiltered(tile, InventoryFarm.SLOT_RESOURCES_1 + j + i * 2, 123 + j * 18, 22 + i * 18)); - } - } + // Resources + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { + addSlotToContainer( + new SlotFiltered(tile, InventoryFarm.SLOT_RESOURCES_1 + j + i * 2, 123 + j * 18, 22 + i * 18)); + } + } - // Germlings - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 2; j++) { - addSlotToContainer(new SlotFiltered(tile, InventoryFarm.SLOT_GERMLINGS_1 + j + i * 2, 164 + j * 18, 22 + i * 18)); - } - } + // Germlings + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { + addSlotToContainer( + new SlotFiltered(tile, InventoryFarm.SLOT_GERMLINGS_1 + j + i * 2, 164 + j * 18, 22 + i * 18)); + } + } - // Production 1 - for (int i = 0; i < 2; i++) { - for (int j = 0; j < 2; j++) { - addSlotToContainer(new SlotOutput(tile, InventoryFarm.SLOT_PRODUCTION_1 + j + i * 2, 123 + j * 18, 86 + i * 18)); - } - } + // Production 1 + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 2; j++) { + addSlotToContainer( + new SlotOutput(tile, InventoryFarm.SLOT_PRODUCTION_1 + j + i * 2, 123 + j * 18, 86 + i * 18)); + } + } - // Production 2 - for (int i = 0; i < 2; i++) { - for (int j = 0; j < 2; j++) { - addSlotToContainer(new SlotOutput(tile, InventoryFarm.SLOT_PRODUCTION_1 + 4 + j + i * 2, 164 + j * 18, 86 + i * 18)); - } - } + // Production 2 + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 2; j++) { + addSlotToContainer(new SlotOutput( + tile, InventoryFarm.SLOT_PRODUCTION_1 + 4 + j + i * 2, 164 + j * 18, 86 + i * 18)); + } + } - // Fertilizer - addSlotToContainer(new SlotFiltered(tile, InventoryFarm.SLOT_FERTILIZER, 63, 95)); - // Can Slot - addSlotToContainer(new SlotFiltered(tile, InventoryFarm.SLOT_CAN, 15, 95)); - } + // Fertilizer + addSlotToContainer(new SlotFiltered(tile, InventoryFarm.SLOT_FERTILIZER, 63, 95)); + // Can Slot + addSlotToContainer(new SlotFiltered(tile, InventoryFarm.SLOT_CAN, 15, 95)); + } - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - PacketGuiUpdate packet = new PacketGuiUpdate(tile); - sendPacketToCrafters(packet); - } - - public IFluidTank getTank(int slot) { - return tile.getMultiblockLogic().getController().getTankManager().getTank(slot); - } + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + PacketGuiUpdate packet = new PacketGuiUpdate(tile); + sendPacketToCrafters(packet); + } + public IFluidTank getTank(int slot) { + return tile.getMultiblockLogic().getController().getTankManager().getTank(slot); + } } diff --git a/src/main/java/forestry/farming/gui/FarmLedger.java b/src/main/java/forestry/farming/gui/FarmLedger.java index 2724674d6..c2c56d32c 100644 --- a/src/main/java/forestry/farming/gui/FarmLedger.java +++ b/src/main/java/forestry/farming/gui/FarmLedger.java @@ -1,77 +1,80 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.gui; - -import net.minecraft.init.Items; - -import forestry.core.gui.ledgers.Ledger; -import forestry.core.gui.ledgers.LedgerManager; -import forestry.core.utils.StringUtil; - -public class FarmLedger extends Ledger { - private final IFarmLedgerDelegate delegate; - - public FarmLedger(LedgerManager ledgerManager, IFarmLedgerDelegate delegate) { - super(ledgerManager, "farm"); - this.delegate = delegate; - - int titleHeight = StringUtil.getLineHeight(maxTextWidth, getTooltip()); - this.maxHeight = titleHeight + 110; - } - - @Override - public void draw(int x, int y) { - - // Draw background - drawBackground(x, y); - y += 4; - - int xIcon = x + 3; - int xBody = x + 10; - int xHeader = x + 22; - - // Draw icon - drawIcon(Items.water_bucket.getIconFromDamage(0), xIcon, y); - y += 4; - - if (!isFullyOpened()) { - return; - } - - y += drawHeader(StringUtil.localize("gui.hydration"), xHeader, y); - y += 4; - - y += drawSubheader(StringUtil.localize("gui.hydr.heat") + ':', xBody, y); - y += 3; - y += drawText(StringUtil.floatAsPercent(delegate.getHydrationTempModifier()), xBody, y); - y += 3; - - y += drawSubheader(StringUtil.localize("gui.hydr.humid") + ':', xBody, y); - y += 3; - y += drawText(StringUtil.floatAsPercent(delegate.getHydrationHumidModifier()), xBody, y); - y += 3; - - y += drawSubheader(StringUtil.localize("gui.hydr.rainfall") + ':', xBody, y); - y += 3; - y += drawText(StringUtil.floatAsPercent(delegate.getHydrationRainfallModifier()) + " (" + delegate.getDrought() + " d)", xBody, y); - y += 3; - - y += drawSubheader(StringUtil.localize("gui.hydr.overall") + ':', xBody, y); - y += 3; - drawText(StringUtil.floatAsPercent(delegate.getHydrationModifier()), xBody, y); - } - - @Override - public String getTooltip() { - float hydrationModifier = delegate.getHydrationModifier(); - return StringUtil.floatAsPercent(hydrationModifier) + ' ' + StringUtil.localize("gui.hydration"); - } -} \ No newline at end of file +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.gui; + +import forestry.core.gui.ledgers.Ledger; +import forestry.core.gui.ledgers.LedgerManager; +import forestry.core.utils.StringUtil; +import net.minecraft.init.Items; + +public class FarmLedger extends Ledger { + private final IFarmLedgerDelegate delegate; + + public FarmLedger(LedgerManager ledgerManager, IFarmLedgerDelegate delegate) { + super(ledgerManager, "farm"); + this.delegate = delegate; + + int titleHeight = StringUtil.getLineHeight(maxTextWidth, getTooltip()); + this.maxHeight = titleHeight + 110; + } + + @Override + public void draw(int x, int y) { + + // Draw background + drawBackground(x, y); + y += 4; + + int xIcon = x + 3; + int xBody = x + 10; + int xHeader = x + 22; + + // Draw icon + drawIcon(Items.water_bucket.getIconFromDamage(0), xIcon, y); + y += 4; + + if (!isFullyOpened()) { + return; + } + + y += drawHeader(StringUtil.localize("gui.hydration"), xHeader, y); + y += 4; + + y += drawSubheader(StringUtil.localize("gui.hydr.heat") + ':', xBody, y); + y += 3; + y += drawText(StringUtil.floatAsPercent(delegate.getHydrationTempModifier()), xBody, y); + y += 3; + + y += drawSubheader(StringUtil.localize("gui.hydr.humid") + ':', xBody, y); + y += 3; + y += drawText(StringUtil.floatAsPercent(delegate.getHydrationHumidModifier()), xBody, y); + y += 3; + + y += drawSubheader(StringUtil.localize("gui.hydr.rainfall") + ':', xBody, y); + y += 3; + y += drawText( + StringUtil.floatAsPercent(delegate.getHydrationRainfallModifier()) + " (" + delegate.getDrought() + + " d)", + xBody, + y); + y += 3; + + y += drawSubheader(StringUtil.localize("gui.hydr.overall") + ':', xBody, y); + y += 3; + drawText(StringUtil.floatAsPercent(delegate.getHydrationModifier()), xBody, y); + } + + @Override + public String getTooltip() { + float hydrationModifier = delegate.getHydrationModifier(); + return StringUtil.floatAsPercent(hydrationModifier) + ' ' + StringUtil.localize("gui.hydration"); + } +} diff --git a/src/main/java/forestry/farming/gui/GuiFarm.java b/src/main/java/forestry/farming/gui/GuiFarm.java index 1bf15fe14..3577e0573 100755 --- a/src/main/java/forestry/farming/gui/GuiFarm.java +++ b/src/main/java/forestry/farming/gui/GuiFarm.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.farming.gui; -import net.minecraft.entity.player.EntityPlayer; - import forestry.api.farming.FarmDirection; import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; @@ -21,43 +19,50 @@ import forestry.core.gui.widgets.TankWidget; import forestry.farming.gui.widgets.FarmLogicSlot; import forestry.farming.multiblock.IFarmControllerInternal; import forestry.farming.tiles.TileFarm; +import net.minecraft.entity.player.EntityPlayer; public class GuiFarm extends GuiForestryTitled { - public GuiFarm(EntityPlayer player, TileFarm tile) { - super(Constants.TEXTURE_PATH_GUI + "/mfarm.png", new ContainerFarm(player.inventory, tile), tile); + public GuiFarm(EntityPlayer player, TileFarm tile) { + super(Constants.TEXTURE_PATH_GUI + "/mfarm.png", new ContainerFarm(player.inventory, tile), tile); - widgetManager.add(new TankWidget(widgetManager, 15, 19, 0).setOverlayOrigin(216, 18)); + widgetManager.add(new TankWidget(widgetManager, 15, 19, 0).setOverlayOrigin(216, 18)); - widgetManager.add(new SocketWidget(widgetManager, 69, 40, tile, 0)); + widgetManager.add(new SocketWidget(widgetManager, 69, 40, tile, 0)); - IFarmControllerInternal farmController = inventory.getMultiblockLogic().getController(); + IFarmControllerInternal farmController = inventory.getMultiblockLogic().getController(); - widgetManager.add(new FarmLogicSlot(farmController, widgetManager, 69, 22, FarmDirection.NORTH)); - widgetManager.add(new FarmLogicSlot(farmController, widgetManager, 69, 58, FarmDirection.SOUTH)); - widgetManager.add(new FarmLogicSlot(farmController, widgetManager, 51, 40, FarmDirection.WEST)); - widgetManager.add(new FarmLogicSlot(farmController, widgetManager, 87, 40, FarmDirection.EAST)); + widgetManager.add(new FarmLogicSlot(farmController, widgetManager, 69, 22, FarmDirection.NORTH)); + widgetManager.add(new FarmLogicSlot(farmController, widgetManager, 69, 58, FarmDirection.SOUTH)); + widgetManager.add(new FarmLogicSlot(farmController, widgetManager, 51, 40, FarmDirection.WEST)); + widgetManager.add(new FarmLogicSlot(farmController, widgetManager, 87, 40, FarmDirection.EAST)); - this.xSize = 216; - this.ySize = 220; - } + this.xSize = 216; + this.ySize = 220; + } - @Override - protected void addLedgers() { - IFarmControllerInternal farmController = inventory.getMultiblockLogic().getController(); - ledgerManager.add(new ClimateLedger(ledgerManager, farmController)); - ledgerManager.add(new FarmLedger(ledgerManager, farmController.getFarmLedgerDelegate())); - super.addLedgers(); - } + @Override + protected void addLedgers() { + IFarmControllerInternal farmController = inventory.getMultiblockLogic().getController(); + ledgerManager.add(new ClimateLedger(ledgerManager, farmController)); + ledgerManager.add(new FarmLedger(ledgerManager, farmController.getFarmLedgerDelegate())); + super.addLedgers(); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - // Fuel remaining - int fertilizerRemain = inventory.getMultiblockLogic().getController().getStoredFertilizerScaled(16); - if (fertilizerRemain > 0) { - drawTexturedModalRect(guiLeft + 81, guiTop + 94 + 17 - fertilizerRemain, xSize, 17 - fertilizerRemain, 4, fertilizerRemain); - } - } + // Fuel remaining + int fertilizerRemain = inventory.getMultiblockLogic().getController().getStoredFertilizerScaled(16); + if (fertilizerRemain > 0) { + drawTexturedModalRect( + guiLeft + 81, + guiTop + 94 + 17 - fertilizerRemain, + xSize, + 17 - fertilizerRemain, + 4, + fertilizerRemain); + } + } } diff --git a/src/main/java/forestry/farming/gui/IFarmLedgerDelegate.java b/src/main/java/forestry/farming/gui/IFarmLedgerDelegate.java index 90457025c..c22d960de 100644 --- a/src/main/java/forestry/farming/gui/IFarmLedgerDelegate.java +++ b/src/main/java/forestry/farming/gui/IFarmLedgerDelegate.java @@ -1,23 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.gui; - -public interface IFarmLedgerDelegate { - float getHydrationModifier(); - - float getHydrationTempModifier(); - - float getHydrationHumidModifier(); - - float getHydrationRainfallModifier(); - - double getDrought(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.gui; + +public interface IFarmLedgerDelegate { + float getHydrationModifier(); + + float getHydrationTempModifier(); + + float getHydrationHumidModifier(); + + float getHydrationRainfallModifier(); + + double getDrought(); +} diff --git a/src/main/java/forestry/farming/gui/widgets/FarmLogicSlot.java b/src/main/java/forestry/farming/gui/widgets/FarmLogicSlot.java index d5dd69e8a..72c49044d 100644 --- a/src/main/java/forestry/farming/gui/widgets/FarmLogicSlot.java +++ b/src/main/java/forestry/farming/gui/widgets/FarmLogicSlot.java @@ -1,74 +1,81 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.gui.widgets; - -import net.minecraft.util.IIcon; - -import forestry.api.farming.FarmDirection; -import forestry.api.farming.IFarmLogic; -import forestry.core.gui.tooltips.ToolTip; -import forestry.core.gui.widgets.Widget; -import forestry.core.gui.widgets.WidgetManager; -import forestry.core.proxy.Proxies; -import forestry.farming.multiblock.IFarmControllerInternal; - -public class FarmLogicSlot extends Widget { - - private final IFarmControllerInternal farmController; - private final FarmDirection farmDirection; - - public FarmLogicSlot(IFarmControllerInternal farmController, WidgetManager manager, int xPos, int yPos, FarmDirection farmDirection) { - super(manager, xPos, yPos); - this.farmController = farmController; - this.farmDirection = farmDirection; - } - - private IFarmLogic getLogic() { - return farmController.getFarmLogic(farmDirection); - } - - private IIcon getIconIndex() { - if (getLogic() == null) { - return null; - } - return getLogic().getIcon(); - } - - @Override - public void draw(int startX, int startY) { - if (getIconIndex() != null) { - Proxies.render.bindTexture(getLogic().getSpriteSheet()); - manager.gui.drawTexturedModelRectFromIcon(startX + xPos, startY + yPos, getIconIndex(), 16, 16); - } - } - - @Override - public ToolTip getToolTip(int mouseX, int mouseY) { - if (isMouseOver(mouseX, mouseY)) { - return toolTip; - } else { - return null; - } - } - - protected final ToolTip toolTip = new ToolTip(250) { - @Override - public void refresh() { - toolTip.clear(); - if (getLogic() == null) { - return; - } - toolTip.add(getLogic().getName()); - toolTip.add("Fertilizer: " + getLogic().getFertilizerConsumption()); - toolTip.add("Water: " + getLogic().getWaterConsumption(farmController.getFarmLedgerDelegate().getHydrationModifier())); - } - }; -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.gui.widgets; + +import forestry.api.farming.FarmDirection; +import forestry.api.farming.IFarmLogic; +import forestry.core.gui.tooltips.ToolTip; +import forestry.core.gui.widgets.Widget; +import forestry.core.gui.widgets.WidgetManager; +import forestry.core.proxy.Proxies; +import forestry.farming.multiblock.IFarmControllerInternal; +import net.minecraft.util.IIcon; + +public class FarmLogicSlot extends Widget { + + private final IFarmControllerInternal farmController; + private final FarmDirection farmDirection; + + public FarmLogicSlot( + IFarmControllerInternal farmController, + WidgetManager manager, + int xPos, + int yPos, + FarmDirection farmDirection) { + super(manager, xPos, yPos); + this.farmController = farmController; + this.farmDirection = farmDirection; + } + + private IFarmLogic getLogic() { + return farmController.getFarmLogic(farmDirection); + } + + private IIcon getIconIndex() { + if (getLogic() == null) { + return null; + } + return getLogic().getIcon(); + } + + @Override + public void draw(int startX, int startY) { + if (getIconIndex() != null) { + Proxies.render.bindTexture(getLogic().getSpriteSheet()); + manager.gui.drawTexturedModelRectFromIcon(startX + xPos, startY + yPos, getIconIndex(), 16, 16); + } + } + + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + if (isMouseOver(mouseX, mouseY)) { + return toolTip; + } else { + return null; + } + } + + protected final ToolTip toolTip = new ToolTip(250) { + @Override + public void refresh() { + toolTip.clear(); + if (getLogic() == null) { + return; + } + toolTip.add(getLogic().getName()); + toolTip.add("Fertilizer: " + getLogic().getFertilizerConsumption()); + toolTip.add("Water: " + + getLogic() + .getWaterConsumption( + farmController.getFarmLedgerDelegate().getHydrationModifier())); + } + }; +} diff --git a/src/main/java/forestry/farming/items/ItemBlockFarm.java b/src/main/java/forestry/farming/items/ItemBlockFarm.java index d8c4f8f10..dfbe3670c 100644 --- a/src/main/java/forestry/farming/items/ItemBlockFarm.java +++ b/src/main/java/forestry/farming/items/ItemBlockFarm.java @@ -10,39 +10,38 @@ ******************************************************************************/ package forestry.farming.items; +import forestry.farming.render.EnumFarmBlockTexture; import java.util.List; - import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; -import forestry.farming.render.EnumFarmBlockTexture; - public class ItemBlockFarm extends ItemBlock { - public ItemBlockFarm(Block block) { - super(block); - setHasSubtypes(true); - } + public ItemBlockFarm(Block block) { + super(block); + setHasSubtypes(true); + } - @Override - public int getMetadata(int i) { - return i; - } + @Override + public int getMetadata(int i) { + return i; + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void addInformation(ItemStack itemstack, EntityPlayer player, List info, boolean par4) { - if (!itemstack.hasTagCompound()) { - return; - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void addInformation(ItemStack itemstack, EntityPlayer player, List info, boolean par4) { + if (!itemstack.hasTagCompound()) { + return; + } - info.add(EnumFarmBlockTexture.getFromCompound(itemstack.getTagCompound()).getName()); - } + info.add( + EnumFarmBlockTexture.getFromCompound(itemstack.getTagCompound()).getName()); + } - @Override - public String getUnlocalizedName(ItemStack itemstack) { - return super.getUnlocalizedName(itemstack) + "." + itemstack.getItemDamage(); - } + @Override + public String getUnlocalizedName(ItemStack itemstack) { + return super.getUnlocalizedName(itemstack) + "." + itemstack.getItemDamage(); + } } diff --git a/src/main/java/forestry/farming/logic/Crop.java b/src/main/java/forestry/farming/logic/Crop.java index 235956619..cf27019bd 100755 --- a/src/main/java/forestry/farming/logic/Crop.java +++ b/src/main/java/forestry/farming/logic/Crop.java @@ -10,49 +10,46 @@ ******************************************************************************/ package forestry.farming.logic; +import forestry.api.farming.ICrop; +import forestry.core.config.Constants; +import forestry.core.utils.vect.Vect; import java.util.Collection; - import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import forestry.api.farming.ICrop; -import forestry.core.config.Constants; -import forestry.core.utils.vect.Vect; - public abstract class Crop implements ICrop { - protected final World world; - protected final Vect position; + protected final World world; + protected final Vect position; - protected Crop(World world, Vect position) { - this.world = world; - this.position = position; - } + protected Crop(World world, Vect position) { + this.world = world; + this.position = position; + } - protected final void setBlock(Vect position, Block block, int meta) { - world.setBlock(position.x, position.y, position.z, block, meta, Constants.FLAG_BLOCK_SYNCH); - } + protected final void setBlock(Vect position, Block block, int meta) { + world.setBlock(position.x, position.y, position.z, block, meta, Constants.FLAG_BLOCK_SYNCH); + } - protected final Block getBlock(Vect position) { - return world.getBlock(position.x, position.y, position.z); - } + protected final Block getBlock(Vect position) { + return world.getBlock(position.x, position.y, position.z); + } - protected final int getBlockMeta(Vect position) { - return world.getBlockMetadata(position.x, position.y, position.z); - } + protected final int getBlockMeta(Vect position) { + return world.getBlockMetadata(position.x, position.y, position.z); + } - protected abstract boolean isCrop(Vect pos); + protected abstract boolean isCrop(Vect pos); - protected abstract Collection harvestBlock(Vect pos); + protected abstract Collection harvestBlock(Vect pos); - @Override - public Collection harvest() { - if (!isCrop(position)) { - return null; - } - - return harvestBlock(position); - } + @Override + public Collection harvest() { + if (!isCrop(position)) { + return null; + } + return harvestBlock(position); + } } diff --git a/src/main/java/forestry/farming/logic/CropBasicAgriCraft.java b/src/main/java/forestry/farming/logic/CropBasicAgriCraft.java index b9d6e2e29..153bbccd9 100644 --- a/src/main/java/forestry/farming/logic/CropBasicAgriCraft.java +++ b/src/main/java/forestry/farming/logic/CropBasicAgriCraft.java @@ -10,50 +10,53 @@ ******************************************************************************/ package forestry.farming.logic; +import forestry.core.config.Constants; +import forestry.core.proxy.Proxies; +import forestry.core.utils.vect.Vect; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; - import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import forestry.core.config.Constants; -import forestry.core.proxy.Proxies; -import forestry.core.utils.vect.Vect; - public class CropBasicAgriCraft extends Crop { - private final Block block; - private final int meta; + private final Block block; + private final int meta; - public CropBasicAgriCraft(World world, Block block, int meta, Vect position) { - super(world, position); - this.block = block; - this.meta = meta; - } + public CropBasicAgriCraft(World world, Block block, int meta, Vect position) { + super(world, position); + this.block = block; + this.meta = meta; + } - @Override - protected boolean isCrop(Vect pos) { - return getBlock(pos) == block && getBlockMeta(pos) == meta; - } + @Override + protected boolean isCrop(Vect pos) { + return getBlock(pos) == block && getBlockMeta(pos) == meta; + } - @Override - protected Collection harvestBlock(Vect pos) { - ArrayList harvest = block.getDrops(world, pos.x, pos.y, pos.z, meta, 0); - if (harvest.size() > 1) { - harvest.remove(1); //AgriCraft returns cropsticks in 0, seeds in 1 in getDrops, removing since harvesting doesn't return them. - } - harvest.remove(0); - Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, Blocks.melon_block, 0); - world.setBlockMetadataWithNotify(pos.x, pos.y, pos.z, 0, Constants.FLAG_BLOCK_SYNCH); - harvest.removeAll(Collections.singleton(null)); //sanatize nulls that get thru from Agricraft+Harvestcraft (sesameseed) - return harvest; - } + @Override + protected Collection harvestBlock(Vect pos) { + ArrayList harvest = block.getDrops(world, pos.x, pos.y, pos.z, meta, 0); + if (harvest.size() > 1) { + harvest.remove( + 1); // AgriCraft returns cropsticks in 0, seeds in 1 in getDrops, removing since harvesting doesn't + // return them. + } + harvest.remove(0); + Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, Blocks.melon_block, 0); + world.setBlockMetadataWithNotify(pos.x, pos.y, pos.z, 0, Constants.FLAG_BLOCK_SYNCH); + harvest.removeAll( + Collections.singleton(null)); // sanatize nulls that get thru from Agricraft+Harvestcraft (sesameseed) + return harvest; + } - @Override - public String toString() { - return String.format("CropBasicAgriCraft [ position: [ %s ]; block: %s; meta: %s ]", position.toString(), block.getUnlocalizedName(), meta); - } + @Override + public String toString() { + return String.format( + "CropBasicAgriCraft [ position: [ %s ]; block: %s; meta: %s ]", + position.toString(), block.getUnlocalizedName(), meta); + } } diff --git a/src/main/java/forestry/farming/logic/CropBasicFruit.java b/src/main/java/forestry/farming/logic/CropBasicFruit.java index 893f9410a..ec0b8dbf4 100644 --- a/src/main/java/forestry/farming/logic/CropBasicFruit.java +++ b/src/main/java/forestry/farming/logic/CropBasicFruit.java @@ -10,42 +10,42 @@ ******************************************************************************/ package forestry.farming.logic; +import forestry.core.config.Constants; +import forestry.core.proxy.Proxies; +import forestry.core.utils.vect.Vect; import java.util.Collection; - import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import forestry.core.config.Constants; -import forestry.core.proxy.Proxies; -import forestry.core.utils.vect.Vect; - public class CropBasicFruit extends Crop { - private final Block block; - private final int meta; + private final Block block; + private final int meta; - public CropBasicFruit(World world, Block block, int meta, Vect position) { - super(world, position); - this.block = block; - this.meta = meta; - } + public CropBasicFruit(World world, Block block, int meta, Vect position) { + super(world, position); + this.block = block; + this.meta = meta; + } - @Override - protected boolean isCrop(Vect pos) { - return getBlock(pos) == block && getBlockMeta(pos) == meta; - } + @Override + protected boolean isCrop(Vect pos) { + return getBlock(pos) == block && getBlockMeta(pos) == meta; + } - @Override - protected Collection harvestBlock(Vect pos) { - Collection harvested = block.getDrops(world, pos.x, pos.y, pos.z, meta, 0); - Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, block, 0); - world.setBlock(pos.x, pos.y, pos.z, block, 0, Constants.FLAG_BLOCK_SYNCH); - return harvested; - } + @Override + protected Collection harvestBlock(Vect pos) { + Collection harvested = block.getDrops(world, pos.x, pos.y, pos.z, meta, 0); + Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, block, 0); + world.setBlock(pos.x, pos.y, pos.z, block, 0, Constants.FLAG_BLOCK_SYNCH); + return harvested; + } - @Override - public String toString() { - return String.format("CropBasicFruit [ position: [ %s ]; block: %s; meta: %s ]", position.toString(), block.getUnlocalizedName(), meta); - } + @Override + public String toString() { + return String.format( + "CropBasicFruit [ position: [ %s ]; block: %s; meta: %s ]", + position.toString(), block.getUnlocalizedName(), meta); + } } diff --git a/src/main/java/forestry/farming/logic/CropBasicGrowthCraft.java b/src/main/java/forestry/farming/logic/CropBasicGrowthCraft.java index 0e8813c10..920c7d92d 100644 --- a/src/main/java/forestry/farming/logic/CropBasicGrowthCraft.java +++ b/src/main/java/forestry/farming/logic/CropBasicGrowthCraft.java @@ -10,60 +10,60 @@ ******************************************************************************/ package forestry.farming.logic; +import forestry.core.config.Constants; +import forestry.core.proxy.Proxies; +import forestry.core.utils.vect.Vect; import java.util.ArrayList; import java.util.Collection; - import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import forestry.core.config.Constants; -import forestry.core.proxy.Proxies; -import forestry.core.utils.vect.Vect; - public class CropBasicGrowthCraft extends Crop { - private final Block block; - private final int meta; - private final boolean isRice; - private final boolean isGrape; + private final Block block; + private final int meta; + private final boolean isRice; + private final boolean isGrape; - public CropBasicGrowthCraft(World world, Block block, int meta, Vect position, boolean isRice, boolean isGrape) { - super(world, position); - this.block = block; - this.meta = meta; - this.isRice = isRice; - this.isGrape = isGrape; - } + public CropBasicGrowthCraft(World world, Block block, int meta, Vect position, boolean isRice, boolean isGrape) { + super(world, position); + this.block = block; + this.meta = meta; + this.isRice = isRice; + this.isGrape = isGrape; + } - @Override - protected boolean isCrop(Vect pos) { - return getBlock(pos) == block && getBlockMeta(pos) == meta; - } + @Override + protected boolean isCrop(Vect pos) { + return getBlock(pos) == block && getBlockMeta(pos) == meta; + } - @Override - protected Collection harvestBlock(Vect pos) { - ArrayList harvest = block.getDrops(world, pos.x, pos.y, pos.z, meta, 0); - if (harvest.size() > 1) { - harvest.remove(0); //Hops have rope as first drop. - } - Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, block, 0); - if (isGrape) { - world.setBlockToAir(pos.x, pos.y, pos.z); + @Override + protected Collection harvestBlock(Vect pos) { + ArrayList harvest = block.getDrops(world, pos.x, pos.y, pos.z, meta, 0); + if (harvest.size() > 1) { + harvest.remove(0); // Hops have rope as first drop. + } + Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, block, 0); + if (isGrape) { + world.setBlockToAir(pos.x, pos.y, pos.z); - } else { - world.setBlockMetadataWithNotify(pos.x, pos.y, pos.z, 0, Constants.FLAG_BLOCK_SYNCH); - } + } else { + world.setBlockMetadataWithNotify(pos.x, pos.y, pos.z, 0, Constants.FLAG_BLOCK_SYNCH); + } - if (isRice) { - world.setBlockMetadataWithNotify(pos.x, pos.y - 1, pos.z, 7, Constants.FLAG_BLOCK_SYNCH); - } + if (isRice) { + world.setBlockMetadataWithNotify(pos.x, pos.y - 1, pos.z, 7, Constants.FLAG_BLOCK_SYNCH); + } - return harvest; - } + return harvest; + } - @Override - public String toString() { - return String.format("CropBasicGrowthCraft [ position: [ %s ]; block: %s; meta: %s ]", position.toString(), block.getUnlocalizedName(), meta); - } + @Override + public String toString() { + return String.format( + "CropBasicGrowthCraft [ position: [ %s ]; block: %s; meta: %s ]", + position.toString(), block.getUnlocalizedName(), meta); + } } diff --git a/src/main/java/forestry/farming/logic/CropBasicIC2Crop.java b/src/main/java/forestry/farming/logic/CropBasicIC2Crop.java index ca0d5014e..845432c46 100644 --- a/src/main/java/forestry/farming/logic/CropBasicIC2Crop.java +++ b/src/main/java/forestry/farming/logic/CropBasicIC2Crop.java @@ -2,27 +2,26 @@ package forestry.farming.logic; import forestry.core.utils.vect.Vect; import forestry.plugins.compat.PluginIC2; +import java.util.Collection; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.Collection; - public class CropBasicIC2Crop extends Crop { - private final TileEntity tileEntity; + private final TileEntity tileEntity; - public CropBasicIC2Crop(World world, TileEntity tileEntity, Vect position) { - super(world, position); - this.tileEntity = tileEntity; - } + public CropBasicIC2Crop(World world, TileEntity tileEntity, Vect position) { + super(world, position); + this.tileEntity = tileEntity; + } - @Override - protected boolean isCrop(Vect pos) { - return PluginIC2.instance.canHarvestCrop(this.tileEntity); - } + @Override + protected boolean isCrop(Vect pos) { + return PluginIC2.instance.canHarvestCrop(this.tileEntity); + } - @Override - protected Collection harvestBlock(Vect pos) { - return PluginIC2.instance.getCropDrops(this.tileEntity); - } + @Override + protected Collection harvestBlock(Vect pos) { + return PluginIC2.instance.getCropDrops(this.tileEntity); + } } diff --git a/src/main/java/forestry/farming/logic/CropBlock.java b/src/main/java/forestry/farming/logic/CropBlock.java index 8044744cf..d5d3fdd38 100755 --- a/src/main/java/forestry/farming/logic/CropBlock.java +++ b/src/main/java/forestry/farming/logic/CropBlock.java @@ -10,42 +10,42 @@ ******************************************************************************/ package forestry.farming.logic; +import forestry.core.proxy.Proxies; +import forestry.core.utils.vect.Vect; import java.util.Collection; - import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import forestry.core.proxy.Proxies; -import forestry.core.utils.vect.Vect; - public class CropBlock extends Crop { - protected final Block block; - protected final int meta; + protected final Block block; + protected final int meta; - public CropBlock(World world, Block block, int meta, Vect position) { - super(world, position); - this.block = block; - this.meta = meta; - } + public CropBlock(World world, Block block, int meta, Vect position) { + super(world, position); + this.block = block; + this.meta = meta; + } - @Override - protected boolean isCrop(Vect pos) { - return getBlock(pos) == block && getBlockMeta(pos) == meta; - } + @Override + protected boolean isCrop(Vect pos) { + return getBlock(pos) == block && getBlockMeta(pos) == meta; + } - @Override - protected Collection harvestBlock(Vect pos) { - Collection harvested = block.getDrops(world, pos.x, pos.y, pos.z, meta, 0); - Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, block, 0); - // Block.breakBlock() is called by vanilla itself, removing TEs. - world.setBlockToAir(pos.x, pos.y, pos.z); - return harvested; - } + @Override + protected Collection harvestBlock(Vect pos) { + Collection harvested = block.getDrops(world, pos.x, pos.y, pos.z, meta, 0); + Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, block, 0); + // Block.breakBlock() is called by vanilla itself, removing TEs. + world.setBlockToAir(pos.x, pos.y, pos.z); + return harvested; + } - @Override - public String toString() { - return String.format("CropBlock [ position: [ %s ]; block: %s; meta: %s ]", position.toString(), block.getUnlocalizedName(), meta); - } + @Override + public String toString() { + return String.format( + "CropBlock [ position: [ %s ]; block: %s; meta: %s ]", + position.toString(), block.getUnlocalizedName(), meta); + } } diff --git a/src/main/java/forestry/farming/logic/CropFruit.java b/src/main/java/forestry/farming/logic/CropFruit.java index d878eb7e5..b45ad660a 100755 --- a/src/main/java/forestry/farming/logic/CropFruit.java +++ b/src/main/java/forestry/farming/logic/CropFruit.java @@ -10,51 +10,55 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.ArrayList; -import java.util.Collection; - -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; - import forestry.api.genetics.IFruitBearer; import forestry.core.network.packets.PacketFXSignal; import forestry.core.proxy.Proxies; import forestry.core.utils.vect.Vect; +import java.util.ArrayList; +import java.util.Collection; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; public class CropFruit extends Crop { - public CropFruit(World world, Vect position) { - super(world, position); - } + public CropFruit(World world, Vect position) { + super(world, position); + } - @Override - protected boolean isCrop(Vect pos) { - TileEntity tile = world.getTileEntity(pos.x, pos.y, pos.z); - if (!(tile instanceof IFruitBearer)) { - return false; - } - IFruitBearer bearer = (IFruitBearer) tile; - if (!bearer.hasFruit()) { - return false; - } - if (bearer.getRipeness() < 0.9f) { - return false; - } + @Override + protected boolean isCrop(Vect pos) { + TileEntity tile = world.getTileEntity(pos.x, pos.y, pos.z); + if (!(tile instanceof IFruitBearer)) { + return false; + } + IFruitBearer bearer = (IFruitBearer) tile; + if (!bearer.hasFruit()) { + return false; + } + if (bearer.getRipeness() < 0.9f) { + return false; + } - return true; - } + return true; + } - @Override - protected Collection harvestBlock(Vect pos) { - TileEntity tile = world.getTileEntity(pos.x, pos.y, pos.z); - if (!(tile instanceof IFruitBearer)) { - return new ArrayList<>(); - } - - Proxies.common.sendFXSignal(PacketFXSignal.VisualFXType.BLOCK_DESTROY, PacketFXSignal.SoundFXType.LEAF, world, pos.x, pos.y, pos.z, - world.getBlock(pos.x, pos.y, pos.z), 0); - return ((IFruitBearer) tile).pickFruit(null); - } + @Override + protected Collection harvestBlock(Vect pos) { + TileEntity tile = world.getTileEntity(pos.x, pos.y, pos.z); + if (!(tile instanceof IFruitBearer)) { + return new ArrayList<>(); + } + Proxies.common.sendFXSignal( + PacketFXSignal.VisualFXType.BLOCK_DESTROY, + PacketFXSignal.SoundFXType.LEAF, + world, + pos.x, + pos.y, + pos.z, + world.getBlock(pos.x, pos.y, pos.z), + 0); + return ((IFruitBearer) tile).pickFruit(null); + } } diff --git a/src/main/java/forestry/farming/logic/CropPeat.java b/src/main/java/forestry/farming/logic/CropPeat.java index e59341e4a..e9b13640c 100755 --- a/src/main/java/forestry/farming/logic/CropPeat.java +++ b/src/main/java/forestry/farming/logic/CropPeat.java @@ -10,46 +10,43 @@ ******************************************************************************/ package forestry.farming.logic; +import forestry.core.blocks.BlockSoil; +import forestry.core.proxy.Proxies; +import forestry.core.utils.vect.Vect; +import forestry.plugins.PluginCore; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import forestry.core.blocks.BlockSoil; -import forestry.core.proxy.Proxies; -import forestry.core.utils.vect.Vect; -import forestry.plugins.PluginCore; - public class CropPeat extends Crop { - public CropPeat(World world, Vect position) { - super(world, position); - } + public CropPeat(World world, Vect position) { + super(world, position); + } - @Override - protected boolean isCrop(Vect pos) { - Block block = getBlock(pos); - if (!(block instanceof BlockSoil)) { - return false; - } + @Override + protected boolean isCrop(Vect pos) { + Block block = getBlock(pos); + if (!(block instanceof BlockSoil)) { + return false; + } - BlockSoil blockSoil = (BlockSoil) block; - BlockSoil.SoilType soilType = blockSoil.getTypeFromMeta(getBlockMeta(pos)); - return soilType == BlockSoil.SoilType.PEAT; - } + BlockSoil blockSoil = (BlockSoil) block; + BlockSoil.SoilType soilType = blockSoil.getTypeFromMeta(getBlockMeta(pos)); + return soilType == BlockSoil.SoilType.PEAT; + } - @Override - protected Collection harvestBlock(Vect pos) { - List drops = new ArrayList<>(); - drops.add(PluginCore.items.peat.getItemStack()); - - Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, world.getBlock(pos.x, pos.y, pos.z), 0); - setBlock(pos, Blocks.dirt, 0); - return drops; - } + @Override + protected Collection harvestBlock(Vect pos) { + List drops = new ArrayList<>(); + drops.add(PluginCore.items.peat.getItemStack()); + Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, world.getBlock(pos.x, pos.y, pos.z), 0); + setBlock(pos, Blocks.dirt, 0); + return drops; + } } diff --git a/src/main/java/forestry/farming/logic/CropRubber.java b/src/main/java/forestry/farming/logic/CropRubber.java index 6565da333..3b7ea327e 100755 --- a/src/main/java/forestry/farming/logic/CropRubber.java +++ b/src/main/java/forestry/farming/logic/CropRubber.java @@ -10,31 +10,28 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.ArrayList; -import java.util.Collection; - -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import forestry.core.config.Constants; import forestry.core.proxy.Proxies; import forestry.core.utils.vect.Vect; import forestry.plugins.compat.PluginIC2; +import java.util.ArrayList; +import java.util.Collection; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; public class CropRubber extends CropBlock { - public CropRubber(World world, Block block, int meta, Vect position) { - super(world, block, meta, position); - } - - @Override - protected Collection harvestBlock(Vect pos) { - Collection harvested = new ArrayList<>(); - harvested.add(PluginIC2.resin.copy()); - Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, block, 0); - world.setBlock(pos.x, pos.y, pos.z, block, meta + 6, Constants.FLAG_BLOCK_SYNCH); - return harvested; - } + public CropRubber(World world, Block block, int meta, Vect position) { + super(world, block, meta, position); + } + @Override + protected Collection harvestBlock(Vect pos) { + Collection harvested = new ArrayList<>(); + harvested.add(PluginIC2.resin.copy()); + Proxies.common.addBlockDestroyEffects(world, pos.x, pos.y, pos.z, block, 0); + world.setBlock(pos.x, pos.y, pos.z, block, meta + 6, Constants.FLAG_BLOCK_SYNCH); + return harvested; + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogic.java b/src/main/java/forestry/farming/logic/FarmLogic.java index f62ae0a9d..7825dcd3b 100755 --- a/src/main/java/forestry/farming/logic/FarmLogic.java +++ b/src/main/java/forestry/farming/logic/FarmLogic.java @@ -10,9 +10,16 @@ ******************************************************************************/ package forestry.farming.logic; +import forestry.api.farming.FarmDirection; +import forestry.api.farming.IFarmHousing; +import forestry.api.farming.IFarmLogic; +import forestry.core.config.Constants; +import forestry.core.entities.EntitySelector; +import forestry.core.render.SpriteSheet; +import forestry.core.utils.EntityUtil; +import forestry.core.utils.vect.Vect; import java.util.ArrayList; import java.util.List; - import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.item.EntityItem; @@ -22,102 +29,94 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; -import forestry.api.farming.FarmDirection; -import forestry.api.farming.IFarmHousing; -import forestry.api.farming.IFarmLogic; -import forestry.core.config.Constants; -import forestry.core.entities.EntitySelector; -import forestry.core.render.SpriteSheet; -import forestry.core.utils.EntityUtil; -import forestry.core.utils.vect.Vect; - public abstract class FarmLogic implements IFarmLogic { - private final EntitySelectorFarm entitySelectorFarm = new EntitySelectorFarm(this); - protected final IFarmHousing housing; - protected boolean isManual; + private final EntitySelectorFarm entitySelectorFarm = new EntitySelectorFarm(this); + protected final IFarmHousing housing; + protected boolean isManual; - protected FarmLogic(IFarmHousing housing) { - this.housing = housing; - } + protected FarmLogic(IFarmHousing housing) { + this.housing = housing; + } - public FarmLogic setManual(boolean flag) { - isManual = flag; - return this; - } + public FarmLogic setManual(boolean flag) { + isManual = flag; + return this; + } - protected World getWorld() { - return housing.getWorld(); - } + protected World getWorld() { + return housing.getWorld(); + } - @Override - public ResourceLocation getSpriteSheet() { - return SpriteSheet.ITEMS.getLocation(); - } + @Override + public ResourceLocation getSpriteSheet() { + return SpriteSheet.ITEMS.getLocation(); + } - public abstract boolean isAcceptedWindfall(ItemStack stack); + public abstract boolean isAcceptedWindfall(ItemStack stack); - protected final boolean isAirBlock(Block block) { - return block.getMaterial() == Material.air; - } + protected final boolean isAirBlock(Block block) { + return block.getMaterial() == Material.air; + } - protected final boolean isWaterSourceBlock(World world, Vect position) { - return world.getBlock(position.x, position.y, position.z) == Blocks.water && - world.getBlockMetadata(position.x, position.y, position.z) == 0; - } + protected final boolean isWaterSourceBlock(World world, Vect position) { + return world.getBlock(position.x, position.y, position.z) == Blocks.water + && world.getBlockMetadata(position.x, position.y, position.z) == 0; + } - protected final Vect translateWithOffset(int x, int y, int z, FarmDirection farmDirection, int step) { - return new Vect(farmDirection.getForgeDirection()).multiply(step).add(x, y, z); - } + protected final Vect translateWithOffset(int x, int y, int z, FarmDirection farmDirection, int step) { + return new Vect(farmDirection.getForgeDirection()).multiply(step).add(x, y, z); + } - protected final void setBlock(Vect position, Block block, int meta) { - getWorld().setBlock(position.x, position.y, position.z, block, meta, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); - } + protected final void setBlock(Vect position, Block block, int meta) { + getWorld().setBlock(position.x, position.y, position.z, block, meta, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); + } - private AxisAlignedBB getHarvestBox(IFarmHousing farmHousing, boolean toWorldHeight) { - Vect coords = new Vect(farmHousing.getCoords()); - Vect area = new Vect(farmHousing.getArea()); - Vect offset = new Vect(farmHousing.getOffset()); + private AxisAlignedBB getHarvestBox(IFarmHousing farmHousing, boolean toWorldHeight) { + Vect coords = new Vect(farmHousing.getCoords()); + Vect area = new Vect(farmHousing.getArea()); + Vect offset = new Vect(farmHousing.getOffset()); - Vect min = coords.add(offset); - Vect max = min.add(area); + Vect min = coords.add(offset); + Vect max = min.add(area); - int maxY = max.y; - if (toWorldHeight) { - maxY = getWorld().getHeight(); - } + int maxY = max.y; + if (toWorldHeight) { + maxY = getWorld().getHeight(); + } - return AxisAlignedBB.getBoundingBox(min.x, min.y, min.z, max.x, maxY, max.z); - } + return AxisAlignedBB.getBoundingBox(min.x, min.y, min.z, max.x, maxY, max.z); + } - protected List collectEntityItems(boolean toWorldHeight) { - AxisAlignedBB harvestBox = getHarvestBox(housing, toWorldHeight); + protected List collectEntityItems(boolean toWorldHeight) { + AxisAlignedBB harvestBox = getHarvestBox(housing, toWorldHeight); - List entityItems = EntityUtil.selectEntitiesWithinAABB(housing.getWorld(), entitySelectorFarm, harvestBox); - List stacks = new ArrayList<>(); - for (EntityItem entity : entityItems) { - ItemStack contained = entity.getEntityItem(); - stacks.add(contained.copy()); - entity.setDead(); - } - return stacks; - } + List entityItems = + EntityUtil.selectEntitiesWithinAABB(housing.getWorld(), entitySelectorFarm, harvestBox); + List stacks = new ArrayList<>(); + for (EntityItem entity : entityItems) { + ItemStack contained = entity.getEntityItem(); + stacks.add(contained.copy()); + entity.setDead(); + } + return stacks; + } - private static class EntitySelectorFarm extends EntitySelector { - private final FarmLogic farmLogic; + private static class EntitySelectorFarm extends EntitySelector { + private final FarmLogic farmLogic; - public EntitySelectorFarm(FarmLogic farmLogic) { - super(EntityItem.class); - this.farmLogic = farmLogic; - } + public EntitySelectorFarm(FarmLogic farmLogic) { + super(EntityItem.class); + this.farmLogic = farmLogic; + } - @Override - protected boolean isEntityApplicableTyped(EntityItem entity) { - if (entity.isDead) { - return false; - } + @Override + protected boolean isEntityApplicableTyped(EntityItem entity) { + if (entity.isDead) { + return false; + } - ItemStack contained = entity.getEntityItem(); - return farmLogic.isAcceptedGermling(contained) || farmLogic.isAcceptedWindfall(contained); - } - } + ItemStack contained = entity.getEntityItem(); + return farmLogic.isAcceptedGermling(contained) || farmLogic.isAcceptedWindfall(contained); + } + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicArboreal.java b/src/main/java/forestry/farming/logic/FarmLogicArboreal.java index dd17571b9..767350fef 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicArboreal.java +++ b/src/main/java/forestry/farming/logic/FarmLogicArboreal.java @@ -10,24 +10,8 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; -import java.util.Stack; - -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.util.ResourceLocation; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.farming.FarmDirection; import forestry.api.farming.Farmables; import forestry.api.farming.ICrop; @@ -38,195 +22,213 @@ import forestry.core.render.SpriteSheet; import forestry.core.utils.vect.Vect; import forestry.core.utils.vect.VectUtil; import forestry.plugins.PluginCore; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; +import java.util.Stack; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.World; public class FarmLogicArboreal extends FarmLogicHomogeneous { - private static final int BRANCH_RANGE = 20; + private static final int BRANCH_RANGE = 20; - public FarmLogicArboreal(IFarmHousing housing, ItemStack resource, ItemStack ground, Iterable germlings) { - super(housing, resource, ground, germlings); - } + public FarmLogicArboreal( + IFarmHousing housing, ItemStack resource, ItemStack ground, Iterable germlings) { + super(housing, resource, ground, germlings); + } - public FarmLogicArboreal(IFarmHousing housing) { - super(housing, new ItemStack(Blocks.dirt), PluginCore.blocks.soil.get(BlockSoil.SoilType.HUMUS, 1), Farmables.farmables.get(FarmableReference.Arboreal.get())); - } + public FarmLogicArboreal(IFarmHousing housing) { + super( + housing, + new ItemStack(Blocks.dirt), + PluginCore.blocks.soil.get(BlockSoil.SoilType.HUMUS, 1), + Farmables.farmables.get(FarmableReference.Arboreal.get())); + } - @Override - public boolean isAcceptedSoil(ItemStack soil) { - if (super.isAcceptedSoil(soil)) { - return true; - } + @Override + public boolean isAcceptedSoil(ItemStack soil) { + if (super.isAcceptedSoil(soil)) { + return true; + } - Block block = BlockSoil.getBlockFromItem(soil.getItem()); - if (!(block instanceof BlockSoil)) { - return false; - } - BlockSoil blockSoil = (BlockSoil) block; - return blockSoil.getTypeFromMeta(soil.getItemDamage()) == BlockSoil.SoilType.HUMUS; - } + Block block = BlockSoil.getBlockFromItem(soil.getItem()); + if (!(block instanceof BlockSoil)) { + return false; + } + BlockSoil blockSoil = (BlockSoil) block; + return blockSoil.getTypeFromMeta(soil.getItemDamage()) == BlockSoil.SoilType.HUMUS; + } - @Override - public String getName() { - return "Managed Arboretum"; - } + @Override + public String getName() { + return "Managed Arboretum"; + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return Blocks.sapling.getBlockTextureFromSide(0); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return Blocks.sapling.getBlockTextureFromSide(0); + } - @Override - public ResourceLocation getSpriteSheet() { - return SpriteSheet.BLOCKS.getLocation(); - } + @Override + public ResourceLocation getSpriteSheet() { + return SpriteSheet.BLOCKS.getLocation(); + } - @Override - public int getFertilizerConsumption() { - return 10; - } + @Override + public int getFertilizerConsumption() { + return 10; + } - @Override - public int getWaterConsumption(float hydrationModifier) { - return (int) (10 * hydrationModifier); - } + @Override + public int getWaterConsumption(float hydrationModifier) { + return (int) (10 * hydrationModifier); + } - @Override - public Collection collect() { - Collection products = produce; - produce = collectEntityItems(true); - return products; - } + @Override + public Collection collect() { + Collection products = produce; + produce = collectEntityItems(true); + return products; + } - private final HashMap lastExtentsHarvest = new HashMap<>(); + private final HashMap lastExtentsHarvest = new HashMap<>(); - @Override - public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { + @Override + public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { - Vect start = new Vect(x, y, z); - if (!lastExtentsHarvest.containsKey(start)) { - lastExtentsHarvest.put(start, 0); - } + Vect start = new Vect(x, y, z); + if (!lastExtentsHarvest.containsKey(start)) { + lastExtentsHarvest.put(start, 0); + } - int lastExtent = lastExtentsHarvest.get(start); - if (lastExtent > extent) { - lastExtent = 0; - } + int lastExtent = lastExtentsHarvest.get(start); + if (lastExtent > extent) { + lastExtent = 0; + } - Vect position = translateWithOffset(x, y + 1, z, direction, lastExtent); - Collection crops = getHarvestBlocks(position); - lastExtent++; - lastExtentsHarvest.put(start, lastExtent); + Vect position = translateWithOffset(x, y + 1, z, direction, lastExtent); + Collection crops = getHarvestBlocks(position); + lastExtent++; + lastExtentsHarvest.put(start, lastExtent); - return crops; - } + return crops; + } - private Collection getHarvestBlocks(Vect position) { + private Collection getHarvestBlocks(Vect position) { - World world = getWorld(); + World world = getWorld(); - Set seen = new HashSet<>(); - Stack crops = new Stack<>(); + Set seen = new HashSet<>(); + Stack crops = new Stack<>(); - // Determine what type we want to harvest. - IFarmable germling = null; - for (IFarmable germl : germlings) { - ICrop crop = germl.getCropAt(world, position.x, position.y, position.z); - if (crop == null) { - continue; - } + // Determine what type we want to harvest. + IFarmable germling = null; + for (IFarmable germl : germlings) { + ICrop crop = germl.getCropAt(world, position.x, position.y, position.z); + if (crop == null) { + continue; + } - crops.push(crop); - seen.add(position); - germling = germl; - break; - } + crops.push(crop); + seen.add(position); + germling = germl; + break; + } - if (germling == null) { - return crops; - } + if (germling == null) { + return crops; + } - ArrayList candidates = processHarvestBlock(germling, crops, seen, position, position); - ArrayList temp = new ArrayList<>(); - while (!candidates.isEmpty()) { - for (Vect candidate : candidates) { - temp.addAll(processHarvestBlock(germling, crops, seen, position, candidate)); - } - candidates.clear(); - candidates.addAll(temp); - temp.clear(); - } + ArrayList candidates = processHarvestBlock(germling, crops, seen, position, position); + ArrayList temp = new ArrayList<>(); + while (!candidates.isEmpty()) { + for (Vect candidate : candidates) { + temp.addAll(processHarvestBlock(germling, crops, seen, position, candidate)); + } + candidates.clear(); + candidates.addAll(temp); + temp.clear(); + } - return crops; - } + return crops; + } - private ArrayList processHarvestBlock(IFarmable germling, Stack crops, Set seen, Vect start, Vect position) { + private ArrayList processHarvestBlock( + IFarmable germling, Stack crops, Set seen, Vect start, Vect position) { - World world = getWorld(); + World world = getWorld(); - ArrayList candidates = new ArrayList<>(); + ArrayList candidates = new ArrayList<>(); - // Get additional candidates to return - for (int x = -1; x < 2; x++) { - for (int y = -1; y < 2; y++) { - for (int z = -1; z < 2; z++) { - Vect candidate = position.add(x, y, z); - if (candidate.equals(position)) { - continue; - } - if (Math.abs(candidate.x - start.x) > BRANCH_RANGE) { - continue; - } - if (Math.abs(candidate.z - start.z) > BRANCH_RANGE) { - continue; - } + // Get additional candidates to return + for (int x = -1; x < 2; x++) { + for (int y = -1; y < 2; y++) { + for (int z = -1; z < 2; z++) { + Vect candidate = position.add(x, y, z); + if (candidate.equals(position)) { + continue; + } + if (Math.abs(candidate.x - start.x) > BRANCH_RANGE) { + continue; + } + if (Math.abs(candidate.z - start.z) > BRANCH_RANGE) { + continue; + } - // See whether the given position has already been processed - if (seen.contains(candidate)) { - continue; - } + // See whether the given position has already been processed + if (seen.contains(candidate)) { + continue; + } - ICrop crop = germling.getCropAt(world, candidate.x, candidate.y, candidate.z); - if (crop != null) { - crops.push(crop); - candidates.add(candidate); - seen.add(candidate); - } - } - } - } + ICrop crop = germling.getCropAt(world, candidate.x, candidate.y, candidate.z); + if (crop != null) { + crops.push(crop); + candidates.add(candidate); + seen.add(candidate); + } + } + } + } - return candidates; - } + return candidates; + } - @Override - protected boolean maintainGermlings(int x, int ySaplings, int z, FarmDirection direction, int extent) { + @Override + protected boolean maintainGermlings(int x, int ySaplings, int z, FarmDirection direction, int extent) { - World world = getWorld(); + World world = getWorld(); - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, ySaplings, z, direction, i); + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, ySaplings, z, direction, i); - if (VectUtil.isAirBlock(world, position)) { - Vect soilBelowPosition = new Vect(position.x, position.y - 1, position.z); - ItemStack soilBelow = VectUtil.getAsItemStack(world, soilBelowPosition); - if (isAcceptedSoil(soilBelow)) { - return plantSapling(position); - } - } - } - return false; - } + if (VectUtil.isAirBlock(world, position)) { + Vect soilBelowPosition = new Vect(position.x, position.y - 1, position.z); + ItemStack soilBelow = VectUtil.getAsItemStack(world, soilBelowPosition); + if (isAcceptedSoil(soilBelow)) { + return plantSapling(position); + } + } + } + return false; + } - private boolean plantSapling(Vect position) { - World world = getWorld(); - Collections.shuffle(germlings); - for (IFarmable candidate : germlings) { - if (housing.plantGermling(candidate, world, position.x, position.y, position.z)) { - return true; - } - } - - return false; - } + private boolean plantSapling(Vect position) { + World world = getWorld(); + Collections.shuffle(germlings); + for (IFarmable candidate : germlings) { + if (housing.plantGermling(candidate, world, position.x, position.y, position.z)) { + return true; + } + } + return false; + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicCereal.java b/src/main/java/forestry/farming/logic/FarmLogicCereal.java index 3a361f48e..038ffe9fe 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicCereal.java +++ b/src/main/java/forestry/farming/logic/FarmLogicCereal.java @@ -10,34 +10,31 @@ ******************************************************************************/ package forestry.farming.logic; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.farming.Farmables; +import forestry.api.farming.IFarmHousing; import net.minecraft.init.Items; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.farming.Farmables; -import forestry.api.farming.IFarmHousing; - public class FarmLogicCereal extends FarmLogicCrops { - public FarmLogicCereal(IFarmHousing housing) { - super(housing, Farmables.farmables.get(FarmableReference.Wheat.get())); - } + public FarmLogicCereal(IFarmHousing housing) { + super(housing, Farmables.farmables.get(FarmableReference.Wheat.get())); + } - @Override - public String getName() { - if (isManual) { - return "Manual Farm"; - } else { - return "Managed Farm"; - } - } - - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return Items.wheat.getIconFromDamage(0); - } + @Override + public String getName() { + if (isManual) { + return "Manual Farm"; + } else { + return "Managed Farm"; + } + } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return Items.wheat.getIconFromDamage(0); + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicCocoa.java b/src/main/java/forestry/farming/logic/FarmLogicCocoa.java index 7e3ac8f99..8ffe2100b 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicCocoa.java +++ b/src/main/java/forestry/farming/logic/FarmLogicCocoa.java @@ -10,25 +10,8 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; -import java.util.Stack; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockLog; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.farming.FarmDirection; import forestry.api.farming.ICrop; import forestry.api.farming.IFarmHousing; @@ -36,205 +19,219 @@ import forestry.api.farming.IFarmable; import forestry.core.utils.vect.MutableVect; import forestry.core.utils.vect.Vect; import forestry.core.utils.vect.VectUtil; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; +import java.util.Stack; +import net.minecraft.block.Block; +import net.minecraft.block.BlockLog; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; public class FarmLogicCocoa extends FarmLogic { - private final IFarmable cocoa = new FarmableCocoa(); + private final IFarmable cocoa = new FarmableCocoa(); - public FarmLogicCocoa(IFarmHousing housing) { - super(housing); - } + public FarmLogicCocoa(IFarmHousing housing) { + super(housing); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return Items.dye.getIconFromDamage(3); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return Items.dye.getIconFromDamage(3); + } - @Override - public String getName() { - return "Cocoa Plantation"; - } + @Override + public String getName() { + return "Cocoa Plantation"; + } - @Override - public int getFertilizerConsumption() { - return 120; - } + @Override + public int getFertilizerConsumption() { + return 120; + } - @Override - public int getWaterConsumption(float hydrationModifier) { - return (int) (20 * hydrationModifier); - } + @Override + public int getWaterConsumption(float hydrationModifier) { + return (int) (20 * hydrationModifier); + } - @Override - public boolean isAcceptedResource(ItemStack itemstack) { - return false; - } + @Override + public boolean isAcceptedResource(ItemStack itemstack) { + return false; + } - @Override - public boolean isAcceptedGermling(ItemStack itemstack) { - return cocoa.isGermling(itemstack); - } + @Override + public boolean isAcceptedGermling(ItemStack itemstack) { + return cocoa.isGermling(itemstack); + } - @Override - public boolean isAcceptedWindfall(ItemStack stack) { - return false; - } + @Override + public boolean isAcceptedWindfall(ItemStack stack) { + return false; + } - @Override - public Collection collect() { - return null; - } + @Override + public Collection collect() { + return null; + } - private final HashMap lastExtentsCultivation = new HashMap<>(); + private final HashMap lastExtentsCultivation = new HashMap<>(); - @Override - public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { + @Override + public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { - Vect start = new Vect(x, y, z); - if (!lastExtentsCultivation.containsKey(start)) { - lastExtentsCultivation.put(start, 0); - } + Vect start = new Vect(x, y, z); + if (!lastExtentsCultivation.containsKey(start)) { + lastExtentsCultivation.put(start, 0); + } - int lastExtent = lastExtentsCultivation.get(start); - if (lastExtent > extent) { - lastExtent = 0; - } + int lastExtent = lastExtentsCultivation.get(start); + if (lastExtent > extent) { + lastExtent = 0; + } - Vect position = translateWithOffset(x, y + 1, z, direction, lastExtent); - boolean result = tryPlantingCocoa(position); + Vect position = translateWithOffset(x, y + 1, z, direction, lastExtent); + boolean result = tryPlantingCocoa(position); - lastExtent++; - lastExtentsCultivation.put(start, lastExtent); + lastExtent++; + lastExtentsCultivation.put(start, lastExtent); - return result; - } + return result; + } - private final HashMap lastExtentsHarvest = new HashMap<>(); + private final HashMap lastExtentsHarvest = new HashMap<>(); - @Override - public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { + @Override + public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { - Vect start = new Vect(x, y, z); - if (!lastExtentsHarvest.containsKey(start)) { - lastExtentsHarvest.put(start, 0); - } + Vect start = new Vect(x, y, z); + if (!lastExtentsHarvest.containsKey(start)) { + lastExtentsHarvest.put(start, 0); + } - int lastExtent = lastExtentsHarvest.get(start); - if (lastExtent > extent) { - lastExtent = 0; - } + int lastExtent = lastExtentsHarvest.get(start); + if (lastExtent > extent) { + lastExtent = 0; + } - Vect position = translateWithOffset(x, y + 1, z, direction, lastExtent); - Collection crops = getHarvestBlocks(position); - lastExtent++; - lastExtentsHarvest.put(start, lastExtent); + Vect position = translateWithOffset(x, y + 1, z, direction, lastExtent); + Collection crops = getHarvestBlocks(position); + lastExtent++; + lastExtentsHarvest.put(start, lastExtent); - return crops; - } + return crops; + } - private boolean tryPlantingCocoa(Vect position) { + private boolean tryPlantingCocoa(Vect position) { - World world = getWorld(); + World world = getWorld(); - MutableVect current = new MutableVect(position); - while (VectUtil.isWoodBlock(world, current) && BlockLog.func_150165_c(VectUtil.getBlockMeta(world, current)) == 3) { + MutableVect current = new MutableVect(position); + while (VectUtil.isWoodBlock(world, current) + && BlockLog.func_150165_c(VectUtil.getBlockMeta(world, current)) == 3) { - for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) { - if (direction == ForgeDirection.UP || direction == ForgeDirection.DOWN) { - continue; - } + for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) { + if (direction == ForgeDirection.UP || direction == ForgeDirection.DOWN) { + continue; + } - Vect candidate = new Vect(current.x + direction.offsetX, current.y, current.z + direction.offsetZ); - if (VectUtil.isAirBlock(world, candidate)) { - return housing.plantGermling(cocoa, world, candidate.x, candidate.y, candidate.z); - } - } + Vect candidate = new Vect(current.x + direction.offsetX, current.y, current.z + direction.offsetZ); + if (VectUtil.isAirBlock(world, candidate)) { + return housing.plantGermling(cocoa, world, candidate.x, candidate.y, candidate.z); + } + } - current.y++; - if (current.y - position.y > 1) { - break; - } - } + current.y++; + if (current.y - position.y > 1) { + break; + } + } - return false; - } + return false; + } - private Collection getHarvestBlocks(Vect position) { + private Collection getHarvestBlocks(Vect position) { - Set seen = new HashSet<>(); - Stack crops = new Stack<>(); + Set seen = new HashSet<>(); + Stack crops = new Stack<>(); - // Determine what type we want to harvest. - Block block = VectUtil.getBlock(getWorld(), position); + // Determine what type we want to harvest. + Block block = VectUtil.getBlock(getWorld(), position); - ICrop crop = null; - if (!block.isWood(getWorld(), position.x, position.y, position.z)) { - crop = cocoa.getCropAt(getWorld(), position.x, position.y, position.z); - if (crop == null) { - return crops; - } - } + ICrop crop = null; + if (!block.isWood(getWorld(), position.x, position.y, position.z)) { + crop = cocoa.getCropAt(getWorld(), position.x, position.y, position.z); + if (crop == null) { + return crops; + } + } - if (crop != null) { - crops.add(crop); - } + if (crop != null) { + crops.add(crop); + } - ArrayList candidates = processHarvestBlock(crops, seen, position, position); - ArrayList temp = new ArrayList<>(); - while (!candidates.isEmpty() && crops.size() < 20) { - for (Vect candidate : candidates) { - temp.addAll(processHarvestBlock(crops, seen, position, candidate)); - } - candidates.clear(); - candidates.addAll(temp); - temp.clear(); - } - // Log.finest("Logic %s at %s/%s/%s has seen %s blocks.", getClass().getName(), position.x, position.y, position.z, seen.size()); + ArrayList candidates = processHarvestBlock(crops, seen, position, position); + ArrayList temp = new ArrayList<>(); + while (!candidates.isEmpty() && crops.size() < 20) { + for (Vect candidate : candidates) { + temp.addAll(processHarvestBlock(crops, seen, position, candidate)); + } + candidates.clear(); + candidates.addAll(temp); + temp.clear(); + } + // Log.finest("Logic %s at %s/%s/%s has seen %s blocks.", getClass().getName(), position.x, position.y, + // position.z, seen.size()); - return crops; - } + return crops; + } - private ArrayList processHarvestBlock(Stack crops, Set seen, Vect start, Vect position) { + private ArrayList processHarvestBlock(Stack crops, Set seen, Vect start, Vect position) { - World world = getWorld(); + World world = getWorld(); - ArrayList candidates = new ArrayList<>(); + ArrayList candidates = new ArrayList<>(); - // Get additional candidates to return - for (int i = -1; i < 2; i++) { - for (int j = 0; j < 2; j++) { - for (int k = -1; k < 2; k++) { - Vect candidate = position.add(i, j, k); - if (candidate.equals(position)) { - continue; - } - if (Math.abs(candidate.x - start.x) > 5) { - continue; - } - if (Math.abs(candidate.z - start.z) > 5) { - continue; - } + // Get additional candidates to return + for (int i = -1; i < 2; i++) { + for (int j = 0; j < 2; j++) { + for (int k = -1; k < 2; k++) { + Vect candidate = position.add(i, j, k); + if (candidate.equals(position)) { + continue; + } + if (Math.abs(candidate.x - start.x) > 5) { + continue; + } + if (Math.abs(candidate.z - start.z) > 5) { + continue; + } - // See whether the given position has already been processed - if (seen.contains(candidate)) { - continue; - } + // See whether the given position has already been processed + if (seen.contains(candidate)) { + continue; + } - ICrop crop = cocoa.getCropAt(world, candidate.x, candidate.y, candidate.z); - if (crop != null) { - crops.push(crop); - candidates.add(candidate); - seen.add(candidate); - } else if (VectUtil.isWoodBlock(world, candidate)) { - candidates.add(candidate); - seen.add(candidate); - } - } - } - } - - return candidates; - } + ICrop crop = cocoa.getCropAt(world, candidate.x, candidate.y, candidate.z); + if (crop != null) { + crops.push(crop); + candidates.add(candidate); + seen.add(candidate); + } else if (VectUtil.isWoodBlock(world, candidate)) { + candidates.add(candidate); + seen.add(candidate); + } + } + } + } + return candidates; + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicCrops.java b/src/main/java/forestry/farming/logic/FarmLogicCrops.java index b7f709095..b6fbbeeff 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicCrops.java +++ b/src/main/java/forestry/farming/logic/FarmLogicCrops.java @@ -10,15 +10,6 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.Collection; -import java.util.Stack; - -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -import net.minecraftforge.oredict.OreDictionary; - import forestry.api.farming.FarmDirection; import forestry.api.farming.ICrop; import forestry.api.farming.IFarmHousing; @@ -28,101 +19,107 @@ import forestry.core.utils.ItemStackUtil; import forestry.core.utils.vect.IVect; import forestry.core.utils.vect.Vect; import forestry.core.utils.vect.VectUtil; +import java.util.Collection; +import java.util.Stack; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraftforge.oredict.OreDictionary; public abstract class FarmLogicCrops extends FarmLogicWatered { - private static final ItemStack farmland = new ItemStack(Blocks.farmland, 1, OreDictionary.WILDCARD_VALUE); - private final Iterable seeds; + private static final ItemStack farmland = new ItemStack(Blocks.farmland, 1, OreDictionary.WILDCARD_VALUE); + private final Iterable seeds; - protected FarmLogicCrops(IFarmHousing housing, Iterable seeds) { - super(housing, new ItemStack(Blocks.dirt), new ItemStack(Blocks.farmland)); + protected FarmLogicCrops(IFarmHousing housing, Iterable seeds) { + super(housing, new ItemStack(Blocks.dirt), new ItemStack(Blocks.farmland)); - this.seeds = seeds; - } + this.seeds = seeds; + } - @Override - public boolean isAcceptedGround(ItemStack itemStack) { - return super.isAcceptedGround(itemStack) || ItemStackUtil.isIdenticalItem(farmland, itemStack); - } + @Override + public boolean isAcceptedGround(ItemStack itemStack) { + return super.isAcceptedGround(itemStack) || ItemStackUtil.isIdenticalItem(farmland, itemStack); + } - @Override - public boolean isAcceptedGermling(ItemStack itemstack) { - for (IFarmable germling : seeds) { - if (germling.isGermling(itemstack)) { - return true; - } - } - return false; - } + @Override + public boolean isAcceptedGermling(ItemStack itemstack) { + for (IFarmable germling : seeds) { + if (germling.isGermling(itemstack)) { + return true; + } + } + return false; + } - @Override - public boolean isAcceptedWindfall(ItemStack itemstack) { - for (IFarmable germling : seeds) { - if (germling.isWindfall(itemstack)) { - return true; - } - } - return false; - } + @Override + public boolean isAcceptedWindfall(ItemStack itemstack) { + for (IFarmable germling : seeds) { + if (germling.isWindfall(itemstack)) { + return true; + } + } + return false; + } - @Override - public Collection collect() { - Collection products = produce; - produce = collectEntityItems(false); - return products; - } + @Override + public Collection collect() { + Collection products = produce; + produce = collectEntityItems(false); + return products; + } - @Override - protected boolean maintainCrops(int x, int y, int z, FarmDirection direction, int extent) { + @Override + protected boolean maintainCrops(int x, int y, int z, FarmDirection direction, int extent) { - World world = getWorld(); + World world = getWorld(); - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, y, z, direction, i); - if (!VectUtil.isAirBlock(world, position) && !BlockUtil.isReplaceableBlock(getWorld(), position.x, position.y, position.z)) { - continue; - } + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, y, z, direction, i); + if (!VectUtil.isAirBlock(world, position) + && !BlockUtil.isReplaceableBlock(getWorld(), position.x, position.y, position.z)) { + continue; + } - ItemStack below = VectUtil.getAsItemStack(world, position.add(0, -1, 0)); - if (ground.getItem() != below.getItem()) { - continue; - } - if (below.getItemDamage() <= 0) { - continue; - } + ItemStack below = VectUtil.getAsItemStack(world, position.add(0, -1, 0)); + if (ground.getItem() != below.getItem()) { + continue; + } + if (below.getItemDamage() <= 0) { + continue; + } - return trySetCrop(position); - } + return trySetCrop(position); + } - return false; - } + return false; + } - private boolean trySetCrop(IVect position) { - World world = getWorld(); + private boolean trySetCrop(IVect position) { + World world = getWorld(); - for (IFarmable candidate : seeds) { - if (housing.plantGermling(candidate, world, position.getX(), position.getY(), position.getZ())) { - return true; - } - } + for (IFarmable candidate : seeds) { + if (housing.plantGermling(candidate, world, position.getX(), position.getY(), position.getZ())) { + return true; + } + } - return false; - } + return false; + } - @Override - public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { - World world = getWorld(); - - Stack crops = new Stack<>(); - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, y + 1, z, direction, i); - for (IFarmable seed : seeds) { - ICrop crop = seed.getCropAt(world, position.x, position.y, position.z); - if (crop != null) { - crops.push(crop); - } - } - } - return crops; - } + @Override + public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { + World world = getWorld(); + Stack crops = new Stack<>(); + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, y + 1, z, direction, i); + for (IFarmable seed : seeds) { + ICrop crop = seed.getCropAt(world, position.x, position.y, position.z); + if (crop != null) { + crops.push(crop); + } + } + } + return crops; + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicEnder.java b/src/main/java/forestry/farming/logic/FarmLogicEnder.java index 062951c20..e897a7694 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicEnder.java +++ b/src/main/java/forestry/farming/logic/FarmLogicEnder.java @@ -10,18 +10,8 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.Collection; -import java.util.Stack; - -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.farming.FarmDirection; import forestry.api.farming.Farmables; import forestry.api.farming.ICrop; @@ -30,89 +20,98 @@ import forestry.api.farming.IFarmable; import forestry.core.utils.BlockUtil; import forestry.core.utils.vect.Vect; import forestry.core.utils.vect.VectUtil; +import java.util.Collection; +import java.util.Stack; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; public class FarmLogicEnder extends FarmLogicHomogeneous { - public FarmLogicEnder(IFarmHousing housing) { - super(housing, new ItemStack(Blocks.end_stone), new ItemStack(Blocks.end_stone), Farmables.farmables.get(FarmableReference.Ender.get())); - } + public FarmLogicEnder(IFarmHousing housing) { + super( + housing, + new ItemStack(Blocks.end_stone), + new ItemStack(Blocks.end_stone), + Farmables.farmables.get(FarmableReference.Ender.get())); + } - @Override - public String getName() { - return "Managed Ender Farm"; - } + @Override + public String getName() { + return "Managed Ender Farm"; + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return Items.ender_eye.getIconFromDamage(0); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return Items.ender_eye.getIconFromDamage(0); + } - @Override - public int getFertilizerConsumption() { - return 20; - } + @Override + public int getFertilizerConsumption() { + return 20; + } - @Override - public int getWaterConsumption(float hydrationModifier) { - return 0; - } + @Override + public int getWaterConsumption(float hydrationModifier) { + return 0; + } - @Override - public Collection collect() { - return null; - } + @Override + public Collection collect() { + return null; + } - @Override - public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { - World world = getWorld(); + @Override + public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { + World world = getWorld(); - Stack crops = new Stack<>(); - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, y + 1, z, direction, i); - for (IFarmable farmable : germlings) { - ICrop crop = farmable.getCropAt(world, position.x, position.y, position.z); - if (crop != null) { - crops.push(crop); - } - } + Stack crops = new Stack<>(); + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, y + 1, z, direction, i); + for (IFarmable farmable : germlings) { + ICrop crop = farmable.getCropAt(world, position.x, position.y, position.z); + if (crop != null) { + crops.push(crop); + } + } + } + return crops; + } - } - return crops; + @Override + protected boolean maintainGermlings(int x, int y, int z, FarmDirection direction, int extent) { + World world = getWorld(); - } + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, y, z, direction, i); + if (!VectUtil.isAirBlock(world, position) + && !BlockUtil.isReplaceableBlock(world, position.x, position.y, position.z)) { + continue; + } - @Override - protected boolean maintainGermlings(int x, int y, int z, FarmDirection direction, int extent) { - World world = getWorld(); + ItemStack below = VectUtil.getAsItemStack(world, position.add(0, -1, 0)); + if (!isAcceptedSoil(below)) { + continue; + } - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, y, z, direction, i); - if (!VectUtil.isAirBlock(world, position) && !BlockUtil.isReplaceableBlock(world, position.x, position.y, position.z)) { - continue; - } + return trySetCrop(position); + } - ItemStack below = VectUtil.getAsItemStack(world, position.add(0, -1, 0)); - if (!isAcceptedSoil(below)) { - continue; - } + return false; + } - return trySetCrop(position); - } + private boolean trySetCrop(Vect position) { + World world = getWorld(); - return false; - } - - private boolean trySetCrop(Vect position) { - World world = getWorld(); - - for (IFarmable candidate : germlings) { - if (housing.plantGermling(candidate, world, position.x, position.y, position.z)) { - return true; - } - } - - return false; - } + for (IFarmable candidate : germlings) { + if (housing.plantGermling(candidate, world, position.x, position.y, position.z)) { + return true; + } + } + return false; + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicGourd.java b/src/main/java/forestry/farming/logic/FarmLogicGourd.java index e1fc4d588..e2909dfd3 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicGourd.java +++ b/src/main/java/forestry/farming/logic/FarmLogicGourd.java @@ -10,95 +10,91 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.Collection; -import java.util.Stack; - -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.farming.FarmDirection; import forestry.api.farming.Farmables; import forestry.api.farming.ICrop; import forestry.api.farming.IFarmHousing; import forestry.api.farming.IFarmable; import forestry.core.utils.vect.Vect; +import java.util.Collection; +import java.util.Stack; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; public class FarmLogicGourd extends FarmLogic { - private final IFarmable[] seeds; + private final IFarmable[] seeds; - public FarmLogicGourd(IFarmHousing housing) { - super(housing); - Collection farmables = Farmables.farmables.get(FarmableReference.Gourd.get()); - seeds = farmables.toArray(new IFarmable[farmables.size()]); - } + public FarmLogicGourd(IFarmHousing housing) { + super(housing); + Collection farmables = Farmables.farmables.get(FarmableReference.Gourd.get()); + seeds = farmables.toArray(new IFarmable[farmables.size()]); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return Items.melon.getIconFromDamage(0); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return Items.melon.getIconFromDamage(0); + } - @Override - public String getName() { - return "Gourd Farm"; - } + @Override + public String getName() { + return "Gourd Farm"; + } - @Override - public int getFertilizerConsumption() { - return 10; - } + @Override + public int getFertilizerConsumption() { + return 10; + } - @Override - public int getWaterConsumption(float hydrationModifier) { - return (int) (40 * hydrationModifier); - } + @Override + public int getWaterConsumption(float hydrationModifier) { + return (int) (40 * hydrationModifier); + } - @Override - public boolean isAcceptedResource(ItemStack itemstack) { - return false; - } + @Override + public boolean isAcceptedResource(ItemStack itemstack) { + return false; + } - @Override - public boolean isAcceptedGermling(ItemStack itemstack) { - return false; - } + @Override + public boolean isAcceptedGermling(ItemStack itemstack) { + return false; + } - @Override - public boolean isAcceptedWindfall(ItemStack stack) { - return false; - } + @Override + public boolean isAcceptedWindfall(ItemStack stack) { + return false; + } - @Override - public Collection collect() { - return null; - } + @Override + public Collection collect() { + return null; + } - @Override - public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { - return false; - } + @Override + public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { + return false; + } - @Override - public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { - World world = getWorld(); - - Stack crops = new Stack<>(); - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, y + 1, z, direction, i); - for (IFarmable seed : seeds) { - ICrop crop = seed.getCropAt(world, position.x, position.y, position.z); - if (crop != null) { - crops.push(crop); - } - } - } - return crops; - } + @Override + public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { + World world = getWorld(); + Stack crops = new Stack<>(); + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, y + 1, z, direction, i); + for (IFarmable seed : seeds) { + ICrop crop = seed.getCropAt(world, position.x, position.y, position.z); + if (crop != null) { + crops.push(crop); + } + } + } + return crops; + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java b/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java index a5c4ac2bd..aa6aafa4e 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java +++ b/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java @@ -10,13 +10,6 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import forestry.api.farming.FarmDirection; import forestry.api.farming.IFarmHousing; import forestry.api.farming.IFarmable; @@ -25,101 +18,107 @@ import forestry.core.utils.ItemStackUtil; import forestry.core.utils.vect.Vect; import forestry.core.utils.vect.VectUtil; import forestry.farming.FarmHelper; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; public abstract class FarmLogicHomogeneous extends FarmLogic { - private final ItemStack resource; - private final ItemStack soilBlock; - protected final List germlings; + private final ItemStack resource; + private final ItemStack soilBlock; + protected final List germlings; - List produce = new ArrayList<>(); + List produce = new ArrayList<>(); - protected FarmLogicHomogeneous(IFarmHousing housing, ItemStack resource, ItemStack soilBlock, Iterable germlings) { - super(housing); - this.resource = resource; - this.soilBlock = soilBlock; - this.germlings = new ArrayList<>(); - for (IFarmable germling : germlings) { - this.germlings.add(germling); - } - } + protected FarmLogicHomogeneous( + IFarmHousing housing, ItemStack resource, ItemStack soilBlock, Iterable germlings) { + super(housing); + this.resource = resource; + this.soilBlock = soilBlock; + this.germlings = new ArrayList<>(); + for (IFarmable germling : germlings) { + this.germlings.add(germling); + } + } - protected boolean isAcceptedSoil(ItemStack itemStack) { - return ItemStackUtil.isIdenticalItem(soilBlock, itemStack); - } + protected boolean isAcceptedSoil(ItemStack itemStack) { + return ItemStackUtil.isIdenticalItem(soilBlock, itemStack); + } - @Override - public boolean isAcceptedResource(ItemStack itemstack) { - return resource.isItemEqual(itemstack); - } + @Override + public boolean isAcceptedResource(ItemStack itemstack) { + return resource.isItemEqual(itemstack); + } - @Override - public boolean isAcceptedGermling(ItemStack itemstack) { - for (IFarmable germling : germlings) { - if (germling.isGermling(itemstack)) { - return true; - } - } - return false; - } + @Override + public boolean isAcceptedGermling(ItemStack itemstack) { + for (IFarmable germling : germlings) { + if (germling.isGermling(itemstack)) { + return true; + } + } + return false; + } - @Override - public boolean isAcceptedWindfall(ItemStack itemstack) { - for (IFarmable germling : germlings) { - if (germling.isWindfall(itemstack)) { - return true; - } - } - return false; - } + @Override + public boolean isAcceptedWindfall(ItemStack itemstack) { + for (IFarmable germling : germlings) { + if (germling.isWindfall(itemstack)) { + return true; + } + } + return false; + } - @Override - public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { + @Override + public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { - if (maintainSoil(x, y, z, direction, extent)) { - return true; - } + if (maintainSoil(x, y, z, direction, extent)) { + return true; + } - return maintainGermlings(x, y + 1, z, direction, extent); - } + return maintainGermlings(x, y + 1, z, direction, extent); + } - private boolean maintainSoil(int x, int yGround, int z, FarmDirection direction, int extent) { - ItemStack[] resources = new ItemStack[]{resource}; - if (!housing.getFarmInventory().hasResources(resources)) { - return false; - } + private boolean maintainSoil(int x, int yGround, int z, FarmDirection direction, int extent) { + ItemStack[] resources = new ItemStack[] {resource}; + if (!housing.getFarmInventory().hasResources(resources)) { + return false; + } - World world = getWorld(); + World world = getWorld(); - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, yGround, z, direction, i); - Block soil = VectUtil.getBlock(world, position); + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, yGround, z, direction, i); + Block soil = VectUtil.getBlock(world, position); - if (FarmHelper.bricks.contains(soil)) { - break; - } + if (FarmHelper.bricks.contains(soil)) { + break; + } - ItemStack soilStack = VectUtil.getAsItemStack(world, position); - if (isAcceptedSoil(soilStack)) { - continue; - } + ItemStack soilStack = VectUtil.getAsItemStack(world, position); + if (isAcceptedSoil(soilStack)) { + continue; + } - Vect platformPosition = position.add(0, -1, 0); - Block platformBlock = VectUtil.getBlock(world, platformPosition); + Vect platformPosition = position.add(0, -1, 0); + Block platformBlock = VectUtil.getBlock(world, platformPosition); - if (!FarmHelper.bricks.contains(platformBlock)) { - break; - } + if (!FarmHelper.bricks.contains(platformBlock)) { + break; + } - produce.addAll(BlockUtil.getBlockDrops(world, position)); + produce.addAll(BlockUtil.getBlockDrops(world, position)); - setBlock(position, ItemStackUtil.getBlock(soilBlock), soilBlock.getItemDamage()); - housing.getFarmInventory().removeResources(resources); - return true; - } + setBlock(position, ItemStackUtil.getBlock(soilBlock), soilBlock.getItemDamage()); + housing.getFarmInventory().removeResources(resources); + return true; + } - return false; - } + return false; + } - protected abstract boolean maintainGermlings(int x, int ySaplings, int z, FarmDirection direction, int extent); + protected abstract boolean maintainGermlings(int x, int ySaplings, int z, FarmDirection direction, int extent); } diff --git a/src/main/java/forestry/farming/logic/FarmLogicIC2Crops.java b/src/main/java/forestry/farming/logic/FarmLogicIC2Crops.java index 15fa38b97..1be7cd2ac 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicIC2Crops.java +++ b/src/main/java/forestry/farming/logic/FarmLogicIC2Crops.java @@ -13,7 +13,7 @@ package forestry.farming.logic; import forestry.api.farming.Farmables; import forestry.api.farming.IFarmHousing; -//TODO: Make special Logic for Crops, maybe a virtual map of references to iterate faster? +// TODO: Make special Logic for Crops, maybe a virtual map of references to iterate faster? public class FarmLogicIC2Crops extends FarmLogicOrchard { public FarmLogicIC2Crops(IFarmHousing housing) { super(housing); diff --git a/src/main/java/forestry/farming/logic/FarmLogicInfernal.java b/src/main/java/forestry/farming/logic/FarmLogicInfernal.java index baa41a1d3..dd31bef44 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicInfernal.java +++ b/src/main/java/forestry/farming/logic/FarmLogicInfernal.java @@ -10,18 +10,8 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.Collection; -import java.util.Stack; - -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.farming.FarmDirection; import forestry.api.farming.Farmables; import forestry.api.farming.ICrop; @@ -30,89 +20,98 @@ import forestry.api.farming.IFarmable; import forestry.core.utils.BlockUtil; import forestry.core.utils.vect.Vect; import forestry.core.utils.vect.VectUtil; +import java.util.Collection; +import java.util.Stack; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; public class FarmLogicInfernal extends FarmLogicHomogeneous { - public FarmLogicInfernal(IFarmHousing housing) { - super(housing, new ItemStack(Blocks.soul_sand), new ItemStack(Blocks.soul_sand), Farmables.farmables.get(FarmableReference.Infernal.get())); - } + public FarmLogicInfernal(IFarmHousing housing) { + super( + housing, + new ItemStack(Blocks.soul_sand), + new ItemStack(Blocks.soul_sand), + Farmables.farmables.get(FarmableReference.Infernal.get())); + } - @Override - public String getName() { - return "Managed Infernal Farm"; - } + @Override + public String getName() { + return "Managed Infernal Farm"; + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return Items.nether_wart.getIconFromDamage(0); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return Items.nether_wart.getIconFromDamage(0); + } - @Override - public int getFertilizerConsumption() { - return 20; - } + @Override + public int getFertilizerConsumption() { + return 20; + } - @Override - public int getWaterConsumption(float hydrationModifier) { - return 0; - } + @Override + public int getWaterConsumption(float hydrationModifier) { + return 0; + } - @Override - public Collection collect() { - return null; - } + @Override + public Collection collect() { + return null; + } - @Override - public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { - World world = getWorld(); + @Override + public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { + World world = getWorld(); - Stack crops = new Stack<>(); - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, y + 1, z, direction, i); - for (IFarmable farmable : germlings) { - ICrop crop = farmable.getCropAt(world, position.x, position.y, position.z); - if (crop != null) { - crops.push(crop); - } - } + Stack crops = new Stack<>(); + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, y + 1, z, direction, i); + for (IFarmable farmable : germlings) { + ICrop crop = farmable.getCropAt(world, position.x, position.y, position.z); + if (crop != null) { + crops.push(crop); + } + } + } + return crops; + } - } - return crops; + @Override + protected boolean maintainGermlings(int x, int y, int z, FarmDirection direction, int extent) { + World world = getWorld(); - } + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, y, z, direction, i); + if (!VectUtil.isAirBlock(world, position) + && !BlockUtil.isReplaceableBlock(world, position.x, position.y, position.z)) { + continue; + } - @Override - protected boolean maintainGermlings(int x, int y, int z, FarmDirection direction, int extent) { - World world = getWorld(); + ItemStack below = VectUtil.getAsItemStack(world, position.add(0, -1, 0)); + if (!isAcceptedSoil(below)) { + continue; + } - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, y, z, direction, i); - if (!VectUtil.isAirBlock(world, position) && !BlockUtil.isReplaceableBlock(world, position.x, position.y, position.z)) { - continue; - } + return trySetCrop(position); + } - ItemStack below = VectUtil.getAsItemStack(world, position.add(0, -1, 0)); - if (!isAcceptedSoil(below)) { - continue; - } + return false; + } - return trySetCrop(position); - } + private boolean trySetCrop(Vect position) { + World world = getWorld(); - return false; - } - - private boolean trySetCrop(Vect position) { - World world = getWorld(); - - for (IFarmable candidate : germlings) { - if (housing.plantGermling(candidate, world, position.x, position.y, position.z)) { - return true; - } - } - - return false; - } + for (IFarmable candidate : germlings) { + if (housing.plantGermling(candidate, world, position.x, position.y, position.z)) { + return true; + } + } + return false; + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicOrchard.java b/src/main/java/forestry/farming/logic/FarmLogicOrchard.java index bb86b8dac..55d2ec453 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicOrchard.java +++ b/src/main/java/forestry/farming/logic/FarmLogicOrchard.java @@ -11,7 +11,15 @@ package forestry.farming.logic; import com.google.common.collect.ImmutableList; - +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.farming.*; +import forestry.api.genetics.IFruitBearer; +import forestry.core.utils.vect.Vect; +import forestry.core.utils.vect.VectUtil; +import forestry.plugins.PluginCore; +import forestry.plugins.PluginManager; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -19,8 +27,6 @@ import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Stack; - -import forestry.api.farming.*; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; @@ -28,250 +34,242 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.World; -import cpw.mods.fml.common.registry.GameRegistry; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.genetics.IFruitBearer; -import forestry.core.utils.vect.Vect; -import forestry.core.utils.vect.VectUtil; -import forestry.plugins.PluginCore; -import forestry.plugins.PluginManager; - public class FarmLogicOrchard extends FarmLogic { - protected Collection farmables; - protected final HashMap lastExtents = new HashMap<>(); - protected final ImmutableList traversalBlocks; + protected Collection farmables; + protected final HashMap lastExtents = new HashMap<>(); + protected final ImmutableList traversalBlocks; - protected boolean precalcBlockType; - protected boolean precalcBlockMeta; + protected boolean precalcBlockType; + protected boolean precalcBlockMeta; - public FarmLogicOrchard(IFarmHousing housing) { - super(housing); - this.setFarmables(Farmables.farmables.get(FarmableReference.Orchard.get())); + public FarmLogicOrchard(IFarmHousing housing) { + super(housing); + this.setFarmables(Farmables.farmables.get(FarmableReference.Orchard.get())); - ImmutableList.Builder traversalBlocksBuilder = ImmutableList.builder(); - if (PluginManager.Module.AGRICRAFT.isEnabled() || PluginManager.Module.INDUSTRIALCRAFT.isEnabled()) { - traversalBlocksBuilder.add(Blocks.farmland); - } - if (PluginManager.Module.INDUSTRIALCRAFT.isEnabled()) { - traversalBlocksBuilder.add(Blocks.dirt); - } - if (PluginManager.Module.PLANTMEGAPACK.isEnabled()) { - traversalBlocksBuilder.add(Blocks.water); - } + ImmutableList.Builder traversalBlocksBuilder = ImmutableList.builder(); + if (PluginManager.Module.AGRICRAFT.isEnabled() || PluginManager.Module.INDUSTRIALCRAFT.isEnabled()) { + traversalBlocksBuilder.add(Blocks.farmland); + } + if (PluginManager.Module.INDUSTRIALCRAFT.isEnabled()) { + traversalBlocksBuilder.add(Blocks.dirt); + } + if (PluginManager.Module.PLANTMEGAPACK.isEnabled()) { + traversalBlocksBuilder.add(Blocks.water); + } - { - Block grapeVine = GameRegistry.findBlock("Growthcraft|Grapes", "grc.grapeVine1"); - if (grapeVine != null) { - traversalBlocksBuilder.add(grapeVine); - } - } + { + Block grapeVine = GameRegistry.findBlock("Growthcraft|Grapes", "grc.grapeVine1"); + if (grapeVine != null) { + traversalBlocksBuilder.add(grapeVine); + } + } - traversalBlocksBuilder.build(); - this.traversalBlocks = traversalBlocksBuilder.build(); - } + traversalBlocksBuilder.build(); + this.traversalBlocks = traversalBlocksBuilder.build(); + } - @Override - public int getFertilizerConsumption() { - return 10; - } + @Override + public int getFertilizerConsumption() { + return 10; + } - @Override - public int getWaterConsumption(float hydrationModifier) { - return (int) (40 * hydrationModifier); - } + @Override + public int getWaterConsumption(float hydrationModifier) { + return (int) (40 * hydrationModifier); + } - @Override - public boolean isAcceptedResource(ItemStack itemstack) { - return false; - } + @Override + public boolean isAcceptedResource(ItemStack itemstack) { + return false; + } - @Override - public boolean isAcceptedGermling(ItemStack itemstack) { - return false; - } + @Override + public boolean isAcceptedGermling(ItemStack itemstack) { + return false; + } - @Override - public boolean isAcceptedWindfall(ItemStack stack) { - return false; - } + @Override + public boolean isAcceptedWindfall(ItemStack stack) { + return false; + } - @Override - public Collection collect() { - return null; - } + @Override + public Collection collect() { + return null; + } - @Override - public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { - return false; - } + @Override + public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { + return false; + } - @Override - public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { + @Override + public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { - Vect start = new Vect(x, y, z); - if (!lastExtents.containsKey(start)) { - lastExtents.put(start, 0); - } + Vect start = new Vect(x, y, z); + if (!lastExtents.containsKey(start)) { + lastExtents.put(start, 0); + } - int lastExtent = lastExtents.get(start); - if (lastExtent > extent) { - lastExtent = 0; - } + int lastExtent = lastExtents.get(start); + if (lastExtent > extent) { + lastExtent = 0; + } - Vect position = translateWithOffset(x, y + 1, z, direction, lastExtent); - Collection crops = getHarvestBlocks(position); - lastExtent++; - lastExtents.put(start, lastExtent); + Vect position = translateWithOffset(x, y + 1, z, direction, lastExtent); + Collection crops = getHarvestBlocks(position); + lastExtent++; + lastExtents.put(start, lastExtent); - return crops; - } + return crops; + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return PluginCore.items.fruits.getIconFromDamage(0); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return PluginCore.items.fruits.getIconFromDamage(0); + } - @Override - public String getName() { - return "Orchard"; - } + @Override + public String getName() { + return "Orchard"; + } - private Collection getHarvestBlocks(Vect position) { + private Collection getHarvestBlocks(Vect position) { - Set seen = new HashSet<>(); - Stack crops = new Stack<>(); + Set seen = new HashSet<>(); + Stack crops = new Stack<>(); - World world = getWorld(); + World world = getWorld(); - // Determine what type we want to harvest. - if (!VectUtil.isWoodBlock(world, position) && !isBlockTraversable(world, position, traversalBlocks) && !isFruitBearer(world, position)) { - return crops; - } + // Determine what type we want to harvest. + if (!VectUtil.isWoodBlock(world, position) + && !isBlockTraversable(world, position, traversalBlocks) + && !isFruitBearer(world, position)) { + return crops; + } - List candidates = processHarvestBlock(crops, seen, position, position); - List temp = new ArrayList<>(); - while (!candidates.isEmpty() && crops.size() < 20) { - for (Vect candidate : candidates) { - temp.addAll(processHarvestBlock(crops, seen, position, candidate)); - } - candidates.clear(); - candidates.addAll(temp); - temp.clear(); - } + List candidates = processHarvestBlock(crops, seen, position, position); + List temp = new ArrayList<>(); + while (!candidates.isEmpty() && crops.size() < 20) { + for (Vect candidate : candidates) { + temp.addAll(processHarvestBlock(crops, seen, position, candidate)); + } + candidates.clear(); + candidates.addAll(temp); + temp.clear(); + } - return crops; - } + return crops; + } - private List processHarvestBlock(Stack crops, Set seen, Vect start, Vect position) { - World world = getWorld(); + private List processHarvestBlock(Stack crops, Set seen, Vect start, Vect position) { + World world = getWorld(); - List candidates = new ArrayList<>(); + List candidates = new ArrayList<>(); - // Get additional candidates to return - for (int i = -2; i < 3; i++) { - for (int j = 0; j < 2; j++) { - for (int k = -1; k < 2; k++) { - Vect candidate = position.add(i, j, k); - if (Math.abs(candidate.x - start.x) > 5) { - continue; - } - if (Math.abs(candidate.z - start.z) > 5) { - continue; - } + // Get additional candidates to return + for (int i = -2; i < 3; i++) { + for (int j = 0; j < 2; j++) { + for (int k = -1; k < 2; k++) { + Vect candidate = position.add(i, j, k); + if (Math.abs(candidate.x - start.x) > 5) { + continue; + } + if (Math.abs(candidate.z - start.z) > 5) { + continue; + } - // See whether the given position has already been processed - if (seen.contains(candidate)) { - continue; - } - if (VectUtil.isAirBlock(world, candidate)) { - continue; - } - if (VectUtil.isWoodBlock(world, candidate) || isBlockTraversable(world, candidate, traversalBlocks)) { - candidates.add(candidate); - seen.add(candidate); - } else if (isFruitBearer(world, candidate)) { - candidates.add(candidate); - seen.add(candidate); + // See whether the given position has already been processed + if (seen.contains(candidate)) { + continue; + } + if (VectUtil.isAirBlock(world, candidate)) { + continue; + } + if (VectUtil.isWoodBlock(world, candidate) + || isBlockTraversable(world, candidate, traversalBlocks)) { + candidates.add(candidate); + seen.add(candidate); + } else if (isFruitBearer(world, candidate)) { + candidates.add(candidate); + seen.add(candidate); - ICrop crop = getCrop(world, candidate); - if (crop != null) { - crops.push(crop); - } - } - } - } - } + ICrop crop = getCrop(world, candidate); + if (crop != null) { + crops.push(crop); + } + } + } + } + } - return candidates; - } + return candidates; + } - private boolean isFruitBearer(World world, Vect position) { + private boolean isFruitBearer(World world, Vect position) { - TileEntity tile = world.getTileEntity(position.x, position.y, position.z); - if (tile instanceof IFruitBearer) { - return true; - } + TileEntity tile = world.getTileEntity(position.x, position.y, position.z); + if (tile instanceof IFruitBearer) { + return true; + } - Block block = precalcBlockType ? world.getBlock(position.x, position.y, position.z) : null; - int meta = precalcBlockMeta ? world.getBlockMetadata(position.x, position.y, position.z) : -1; + Block block = precalcBlockType ? world.getBlock(position.x, position.y, position.z) : null; + int meta = precalcBlockMeta ? world.getBlockMetadata(position.x, position.y, position.z) : -1; - for (IFarmable farmable : farmables) { - if (farmable instanceof IFarmableBasic) { - if (((IFarmableBasic) farmable).isSapling(block, meta)) - return true; - } else if (farmable.isSaplingAt(world, position.x, position.y, position.z)) { - return true; - } - } + for (IFarmable farmable : farmables) { + if (farmable instanceof IFarmableBasic) { + if (((IFarmableBasic) farmable).isSapling(block, meta)) return true; + } else if (farmable.isSaplingAt(world, position.x, position.y, position.z)) { + return true; + } + } - return false; - } + return false; + } - private static boolean isBlockTraversable(World world, Vect position, ImmutableList traversalBlocks) { + private static boolean isBlockTraversable(World world, Vect position, ImmutableList traversalBlocks) { - Block candidate = VectUtil.getBlock(world, position); - for (Block block : traversalBlocks) { - if (block == (candidate)) { - return true; - } - } - return false; - } + Block candidate = VectUtil.getBlock(world, position); + for (Block block : traversalBlocks) { + if (block == (candidate)) { + return true; + } + } + return false; + } - private ICrop getCrop(World world, Vect position) { + private ICrop getCrop(World world, Vect position) { - TileEntity tile = world.getTileEntity(position.x, position.y, position.z); + TileEntity tile = world.getTileEntity(position.x, position.y, position.z); - if (tile instanceof IFruitBearer) { - IFruitBearer fruitBearer = (IFruitBearer) tile; - if (fruitBearer.hasFruit() && fruitBearer.getRipeness() >= 0.9f) { - return new CropFruit(world, position); - } - } else { - for (IFarmable seed : farmables) { - ICrop crop = seed.getCropAt(world, position.x, position.y, position.z); - if (crop != null) { - return crop; - } - } - } - return null; - } + if (tile instanceof IFruitBearer) { + IFruitBearer fruitBearer = (IFruitBearer) tile; + if (fruitBearer.hasFruit() && fruitBearer.getRipeness() >= 0.9f) { + return new CropFruit(world, position); + } + } else { + for (IFarmable seed : farmables) { + ICrop crop = seed.getCropAt(world, position.x, position.y, position.z); + if (crop != null) { + return crop; + } + } + } + return null; + } - protected void setFarmables(Collection farmables) { - this.farmables = farmables; - for (IFarmable farmable : farmables) { - if (farmable instanceof IFarmableBasic) { - precalcBlockType = true; - if (((IFarmableBasic) farmable).isMetadataAware()) { - precalcBlockMeta = true; - return; - } - } - } - } + protected void setFarmables(Collection farmables) { + this.farmables = farmables; + for (IFarmable farmable : farmables) { + if (farmable instanceof IFarmableBasic) { + precalcBlockType = true; + if (((IFarmableBasic) farmable).isMetadataAware()) { + precalcBlockMeta = true; + return; + } + } + } + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicPeat.java b/src/main/java/forestry/farming/logic/FarmLogicPeat.java index c877b7eff..946ef0d4d 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicPeat.java +++ b/src/main/java/forestry/farming/logic/FarmLogicPeat.java @@ -10,17 +10,8 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.Collection; -import java.util.Stack; - -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.farming.FarmDirection; import forestry.api.farming.ICrop; import forestry.api.farming.IFarmHousing; @@ -28,85 +19,90 @@ import forestry.core.blocks.BlockSoil; import forestry.core.utils.vect.Vect; import forestry.core.utils.vect.VectUtil; import forestry.plugins.PluginCore; +import java.util.Collection; +import java.util.Stack; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; public class FarmLogicPeat extends FarmLogicWatered { - private static final ItemStack bogEarth = PluginCore.blocks.soil.get(BlockSoil.SoilType.BOG_EARTH, 1); + private static final ItemStack bogEarth = PluginCore.blocks.soil.get(BlockSoil.SoilType.BOG_EARTH, 1); - public FarmLogicPeat(IFarmHousing housing) { - super(housing, bogEarth, bogEarth); - } + public FarmLogicPeat(IFarmHousing housing) { + super(housing, bogEarth, bogEarth); + } - @Override - public boolean isAcceptedGround(ItemStack itemStack) { - if (super.isAcceptedGround(itemStack)) { - return true; - } + @Override + public boolean isAcceptedGround(ItemStack itemStack) { + if (super.isAcceptedGround(itemStack)) { + return true; + } - Block block = BlockSoil.getBlockFromItem(itemStack.getItem()); - if (!(block instanceof BlockSoil)) { - return false; - } - BlockSoil blockSoil = (BlockSoil) block; - BlockSoil.SoilType soilType = blockSoil.getTypeFromMeta(itemStack.getItemDamage()); - return soilType == BlockSoil.SoilType.BOG_EARTH || soilType == BlockSoil.SoilType.PEAT; - } + Block block = BlockSoil.getBlockFromItem(itemStack.getItem()); + if (!(block instanceof BlockSoil)) { + return false; + } + BlockSoil blockSoil = (BlockSoil) block; + BlockSoil.SoilType soilType = blockSoil.getTypeFromMeta(itemStack.getItemDamage()); + return soilType == BlockSoil.SoilType.BOG_EARTH || soilType == BlockSoil.SoilType.PEAT; + } - @Override - public int getFertilizerConsumption() { - return 2; - } + @Override + public int getFertilizerConsumption() { + return 2; + } - @Override - public String getName() { - if (isManual) { - return "Manual Peat Bog"; - } else { - return "Managed Peat Bog"; - } - } + @Override + public String getName() { + if (isManual) { + return "Manual Peat Bog"; + } else { + return "Managed Peat Bog"; + } + } - @Override - public boolean isAcceptedGermling(ItemStack itemstack) { - return false; - } + @Override + public boolean isAcceptedGermling(ItemStack itemstack) { + return false; + } - @Override - public boolean isAcceptedWindfall(ItemStack stack) { - return false; - } + @Override + public boolean isAcceptedWindfall(ItemStack stack) { + return false; + } - @Override - public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { - World world = getWorld(); + @Override + public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { + World world = getWorld(); - Stack crops = new Stack<>(); - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, y, z, direction, i); - ItemStack occupant = VectUtil.getAsItemStack(world, position); + Stack crops = new Stack<>(); + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, y, z, direction, i); + ItemStack occupant = VectUtil.getAsItemStack(world, position); - if (occupant.getItem() == null) { - continue; - } + if (occupant.getItem() == null) { + continue; + } - Block block = Block.getBlockFromItem(occupant.getItem()); - if (!(block instanceof BlockSoil)) { - continue; - } + Block block = Block.getBlockFromItem(occupant.getItem()); + if (!(block instanceof BlockSoil)) { + continue; + } - BlockSoil blockSoil = (BlockSoil) block; - BlockSoil.SoilType soilType = blockSoil.getTypeFromMeta(occupant.getItemDamage()); + BlockSoil blockSoil = (BlockSoil) block; + BlockSoil.SoilType soilType = blockSoil.getTypeFromMeta(occupant.getItemDamage()); - if (soilType == BlockSoil.SoilType.PEAT) { - crops.push(new CropPeat(world, position)); - } - } - return crops; - } - - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return PluginCore.items.peat.getIconFromDamage(0); - } + if (soilType == BlockSoil.SoilType.PEAT) { + crops.push(new CropPeat(world, position)); + } + } + return crops; + } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return PluginCore.items.peat.getIconFromDamage(0); + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicReeds.java b/src/main/java/forestry/farming/logic/FarmLogicReeds.java index 5f0094609..1b46f7a8d 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicReeds.java +++ b/src/main/java/forestry/farming/logic/FarmLogicReeds.java @@ -10,18 +10,8 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.Collection; -import java.util.Stack; - -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.farming.FarmDirection; import forestry.api.farming.Farmables; import forestry.api.farming.ICrop; @@ -29,90 +19,96 @@ import forestry.api.farming.IFarmHousing; import forestry.api.farming.IFarmable; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.vect.Vect; +import java.util.Collection; +import java.util.Stack; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; public class FarmLogicReeds extends FarmLogic { - private final IFarmable[] germlings; + private final IFarmable[] germlings; - public FarmLogicReeds(IFarmHousing housing) { - super(housing); - Collection farmables = Farmables.farmables.get(FarmableReference.Poales.get()); - germlings = farmables.toArray(new IFarmable[farmables.size()]); - } + public FarmLogicReeds(IFarmHousing housing) { + super(housing); + Collection farmables = Farmables.farmables.get(FarmableReference.Poales.get()); + germlings = farmables.toArray(new IFarmable[farmables.size()]); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return Items.reeds.getIconFromDamage(0); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return Items.reeds.getIconFromDamage(0); + } - @Override - public String getName() { - if (isManual) { - return "Manual Reed Farm"; - } else { - return "Managed Reed Farm"; - } - } + @Override + public String getName() { + if (isManual) { + return "Manual Reed Farm"; + } else { + return "Managed Reed Farm"; + } + } - @Override - public int getFertilizerConsumption() { - return 10; - } + @Override + public int getFertilizerConsumption() { + return 10; + } - @Override - public int getWaterConsumption(float hydrationModifier) { - return (int) (20 * hydrationModifier); - } + @Override + public int getWaterConsumption(float hydrationModifier) { + return (int) (20 * hydrationModifier); + } - @Override - public boolean isAcceptedResource(ItemStack itemstack) { - if (isManual) { - return false; - } + @Override + public boolean isAcceptedResource(ItemStack itemstack) { + if (isManual) { + return false; + } - return ItemStackUtil.equals(Blocks.sand, itemstack) || ItemStackUtil.equals(Blocks.dirt, itemstack); - } + return ItemStackUtil.equals(Blocks.sand, itemstack) || ItemStackUtil.equals(Blocks.dirt, itemstack); + } - @Override - public boolean isAcceptedGermling(ItemStack itemstack) { - if (isManual) { - return false; - } + @Override + public boolean isAcceptedGermling(ItemStack itemstack) { + if (isManual) { + return false; + } - return itemstack.getItem() == Items.reeds; - } + return itemstack.getItem() == Items.reeds; + } - @Override - public boolean isAcceptedWindfall(ItemStack stack) { - return false; - } + @Override + public boolean isAcceptedWindfall(ItemStack stack) { + return false; + } - @Override - public Collection collect() { - return null; - } + @Override + public Collection collect() { + return null; + } - @Override - public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { - return false; - } + @Override + public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { + return false; + } - @Override - public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { - World world = getWorld(); - - Stack crops = new Stack<>(); - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, y + 1, z, direction, i); - for (IFarmable seed : germlings) { - ICrop crop = seed.getCropAt(world, position.x, position.y, position.z); - if (crop != null) { - crops.push(crop); - } - } - } - return crops; - } + @Override + public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { + World world = getWorld(); + Stack crops = new Stack<>(); + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, y + 1, z, direction, i); + for (IFarmable seed : germlings) { + ICrop crop = seed.getCropAt(world, position.x, position.y, position.z); + if (crop != null) { + crops.push(crop); + } + } + } + return crops; + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicRubber.java b/src/main/java/forestry/farming/logic/FarmLogicRubber.java index bfdf229d1..bac3991d2 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicRubber.java +++ b/src/main/java/forestry/farming/logic/FarmLogicRubber.java @@ -10,22 +10,8 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; -import java.util.Stack; - -import net.minecraft.block.Block; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.farming.FarmDirection; import forestry.api.farming.ICrop; import forestry.api.farming.IFarmHousing; @@ -34,156 +20,168 @@ import forestry.core.utils.Log; import forestry.core.utils.vect.Vect; import forestry.core.utils.vect.VectUtil; import forestry.plugins.compat.PluginIC2; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; +import java.util.Stack; +import net.minecraft.block.Block; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; public class FarmLogicRubber extends FarmLogic { - private boolean inActive; + private boolean inActive; - public FarmLogicRubber(IFarmHousing housing) { - super(housing); - if (PluginIC2.rubberwood == null || PluginIC2.resin == null) { - Log.warning("Failed to init a farm logic %s since IC2 was not found", getClass().getName()); - inActive = true; - } - } + public FarmLogicRubber(IFarmHousing housing) { + super(housing); + if (PluginIC2.rubberwood == null || PluginIC2.resin == null) { + Log.warning( + "Failed to init a farm logic %s since IC2 was not found", + getClass().getName()); + inActive = true; + } + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - if (!inActive) { - return PluginIC2.resin.getIconIndex(); - } else { - return Items.gunpowder.getIconFromDamage(0); - } - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + if (!inActive) { + return PluginIC2.resin.getIconIndex(); + } else { + return Items.gunpowder.getIconFromDamage(0); + } + } - @Override - public String getName() { - return "Rubber Plantation"; - } + @Override + public String getName() { + return "Rubber Plantation"; + } - @Override - public int getFertilizerConsumption() { - return 40; - } + @Override + public int getFertilizerConsumption() { + return 40; + } - @Override - public int getWaterConsumption(float hydrationModifier) { - return (int) (5 * hydrationModifier); - } + @Override + public int getWaterConsumption(float hydrationModifier) { + return (int) (5 * hydrationModifier); + } - @Override - public boolean isAcceptedResource(ItemStack itemstack) { - return false; - } + @Override + public boolean isAcceptedResource(ItemStack itemstack) { + return false; + } - @Override - public boolean isAcceptedGermling(ItemStack itemstack) { - return false; - } + @Override + public boolean isAcceptedGermling(ItemStack itemstack) { + return false; + } - @Override - public boolean isAcceptedWindfall(ItemStack stack) { - return false; - } + @Override + public boolean isAcceptedWindfall(ItemStack stack) { + return false; + } - @Override - public Collection collect() { - return null; - } + @Override + public Collection collect() { + return null; + } - @Override - public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { - return false; - } + @Override + public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { + return false; + } - private final HashMap lastExtents = new HashMap<>(); + private final HashMap lastExtents = new HashMap<>(); - @Override - public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { - if (inActive) { - return null; - } + @Override + public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { + if (inActive) { + return null; + } - Vect start = new Vect(x, y, z); - if (!lastExtents.containsKey(start)) { - lastExtents.put(start, 0); - } + Vect start = new Vect(x, y, z); + if (!lastExtents.containsKey(start)) { + lastExtents.put(start, 0); + } - int lastExtent = lastExtents.get(start); - if (lastExtent > extent) { - lastExtent = 0; - } + int lastExtent = lastExtents.get(start); + if (lastExtent > extent) { + lastExtent = 0; + } - Vect position = translateWithOffset(x, y + 1, z, direction, lastExtent); - Collection crops = getHarvestBlocks(position); - lastExtent++; - lastExtents.put(start, lastExtent); + Vect position = translateWithOffset(x, y + 1, z, direction, lastExtent); + Collection crops = getHarvestBlocks(position); + lastExtent++; + lastExtents.put(start, lastExtent); - return crops; - } + return crops; + } - private Collection getHarvestBlocks(Vect position) { + private Collection getHarvestBlocks(Vect position) { - Set seen = new HashSet<>(); - Stack crops = new Stack<>(); + Set seen = new HashSet<>(); + Stack crops = new Stack<>(); - World world = getWorld(); + World world = getWorld(); - // Determine what type we want to harvest. - Block block = VectUtil.getBlock(world, position); - if (!ItemStackUtil.equals(block, PluginIC2.rubberwood)) { - return crops; - } + // Determine what type we want to harvest. + Block block = VectUtil.getBlock(world, position); + if (!ItemStackUtil.equals(block, PluginIC2.rubberwood)) { + return crops; + } - int meta = VectUtil.getBlockMeta(world, position); - if (meta >= 2 && meta <= 5) { - crops.push(new CropRubber(getWorld(), block, meta, position)); - } + int meta = VectUtil.getBlockMeta(world, position); + if (meta >= 2 && meta <= 5) { + crops.push(new CropRubber(getWorld(), block, meta, position)); + } - ArrayList candidates = processHarvestBlock(crops, seen, position); - ArrayList temp = new ArrayList<>(); - while (!candidates.isEmpty() && crops.size() < 100) { - for (Vect candidate : candidates) { - temp.addAll(processHarvestBlock(crops, seen, candidate)); - } - candidates.clear(); - candidates.addAll(temp); - temp.clear(); - } + ArrayList candidates = processHarvestBlock(crops, seen, position); + ArrayList temp = new ArrayList<>(); + while (!candidates.isEmpty() && crops.size() < 100) { + for (Vect candidate : candidates) { + temp.addAll(processHarvestBlock(crops, seen, candidate)); + } + candidates.clear(); + candidates.addAll(temp); + temp.clear(); + } - return crops; - } + return crops; + } - private ArrayList processHarvestBlock(Stack crops, Set seen, Vect position) { - World world = getWorld(); + private ArrayList processHarvestBlock(Stack crops, Set seen, Vect position) { + World world = getWorld(); - ArrayList candidates = new ArrayList<>(); + ArrayList candidates = new ArrayList<>(); - // Get additional candidates to return - for (int j = 0; j < 2; j++) { - Vect candidate = new Vect(position.x, position.y + j, position.z); - if (candidate.equals(position)) { - continue; - } + // Get additional candidates to return + for (int j = 0; j < 2; j++) { + Vect candidate = new Vect(position.x, position.y + j, position.z); + if (candidate.equals(position)) { + continue; + } - // See whether the given position has already been processed - if (seen.contains(candidate)) { - continue; - } + // See whether the given position has already been processed + if (seen.contains(candidate)) { + continue; + } - Block block = VectUtil.getBlock(world, candidate); - if (ItemStackUtil.equals(block, PluginIC2.rubberwood)) { - int meta = VectUtil.getBlockMeta(world, candidate); - if (meta >= 2 && meta <= 5) { - crops.push(new CropRubber(world, block, meta, candidate)); - } - candidates.add(candidate); - seen.add(candidate); - } - } - - return candidates; - } + Block block = VectUtil.getBlock(world, candidate); + if (ItemStackUtil.equals(block, PluginIC2.rubberwood)) { + int meta = VectUtil.getBlockMeta(world, candidate); + if (meta >= 2 && meta <= 5) { + crops.push(new CropRubber(world, block, meta, candidate)); + } + candidates.add(candidate); + seen.add(candidate); + } + } + return candidates; + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicShroom.java b/src/main/java/forestry/farming/logic/FarmLogicShroom.java index 10fa23ce3..ad5eb4d91 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicShroom.java +++ b/src/main/java/forestry/farming/logic/FarmLogicShroom.java @@ -10,55 +10,55 @@ ******************************************************************************/ package forestry.farming.logic; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.farming.Farmables; +import forestry.api.farming.IFarmHousing; import java.util.ArrayList; import java.util.Collection; - import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.farming.Farmables; -import forestry.api.farming.IFarmHousing; - public class FarmLogicShroom extends FarmLogicArboreal { - public FarmLogicShroom(IFarmHousing housing) { - super(housing, new ItemStack(Blocks.mycelium), new ItemStack(Blocks.mycelium), Farmables.farmables.get(FarmableReference.Shroom.get())); - } + public FarmLogicShroom(IFarmHousing housing) { + super( + housing, + new ItemStack(Blocks.mycelium), + new ItemStack(Blocks.mycelium), + Farmables.farmables.get(FarmableReference.Shroom.get())); + } - @Override - public String getName() { - if (isManual) { - return "Manual Shroom Farm"; - } else { - return "Managed Shroom Farm"; - } - } + @Override + public String getName() { + if (isManual) { + return "Manual Shroom Farm"; + } else { + return "Managed Shroom Farm"; + } + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return Blocks.red_mushroom.getBlockTextureFromSide(0); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return Blocks.red_mushroom.getBlockTextureFromSide(0); + } - @Override - public int getFertilizerConsumption() { - return 20; - } + @Override + public int getFertilizerConsumption() { + return 20; + } - @Override - public int getWaterConsumption(float hydrationModifier) { - return (int) (80 * hydrationModifier); - } - - @Override - public Collection collect() { - Collection products = produce; - produce = new ArrayList<>(); - return products; - } + @Override + public int getWaterConsumption(float hydrationModifier) { + return (int) (80 * hydrationModifier); + } + @Override + public Collection collect() { + Collection products = produce; + produce = new ArrayList<>(); + return products; + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicSucculent.java b/src/main/java/forestry/farming/logic/FarmLogicSucculent.java index 88d0cfd0c..18a1d0e4a 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicSucculent.java +++ b/src/main/java/forestry/farming/logic/FarmLogicSucculent.java @@ -10,18 +10,8 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.Collection; -import java.util.Stack; - -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.farming.FarmDirection; import forestry.api.farming.Farmables; import forestry.api.farming.ICrop; @@ -29,90 +19,96 @@ import forestry.api.farming.IFarmHousing; import forestry.api.farming.IFarmable; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.vect.Vect; +import java.util.Collection; +import java.util.Stack; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; public class FarmLogicSucculent extends FarmLogic { - private final IFarmable[] germlings; + private final IFarmable[] germlings; - public FarmLogicSucculent(IFarmHousing housing) { - super(housing); - Collection farmables = Farmables.farmables.get(FarmableReference.Succulentes.get()); - germlings = farmables.toArray(new IFarmable[farmables.size()]); - } + public FarmLogicSucculent(IFarmHousing housing) { + super(housing); + Collection farmables = Farmables.farmables.get(FarmableReference.Succulentes.get()); + germlings = farmables.toArray(new IFarmable[farmables.size()]); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return Items.dye.getIconFromDamage(2); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return Items.dye.getIconFromDamage(2); + } - @Override - public String getName() { - if (isManual) { - return "Manual Succulent Farm"; - } else { - return "Managed Succulent Farm"; - } - } + @Override + public String getName() { + if (isManual) { + return "Manual Succulent Farm"; + } else { + return "Managed Succulent Farm"; + } + } - @Override - public int getFertilizerConsumption() { - return 10; - } + @Override + public int getFertilizerConsumption() { + return 10; + } - @Override - public int getWaterConsumption(float hydrationModifier) { - return 1; - } + @Override + public int getWaterConsumption(float hydrationModifier) { + return 1; + } - @Override - public boolean isAcceptedResource(ItemStack itemstack) { - if (isManual) { - return false; - } + @Override + public boolean isAcceptedResource(ItemStack itemstack) { + if (isManual) { + return false; + } - return ItemStackUtil.equals(Blocks.sand, itemstack); - } + return ItemStackUtil.equals(Blocks.sand, itemstack); + } - @Override - public boolean isAcceptedGermling(ItemStack itemstack) { - if (isManual) { - return false; - } + @Override + public boolean isAcceptedGermling(ItemStack itemstack) { + if (isManual) { + return false; + } - return ItemStackUtil.equals(Blocks.cactus, itemstack); - } + return ItemStackUtil.equals(Blocks.cactus, itemstack); + } - @Override - public boolean isAcceptedWindfall(ItemStack stack) { - return false; - } + @Override + public boolean isAcceptedWindfall(ItemStack stack) { + return false; + } - @Override - public Collection collect() { - return null; - } + @Override + public Collection collect() { + return null; + } - @Override - public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { - return false; - } + @Override + public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { + return false; + } - @Override - public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { - World world = getWorld(); - - Stack crops = new Stack<>(); - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, y + 1, z, direction, i); - for (IFarmable seed : germlings) { - ICrop crop = seed.getCropAt(world, position.x, position.y, position.z); - if (crop != null) { - crops.push(crop); - } - } - } - return crops; - } + @Override + public Collection harvest(int x, int y, int z, FarmDirection direction, int extent) { + World world = getWorld(); + Stack crops = new Stack<>(); + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, y + 1, z, direction, i); + for (IFarmable seed : germlings) { + ICrop crop = seed.getCropAt(world, position.x, position.y, position.z); + if (crop != null) { + crops.push(crop); + } + } + } + return crops; + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicVegetable.java b/src/main/java/forestry/farming/logic/FarmLogicVegetable.java index 2dadfa3bd..91fc1b45b 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicVegetable.java +++ b/src/main/java/forestry/farming/logic/FarmLogicVegetable.java @@ -10,34 +10,31 @@ ******************************************************************************/ package forestry.farming.logic; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.farming.Farmables; +import forestry.api.farming.IFarmHousing; import net.minecraft.init.Items; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.farming.Farmables; -import forestry.api.farming.IFarmHousing; - public class FarmLogicVegetable extends FarmLogicCrops { - public FarmLogicVegetable(IFarmHousing housing) { - super(housing, Farmables.farmables.get(FarmableReference.Vegetables.get())); - } + public FarmLogicVegetable(IFarmHousing housing) { + super(housing, Farmables.farmables.get(FarmableReference.Vegetables.get())); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return Items.carrot.getIconFromDamage(0); - } - - @Override - public String getName() { - if (isManual) { - return "Manual Vegetable Farm"; - } else { - return "Managed Vegetable Farm"; - } - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return Items.carrot.getIconFromDamage(0); + } + @Override + public String getName() { + if (isManual) { + return "Manual Vegetable Farm"; + } else { + return "Managed Vegetable Farm"; + } + } } diff --git a/src/main/java/forestry/farming/logic/FarmLogicWatered.java b/src/main/java/forestry/farming/logic/FarmLogicWatered.java index f07030da6..b02581409 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicWatered.java +++ b/src/main/java/forestry/farming/logic/FarmLogicWatered.java @@ -10,17 +10,6 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -import net.minecraftforge.fluids.FluidStack; - import forestry.api.farming.FarmDirection; import forestry.api.farming.IFarmHousing; import forestry.core.fluids.Fluids; @@ -29,181 +18,188 @@ import forestry.core.utils.ItemStackUtil; import forestry.core.utils.vect.Vect; import forestry.core.utils.vect.VectUtil; import forestry.farming.FarmHelper; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraftforge.fluids.FluidStack; public abstract class FarmLogicWatered extends FarmLogic { - protected final ItemStack ground; - private final ItemStack resource; + protected final ItemStack ground; + private final ItemStack resource; - private static final FluidStack STACK_WATER = Fluids.WATER.getFluid(1000); + private static final FluidStack STACK_WATER = Fluids.WATER.getFluid(1000); - List produce = new ArrayList<>(); + List produce = new ArrayList<>(); - protected FarmLogicWatered(IFarmHousing housing, ItemStack resource, ItemStack ground) { - super(housing); - this.ground = ground; - this.resource = resource; - } + protected FarmLogicWatered(IFarmHousing housing, ItemStack resource, ItemStack ground) { + super(housing); + this.ground = ground; + this.resource = resource; + } - @Override - public int getFertilizerConsumption() { - return 5; - } + @Override + public int getFertilizerConsumption() { + return 5; + } - @Override - public int getWaterConsumption(float hydrationModifier) { - return (int) (20 * hydrationModifier); - } + @Override + public int getWaterConsumption(float hydrationModifier) { + return (int) (20 * hydrationModifier); + } - protected boolean isAcceptedGround(ItemStack ground) { - return ItemStackUtil.isIdenticalItem(this.ground, ground); - } + protected boolean isAcceptedGround(ItemStack ground) { + return ItemStackUtil.isIdenticalItem(this.ground, ground); + } - @Override - public boolean isAcceptedResource(ItemStack itemstack) { - return resource.isItemEqual(itemstack); - } + @Override + public boolean isAcceptedResource(ItemStack itemstack) { + return resource.isItemEqual(itemstack); + } - @Override - public Collection collect() { - Collection products = produce; - produce = new ArrayList<>(); - return products; - } + @Override + public Collection collect() { + Collection products = produce; + produce = new ArrayList<>(); + return products; + } - @Override - public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { + @Override + public boolean cultivate(int x, int y, int z, FarmDirection direction, int extent) { - if (maintainSoil(x, y, z, direction, extent)) { - return true; - } + if (maintainSoil(x, y, z, direction, extent)) { + return true; + } - if (!isManual && maintainWater(x, y, z, direction, extent)) { - return true; - } + if (!isManual && maintainWater(x, y, z, direction, extent)) { + return true; + } - if (maintainCrops(x, y + 1, z, direction, extent)) { - return true; - } + if (maintainCrops(x, y + 1, z, direction, extent)) { + return true; + } - return false; - } + return false; + } - private boolean maintainSoil(int x, int y, int z, FarmDirection direction, int extent) { + private boolean maintainSoil(int x, int y, int z, FarmDirection direction, int extent) { - World world = getWorld(); - ItemStack[] resources = new ItemStack[]{resource}; + World world = getWorld(); + ItemStack[] resources = new ItemStack[] {resource}; - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, y, z, direction, i); - Block soil = VectUtil.getBlock(world, position); + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, y, z, direction, i); + Block soil = VectUtil.getBlock(world, position); - ItemStack soilStack = VectUtil.getAsItemStack(world, position); - if (isAcceptedGround(soilStack) || !housing.getFarmInventory().hasResources(resources)) { - continue; - } + ItemStack soilStack = VectUtil.getAsItemStack(world, position); + if (isAcceptedGround(soilStack) || !housing.getFarmInventory().hasResources(resources)) { + continue; + } - Vect platformPosition = position.add(0, -1, 0); - Block platformBlock = VectUtil.getBlock(world, platformPosition); - if (!FarmHelper.bricks.contains(platformBlock)) { - break; - } + Vect platformPosition = position.add(0, -1, 0); + Block platformBlock = VectUtil.getBlock(world, platformPosition); + if (!FarmHelper.bricks.contains(platformBlock)) { + break; + } - if (!isAirBlock(soil) && !BlockUtil.isReplaceableBlock(soil)) { - produce.addAll(BlockUtil.getBlockDrops(getWorld(), position)); - setBlock(position, Blocks.air, 0); - return trySetSoil(position); - } + if (!isAirBlock(soil) && !BlockUtil.isReplaceableBlock(soil)) { + produce.addAll(BlockUtil.getBlockDrops(getWorld(), position)); + setBlock(position, Blocks.air, 0); + return trySetSoil(position); + } - if (isManual || isWaterSourceBlock(world, position)) { - continue; - } + if (isManual || isWaterSourceBlock(world, position)) { + continue; + } - if (trySetWater(world, position)) { - return true; - } + if (trySetWater(world, position)) { + return true; + } - return trySetSoil(position); - } + return trySetSoil(position); + } - return false; - } + return false; + } - private boolean maintainWater(int x, int y, int z, FarmDirection direction, int extent) { - // Still not done, check water then - World world = getWorld(); - for (int i = 0; i < extent; i++) { - Vect position = translateWithOffset(x, y, z, direction, i); + private boolean maintainWater(int x, int y, int z, FarmDirection direction, int extent) { + // Still not done, check water then + World world = getWorld(); + for (int i = 0; i < extent; i++) { + Vect position = translateWithOffset(x, y, z, direction, i); - Vect platformPosition = position.add(0, -1, 0); - Block platformBlock = VectUtil.getBlock(world, platformPosition); - if (!FarmHelper.bricks.contains(platformBlock)) { - break; - } + Vect platformPosition = position.add(0, -1, 0); + Block platformBlock = VectUtil.getBlock(world, platformPosition); + if (!FarmHelper.bricks.contains(platformBlock)) { + break; + } - if (trySetWater(world, position)) { - return true; - } - } + if (trySetWater(world, position)) { + return true; + } + } - return false; - } + return false; + } - protected boolean maintainCrops(int x, int y, int z, FarmDirection direction, int extent) { - return false; - } + protected boolean maintainCrops(int x, int y, int z, FarmDirection direction, int extent) { + return false; + } - private boolean trySetSoil(Vect position) { - ItemStack[] resources = new ItemStack[]{resource}; - if (!housing.getFarmInventory().hasResources(resources)) { - return false; - } - setBlock(position, ItemStackUtil.getBlock(ground), ground.getItemDamage()); - housing.getFarmInventory().removeResources(resources); - return true; - } + private boolean trySetSoil(Vect position) { + ItemStack[] resources = new ItemStack[] {resource}; + if (!housing.getFarmInventory().hasResources(resources)) { + return false; + } + setBlock(position, ItemStackUtil.getBlock(ground), ground.getItemDamage()); + housing.getFarmInventory().removeResources(resources); + return true; + } - private boolean trySetWater(World world, Vect position) { - if (isWaterSourceBlock(world, position) || !canPlaceWater(world, position)) { - return false; - } + private boolean trySetWater(World world, Vect position) { + if (isWaterSourceBlock(world, position) || !canPlaceWater(world, position)) { + return false; + } - if (!housing.hasLiquid(STACK_WATER)) { - return false; - } + if (!housing.hasLiquid(STACK_WATER)) { + return false; + } - produce.addAll(BlockUtil.getBlockDrops(world, position)); - setBlock(position, Blocks.water, 0); - housing.removeLiquid(STACK_WATER); - return true; - } + produce.addAll(BlockUtil.getBlockDrops(world, position)); + setBlock(position, Blocks.water, 0); + housing.removeLiquid(STACK_WATER); + return true; + } - private boolean canPlaceWater(World world, Vect position) { - // don't place water close to other water - for (int x = -2; x <= 2; x++) { - for (int z = -2; z <= 2; z++) { - Vect offsetPosition = position.add(x, 0, z); - if (isWaterSourceBlock(world, offsetPosition)) { - return false; - } - } - } + private boolean canPlaceWater(World world, Vect position) { + // don't place water close to other water + for (int x = -2; x <= 2; x++) { + for (int z = -2; z <= 2; z++) { + Vect offsetPosition = position.add(x, 0, z); + if (isWaterSourceBlock(world, offsetPosition)) { + return false; + } + } + } - // don't place water if it can flow into blocks next to it - for (int x = -1; x <= 1; x++) { - Vect offsetPosition = position.add(x, 0, 0); - if (VectUtil.isAirBlock(world, offsetPosition)) { - return false; - } - } - for (int z = -1; z <= 1; z++) { - Vect offsetPosition = position.add(0, 0, z); - if (VectUtil.isAirBlock(world, offsetPosition)) { - return false; - } - } - - return true; - } + // don't place water if it can flow into blocks next to it + for (int x = -1; x <= 1; x++) { + Vect offsetPosition = position.add(x, 0, 0); + if (VectUtil.isAirBlock(world, offsetPosition)) { + return false; + } + } + for (int z = -1; z <= 1; z++) { + Vect offsetPosition = position.add(0, 0, z); + if (VectUtil.isAirBlock(world, offsetPosition)) { + return false; + } + } + return true; + } } diff --git a/src/main/java/forestry/farming/logic/FarmableBasicAgricraft.java b/src/main/java/forestry/farming/logic/FarmableBasicAgricraft.java index 84da9b0a1..898717b98 100644 --- a/src/main/java/forestry/farming/logic/FarmableBasicAgricraft.java +++ b/src/main/java/forestry/farming/logic/FarmableBasicAgricraft.java @@ -10,56 +10,54 @@ ******************************************************************************/ package forestry.farming.logic; -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import forestry.api.farming.ICrop; import forestry.api.farming.IFarmableBasic; import forestry.core.config.Constants; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.vect.Vect; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; public class FarmableBasicAgricraft implements IFarmableBasic { - private final Block block; - private final int matureMeta; + private final Block block; + private final int matureMeta; - public FarmableBasicAgricraft(Block block, int matureMeta) { - this.block = block; - this.matureMeta = matureMeta; - } + public FarmableBasicAgricraft(Block block, int matureMeta) { + this.block = block; + this.matureMeta = matureMeta; + } - @Override - public boolean isSapling(Block block, int meta) { - return this.block == block; - } + @Override + public boolean isSapling(Block block, int meta) { + return this.block == block; + } - @Override - public ICrop getCropAt(World world, int x, int y, int z) { - if (world.getBlock(x, y, z) != block) { - return null; - } - if (world.getBlockMetadata(x, y, z) != matureMeta) { - return null; - } - return new CropBasicAgriCraft(world, block, matureMeta, new Vect(x, y, z)); - } + @Override + public ICrop getCropAt(World world, int x, int y, int z) { + if (world.getBlock(x, y, z) != block) { + return null; + } + if (world.getBlockMetadata(x, y, z) != matureMeta) { + return null; + } + return new CropBasicAgriCraft(world, block, matureMeta, new Vect(x, y, z)); + } - @Override - public boolean isGermling(ItemStack itemstack) { - return ItemStackUtil.equals(block, itemstack); - } + @Override + public boolean isGermling(ItemStack itemstack) { + return ItemStackUtil.equals(block, itemstack); + } - @Override - public boolean isWindfall(ItemStack itemstack) { - return false; - } - - @Override - public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { - return world.setBlock(x, y, z, block, 0, Constants.FLAG_BLOCK_SYNCH); - } + @Override + public boolean isWindfall(ItemStack itemstack) { + return false; + } + @Override + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return world.setBlock(x, y, z, block, 0, Constants.FLAG_BLOCK_SYNCH); + } } diff --git a/src/main/java/forestry/farming/logic/FarmableBasicFruit.java b/src/main/java/forestry/farming/logic/FarmableBasicFruit.java index 3800e8436..3c7a6c0fe 100644 --- a/src/main/java/forestry/farming/logic/FarmableBasicFruit.java +++ b/src/main/java/forestry/farming/logic/FarmableBasicFruit.java @@ -10,56 +10,54 @@ ******************************************************************************/ package forestry.farming.logic; -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import forestry.api.farming.ICrop; import forestry.api.farming.IFarmableBasic; import forestry.core.config.Constants; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.vect.Vect; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; public class FarmableBasicFruit implements IFarmableBasic { - private final Block block; - private final int matureMeta; + private final Block block; + private final int matureMeta; - public FarmableBasicFruit(Block block, int matureMeta) { - this.block = block; - this.matureMeta = matureMeta; - } + public FarmableBasicFruit(Block block, int matureMeta) { + this.block = block; + this.matureMeta = matureMeta; + } - @Override - public boolean isSapling(Block block, int meta) { - return this.block == block; - } + @Override + public boolean isSapling(Block block, int meta) { + return this.block == block; + } - @Override - public ICrop getCropAt(World world, int x, int y, int z) { - if (world.getBlock(x, y, z) != block) { - return null; - } - if (world.getBlockMetadata(x, y, z) != matureMeta) { - return null; - } - return new CropBasicFruit(world, block, matureMeta, new Vect(x, y, z)); - } + @Override + public ICrop getCropAt(World world, int x, int y, int z) { + if (world.getBlock(x, y, z) != block) { + return null; + } + if (world.getBlockMetadata(x, y, z) != matureMeta) { + return null; + } + return new CropBasicFruit(world, block, matureMeta, new Vect(x, y, z)); + } - @Override - public boolean isGermling(ItemStack itemstack) { - return ItemStackUtil.equals(block, itemstack); - } + @Override + public boolean isGermling(ItemStack itemstack) { + return ItemStackUtil.equals(block, itemstack); + } - @Override - public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { - return world.setBlock(x, y, z, block, 0, Constants.FLAG_BLOCK_SYNCH); - } - - @Override - public boolean isWindfall(ItemStack itemstack) { - return false; - } + @Override + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return world.setBlock(x, y, z, block, 0, Constants.FLAG_BLOCK_SYNCH); + } + @Override + public boolean isWindfall(ItemStack itemstack) { + return false; + } } diff --git a/src/main/java/forestry/farming/logic/FarmableBasicGrowthCraft.java b/src/main/java/forestry/farming/logic/FarmableBasicGrowthCraft.java index e2da8a724..18aec0351 100644 --- a/src/main/java/forestry/farming/logic/FarmableBasicGrowthCraft.java +++ b/src/main/java/forestry/farming/logic/FarmableBasicGrowthCraft.java @@ -10,60 +10,58 @@ ******************************************************************************/ package forestry.farming.logic; -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import forestry.api.farming.ICrop; import forestry.api.farming.IFarmableBasic; import forestry.core.config.Constants; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.vect.Vect; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; public class FarmableBasicGrowthCraft implements IFarmableBasic { - private final Block block; - private final int matureMeta; - private final boolean isRice; - private final boolean isGrape; + private final Block block; + private final int matureMeta; + private final boolean isRice; + private final boolean isGrape; - public FarmableBasicGrowthCraft(Block block, int matureMeta, boolean isRice, boolean isGrape) { - this.block = block; - this.matureMeta = matureMeta; - this.isRice = isRice; - this.isGrape = isGrape; - } + public FarmableBasicGrowthCraft(Block block, int matureMeta, boolean isRice, boolean isGrape) { + this.block = block; + this.matureMeta = matureMeta; + this.isRice = isRice; + this.isGrape = isGrape; + } - @Override - public boolean isSapling(Block block, int meta) { - return this.block == block; - } + @Override + public boolean isSapling(Block block, int meta) { + return this.block == block; + } - @Override - public ICrop getCropAt(World world, int x, int y, int z) { - if (world.getBlock(x, y, z) != block) { - return null; - } - if (world.getBlockMetadata(x, y, z) != matureMeta) { - return null; - } - return new CropBasicGrowthCraft(world, block, matureMeta, new Vect(x, y, z), isRice, isGrape); - } + @Override + public ICrop getCropAt(World world, int x, int y, int z) { + if (world.getBlock(x, y, z) != block) { + return null; + } + if (world.getBlockMetadata(x, y, z) != matureMeta) { + return null; + } + return new CropBasicGrowthCraft(world, block, matureMeta, new Vect(x, y, z), isRice, isGrape); + } - @Override - public boolean isGermling(ItemStack itemstack) { - return ItemStackUtil.equals(block, itemstack); - } + @Override + public boolean isGermling(ItemStack itemstack) { + return ItemStackUtil.equals(block, itemstack); + } - @Override - public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { - return world.setBlock(x, y, z, block, 0, Constants.FLAG_BLOCK_SYNCH); - } - - @Override - public boolean isWindfall(ItemStack itemstack) { - return false; - } + @Override + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return world.setBlock(x, y, z, block, 0, Constants.FLAG_BLOCK_SYNCH); + } + @Override + public boolean isWindfall(ItemStack itemstack) { + return false; + } } diff --git a/src/main/java/forestry/farming/logic/FarmableBasicIC2Crop.java b/src/main/java/forestry/farming/logic/FarmableBasicIC2Crop.java index 7f867df9f..c7888227a 100644 --- a/src/main/java/forestry/farming/logic/FarmableBasicIC2Crop.java +++ b/src/main/java/forestry/farming/logic/FarmableBasicIC2Crop.java @@ -10,43 +10,43 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; public class FarmableBasicIC2Crop implements IFarmable { - @Override - public boolean isSaplingAt(World world, int x, int y, int z) { - TileEntity crop = world.getTileEntity(x, y, z); - if(PluginIC2.instance.isIC2Crop(crop)) { - PluginIC2.instance.babysitCrop(crop); - return true; - } - return false; - } + @Override + public boolean isSaplingAt(World world, int x, int y, int z) { + TileEntity crop = world.getTileEntity(x, y, z); + if (PluginIC2.instance.isIC2Crop(crop)) { + PluginIC2.instance.babysitCrop(crop); + return true; + } + return false; + } - @Override - public ICrop getCropAt(World world, int x, int y, int z) { - TileEntity crop = world.getTileEntity(x, y, z); - if (crop == null) { - return null; - } - if (!PluginIC2.instance.isIC2Crop(crop)) { - return null; - } - if (!PluginIC2.instance.canHarvestCrop(crop)) { - return null; - } - return new CropBasicIC2Crop(world, crop, new Vect(x, y, z)); - } + @Override + public ICrop getCropAt(World world, int x, int y, int z) { + TileEntity crop = world.getTileEntity(x, y, z); + if (crop == null) { + return null; + } + if (!PluginIC2.instance.isIC2Crop(crop)) { + return null; + } + if (!PluginIC2.instance.canHarvestCrop(crop)) { + return null; + } + return new CropBasicIC2Crop(world, crop, new Vect(x, y, z)); + } - @Override - public boolean isGermling(ItemStack itemstack) { - return false; - } + @Override + public boolean isGermling(ItemStack itemstack) { + return false; + } - @Override - public boolean isWindfall(ItemStack itemstack) { - return false; - } + @Override + public boolean isWindfall(ItemStack itemstack) { + return false; + } - @Override - public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { - return false; - } + @Override + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return false; + } } diff --git a/src/main/java/forestry/farming/logic/FarmableCocoa.java b/src/main/java/forestry/farming/logic/FarmableCocoa.java index 1e7f840a3..159c66560 100755 --- a/src/main/java/forestry/farming/logic/FarmableCocoa.java +++ b/src/main/java/forestry/farming/logic/FarmableCocoa.java @@ -10,6 +10,10 @@ ******************************************************************************/ package forestry.farming.logic; +import forestry.api.farming.ICrop; +import forestry.api.farming.IFarmableBasic; +import forestry.core.utils.BlockUtil; +import forestry.core.utils.vect.Vect; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; @@ -18,49 +22,43 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import forestry.api.farming.ICrop; -import forestry.api.farming.IFarmableBasic; -import forestry.core.utils.BlockUtil; -import forestry.core.utils.vect.Vect; - public class FarmableCocoa implements IFarmableBasic { - private static final Block COCOA_PLANT = Blocks.cocoa; - public static final Item COCOA_SEED = Items.dye; - public static final int COCOA_META = 3; + private static final Block COCOA_PLANT = Blocks.cocoa; + public static final Item COCOA_SEED = Items.dye; + public static final int COCOA_META = 3; - @Override - public boolean isSapling(Block block, int meta) { - return block == COCOA_PLANT; - } + @Override + public boolean isSapling(Block block, int meta) { + return block == COCOA_PLANT; + } - @Override - public ICrop getCropAt(World world, int x, int y, int z) { - Block block = world.getBlock(x, y, z); - if (block != COCOA_PLANT) { - return null; - } - int meta = world.getBlockMetadata(x, y, z); - if (BlockUtil.getMaturityPod(meta) < 2) { - return null; - } + @Override + public ICrop getCropAt(World world, int x, int y, int z) { + Block block = world.getBlock(x, y, z); + if (block != COCOA_PLANT) { + return null; + } + int meta = world.getBlockMetadata(x, y, z); + if (BlockUtil.getMaturityPod(meta) < 2) { + return null; + } - return new CropBlock(world, block, meta, new Vect(x, y, z)); - } + return new CropBlock(world, block, meta, new Vect(x, y, z)); + } - @Override - public boolean isGermling(ItemStack itemstack) { - return itemstack.getItem() == COCOA_SEED && itemstack.getItemDamage() == COCOA_META; - } + @Override + public boolean isGermling(ItemStack itemstack) { + return itemstack.getItem() == COCOA_SEED && itemstack.getItemDamage() == COCOA_META; + } - @Override - public boolean isWindfall(ItemStack itemstack) { - return false; - } - - @Override - public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { - return BlockUtil.tryPlantPot(world, x, y, z, COCOA_PLANT); - } + @Override + public boolean isWindfall(ItemStack itemstack) { + return false; + } + @Override + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return BlockUtil.tryPlantPot(world, x, y, z, COCOA_PLANT); + } } diff --git a/src/main/java/forestry/farming/logic/FarmableGE.java b/src/main/java/forestry/farming/logic/FarmableGE.java index e55e7ea23..0627bf368 100755 --- a/src/main/java/forestry/farming/logic/FarmableGE.java +++ b/src/main/java/forestry/farming/logic/FarmableGE.java @@ -10,49 +10,47 @@ ******************************************************************************/ package forestry.farming.logic; -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.farming.ICrop; import forestry.api.farming.IFarmableBasic; import forestry.arboriculture.genetics.TreeGenome; import forestry.core.utils.vect.Vect; import forestry.plugins.PluginArboriculture; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; public class FarmableGE implements IFarmableBasic { - @Override - public boolean isSapling(Block block, int meta) { - return PluginArboriculture.blocks.saplingGE == block; - } + @Override + public boolean isSapling(Block block, int meta) { + return PluginArboriculture.blocks.saplingGE == block; + } - @Override - public ICrop getCropAt(World world, int x, int y, int z) { - Block block = world.getBlock(x, y, z); + @Override + public ICrop getCropAt(World world, int x, int y, int z) { + Block block = world.getBlock(x, y, z); - if (!block.isWood(world, x, y, z)) { - return null; - } + if (!block.isWood(world, x, y, z)) { + return null; + } - return new CropBlock(world, block, world.getBlockMetadata(x, y, z), new Vect(x, y, z)); - } + return new CropBlock(world, block, world.getBlockMetadata(x, y, z), new Vect(x, y, z)); + } - @Override - public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { - return germling.copy().tryPlaceItemIntoWorld(player, world, x, y - 1, z, 1, 0, 0, 0); - } + @Override + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return germling.copy().tryPlaceItemIntoWorld(player, world, x, y - 1, z, 1, 0, 0, 0); + } - @Override - public boolean isGermling(ItemStack itemstack) { - IAlleleTreeSpecies tree = TreeGenome.getSpecies(itemstack); - return tree != null; - } - - @Override - public boolean isWindfall(ItemStack itemstack) { - return false; - } + @Override + public boolean isGermling(ItemStack itemstack) { + IAlleleTreeSpecies tree = TreeGenome.getSpecies(itemstack); + return tree != null; + } + @Override + public boolean isWindfall(ItemStack itemstack) { + return false; + } } diff --git a/src/main/java/forestry/farming/logic/FarmableGenericCrop.java b/src/main/java/forestry/farming/logic/FarmableGenericCrop.java index 77642863b..fdf7cc794 100755 --- a/src/main/java/forestry/farming/logic/FarmableGenericCrop.java +++ b/src/main/java/forestry/farming/logic/FarmableGenericCrop.java @@ -10,72 +10,70 @@ ******************************************************************************/ package forestry.farming.logic; +import forestry.api.farming.ICrop; +import forestry.api.farming.IFarmableBasic; +import forestry.core.utils.vect.Vect; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import forestry.api.farming.ICrop; -import forestry.api.farming.IFarmableBasic; -import forestry.core.utils.vect.Vect; - public class FarmableGenericCrop implements IFarmableBasic { - private final ItemStack seed; - private final Block block; - private final int mature; - private final ItemStack[] windfall; + private final ItemStack seed; + private final Block block; + private final int mature; + private final ItemStack[] windfall; - public FarmableGenericCrop(ItemStack seed, Block block, int mature, ItemStack... windfall) { - this.seed = seed; - this.block = block; - this.mature = mature; - this.windfall = windfall; - } + public FarmableGenericCrop(ItemStack seed, Block block, int mature, ItemStack... windfall) { + this.seed = seed; + this.block = block; + this.mature = mature; + this.windfall = windfall; + } - @Override - public boolean isSapling(Block block, int meta) { - return this.block == block; - } + @Override + public boolean isSapling(Block block, int meta) { + return this.block == block; + } - @Override - public ICrop getCropAt(World world, int x, int y, int z) { - if (world.getBlock(x, y, z) != block) { - return null; - } - if (world.getBlockMetadata(x, y, z) != mature) { - return null; - } + @Override + public ICrop getCropAt(World world, int x, int y, int z) { + if (world.getBlock(x, y, z) != block) { + return null; + } + if (world.getBlockMetadata(x, y, z) != mature) { + return null; + } - return new CropBlock(world, block, mature, new Vect(x, y, z)); - } + return new CropBlock(world, block, mature, new Vect(x, y, z)); + } - @Override - public boolean isGermling(ItemStack itemstack) { - if (seed.getItem() != itemstack.getItem()) { - return false; - } + @Override + public boolean isGermling(ItemStack itemstack) { + if (seed.getItem() != itemstack.getItem()) { + return false; + } - if (seed.getItemDamage() >= 0) { - return seed.getItemDamage() == itemstack.getItemDamage(); - } else { - return true; - } - } + if (seed.getItemDamage() >= 0) { + return seed.getItemDamage() == itemstack.getItemDamage(); + } else { + return true; + } + } - @Override - public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { - return germling.copy().tryPlaceItemIntoWorld(player, world, x, y - 1, z, 1, 0, 0, 0); - } - - @Override - public boolean isWindfall(ItemStack itemstack) { - for (ItemStack drop : windfall) { - if (drop.isItemEqual(itemstack)) { - return true; - } - } - return false; - } + @Override + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return germling.copy().tryPlaceItemIntoWorld(player, world, x, y - 1, z, 1, 0, 0, 0); + } + @Override + public boolean isWindfall(ItemStack itemstack) { + for (ItemStack drop : windfall) { + if (drop.isItemEqual(itemstack)) { + return true; + } + } + return false; + } } diff --git a/src/main/java/forestry/farming/logic/FarmableGenericSapling.java b/src/main/java/forestry/farming/logic/FarmableGenericSapling.java index 211f03811..931eff5e7 100755 --- a/src/main/java/forestry/farming/logic/FarmableGenericSapling.java +++ b/src/main/java/forestry/farming/logic/FarmableGenericSapling.java @@ -10,75 +10,73 @@ ******************************************************************************/ package forestry.farming.logic; +import forestry.api.farming.ICrop; +import forestry.api.farming.IFarmableBasic; +import forestry.core.utils.ItemStackUtil; +import forestry.core.utils.vect.Vect; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import forestry.api.farming.ICrop; -import forestry.api.farming.IFarmableBasic; -import forestry.core.utils.ItemStackUtil; -import forestry.core.utils.vect.Vect; - public class FarmableGenericSapling implements IFarmableBasic { - protected final Block sapling; - private final int saplingMeta; - private final ItemStack[] windfall; + protected final Block sapling; + private final int saplingMeta; + private final ItemStack[] windfall; - public FarmableGenericSapling(Block sapling, int saplingMeta, ItemStack... windfall) { - this.sapling = sapling; - this.saplingMeta = saplingMeta; - this.windfall = windfall; - } + public FarmableGenericSapling(Block sapling, int saplingMeta, ItemStack... windfall) { + this.sapling = sapling; + this.saplingMeta = saplingMeta; + this.windfall = windfall; + } - @Override - public boolean isSapling(Block block, int meta) { - return block == sapling && (saplingMeta < 0 || meta == saplingMeta); - } + @Override + public boolean isSapling(Block block, int meta) { + return block == sapling && (saplingMeta < 0 || meta == saplingMeta); + } - @Override - public boolean isMetadataAware() { - return saplingMeta >= 0; - } + @Override + public boolean isMetadataAware() { + return saplingMeta >= 0; + } - @Override - public ICrop getCropAt(World world, int x, int y, int z) { - Block block = world.getBlock(x, y, z); - if (!block.isWood(world, x, y, z)) { - return null; - } + @Override + public ICrop getCropAt(World world, int x, int y, int z) { + Block block = world.getBlock(x, y, z); + if (!block.isWood(world, x, y, z)) { + return null; + } - return new CropBlock(world, block, world.getBlockMetadata(x, y, z), new Vect(x, y, z)); - } + return new CropBlock(world, block, world.getBlockMetadata(x, y, z), new Vect(x, y, z)); + } - @Override - public boolean isGermling(ItemStack itemstack) { + @Override + public boolean isGermling(ItemStack itemstack) { - if (!ItemStackUtil.equals(sapling, itemstack)) { - return false; - } + if (!ItemStackUtil.equals(sapling, itemstack)) { + return false; + } - if (saplingMeta >= 0) { - return itemstack.getItemDamage() == saplingMeta; - } else { - return true; - } - } + if (saplingMeta >= 0) { + return itemstack.getItemDamage() == saplingMeta; + } else { + return true; + } + } - @Override - public boolean isWindfall(ItemStack itemstack) { - for (ItemStack drop : windfall) { - if (drop.isItemEqual(itemstack)) { - return true; - } - } - return false; - } - - @Override - public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { - return germling.copy().tryPlaceItemIntoWorld(player, world, x, y - 1, z, 1, 0, 0, 0); - } + @Override + public boolean isWindfall(ItemStack itemstack) { + for (ItemStack drop : windfall) { + if (drop.isItemEqual(itemstack)) { + return true; + } + } + return false; + } + @Override + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return germling.copy().tryPlaceItemIntoWorld(player, world, x, y - 1, z, 1, 0, 0, 0); + } } diff --git a/src/main/java/forestry/farming/logic/FarmableGourd.java b/src/main/java/forestry/farming/logic/FarmableGourd.java index 7c780d858..533f2ca4f 100755 --- a/src/main/java/forestry/farming/logic/FarmableGourd.java +++ b/src/main/java/forestry/farming/logic/FarmableGourd.java @@ -10,64 +10,62 @@ ******************************************************************************/ package forestry.farming.logic; -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import forestry.api.farming.ICrop; import forestry.api.farming.IFarmableBasic; import forestry.core.config.Constants; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.vect.Vect; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; public class FarmableGourd implements IFarmableBasic { - private final ItemStack seed; - private final ItemStack stem; - private final ItemStack fruit; + private final ItemStack seed; + private final ItemStack stem; + private final ItemStack fruit; - public FarmableGourd(ItemStack seed, ItemStack stem, ItemStack fruit) { - this.seed = seed; - this.stem = stem; - this.fruit = fruit; - } + public FarmableGourd(ItemStack seed, ItemStack stem, ItemStack fruit) { + this.seed = seed; + this.stem = stem; + this.fruit = fruit; + } - @Override - public boolean isSapling(Block block, int meta) { - return ItemStackUtil.equals(block, stem); - } + @Override + public boolean isSapling(Block block, int meta) { + return ItemStackUtil.equals(block, stem); + } - @Override - public ICrop getCropAt(World world, int x, int y, int z) { - if (world.isAirBlock(x, y, z)) { - return null; - } + @Override + public ICrop getCropAt(World world, int x, int y, int z) { + if (world.isAirBlock(x, y, z)) { + return null; + } - if (!ItemStackUtil.equals(world.getBlock(x, y, z), fruit)) { - return null; - } + if (!ItemStackUtil.equals(world.getBlock(x, y, z), fruit)) { + return null; + } - if (world.getBlockMetadata(x, y, z) != fruit.getItemDamage()) { - return null; - } + if (world.getBlockMetadata(x, y, z) != fruit.getItemDamage()) { + return null; + } - return new CropBlock(world, ItemStackUtil.getBlock(fruit), fruit.getItemDamage(), new Vect(x, y, z)); - } + return new CropBlock(world, ItemStackUtil.getBlock(fruit), fruit.getItemDamage(), new Vect(x, y, z)); + } - @Override - public boolean isGermling(ItemStack itemstack) { - return seed.isItemEqual(itemstack); - } + @Override + public boolean isGermling(ItemStack itemstack) { + return seed.isItemEqual(itemstack); + } - @Override - public boolean isWindfall(ItemStack itemstack) { - return false; - } - - @Override - public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { - return world.setBlock(x, y, z, ItemStackUtil.getBlock(stem), 0, Constants.FLAG_BLOCK_SYNCH); - } + @Override + public boolean isWindfall(ItemStack itemstack) { + return false; + } + @Override + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return world.setBlock(x, y, z, ItemStackUtil.getBlock(stem), 0, Constants.FLAG_BLOCK_SYNCH); + } } diff --git a/src/main/java/forestry/farming/logic/FarmableReference.java b/src/main/java/forestry/farming/logic/FarmableReference.java index af851b770..9c64c8848 100644 --- a/src/main/java/forestry/farming/logic/FarmableReference.java +++ b/src/main/java/forestry/farming/logic/FarmableReference.java @@ -24,7 +24,6 @@ public enum FarmableReference { Shroom, Succulentes, Vegetables, - ; private final String VALUE; diff --git a/src/main/java/forestry/farming/logic/FarmableStacked.java b/src/main/java/forestry/farming/logic/FarmableStacked.java index 07a713a53..cc172edfa 100755 --- a/src/main/java/forestry/farming/logic/FarmableStacked.java +++ b/src/main/java/forestry/farming/logic/FarmableStacked.java @@ -10,55 +10,53 @@ ******************************************************************************/ package forestry.farming.logic; -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import forestry.api.farming.ICrop; import forestry.api.farming.IFarmableBasic; import forestry.core.config.Constants; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.vect.Vect; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; public class FarmableStacked implements IFarmableBasic { - private final Block block; - private final int matureHeight; - private final int matureMeta; + private final Block block; + private final int matureHeight; + private final int matureMeta; - public FarmableStacked(Block block, int matureHeight, int matureMeta) { - this.block = block; - this.matureHeight = matureHeight; - this.matureMeta = matureMeta; - } + public FarmableStacked(Block block, int matureHeight, int matureMeta) { + this.block = block; + this.matureHeight = matureHeight; + this.matureMeta = matureMeta; + } - @Override - public boolean isSapling(Block block, int meta) { - return this.block == block; - } + @Override + public boolean isSapling(Block block, int meta) { + return this.block == block; + } - @Override - public ICrop getCropAt(World world, int x, int y, int z) { - if (world.getBlock(x, y + (matureHeight - 1), z) != block) { - return null; - } - return new CropBlock(world, block, matureMeta, new Vect(x, y + (matureHeight - 1), z)); - } + @Override + public ICrop getCropAt(World world, int x, int y, int z) { + if (world.getBlock(x, y + (matureHeight - 1), z) != block) { + return null; + } + return new CropBlock(world, block, matureMeta, new Vect(x, y + (matureHeight - 1), z)); + } - @Override - public boolean isGermling(ItemStack itemstack) { - return ItemStackUtil.equals(block, itemstack); - } + @Override + public boolean isGermling(ItemStack itemstack) { + return ItemStackUtil.equals(block, itemstack); + } - @Override - public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { - return world.setBlock(x, y, z, block, 0, Constants.FLAG_BLOCK_SYNCH); - } - - @Override - public boolean isWindfall(ItemStack itemstack) { - return false; - } + @Override + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + return world.setBlock(x, y, z, block, 0, Constants.FLAG_BLOCK_SYNCH); + } + @Override + public boolean isWindfall(ItemStack itemstack) { + return false; + } } diff --git a/src/main/java/forestry/farming/logic/FarmableVanillaMushroom.java b/src/main/java/forestry/farming/logic/FarmableVanillaMushroom.java index 605b90d23..3e47083a6 100644 --- a/src/main/java/forestry/farming/logic/FarmableVanillaMushroom.java +++ b/src/main/java/forestry/farming/logic/FarmableVanillaMushroom.java @@ -10,49 +10,48 @@ ******************************************************************************/ package forestry.farming.logic; -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import forestry.api.farming.ICrop; import forestry.core.config.Constants; import forestry.core.proxy.Proxies; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.vect.Vect; import forestry.plugins.PluginFarming; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; public class FarmableVanillaMushroom extends FarmableGenericSapling { - public FarmableVanillaMushroom(Block sapling, int saplingMeta) { - super(sapling, saplingMeta); - } + public FarmableVanillaMushroom(Block sapling, int saplingMeta) { + super(sapling, saplingMeta); + } - @Override - public ICrop getCropAt(World world, int x, int y, int z) { - Block block = world.getBlock(x, y, z); + @Override + public ICrop getCropAt(World world, int x, int y, int z) { + Block block = world.getBlock(x, y, z); - if (block != Blocks.brown_mushroom_block && block != Blocks.red_mushroom_block) { - return null; - } + if (block != Blocks.brown_mushroom_block && block != Blocks.red_mushroom_block) { + return null; + } - return new CropBlock(world, block, world.getBlockMetadata(x, y, z), new Vect(x, y, z)); - } + return new CropBlock(world, block, world.getBlockMetadata(x, y, z), new Vect(x, y, z)); + } - @Override - public boolean isGermling(ItemStack itemstack) { - return ItemStackUtil.equals(sapling, itemstack); - } + @Override + public boolean isGermling(ItemStack itemstack) { + return ItemStackUtil.equals(sapling, itemstack); + } - @Override - public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { - int meta = 0; - if (ItemStackUtil.equals(Blocks.red_mushroom, germling)) { - meta = 1; - } + @Override + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + int meta = 0; + if (ItemStackUtil.equals(Blocks.red_mushroom, germling)) { + meta = 1; + } - Proxies.common.addBlockPlaceEffects(world, x, y, z, Blocks.brown_mushroom, 0); - return world.setBlock(x, y, z, PluginFarming.blocks.mushroom, meta, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); - } + Proxies.common.addBlockPlaceEffects(world, x, y, z, Blocks.brown_mushroom, 0); + return world.setBlock(x, y, z, PluginFarming.blocks.mushroom, meta, Constants.FLAG_BLOCK_SYNCH_AND_UPDATE); + } } diff --git a/src/main/java/forestry/farming/logic/FarmableVanillaSapling.java b/src/main/java/forestry/farming/logic/FarmableVanillaSapling.java index 0e9e12f75..a1112f088 100755 --- a/src/main/java/forestry/farming/logic/FarmableVanillaSapling.java +++ b/src/main/java/forestry/farming/logic/FarmableVanillaSapling.java @@ -10,36 +10,38 @@ ******************************************************************************/ package forestry.farming.logic; +import forestry.api.arboriculture.ITree; +import forestry.api.arboriculture.TreeManager; +import forestry.api.genetics.IIndividual; +import forestry.core.utils.GeneticsUtil; +import forestry.plugins.PluginManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import forestry.api.arboriculture.ITree; -import forestry.api.arboriculture.TreeManager; -import forestry.api.genetics.IIndividual; -import forestry.core.utils.GeneticsUtil; -import forestry.plugins.PluginManager; - public class FarmableVanillaSapling extends FarmableGenericSapling { - public FarmableVanillaSapling() { - super(Blocks.sapling, -1, new ItemStack(Items.apple), new ItemStack(FarmableCocoa.COCOA_SEED, 1, FarmableCocoa.COCOA_META)); - } + public FarmableVanillaSapling() { + super( + Blocks.sapling, + -1, + new ItemStack(Items.apple), + new ItemStack(FarmableCocoa.COCOA_SEED, 1, FarmableCocoa.COCOA_META)); + } - @Override - public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { - if (PluginManager.Module.ARBORICULTURE.isEnabled()) { - IIndividual tree = GeneticsUtil.getGeneticEquivalent(germling); - if (!(tree instanceof ITree)) { - return false; - } - - return TreeManager.treeRoot.plantSapling(world, (ITree) tree, player.getGameProfile(), x, y, z); - } else { - return germling.copy().tryPlaceItemIntoWorld(player, world, x, y - 1, z, 1, 0, 0, 0); - } - } + @Override + public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, int x, int y, int z) { + if (PluginManager.Module.ARBORICULTURE.isEnabled()) { + IIndividual tree = GeneticsUtil.getGeneticEquivalent(germling); + if (!(tree instanceof ITree)) { + return false; + } + return TreeManager.treeRoot.plantSapling(world, (ITree) tree, player.getGameProfile(), x, y, z); + } else { + return germling.copy().tryPlaceItemIntoWorld(player, world, x, y - 1, z, 1, 0, 0, 0); + } + } } diff --git a/src/main/java/forestry/farming/multiblock/FakeFarmController.java b/src/main/java/forestry/farming/multiblock/FakeFarmController.java index 3c786ab73..026ac9d69 100644 --- a/src/main/java/forestry/farming/multiblock/FakeFarmController.java +++ b/src/main/java/forestry/farming/multiblock/FakeFarmController.java @@ -1,221 +1,202 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.multiblock; - -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.circuits.CircuitSocketType; -import forestry.api.circuits.ICircuitSocketType; -import forestry.api.farming.FarmDirection; -import forestry.api.farming.IFarmInventory; -import forestry.api.farming.IFarmLogic; -import forestry.api.farming.IFarmable; -import forestry.core.fluids.FakeTankManager; -import forestry.core.fluids.ITankManager; -import forestry.core.inventory.FakeInventoryAdapter; -import forestry.core.inventory.IInventoryAdapter; -import forestry.core.multiblock.FakeMultiblockController; -import forestry.farming.gui.IFarmLedgerDelegate; - -import io.netty.util.internal.EmptyArrays; - -public class FakeFarmController extends FakeMultiblockController implements IFarmControllerInternal { - public static final FakeFarmController instance = new FakeFarmController(); - - private FakeFarmController() { - - } - - @Override - public int[] getCoords() { - return EmptyArrays.EMPTY_INTS; - } - - @Override - public int[] getArea() { - return EmptyArrays.EMPTY_INTS; - } - - @Override - public int[] getOffset() { - return EmptyArrays.EMPTY_INTS; - } - - @Override - public boolean doWork() { - return false; - } - - @Override - public boolean hasLiquid(FluidStack liquid) { - return false; - } - - @Override - public void removeLiquid(FluidStack liquid) { - - } - - @Override - public boolean plantGermling(IFarmable farmable, World world, int x, int y, int z) { - return false; - } - - @Override - public IFarmInventory getFarmInventory() { - return FakeFarmInventory.instance; - } - - @Override - public void setFarmLogic(FarmDirection direction, IFarmLogic logic) { - - } - - @Override - public IFarmLogic getFarmLogic(FarmDirection direction) { - return null; - } - - @Override - public void resetFarmLogic(FarmDirection direction) { - - } - - @Override - public int getStoredFertilizerScaled(int scale) { - return 0; - } - - @Override - public int getSocketCount() { - return 0; - } - - @Override - public ItemStack getSocket(int slot) { - return null; - } - - @Override - public void setSocket(int slot, ItemStack stack) { - - } - - @Override - public ICircuitSocketType getSocketType() { - return CircuitSocketType.NONE; - } - - @Override - public IFarmLedgerDelegate getFarmLedgerDelegate() { - return FakeFarmLedgerDelegate.instance; - } - - @Override - public IInventoryAdapter getInternalInventory() { - return FakeInventoryAdapter.instance(); - } - - @Override - public ITankManager getTankManager() { - return FakeTankManager.instance; - } - - private static class FakeFarmInventory implements IFarmInventory { - public static final FakeFarmInventory instance = new FakeFarmInventory(); - - private FakeFarmInventory() { - - } - - @Override - public boolean hasResources(ItemStack[] resources) { - return false; - } - - @Override - public void removeResources(ItemStack[] resources) { - - } - - @Override - public boolean acceptsAsGermling(ItemStack itemstack) { - return false; - } - - @Override - public boolean acceptsAsResource(ItemStack itemstack) { - return false; - } - - @Override - public boolean acceptsAsFertilizer(ItemStack itemstack) { - return false; - } - - @Override - public IInventory getProductInventory() { - return FakeInventoryAdapter.instance(); - } - - @Override - public IInventory getGermlingsInventory() { - return FakeInventoryAdapter.instance(); - } - - @Override - public IInventory getResourcesInventory() { - return FakeInventoryAdapter.instance(); - } - - @Override - public IInventory getFertilizerInventory() { - return FakeInventoryAdapter.instance(); - } - } - - private static class FakeFarmLedgerDelegate implements IFarmLedgerDelegate { - public static final FakeFarmLedgerDelegate instance = new FakeFarmLedgerDelegate(); - - private FakeFarmLedgerDelegate() { - - } - - @Override - public float getHydrationModifier() { - return 0; - } - - @Override - public float getHydrationTempModifier() { - return 0; - } - - @Override - public float getHydrationHumidModifier() { - return 0; - } - - @Override - public float getHydrationRainfallModifier() { - return 0; - } - - @Override - public double getDrought() { - return 0; - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.multiblock; + +import forestry.api.circuits.CircuitSocketType; +import forestry.api.circuits.ICircuitSocketType; +import forestry.api.farming.FarmDirection; +import forestry.api.farming.IFarmInventory; +import forestry.api.farming.IFarmLogic; +import forestry.api.farming.IFarmable; +import forestry.core.fluids.FakeTankManager; +import forestry.core.fluids.ITankManager; +import forestry.core.inventory.FakeInventoryAdapter; +import forestry.core.inventory.IInventoryAdapter; +import forestry.core.multiblock.FakeMultiblockController; +import forestry.farming.gui.IFarmLedgerDelegate; +import io.netty.util.internal.EmptyArrays; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraftforge.fluids.FluidStack; + +public class FakeFarmController extends FakeMultiblockController implements IFarmControllerInternal { + public static final FakeFarmController instance = new FakeFarmController(); + + private FakeFarmController() {} + + @Override + public int[] getCoords() { + return EmptyArrays.EMPTY_INTS; + } + + @Override + public int[] getArea() { + return EmptyArrays.EMPTY_INTS; + } + + @Override + public int[] getOffset() { + return EmptyArrays.EMPTY_INTS; + } + + @Override + public boolean doWork() { + return false; + } + + @Override + public boolean hasLiquid(FluidStack liquid) { + return false; + } + + @Override + public void removeLiquid(FluidStack liquid) {} + + @Override + public boolean plantGermling(IFarmable farmable, World world, int x, int y, int z) { + return false; + } + + @Override + public IFarmInventory getFarmInventory() { + return FakeFarmInventory.instance; + } + + @Override + public void setFarmLogic(FarmDirection direction, IFarmLogic logic) {} + + @Override + public IFarmLogic getFarmLogic(FarmDirection direction) { + return null; + } + + @Override + public void resetFarmLogic(FarmDirection direction) {} + + @Override + public int getStoredFertilizerScaled(int scale) { + return 0; + } + + @Override + public int getSocketCount() { + return 0; + } + + @Override + public ItemStack getSocket(int slot) { + return null; + } + + @Override + public void setSocket(int slot, ItemStack stack) {} + + @Override + public ICircuitSocketType getSocketType() { + return CircuitSocketType.NONE; + } + + @Override + public IFarmLedgerDelegate getFarmLedgerDelegate() { + return FakeFarmLedgerDelegate.instance; + } + + @Override + public IInventoryAdapter getInternalInventory() { + return FakeInventoryAdapter.instance(); + } + + @Override + public ITankManager getTankManager() { + return FakeTankManager.instance; + } + + private static class FakeFarmInventory implements IFarmInventory { + public static final FakeFarmInventory instance = new FakeFarmInventory(); + + private FakeFarmInventory() {} + + @Override + public boolean hasResources(ItemStack[] resources) { + return false; + } + + @Override + public void removeResources(ItemStack[] resources) {} + + @Override + public boolean acceptsAsGermling(ItemStack itemstack) { + return false; + } + + @Override + public boolean acceptsAsResource(ItemStack itemstack) { + return false; + } + + @Override + public boolean acceptsAsFertilizer(ItemStack itemstack) { + return false; + } + + @Override + public IInventory getProductInventory() { + return FakeInventoryAdapter.instance(); + } + + @Override + public IInventory getGermlingsInventory() { + return FakeInventoryAdapter.instance(); + } + + @Override + public IInventory getResourcesInventory() { + return FakeInventoryAdapter.instance(); + } + + @Override + public IInventory getFertilizerInventory() { + return FakeInventoryAdapter.instance(); + } + } + + private static class FakeFarmLedgerDelegate implements IFarmLedgerDelegate { + public static final FakeFarmLedgerDelegate instance = new FakeFarmLedgerDelegate(); + + private FakeFarmLedgerDelegate() {} + + @Override + public float getHydrationModifier() { + return 0; + } + + @Override + public float getHydrationTempModifier() { + return 0; + } + + @Override + public float getHydrationHumidModifier() { + return 0; + } + + @Override + public float getHydrationRainfallModifier() { + return 0; + } + + @Override + public double getDrought() { + return 0; + } + } +} diff --git a/src/main/java/forestry/farming/multiblock/FarmController.java b/src/main/java/forestry/farming/multiblock/FarmController.java index 0e4f76a90..f2e013cff 100644 --- a/src/main/java/forestry/farming/multiblock/FarmController.java +++ b/src/main/java/forestry/farming/multiblock/FarmController.java @@ -1,861 +1,890 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.multiblock; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.StatCollector; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - -import forestry.api.circuits.ChipsetManager; -import forestry.api.circuits.CircuitSocketType; -import forestry.api.circuits.ICircuitBoard; -import forestry.api.circuits.ICircuitSocketType; -import forestry.api.core.EnumHumidity; -import forestry.api.core.EnumTemperature; -import forestry.api.core.IErrorLogic; -import forestry.api.farming.FarmDirection; -import forestry.api.farming.ICrop; -import forestry.api.farming.IFarmInventory; -import forestry.api.farming.IFarmListener; -import forestry.api.farming.IFarmLogic; -import forestry.api.farming.IFarmable; -import forestry.api.multiblock.IFarmComponent; -import forestry.api.multiblock.IMultiblockComponent; -import forestry.core.access.EnumAccess; -import forestry.core.config.Config; -import forestry.core.config.Constants; -import forestry.core.errors.EnumErrorCode; -import forestry.core.fluids.Fluids; -import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.FilteredTank; -import forestry.core.fluids.tanks.StandardTank; -import forestry.core.inventory.FakeInventoryAdapter; -import forestry.core.inventory.IInventoryAdapter; -import forestry.core.inventory.InventoryAdapter; -import forestry.core.multiblock.IMultiblockControllerInternal; -import forestry.core.multiblock.MultiblockValidationException; -import forestry.core.multiblock.RectangularMultiblockControllerBase; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.tiles.ILiquidTankTile; -import forestry.core.utils.Log; -import forestry.core.utils.PlayerUtil; -import forestry.core.utils.vect.Vect; -import forestry.core.utils.vect.VectUtil; -import forestry.farming.FarmHelper; -import forestry.farming.FarmTarget; -import forestry.farming.gui.IFarmLedgerDelegate; -import forestry.farming.logic.FarmLogicArboreal; -import forestry.farming.tiles.TileFarmGearbox; -import forestry.farming.tiles.TileFarmPlain; - -public class FarmController extends RectangularMultiblockControllerBase implements IFarmControllerInternal, ILiquidTankTile { - - private enum Stage { - CULTIVATE, HARVEST; - - public Stage next() { - if (this == CULTIVATE) { - return HARVEST; - } else { - return CULTIVATE; - } - } - } - - private static FarmDirection getLayoutDirection(FarmDirection farmSide) { - switch (farmSide) { - case NORTH: - return FarmDirection.WEST; - case WEST: - return FarmDirection.SOUTH; - case SOUTH: - return FarmDirection.EAST; - case EAST: - return FarmDirection.NORTH; - } - return null; - } - - private final Map> targets = new EnumMap<>(FarmDirection.class); - private int allowedExtent = 0; - - private IFarmLogic harvestProvider; // The farm logic which supplied the pending crops. - private final Stack pendingCrops = new Stack<>(); - private final Stack pendingProduce = new Stack<>(); - - private Stage stage = Stage.CULTIVATE; - - // active components are stored with a tick offset so they do not all tick together - private final Map farmActiveComponents = new HashMap<>(); - private final Set farmListeners = new HashSet<>(); - - private final Map farmLogics = new EnumMap<>(FarmDirection.class); - - private final InventoryAdapter sockets; - private final InventoryFarm inventory; - private final TankManager tankManager; - private final StandardTank resourceTank; - private final FarmHydrationManager hydrationManager; - private final FarmFertilizerManager fertilizerManager; - - // the number of work ticks that this farm has had no power - private int noPowerTime = 0; - - // tick updates can come from multiple gearboxes so keep track of them here - private int farmWorkTicks = 0; - - private BiomeGenBase cachedBiome; - - public FarmController(World world) { - super(world, FarmMultiblockSizeLimits.instance); - - this.resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, FluidRegistry.WATER); - this.tankManager = new TankManager(this, resourceTank); - - this.inventory = new InventoryFarm(this); - this.sockets = new InventoryAdapter(1, "sockets"); - this.hydrationManager = new FarmHydrationManager(this); - this.fertilizerManager = new FarmFertilizerManager(); - - refreshFarmLogics(); - } - - @Override - public IFarmLedgerDelegate getFarmLedgerDelegate() { - return hydrationManager; - } - - @Override - public IInventoryAdapter getInternalInventory() { - if (isAssembled()) { - return inventory; - } else { - return FakeInventoryAdapter.instance(); - } - } - - @Override - public TankManager getTankManager() { - return tankManager; - } - - private BiomeGenBase getBiome() { - if (cachedBiome == null) { - ChunkCoordinates coords = getReferenceCoord(); - cachedBiome = worldObj.getBiomeGenForCoords(coords.posX, coords.posZ); - } - return cachedBiome; - } - - @Override - public void onAttachedPartWithMultiblockData(IMultiblockComponent part, NBTTagCompound data) { - this.readFromNBT(data); - } - - @Override - protected void onBlockAdded(IMultiblockComponent newPart) { - if (newPart instanceof IFarmComponent.Listener) { - IFarmComponent.Listener listenerPart = (IFarmComponent.Listener) newPart; - farmListeners.add(listenerPart.getFarmListener()); - } - - if (newPart instanceof IFarmComponent.Active) { - farmActiveComponents.put((IFarmComponent.Active) newPart, worldObj.rand.nextInt(256)); - } - } - - @Override - protected void onBlockRemoved(IMultiblockComponent oldPart) { - if (oldPart instanceof IFarmComponent.Listener) { - IFarmComponent.Listener listenerPart = (IFarmComponent.Listener) oldPart; - farmListeners.remove(listenerPart.getFarmListener()); - } - - if (oldPart instanceof IFarmComponent.Active) { - farmActiveComponents.remove(oldPart); - } - } - - @Override - protected void isMachineWhole() throws MultiblockValidationException { - super.isMachineWhole(); - - boolean hasGearbox = false; - for (IMultiblockComponent part : connectedParts) { - if (part instanceof TileFarmGearbox) { - hasGearbox = true; - break; - } - } - - if (!hasGearbox) { - throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.farm.error.needGearbox")); - } - } - - @Override - protected void onMachineDisassembled() { - super.onMachineDisassembled(); - targets.clear(); - } - - @Override - public void isGoodForExteriorLevel(IMultiblockComponent part, int level) throws MultiblockValidationException { - if (level == 2 && !(part instanceof TileFarmPlain)) { - throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.farm.error.needPlainBand")); - } - } - - @Override - public void isGoodForInterior(IMultiblockComponent part) throws MultiblockValidationException { - if (!(part instanceof TileFarmPlain)) { - throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.farm.error.needPlainInterior")); - } - } - - @Override - public void onAssimilate(IMultiblockControllerInternal assimilated) { - - } - - @Override - public void onAssimilated(IMultiblockControllerInternal assimilator) { - - } - - @Override - protected boolean updateServer(int tickCount) { - hydrationManager.updateServer(worldObj, getBiome()); - - if (updateOnInterval(20)) { - inventory.drainCan(tankManager); - } - - boolean hasPower = false; - for (Map.Entry entry : farmActiveComponents.entrySet()) { - IFarmComponent.Active farmComponent = entry.getKey(); - if (farmComponent instanceof TileFarmGearbox) { - hasPower |= ((TileFarmGearbox) farmComponent).getEnergyManager().getTotalEnergyStored() > 0; - } - - int tickOffset = entry.getValue(); - farmComponent.updateServer(tickCount + tickOffset); - } - - if (hasPower) { - noPowerTime = 0; - getErrorLogic().setCondition(false, EnumErrorCode.NO_POWER); - } else { - if (noPowerTime <= 4) { - noPowerTime++; - } else { - getErrorLogic().setCondition(true, EnumErrorCode.NO_POWER); - } - } - - //FIXME: be smarter about the farm needing to save - return true; - } - - @Override - protected void updateClient(int tickCount) { - for (Map.Entry entry : farmActiveComponents.entrySet()) { - IFarmComponent.Active farmComponent = entry.getKey(); - int tickOffset = entry.getValue(); - farmComponent.updateClient(tickCount + tickOffset); - } - } - - @Override - public void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - sockets.writeToNBT(data); - hydrationManager.writeToNBT(data); - tankManager.writeToNBT(data); - fertilizerManager.writeToNBT(data); - inventory.writeToNBT(data); - } - - @Override - public void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - sockets.readFromNBT(data); - hydrationManager.readFromNBT(data); - tankManager.readFromNBT(data); - fertilizerManager.readFromNBT(data); - inventory.readFromNBT(data); - - refreshFarmLogics(); - } - - @Override - public void formatDescriptionPacket(NBTTagCompound data) { - sockets.writeToNBT(data); - hydrationManager.writeToNBT(data); - tankManager.writeToNBT(data); - fertilizerManager.writeToNBT(data); - } - - @Override - public void decodeDescriptionPacket(NBTTagCompound data) { - sockets.readFromNBT(data); - hydrationManager.readFromNBT(data); - tankManager.readFromNBT(data); - fertilizerManager.readFromNBT(data); - - refreshFarmLogics(); - } - - @Override - public ChunkCoordinates getCoordinates() { - ChunkCoordinates coord = getReferenceCoord(); - return new ChunkCoordinates(coord); - } - - @Override - public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { - if (oldAccess == EnumAccess.SHARED || newAccess == EnumAccess.SHARED) { - // pipes connected to this need to update - for (IMultiblockComponent part : connectedParts) { - if (part instanceof TileEntity) { - TileEntity tile = (TileEntity) part; - tile.getWorldObj().notifyBlocksOfNeighborChange(tile.xCoord, tile.yCoord, tile.zCoord, tile.getBlockType()); - } - } - markDirty(); - } - } - - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - tankManager.writeData(data); - hydrationManager.writeData(data); - fertilizerManager.writeData(data); - } - - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - tankManager.readData(data); - hydrationManager.readData(data); - fertilizerManager.readData(data); - } - - private void refreshFarmLogics() { - for (FarmDirection direction : FarmDirection.values()) { - resetFarmLogic(direction); - } - - // See whether we have socketed stuff. - ItemStack chip = sockets.getStackInSlot(0); - if (chip != null) { - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(chip); - if (chipset != null) { - chipset.onLoad(this); - } - } - } - - @Override - public EnumTemperature getTemperature() { - ChunkCoordinates coords = getReferenceCoord(); - return EnumTemperature.getFromBiome(getBiome(), coords.posX, coords.posY, coords.posZ); - } - - @Override - public EnumHumidity getHumidity() { - return EnumHumidity.getFromValue(getExactHumidity()); - } - - @Override - public float getExactTemperature() { - ChunkCoordinates coords = getReferenceCoord(); - return getBiome().getFloatTemperature(coords.posX, coords.posY, coords.posZ); - } - - @Override - public float getExactHumidity() { - return getBiome().rainfall; - } - - private int[] coords; - private int[] offset; - private int[] area; - - @Override - public int[] getCoords() { - if (coords == null) { - ChunkCoordinates centerCoord = getCenterCoord(); - coords = new int[]{centerCoord.posX, centerCoord.posY, centerCoord.posZ}; - } - return coords; - } - - @Override - public int[] getOffset() { - if (offset == null) { - offset = new int[]{-getArea()[0] / 2, -2, -getArea()[2] / 2}; - } - return offset; - } - - @Override - public int[] getArea() { - if (area == null) { - area = new int[]{7 + (allowedExtent * 2), 13, 7 + (allowedExtent * 2)}; - } - return area; - } - - @Override - public World getWorld() { - return worldObj; - } - - @Override - public boolean doWork() { - farmWorkTicks++; - if (targets.isEmpty() || farmWorkTicks % 20 == 0) { - setUpFarmlandTargets(); - } - - IErrorLogic errorLogic = getErrorLogic(); - - if (!pendingProduce.isEmpty()) { - boolean added = inventory.tryAddPendingProduce(pendingProduce); - errorLogic.setCondition(!added, EnumErrorCode.NO_SPACE_INVENTORY); - return added; - } - - boolean hasFertilizer = fertilizerManager.maintainFertilizer(inventory); - if (errorLogic.setCondition(!hasFertilizer, EnumErrorCode.NO_FERTILIZER)) { - return false; - } - - // Cull queued crops. - if (!pendingCrops.isEmpty()) { - if (cullCrop(pendingCrops.peek(), harvestProvider)) { - pendingCrops.pop(); - return true; - } else { - return false; - } - } - - // Cultivation and collection - FarmWorkStatus farmWorkStatus = new FarmWorkStatus(); - - for (FarmDirection farmSide : FarmDirection.values()) { - - IFarmLogic logic = getFarmLogic(farmSide); - if (logic == null) { - continue; - } - - // Allow listeners to cancel this cycle. - if (isCycleCanceledByListeners(logic, farmSide, farmListeners)) { - continue; - } - - // Always try to collect windfall. - if (collectWindfall(logic)) { - farmWorkStatus.didWork = true; - } - - List farmTargets = targets.get(farmSide); - - if (stage == Stage.HARVEST) { - Collection harvested = harvestTargets(farmTargets, logic, farmListeners); - farmWorkStatus.didWork = harvested.size() > 0; - if (harvested.size() > 0) { - pendingCrops.addAll(harvested); - harvestProvider = logic; - } - } else if (stage == Stage.CULTIVATE) { - farmWorkStatus = cultivateTargets(farmWorkStatus, farmTargets, logic); - } - - if (farmWorkStatus.didWork) { - break; - } - } - - if (stage == Stage.CULTIVATE) { - errorLogic.setCondition(!farmWorkStatus.hasFarmland, EnumErrorCode.NO_FARMLAND); - errorLogic.setCondition(!farmWorkStatus.hasFertilizer, EnumErrorCode.NO_FERTILIZER); - errorLogic.setCondition(!farmWorkStatus.hasLiquid, EnumErrorCode.NO_LIQUID_FARM); - } - - // alternate between cultivation and harvest. - stage = stage.next(); - - return farmWorkStatus.didWork; - } - - private void setUpFarmlandTargets() { - Vect targetStart = new Vect(getCoords()); - - ChunkCoordinates max = getMaximumCoord(); - ChunkCoordinates min = getMinimumCoord(); - - int sizeNorthSouth = Math.abs(max.posZ - min.posZ) + 1; - int sizeEastWest = Math.abs(max.posX - min.posX) + 1; - - // Set the maximum allowed extent. - allowedExtent = Math.max(sizeNorthSouth, sizeEastWest) * Config.farmSize + 1; - - createTargets(worldObj, targets, targetStart, allowedExtent, sizeNorthSouth, sizeEastWest); - setExtents(worldObj, targets); - } - - private static void createTargets(World world, Map> targets, Vect targetStart, final int allowedExtent, final int farmSizeNorthSouth, final int farmSizeEastWest) { - - for (FarmDirection farmSide : FarmDirection.values()) { - - final int farmWidth; - if (farmSide == FarmDirection.NORTH || farmSide == FarmDirection.SOUTH) { - farmWidth = farmSizeEastWest; - } else { - farmWidth = farmSizeNorthSouth; - } - - // targets extend sideways in a pinwheel pattern around the farm, so they need to go a little extra distance - final int targetMaxLimit = allowedExtent + farmWidth; - - FarmDirection layoutDirection = getLayoutDirection(farmSide); - - Vect targetLocation = FarmHelper.getFarmMultiblockCorner(world, targetStart, farmSide, layoutDirection); - Vect firstLocation = targetLocation.add(farmSide); - Vect firstGroundPosition = getGroundPosition(world, firstLocation); - if (firstGroundPosition == null) { - continue; - } - int groundHeight = firstGroundPosition.getY(); - - List farmSideTargets = new ArrayList<>(); - for (int i = 0; i < allowedExtent; i++) { - targetLocation = targetLocation.add(farmSide); - Vect groundLocation = new Vect(targetLocation.getX(), groundHeight, targetLocation.getZ()); - - int targetLimit = targetMaxLimit; - if (!Config.squareFarms) { - targetLimit = targetMaxLimit - i - 1; - } - - Block platform = VectUtil.getBlock(world, groundLocation); - if (!FarmHelper.bricks.contains(platform)) { - break; - } - - FarmTarget target = new FarmTarget(targetLocation, layoutDirection, targetLimit); - farmSideTargets.add(target); - } - - targets.put(farmSide, farmSideTargets); - } - } - - private static Vect getGroundPosition(World world, Vect targetPosition) { - for (int yOffset = 2; yOffset > -4; yOffset--) { - Vect position = targetPosition.add(0, yOffset, 0); - Block ground = VectUtil.getBlock(world, position); - if (FarmHelper.bricks.contains(ground)) { - return position; - } - } - return null; - } - - private static boolean isCycleCanceledByListeners(IFarmLogic logic, FarmDirection direction, Iterable farmListeners) { - for (IFarmListener listener : farmListeners) { - if (listener.cancelTask(logic, direction)) { - return true; - } - } - return false; - } - - private static void setExtents(World worldObj, Map> targets) { - for (List targetsList : targets.values()) { - if (!targetsList.isEmpty()) { - Vect groundPosition = getGroundPosition(worldObj, targetsList.get(0).getStart()); - - for (FarmTarget target : targetsList) { - target.setExtentAndYOffset(worldObj, groundPosition); - } - } - } - } - - private static class FarmWorkStatus { - public boolean didWork = false; - public boolean hasFarmland = false; - public boolean hasFertilizer = false; - public boolean hasLiquid = false; - } - - private FarmWorkStatus cultivateTargets(FarmWorkStatus farmWorkStatus, List farmTargets, IFarmLogic logic) { - float hydrationModifier = hydrationManager.getHydrationModifier(); - - final int fertilizerConsumption = logic.getFertilizerConsumption(); - int liquidConsumption = logic.getWaterConsumption(hydrationModifier); - FluidStack liquid = Fluids.WATER.getFluid(liquidConsumption); - - if (farmTargets != null) { - for (FarmTarget target : farmTargets) { - if (target.getExtent() <= 0) { - break; - } else { - farmWorkStatus.hasFarmland = true; - } - - // Check fertilizer and water - if (!fertilizerManager.hasFertilizer(fertilizerConsumption)) { - continue; - } - - if (liquid.amount > 0 && !hasLiquid(liquid)) { - continue; - } - - if (cultivateTarget(target, logic, farmListeners)) { - // Remove fertilizer and water - fertilizerManager.removeFertilizer(fertilizerConsumption); - removeLiquid(liquid); - - farmWorkStatus.didWork = true; - } - } - } - - farmWorkStatus.hasLiquid = liquid.amount <= 0 || hasLiquid(liquid); - farmWorkStatus.hasFertilizer = fertilizerManager.hasFertilizer(fertilizerConsumption); - - return farmWorkStatus; - } - - private static boolean cultivateTarget(FarmTarget target, IFarmLogic logic, Iterable farmListeners) { - Vect targetPosition = target.getStart().add(0, target.getYOffset(), 0); - if (logic.cultivate(targetPosition.x, targetPosition.y, targetPosition.z, target.getDirection(), target.getExtent())) { - for (IFarmListener listener : farmListeners) { - listener.hasCultivated(logic, targetPosition.x, targetPosition.y, targetPosition.z, target.getDirection(), target.getExtent()); - } - return true; - } - - return false; - } - - private static Collection harvestTargets(List farmTargets, IFarmLogic logic, Iterable farmListeners) { - if (farmTargets != null) { - for (FarmTarget target : farmTargets) { - Collection harvested = harvestTarget(target, logic, farmListeners); - if (harvested.size() > 0) { - return harvested; - } - } - } - - return Collections.emptyList(); - } - - private static Collection harvestTarget(FarmTarget target, IFarmLogic logic, Iterable farmListeners) { - Collection harvested = logic.harvest(target.getStart().x, target.getStart().y + target.getYOffset(), target.getStart().z, target.getDirection(), target.getExtent()); - if (harvested == null || harvested.size() == 0) { - return Collections.emptyList(); - } - - // Let event handlers know. - for (IFarmListener listener : farmListeners) { - listener.hasScheduledHarvest(harvested, logic, target.getStart().x, target.getStart().y + target.getYOffset(), target.getStart().z, target.getDirection(), target.getExtent()); - } - - return harvested; - } - - private boolean collectWindfall(IFarmLogic logic) { - - Collection collected = logic.collect(); - if (collected == null || collected.size() <= 0) { - return false; - } - - // Let event handlers know. - for (IFarmListener listener : farmListeners) { - listener.hasCollected(collected, logic); - } - - for (ItemStack produce : collected) { - inventory.addProduce(produce); - pendingProduce.push(produce); - } - - return true; - } - - private boolean cullCrop(ICrop crop, IFarmLogic provider) { - - // Let event handlers handle the harvest first. - for (IFarmListener listener : farmListeners) { - if (listener.beforeCropHarvest(crop)) { - return true; - } - } - - final int fertilizerConsumption = provider.getFertilizerConsumption(); - - IErrorLogic errorLogic = getErrorLogic(); - - // Check fertilizer - Boolean hasFertilizer = fertilizerManager.hasFertilizer(fertilizerConsumption); - if (errorLogic.setCondition(!hasFertilizer, EnumErrorCode.NO_FERTILIZER)) { - return false; - } - - // Check water - float hydrationModifier = hydrationManager.getHydrationModifier(); - int waterConsumption = provider.getWaterConsumption(hydrationModifier); - FluidStack requiredLiquid = Fluids.WATER.getFluid(waterConsumption); - boolean hasLiquid = requiredLiquid.amount == 0 || hasLiquid(requiredLiquid); - - if (errorLogic.setCondition(!hasLiquid, EnumErrorCode.NO_LIQUID_FARM)) { - return false; - } - - Collection harvested = crop.harvest(); - if (harvested == null) { - Log.fine("Failed to harvest crop: " + crop); - return true; - } - - // Remove fertilizer and water - fertilizerManager.removeFertilizer(fertilizerConsumption); - removeLiquid(requiredLiquid); - - // Let event handlers handle the harvest first. - for (IFarmListener listener : farmListeners) { - listener.afterCropHarvest(harvested, crop); - } - - inventory.stowHarvest(harvested, pendingProduce); - - return true; - } - - @Override - public int getStoredFertilizerScaled(int scale) { - return fertilizerManager.getStoredFertilizerScaled(scale); - } - - @Override - public boolean hasLiquid(FluidStack liquid) { - return resourceTank.canDrain(liquid); - } - - @Override - public void removeLiquid(FluidStack liquid) { - resourceTank.drain(liquid.amount, true); - } - - @Override - public boolean plantGermling(IFarmable germling, World world, int x, int y, int z) { - EntityPlayer player = PlayerUtil.getPlayer(world, getAccessHandler().getOwner()); - return inventory.plantGermling(germling, player, world, x, y, z); - } - - @Override - public IFarmInventory getFarmInventory() { - return inventory; - } - - @Override - public void setFarmLogic(FarmDirection direction, IFarmLogic logic) { - if (logic == null) { - throw new NullPointerException("logic must not be null"); - } - farmLogics.put(direction, logic); - } - - @Override - public void resetFarmLogic(FarmDirection direction) { - setFarmLogic(direction, new FarmLogicArboreal(this)); - } - - @Override - public IFarmLogic getFarmLogic(FarmDirection direction) { - return farmLogics.get(direction); - } - - @Override - public int getSocketCount() { - return sockets.getSizeInventory(); - } - - @Override - public ItemStack getSocket(int slot) { - return sockets.getStackInSlot(slot); - } - - @Override - public void setSocket(int slot, ItemStack stack) { - if (stack != null && !ChipsetManager.circuitRegistry.isChipset(stack)) { - return; - } - - // Dispose old chipsets correctly - if (sockets.getStackInSlot(slot) != null) { - if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(sockets.getStackInSlot(slot)); - if (chipset != null) { - chipset.onRemoval(this); - } - } - } - - sockets.setInventorySlotContents(slot, stack); - refreshFarmLogics(); - - if (stack == null) { - return; - } - - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(stack); - if (chipset != null) { - chipset.onInsertion(this); - } - } - - @Override - public ICircuitSocketType getSocketType() { - return CircuitSocketType.FARM; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.multiblock; + +import forestry.api.circuits.ChipsetManager; +import forestry.api.circuits.CircuitSocketType; +import forestry.api.circuits.ICircuitBoard; +import forestry.api.circuits.ICircuitSocketType; +import forestry.api.core.EnumHumidity; +import forestry.api.core.EnumTemperature; +import forestry.api.core.IErrorLogic; +import forestry.api.farming.FarmDirection; +import forestry.api.farming.ICrop; +import forestry.api.farming.IFarmInventory; +import forestry.api.farming.IFarmListener; +import forestry.api.farming.IFarmLogic; +import forestry.api.farming.IFarmable; +import forestry.api.multiblock.IFarmComponent; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.core.access.EnumAccess; +import forestry.core.config.Config; +import forestry.core.config.Constants; +import forestry.core.errors.EnumErrorCode; +import forestry.core.fluids.Fluids; +import forestry.core.fluids.TankManager; +import forestry.core.fluids.tanks.FilteredTank; +import forestry.core.fluids.tanks.StandardTank; +import forestry.core.inventory.FakeInventoryAdapter; +import forestry.core.inventory.IInventoryAdapter; +import forestry.core.inventory.InventoryAdapter; +import forestry.core.multiblock.IMultiblockControllerInternal; +import forestry.core.multiblock.MultiblockValidationException; +import forestry.core.multiblock.RectangularMultiblockControllerBase; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.tiles.ILiquidTankTile; +import forestry.core.utils.Log; +import forestry.core.utils.PlayerUtil; +import forestry.core.utils.vect.Vect; +import forestry.core.utils.vect.VectUtil; +import forestry.farming.FarmHelper; +import forestry.farming.FarmTarget; +import forestry.farming.gui.IFarmLedgerDelegate; +import forestry.farming.logic.FarmLogicArboreal; +import forestry.farming.tiles.TileFarmGearbox; +import forestry.farming.tiles.TileFarmPlain; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Stack; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.StatCollector; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; + +public class FarmController extends RectangularMultiblockControllerBase + implements IFarmControllerInternal, ILiquidTankTile { + + private enum Stage { + CULTIVATE, + HARVEST; + + public Stage next() { + if (this == CULTIVATE) { + return HARVEST; + } else { + return CULTIVATE; + } + } + } + + private static FarmDirection getLayoutDirection(FarmDirection farmSide) { + switch (farmSide) { + case NORTH: + return FarmDirection.WEST; + case WEST: + return FarmDirection.SOUTH; + case SOUTH: + return FarmDirection.EAST; + case EAST: + return FarmDirection.NORTH; + } + return null; + } + + private final Map> targets = new EnumMap<>(FarmDirection.class); + private int allowedExtent = 0; + + private IFarmLogic harvestProvider; // The farm logic which supplied the pending crops. + private final Stack pendingCrops = new Stack<>(); + private final Stack pendingProduce = new Stack<>(); + + private Stage stage = Stage.CULTIVATE; + + // active components are stored with a tick offset so they do not all tick together + private final Map farmActiveComponents = new HashMap<>(); + private final Set farmListeners = new HashSet<>(); + + private final Map farmLogics = new EnumMap<>(FarmDirection.class); + + private final InventoryAdapter sockets; + private final InventoryFarm inventory; + private final TankManager tankManager; + private final StandardTank resourceTank; + private final FarmHydrationManager hydrationManager; + private final FarmFertilizerManager fertilizerManager; + + // the number of work ticks that this farm has had no power + private int noPowerTime = 0; + + // tick updates can come from multiple gearboxes so keep track of them here + private int farmWorkTicks = 0; + + private BiomeGenBase cachedBiome; + + public FarmController(World world) { + super(world, FarmMultiblockSizeLimits.instance); + + this.resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, FluidRegistry.WATER); + this.tankManager = new TankManager(this, resourceTank); + + this.inventory = new InventoryFarm(this); + this.sockets = new InventoryAdapter(1, "sockets"); + this.hydrationManager = new FarmHydrationManager(this); + this.fertilizerManager = new FarmFertilizerManager(); + + refreshFarmLogics(); + } + + @Override + public IFarmLedgerDelegate getFarmLedgerDelegate() { + return hydrationManager; + } + + @Override + public IInventoryAdapter getInternalInventory() { + if (isAssembled()) { + return inventory; + } else { + return FakeInventoryAdapter.instance(); + } + } + + @Override + public TankManager getTankManager() { + return tankManager; + } + + private BiomeGenBase getBiome() { + if (cachedBiome == null) { + ChunkCoordinates coords = getReferenceCoord(); + cachedBiome = worldObj.getBiomeGenForCoords(coords.posX, coords.posZ); + } + return cachedBiome; + } + + @Override + public void onAttachedPartWithMultiblockData(IMultiblockComponent part, NBTTagCompound data) { + this.readFromNBT(data); + } + + @Override + protected void onBlockAdded(IMultiblockComponent newPart) { + if (newPart instanceof IFarmComponent.Listener) { + IFarmComponent.Listener listenerPart = (IFarmComponent.Listener) newPart; + farmListeners.add(listenerPart.getFarmListener()); + } + + if (newPart instanceof IFarmComponent.Active) { + farmActiveComponents.put((IFarmComponent.Active) newPart, worldObj.rand.nextInt(256)); + } + } + + @Override + protected void onBlockRemoved(IMultiblockComponent oldPart) { + if (oldPart instanceof IFarmComponent.Listener) { + IFarmComponent.Listener listenerPart = (IFarmComponent.Listener) oldPart; + farmListeners.remove(listenerPart.getFarmListener()); + } + + if (oldPart instanceof IFarmComponent.Active) { + farmActiveComponents.remove(oldPart); + } + } + + @Override + protected void isMachineWhole() throws MultiblockValidationException { + super.isMachineWhole(); + + boolean hasGearbox = false; + for (IMultiblockComponent part : connectedParts) { + if (part instanceof TileFarmGearbox) { + hasGearbox = true; + break; + } + } + + if (!hasGearbox) { + throw new MultiblockValidationException( + StatCollector.translateToLocal("for.multiblock.farm.error.needGearbox")); + } + } + + @Override + protected void onMachineDisassembled() { + super.onMachineDisassembled(); + targets.clear(); + } + + @Override + public void isGoodForExteriorLevel(IMultiblockComponent part, int level) throws MultiblockValidationException { + if (level == 2 && !(part instanceof TileFarmPlain)) { + throw new MultiblockValidationException( + StatCollector.translateToLocal("for.multiblock.farm.error.needPlainBand")); + } + } + + @Override + public void isGoodForInterior(IMultiblockComponent part) throws MultiblockValidationException { + if (!(part instanceof TileFarmPlain)) { + throw new MultiblockValidationException( + StatCollector.translateToLocal("for.multiblock.farm.error.needPlainInterior")); + } + } + + @Override + public void onAssimilate(IMultiblockControllerInternal assimilated) {} + + @Override + public void onAssimilated(IMultiblockControllerInternal assimilator) {} + + @Override + protected boolean updateServer(int tickCount) { + hydrationManager.updateServer(worldObj, getBiome()); + + if (updateOnInterval(20)) { + inventory.drainCan(tankManager); + } + + boolean hasPower = false; + for (Map.Entry entry : farmActiveComponents.entrySet()) { + IFarmComponent.Active farmComponent = entry.getKey(); + if (farmComponent instanceof TileFarmGearbox) { + hasPower |= ((TileFarmGearbox) farmComponent).getEnergyManager().getTotalEnergyStored() > 0; + } + + int tickOffset = entry.getValue(); + farmComponent.updateServer(tickCount + tickOffset); + } + + if (hasPower) { + noPowerTime = 0; + getErrorLogic().setCondition(false, EnumErrorCode.NO_POWER); + } else { + if (noPowerTime <= 4) { + noPowerTime++; + } else { + getErrorLogic().setCondition(true, EnumErrorCode.NO_POWER); + } + } + + // FIXME: be smarter about the farm needing to save + return true; + } + + @Override + protected void updateClient(int tickCount) { + for (Map.Entry entry : farmActiveComponents.entrySet()) { + IFarmComponent.Active farmComponent = entry.getKey(); + int tickOffset = entry.getValue(); + farmComponent.updateClient(tickCount + tickOffset); + } + } + + @Override + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + sockets.writeToNBT(data); + hydrationManager.writeToNBT(data); + tankManager.writeToNBT(data); + fertilizerManager.writeToNBT(data); + inventory.writeToNBT(data); + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + sockets.readFromNBT(data); + hydrationManager.readFromNBT(data); + tankManager.readFromNBT(data); + fertilizerManager.readFromNBT(data); + inventory.readFromNBT(data); + + refreshFarmLogics(); + } + + @Override + public void formatDescriptionPacket(NBTTagCompound data) { + sockets.writeToNBT(data); + hydrationManager.writeToNBT(data); + tankManager.writeToNBT(data); + fertilizerManager.writeToNBT(data); + } + + @Override + public void decodeDescriptionPacket(NBTTagCompound data) { + sockets.readFromNBT(data); + hydrationManager.readFromNBT(data); + tankManager.readFromNBT(data); + fertilizerManager.readFromNBT(data); + + refreshFarmLogics(); + } + + @Override + public ChunkCoordinates getCoordinates() { + ChunkCoordinates coord = getReferenceCoord(); + return new ChunkCoordinates(coord); + } + + @Override + public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { + if (oldAccess == EnumAccess.SHARED || newAccess == EnumAccess.SHARED) { + // pipes connected to this need to update + for (IMultiblockComponent part : connectedParts) { + if (part instanceof TileEntity) { + TileEntity tile = (TileEntity) part; + tile.getWorldObj() + .notifyBlocksOfNeighborChange(tile.xCoord, tile.yCoord, tile.zCoord, tile.getBlockType()); + } + } + markDirty(); + } + } + + @Override + public void writeGuiData(DataOutputStreamForestry data) throws IOException { + tankManager.writeData(data); + hydrationManager.writeData(data); + fertilizerManager.writeData(data); + } + + @Override + public void readGuiData(DataInputStreamForestry data) throws IOException { + tankManager.readData(data); + hydrationManager.readData(data); + fertilizerManager.readData(data); + } + + private void refreshFarmLogics() { + for (FarmDirection direction : FarmDirection.values()) { + resetFarmLogic(direction); + } + + // See whether we have socketed stuff. + ItemStack chip = sockets.getStackInSlot(0); + if (chip != null) { + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(chip); + if (chipset != null) { + chipset.onLoad(this); + } + } + } + + @Override + public EnumTemperature getTemperature() { + ChunkCoordinates coords = getReferenceCoord(); + return EnumTemperature.getFromBiome(getBiome(), coords.posX, coords.posY, coords.posZ); + } + + @Override + public EnumHumidity getHumidity() { + return EnumHumidity.getFromValue(getExactHumidity()); + } + + @Override + public float getExactTemperature() { + ChunkCoordinates coords = getReferenceCoord(); + return getBiome().getFloatTemperature(coords.posX, coords.posY, coords.posZ); + } + + @Override + public float getExactHumidity() { + return getBiome().rainfall; + } + + private int[] coords; + private int[] offset; + private int[] area; + + @Override + public int[] getCoords() { + if (coords == null) { + ChunkCoordinates centerCoord = getCenterCoord(); + coords = new int[] {centerCoord.posX, centerCoord.posY, centerCoord.posZ}; + } + return coords; + } + + @Override + public int[] getOffset() { + if (offset == null) { + offset = new int[] {-getArea()[0] / 2, -2, -getArea()[2] / 2}; + } + return offset; + } + + @Override + public int[] getArea() { + if (area == null) { + area = new int[] {7 + (allowedExtent * 2), 13, 7 + (allowedExtent * 2)}; + } + return area; + } + + @Override + public World getWorld() { + return worldObj; + } + + @Override + public boolean doWork() { + farmWorkTicks++; + if (targets.isEmpty() || farmWorkTicks % 20 == 0) { + setUpFarmlandTargets(); + } + + IErrorLogic errorLogic = getErrorLogic(); + + if (!pendingProduce.isEmpty()) { + boolean added = inventory.tryAddPendingProduce(pendingProduce); + errorLogic.setCondition(!added, EnumErrorCode.NO_SPACE_INVENTORY); + return added; + } + + boolean hasFertilizer = fertilizerManager.maintainFertilizer(inventory); + if (errorLogic.setCondition(!hasFertilizer, EnumErrorCode.NO_FERTILIZER)) { + return false; + } + + // Cull queued crops. + if (!pendingCrops.isEmpty()) { + if (cullCrop(pendingCrops.peek(), harvestProvider)) { + pendingCrops.pop(); + return true; + } else { + return false; + } + } + + // Cultivation and collection + FarmWorkStatus farmWorkStatus = new FarmWorkStatus(); + + for (FarmDirection farmSide : FarmDirection.values()) { + + IFarmLogic logic = getFarmLogic(farmSide); + if (logic == null) { + continue; + } + + // Allow listeners to cancel this cycle. + if (isCycleCanceledByListeners(logic, farmSide, farmListeners)) { + continue; + } + + // Always try to collect windfall. + if (collectWindfall(logic)) { + farmWorkStatus.didWork = true; + } + + List farmTargets = targets.get(farmSide); + + if (stage == Stage.HARVEST) { + Collection harvested = harvestTargets(farmTargets, logic, farmListeners); + farmWorkStatus.didWork = harvested.size() > 0; + if (harvested.size() > 0) { + pendingCrops.addAll(harvested); + harvestProvider = logic; + } + } else if (stage == Stage.CULTIVATE) { + farmWorkStatus = cultivateTargets(farmWorkStatus, farmTargets, logic); + } + + if (farmWorkStatus.didWork) { + break; + } + } + + if (stage == Stage.CULTIVATE) { + errorLogic.setCondition(!farmWorkStatus.hasFarmland, EnumErrorCode.NO_FARMLAND); + errorLogic.setCondition(!farmWorkStatus.hasFertilizer, EnumErrorCode.NO_FERTILIZER); + errorLogic.setCondition(!farmWorkStatus.hasLiquid, EnumErrorCode.NO_LIQUID_FARM); + } + + // alternate between cultivation and harvest. + stage = stage.next(); + + return farmWorkStatus.didWork; + } + + private void setUpFarmlandTargets() { + Vect targetStart = new Vect(getCoords()); + + ChunkCoordinates max = getMaximumCoord(); + ChunkCoordinates min = getMinimumCoord(); + + int sizeNorthSouth = Math.abs(max.posZ - min.posZ) + 1; + int sizeEastWest = Math.abs(max.posX - min.posX) + 1; + + // Set the maximum allowed extent. + allowedExtent = Math.max(sizeNorthSouth, sizeEastWest) * Config.farmSize + 1; + + createTargets(worldObj, targets, targetStart, allowedExtent, sizeNorthSouth, sizeEastWest); + setExtents(worldObj, targets); + } + + private static void createTargets( + World world, + Map> targets, + Vect targetStart, + final int allowedExtent, + final int farmSizeNorthSouth, + final int farmSizeEastWest) { + + for (FarmDirection farmSide : FarmDirection.values()) { + + final int farmWidth; + if (farmSide == FarmDirection.NORTH || farmSide == FarmDirection.SOUTH) { + farmWidth = farmSizeEastWest; + } else { + farmWidth = farmSizeNorthSouth; + } + + // targets extend sideways in a pinwheel pattern around the farm, so they need to go a little extra distance + final int targetMaxLimit = allowedExtent + farmWidth; + + FarmDirection layoutDirection = getLayoutDirection(farmSide); + + Vect targetLocation = FarmHelper.getFarmMultiblockCorner(world, targetStart, farmSide, layoutDirection); + Vect firstLocation = targetLocation.add(farmSide); + Vect firstGroundPosition = getGroundPosition(world, firstLocation); + if (firstGroundPosition == null) { + continue; + } + int groundHeight = firstGroundPosition.getY(); + + List farmSideTargets = new ArrayList<>(); + for (int i = 0; i < allowedExtent; i++) { + targetLocation = targetLocation.add(farmSide); + Vect groundLocation = new Vect(targetLocation.getX(), groundHeight, targetLocation.getZ()); + + int targetLimit = targetMaxLimit; + if (!Config.squareFarms) { + targetLimit = targetMaxLimit - i - 1; + } + + Block platform = VectUtil.getBlock(world, groundLocation); + if (!FarmHelper.bricks.contains(platform)) { + break; + } + + FarmTarget target = new FarmTarget(targetLocation, layoutDirection, targetLimit); + farmSideTargets.add(target); + } + + targets.put(farmSide, farmSideTargets); + } + } + + private static Vect getGroundPosition(World world, Vect targetPosition) { + for (int yOffset = 2; yOffset > -4; yOffset--) { + Vect position = targetPosition.add(0, yOffset, 0); + Block ground = VectUtil.getBlock(world, position); + if (FarmHelper.bricks.contains(ground)) { + return position; + } + } + return null; + } + + private static boolean isCycleCanceledByListeners( + IFarmLogic logic, FarmDirection direction, Iterable farmListeners) { + for (IFarmListener listener : farmListeners) { + if (listener.cancelTask(logic, direction)) { + return true; + } + } + return false; + } + + private static void setExtents(World worldObj, Map> targets) { + for (List targetsList : targets.values()) { + if (!targetsList.isEmpty()) { + Vect groundPosition = + getGroundPosition(worldObj, targetsList.get(0).getStart()); + + for (FarmTarget target : targetsList) { + target.setExtentAndYOffset(worldObj, groundPosition); + } + } + } + } + + private static class FarmWorkStatus { + public boolean didWork = false; + public boolean hasFarmland = false; + public boolean hasFertilizer = false; + public boolean hasLiquid = false; + } + + private FarmWorkStatus cultivateTargets( + FarmWorkStatus farmWorkStatus, List farmTargets, IFarmLogic logic) { + float hydrationModifier = hydrationManager.getHydrationModifier(); + + final int fertilizerConsumption = logic.getFertilizerConsumption(); + int liquidConsumption = logic.getWaterConsumption(hydrationModifier); + FluidStack liquid = Fluids.WATER.getFluid(liquidConsumption); + + if (farmTargets != null) { + for (FarmTarget target : farmTargets) { + if (target.getExtent() <= 0) { + break; + } else { + farmWorkStatus.hasFarmland = true; + } + + // Check fertilizer and water + if (!fertilizerManager.hasFertilizer(fertilizerConsumption)) { + continue; + } + + if (liquid.amount > 0 && !hasLiquid(liquid)) { + continue; + } + + if (cultivateTarget(target, logic, farmListeners)) { + // Remove fertilizer and water + fertilizerManager.removeFertilizer(fertilizerConsumption); + removeLiquid(liquid); + + farmWorkStatus.didWork = true; + } + } + } + + farmWorkStatus.hasLiquid = liquid.amount <= 0 || hasLiquid(liquid); + farmWorkStatus.hasFertilizer = fertilizerManager.hasFertilizer(fertilizerConsumption); + + return farmWorkStatus; + } + + private static boolean cultivateTarget(FarmTarget target, IFarmLogic logic, Iterable farmListeners) { + Vect targetPosition = target.getStart().add(0, target.getYOffset(), 0); + if (logic.cultivate( + targetPosition.x, targetPosition.y, targetPosition.z, target.getDirection(), target.getExtent())) { + for (IFarmListener listener : farmListeners) { + listener.hasCultivated( + logic, + targetPosition.x, + targetPosition.y, + targetPosition.z, + target.getDirection(), + target.getExtent()); + } + return true; + } + + return false; + } + + private static Collection harvestTargets( + List farmTargets, IFarmLogic logic, Iterable farmListeners) { + if (farmTargets != null) { + for (FarmTarget target : farmTargets) { + Collection harvested = harvestTarget(target, logic, farmListeners); + if (harvested.size() > 0) { + return harvested; + } + } + } + + return Collections.emptyList(); + } + + private static Collection harvestTarget( + FarmTarget target, IFarmLogic logic, Iterable farmListeners) { + Collection harvested = logic.harvest( + target.getStart().x, + target.getStart().y + target.getYOffset(), + target.getStart().z, + target.getDirection(), + target.getExtent()); + if (harvested == null || harvested.size() == 0) { + return Collections.emptyList(); + } + + // Let event handlers know. + for (IFarmListener listener : farmListeners) { + listener.hasScheduledHarvest( + harvested, + logic, + target.getStart().x, + target.getStart().y + target.getYOffset(), + target.getStart().z, + target.getDirection(), + target.getExtent()); + } + + return harvested; + } + + private boolean collectWindfall(IFarmLogic logic) { + + Collection collected = logic.collect(); + if (collected == null || collected.size() <= 0) { + return false; + } + + // Let event handlers know. + for (IFarmListener listener : farmListeners) { + listener.hasCollected(collected, logic); + } + + for (ItemStack produce : collected) { + inventory.addProduce(produce); + pendingProduce.push(produce); + } + + return true; + } + + private boolean cullCrop(ICrop crop, IFarmLogic provider) { + + // Let event handlers handle the harvest first. + for (IFarmListener listener : farmListeners) { + if (listener.beforeCropHarvest(crop)) { + return true; + } + } + + final int fertilizerConsumption = provider.getFertilizerConsumption(); + + IErrorLogic errorLogic = getErrorLogic(); + + // Check fertilizer + Boolean hasFertilizer = fertilizerManager.hasFertilizer(fertilizerConsumption); + if (errorLogic.setCondition(!hasFertilizer, EnumErrorCode.NO_FERTILIZER)) { + return false; + } + + // Check water + float hydrationModifier = hydrationManager.getHydrationModifier(); + int waterConsumption = provider.getWaterConsumption(hydrationModifier); + FluidStack requiredLiquid = Fluids.WATER.getFluid(waterConsumption); + boolean hasLiquid = requiredLiquid.amount == 0 || hasLiquid(requiredLiquid); + + if (errorLogic.setCondition(!hasLiquid, EnumErrorCode.NO_LIQUID_FARM)) { + return false; + } + + Collection harvested = crop.harvest(); + if (harvested == null) { + Log.fine("Failed to harvest crop: " + crop); + return true; + } + + // Remove fertilizer and water + fertilizerManager.removeFertilizer(fertilizerConsumption); + removeLiquid(requiredLiquid); + + // Let event handlers handle the harvest first. + for (IFarmListener listener : farmListeners) { + listener.afterCropHarvest(harvested, crop); + } + + inventory.stowHarvest(harvested, pendingProduce); + + return true; + } + + @Override + public int getStoredFertilizerScaled(int scale) { + return fertilizerManager.getStoredFertilizerScaled(scale); + } + + @Override + public boolean hasLiquid(FluidStack liquid) { + return resourceTank.canDrain(liquid); + } + + @Override + public void removeLiquid(FluidStack liquid) { + resourceTank.drain(liquid.amount, true); + } + + @Override + public boolean plantGermling(IFarmable germling, World world, int x, int y, int z) { + EntityPlayer player = PlayerUtil.getPlayer(world, getAccessHandler().getOwner()); + return inventory.plantGermling(germling, player, world, x, y, z); + } + + @Override + public IFarmInventory getFarmInventory() { + return inventory; + } + + @Override + public void setFarmLogic(FarmDirection direction, IFarmLogic logic) { + if (logic == null) { + throw new NullPointerException("logic must not be null"); + } + farmLogics.put(direction, logic); + } + + @Override + public void resetFarmLogic(FarmDirection direction) { + setFarmLogic(direction, new FarmLogicArboreal(this)); + } + + @Override + public IFarmLogic getFarmLogic(FarmDirection direction) { + return farmLogics.get(direction); + } + + @Override + public int getSocketCount() { + return sockets.getSizeInventory(); + } + + @Override + public ItemStack getSocket(int slot) { + return sockets.getStackInSlot(slot); + } + + @Override + public void setSocket(int slot, ItemStack stack) { + if (stack != null && !ChipsetManager.circuitRegistry.isChipset(stack)) { + return; + } + + // Dispose old chipsets correctly + if (sockets.getStackInSlot(slot) != null) { + if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(sockets.getStackInSlot(slot)); + if (chipset != null) { + chipset.onRemoval(this); + } + } + } + + sockets.setInventorySlotContents(slot, stack); + refreshFarmLogics(); + + if (stack == null) { + return; + } + + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitboard(stack); + if (chipset != null) { + chipset.onInsertion(this); + } + } + + @Override + public ICircuitSocketType getSocketType() { + return CircuitSocketType.FARM; + } +} diff --git a/src/main/java/forestry/farming/multiblock/FarmFertilizerManager.java b/src/main/java/forestry/farming/multiblock/FarmFertilizerManager.java index f14a7c9c9..94fe00aa0 100644 --- a/src/main/java/forestry/farming/multiblock/FarmFertilizerManager.java +++ b/src/main/java/forestry/farming/multiblock/FarmFertilizerManager.java @@ -1,91 +1,89 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.multiblock; - -import java.io.IOException; - -import net.minecraft.nbt.NBTTagCompound; - -import forestry.api.core.ForestryAPI; -import forestry.api.core.INBTTagable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamable; - -public class FarmFertilizerManager implements INBTTagable, IStreamable { - private static final int BUFFER_FERTILIZER = 200; - - private final int fertilizerValue; - private int storedFertilizer; - - public FarmFertilizerManager() { - this.fertilizerValue = ForestryAPI.activeMode.getIntegerSetting("farms.fertilizer.value"); - } - - public boolean hasFertilizer(int amount) { - if (fertilizerValue < 0) { - return true; - } - - return storedFertilizer >= amount; - } - - public void removeFertilizer(int amount) { - if (fertilizerValue < 0) { - return; - } - - storedFertilizer -= amount; - if (storedFertilizer < 0) { - storedFertilizer = 0; - } - } - - public boolean maintainFertilizer(InventoryFarm inventory) { - if (storedFertilizer <= BUFFER_FERTILIZER) { - if (fertilizerValue < 0) { - storedFertilizer += 2000; - } else if (inventory.useFertilizer()) { - storedFertilizer += fertilizerValue; - } - } - - return storedFertilizer > 0; - } - - @Override - public void readFromNBT(NBTTagCompound data) { - storedFertilizer = data.getInteger("StoredFertilizer"); - } - - @Override - public void writeToNBT(NBTTagCompound data) { - data.setInteger("StoredFertilizer", storedFertilizer); - } - - public int getStoredFertilizerScaled(int scale) { - if (storedFertilizer == 0) { - return 0; - } - - return (storedFertilizer * scale) / (fertilizerValue + BUFFER_FERTILIZER); - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeVarInt(storedFertilizer); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - storedFertilizer = data.readVarInt(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.multiblock; + +import forestry.api.core.ForestryAPI; +import forestry.api.core.INBTTagable; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; +import java.io.IOException; +import net.minecraft.nbt.NBTTagCompound; + +public class FarmFertilizerManager implements INBTTagable, IStreamable { + private static final int BUFFER_FERTILIZER = 200; + + private final int fertilizerValue; + private int storedFertilizer; + + public FarmFertilizerManager() { + this.fertilizerValue = ForestryAPI.activeMode.getIntegerSetting("farms.fertilizer.value"); + } + + public boolean hasFertilizer(int amount) { + if (fertilizerValue < 0) { + return true; + } + + return storedFertilizer >= amount; + } + + public void removeFertilizer(int amount) { + if (fertilizerValue < 0) { + return; + } + + storedFertilizer -= amount; + if (storedFertilizer < 0) { + storedFertilizer = 0; + } + } + + public boolean maintainFertilizer(InventoryFarm inventory) { + if (storedFertilizer <= BUFFER_FERTILIZER) { + if (fertilizerValue < 0) { + storedFertilizer += 2000; + } else if (inventory.useFertilizer()) { + storedFertilizer += fertilizerValue; + } + } + + return storedFertilizer > 0; + } + + @Override + public void readFromNBT(NBTTagCompound data) { + storedFertilizer = data.getInteger("StoredFertilizer"); + } + + @Override + public void writeToNBT(NBTTagCompound data) { + data.setInteger("StoredFertilizer", storedFertilizer); + } + + public int getStoredFertilizerScaled(int scale) { + if (storedFertilizer == 0) { + return 0; + } + + return (storedFertilizer * scale) / (fertilizerValue + BUFFER_FERTILIZER); + } + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeVarInt(storedFertilizer); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + storedFertilizer = data.readVarInt(); + } +} diff --git a/src/main/java/forestry/farming/multiblock/FarmHydrationManager.java b/src/main/java/forestry/farming/multiblock/FarmHydrationManager.java index 8f0326031..7084e28ee 100644 --- a/src/main/java/forestry/farming/multiblock/FarmHydrationManager.java +++ b/src/main/java/forestry/farming/multiblock/FarmHydrationManager.java @@ -1,112 +1,110 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.multiblock; - -import java.io.IOException; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - -import forestry.api.core.BiomeHelper; -import forestry.api.core.INBTTagable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamable; -import forestry.core.tiles.IClimatised; -import forestry.farming.gui.IFarmLedgerDelegate; - -public class FarmHydrationManager implements IFarmLedgerDelegate, INBTTagable, IStreamable { - private static final int DELAY_HYDRATION = 100; - private static final float RAINFALL_MODIFIER_MAX = 15f; - private static final float RAINFALL_MODIFIER_MIN = 0.5f; - - private final IClimatised climatised; - private int hydrationDelay = 0; - private int ticksSinceRainfall = 0; - - public FarmHydrationManager(IClimatised climatised) { - this.climatised = climatised; - } - - public void updateServer(World world, BiomeGenBase biome) { - if (world.isRaining() && BiomeHelper.canRainOrSnow(biome)) { - if (hydrationDelay > 0) { - hydrationDelay--; - } else { - ticksSinceRainfall = 0; - } - } else { - hydrationDelay = DELAY_HYDRATION; - if (ticksSinceRainfall < Integer.MAX_VALUE) { - ticksSinceRainfall++; - } - } - } - - @Override - public float getHydrationModifier() { - return getHydrationTempModifier() * getHydrationHumidModifier() * getHydrationRainfallModifier(); - } - - @Override - public float getHydrationTempModifier() { - float temperature = climatised.getExactTemperature(); - return temperature > 0.8f ? temperature : 0.8f; - } - - @Override - public float getHydrationHumidModifier() { - float mod = 1 / climatised.getExactHumidity(); - return mod < 2.0f ? mod : 2.0f; - } - - @Override - public float getHydrationRainfallModifier() { - float mod = (float) ticksSinceRainfall / 24000; - if (mod <= RAINFALL_MODIFIER_MIN) { - return RAINFALL_MODIFIER_MIN; - } else if (mod >= RAINFALL_MODIFIER_MAX) { - return RAINFALL_MODIFIER_MAX; - } else { - return mod; - } - } - - @Override - public double getDrought() { - return Math.round(((double) ticksSinceRainfall / 24000) * 10) / 10.; - } - - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - hydrationDelay = nbttagcompound.getInteger("HydrationDelay"); - ticksSinceRainfall = nbttagcompound.getInteger("TicksSinceRainfall"); - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setInteger("HydrationDelay", hydrationDelay); - nbttagcompound.setInteger("TicksSinceRainfall", ticksSinceRainfall); - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeVarInt(hydrationDelay); - data.writeVarInt(ticksSinceRainfall); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - hydrationDelay = data.readVarInt(); - ticksSinceRainfall = data.readVarInt(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.multiblock; + +import forestry.api.core.BiomeHelper; +import forestry.api.core.INBTTagable; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IStreamable; +import forestry.core.tiles.IClimatised; +import forestry.farming.gui.IFarmLedgerDelegate; +import java.io.IOException; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; + +public class FarmHydrationManager implements IFarmLedgerDelegate, INBTTagable, IStreamable { + private static final int DELAY_HYDRATION = 100; + private static final float RAINFALL_MODIFIER_MAX = 15f; + private static final float RAINFALL_MODIFIER_MIN = 0.5f; + + private final IClimatised climatised; + private int hydrationDelay = 0; + private int ticksSinceRainfall = 0; + + public FarmHydrationManager(IClimatised climatised) { + this.climatised = climatised; + } + + public void updateServer(World world, BiomeGenBase biome) { + if (world.isRaining() && BiomeHelper.canRainOrSnow(biome)) { + if (hydrationDelay > 0) { + hydrationDelay--; + } else { + ticksSinceRainfall = 0; + } + } else { + hydrationDelay = DELAY_HYDRATION; + if (ticksSinceRainfall < Integer.MAX_VALUE) { + ticksSinceRainfall++; + } + } + } + + @Override + public float getHydrationModifier() { + return getHydrationTempModifier() * getHydrationHumidModifier() * getHydrationRainfallModifier(); + } + + @Override + public float getHydrationTempModifier() { + float temperature = climatised.getExactTemperature(); + return temperature > 0.8f ? temperature : 0.8f; + } + + @Override + public float getHydrationHumidModifier() { + float mod = 1 / climatised.getExactHumidity(); + return mod < 2.0f ? mod : 2.0f; + } + + @Override + public float getHydrationRainfallModifier() { + float mod = (float) ticksSinceRainfall / 24000; + if (mod <= RAINFALL_MODIFIER_MIN) { + return RAINFALL_MODIFIER_MIN; + } else if (mod >= RAINFALL_MODIFIER_MAX) { + return RAINFALL_MODIFIER_MAX; + } else { + return mod; + } + } + + @Override + public double getDrought() { + return Math.round(((double) ticksSinceRainfall / 24000) * 10) / 10.; + } + + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + hydrationDelay = nbttagcompound.getInteger("HydrationDelay"); + ticksSinceRainfall = nbttagcompound.getInteger("TicksSinceRainfall"); + } + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setInteger("HydrationDelay", hydrationDelay); + nbttagcompound.setInteger("TicksSinceRainfall", ticksSinceRainfall); + } + + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + data.writeVarInt(hydrationDelay); + data.writeVarInt(ticksSinceRainfall); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + hydrationDelay = data.readVarInt(); + ticksSinceRainfall = data.readVarInt(); + } +} diff --git a/src/main/java/forestry/farming/multiblock/FarmMultiblockSizeLimits.java b/src/main/java/forestry/farming/multiblock/FarmMultiblockSizeLimits.java index 4b625cf0f..f3d66dd7a 100644 --- a/src/main/java/forestry/farming/multiblock/FarmMultiblockSizeLimits.java +++ b/src/main/java/forestry/farming/multiblock/FarmMultiblockSizeLimits.java @@ -1,56 +1,54 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.multiblock; - -import forestry.core.multiblock.IMultiblockSizeLimits; - -class FarmMultiblockSizeLimits implements IMultiblockSizeLimits { - public static final FarmMultiblockSizeLimits instance = new FarmMultiblockSizeLimits(); - - private FarmMultiblockSizeLimits() { - - } - - @Override - public int getMinimumNumberOfBlocksForAssembledMachine() { - return 3 * 3 * 4; - } - - @Override - public int getMaximumXSize() { - return 5; - } - - @Override - public int getMaximumZSize() { - return 5; - } - - @Override - public int getMaximumYSize() { - return 4; - } - - @Override - public int getMinimumXSize() { - return 3; - } - - @Override - public int getMinimumZSize() { - return 3; - } - - @Override - public int getMinimumYSize() { - return 4; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.multiblock; + +import forestry.core.multiblock.IMultiblockSizeLimits; + +class FarmMultiblockSizeLimits implements IMultiblockSizeLimits { + public static final FarmMultiblockSizeLimits instance = new FarmMultiblockSizeLimits(); + + private FarmMultiblockSizeLimits() {} + + @Override + public int getMinimumNumberOfBlocksForAssembledMachine() { + return 3 * 3 * 4; + } + + @Override + public int getMaximumXSize() { + return 5; + } + + @Override + public int getMaximumZSize() { + return 5; + } + + @Override + public int getMaximumYSize() { + return 4; + } + + @Override + public int getMinimumXSize() { + return 3; + } + + @Override + public int getMinimumZSize() { + return 3; + } + + @Override + public int getMinimumYSize() { + return 4; + } +} diff --git a/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java b/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java index b5eea9497..dda2a607e 100644 --- a/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java +++ b/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java @@ -1,29 +1,35 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.multiblock; - -import forestry.api.multiblock.IFarmController; -import forestry.core.access.IRestrictedAccess; -import forestry.core.circuits.ISocketable; -import forestry.core.fluids.ITankManager; -import forestry.core.inventory.IInventoryAdapter; -import forestry.core.multiblock.IMultiblockControllerInternal; -import forestry.core.network.IStreamableGui; -import forestry.core.tiles.IClimatised; -import forestry.farming.gui.IFarmLedgerDelegate; - -public interface IFarmControllerInternal extends IFarmController, IMultiblockControllerInternal, ISocketable, IClimatised, IRestrictedAccess, IStreamableGui { - IFarmLedgerDelegate getFarmLedgerDelegate(); - - IInventoryAdapter getInternalInventory(); - - ITankManager getTankManager(); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.multiblock; + +import forestry.api.multiblock.IFarmController; +import forestry.core.access.IRestrictedAccess; +import forestry.core.circuits.ISocketable; +import forestry.core.fluids.ITankManager; +import forestry.core.inventory.IInventoryAdapter; +import forestry.core.multiblock.IMultiblockControllerInternal; +import forestry.core.network.IStreamableGui; +import forestry.core.tiles.IClimatised; +import forestry.farming.gui.IFarmLedgerDelegate; + +public interface IFarmControllerInternal + extends IFarmController, + IMultiblockControllerInternal, + ISocketable, + IClimatised, + IRestrictedAccess, + IStreamableGui { + IFarmLedgerDelegate getFarmLedgerDelegate(); + + IInventoryAdapter getInternalInventory(); + + ITankManager getTankManager(); +} diff --git a/src/main/java/forestry/farming/multiblock/InventoryFarm.java b/src/main/java/forestry/farming/multiblock/InventoryFarm.java index 78d257c5e..5edcc8a24 100644 --- a/src/main/java/forestry/farming/multiblock/InventoryFarm.java +++ b/src/main/java/forestry/farming/multiblock/InventoryFarm.java @@ -1,260 +1,261 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.multiblock; - -import java.util.Stack; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import net.minecraft.world.World; -import net.minecraftforge.fluids.Fluid; - -import forestry.api.farming.FarmDirection; -import forestry.api.farming.IFarmInventory; -import forestry.api.farming.IFarmLogic; -import forestry.api.farming.IFarmable; -import forestry.core.fluids.FluidHelper; -import forestry.core.fluids.TankManager; -import forestry.core.inventory.InventoryAdapterRestricted; -import forestry.core.inventory.wrappers.InventoryMapper; -import forestry.core.utils.InventoryUtil; -import forestry.core.utils.PlayerUtil; -import forestry.core.utils.SlotUtil; -import forestry.plugins.PluginCore; -import forestry.plugins.PluginManager; - -import ic2.api.item.IC2Items; - -public class InventoryFarm extends InventoryAdapterRestricted implements IFarmInventory { - public static final int SLOT_RESOURCES_1 = 0; - public static final int SLOT_RESOURCES_COUNT = 6; - public static final int SLOT_GERMLINGS_1 = 6; - public static final int SLOT_GERMLINGS_COUNT = 6; - public static final int SLOT_PRODUCTION_1 = 12; - public static final int SLOT_PRODUCTION_COUNT = 8; - - public static final int SLOT_FERTILIZER = 20; - public static final int SLOT_FERTILIZER_COUNT = 1; - public static final int SLOT_CAN = 21; - public static final int SLOT_CAN_COUNT = 1; - - public static final int SLOT_COUNT = SLOT_RESOURCES_COUNT + SLOT_GERMLINGS_COUNT + SLOT_PRODUCTION_COUNT + SLOT_FERTILIZER_COUNT + SLOT_CAN_COUNT; - - private final FarmController farmController; - - private final IInventory resourcesInventory; - private final IInventory germlingsInventory; - private final IInventory productInventory; - private final IInventory fertilizerInventory; - - public InventoryFarm(FarmController farmController) { - super(SLOT_COUNT, "Items", farmController.getAccessHandler()); - this.farmController = farmController; - - this.resourcesInventory = new InventoryMapper(this, SLOT_RESOURCES_1, SLOT_RESOURCES_COUNT); - this.germlingsInventory = new InventoryMapper(this, SLOT_GERMLINGS_1, SLOT_GERMLINGS_COUNT); - this.productInventory = new InventoryMapper(this, SLOT_PRODUCTION_1, SLOT_PRODUCTION_COUNT); - this.fertilizerInventory = new InventoryMapper(this, SLOT_FERTILIZER, SLOT_FERTILIZER_COUNT); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (SlotUtil.isSlotInRange(slotIndex, SLOT_FERTILIZER, SLOT_FERTILIZER_COUNT)) { - return acceptsAsFertilizer(itemStack); - } else if (SlotUtil.isSlotInRange(slotIndex, SLOT_GERMLINGS_1, SLOT_GERMLINGS_COUNT)) { - return acceptsAsGermling(itemStack); - } else if (SlotUtil.isSlotInRange(slotIndex, SLOT_RESOURCES_1, SLOT_RESOURCES_COUNT)) { - return acceptsAsResource(itemStack); - } else if (SlotUtil.isSlotInRange(slotIndex, SLOT_CAN, SLOT_CAN_COUNT)) { - Fluid fluid = FluidHelper.getFluidInContainer(itemStack); - return farmController.getTankManager().accepts(fluid); - } - return false; - } - - @Override - public boolean canExtractItem(int slotIndex, ItemStack stack, int side) { - return SlotUtil.isSlotInRange(slotIndex, SLOT_PRODUCTION_1, SLOT_PRODUCTION_COUNT); - } - - @Override - public boolean hasResources(ItemStack[] resources) { - return InventoryUtil.contains(resourcesInventory, resources); - } - - @Override - public void removeResources(ItemStack[] resources) { - EntityPlayer player = PlayerUtil.getPlayer(farmController.getWorld(), farmController.getAccessHandler().getOwner()); - InventoryUtil.removeSets(resourcesInventory, 1, resources, player, false, true, false, true); - } - - @Override - public boolean acceptsAsGermling(ItemStack itemstack) { - if (itemstack == null) { - return false; - } - - for (FarmDirection farmDirection : FarmDirection.values()) { - IFarmLogic logic = farmController.getFarmLogic(farmDirection); - if (logic.isAcceptedGermling(itemstack)) { - return true; - } - } - - return false; - } - - @Override - public boolean acceptsAsResource(ItemStack itemstack) { - if (itemstack == null) { - return false; - } - - for (FarmDirection farmDirection : FarmDirection.values()) { - IFarmLogic logic = farmController.getFarmLogic(farmDirection); - if (logic.isAcceptedResource(itemstack)) { - return true; - } - } - - return false; - } - - @Override - public boolean acceptsAsFertilizer(ItemStack itemstack) { - if (itemstack == null) { - return false; - } - Item item = itemstack.getItem(); - if (PluginManager.Module.INDUSTRIALCRAFT.isEnabled()) { - Item ic2fert = IC2Items.getItem("fertilizer").getItem(); - if (ic2fert == item) { - return true; - } - } - - return PluginCore.items.fertilizerCompound == item; - } - - @Override - public IInventory getProductInventory() { - return productInventory; - } - - @Override - public IInventory getGermlingsInventory() { - return germlingsInventory; - } - - @Override - public IInventory getResourcesInventory() { - return resourcesInventory; - } - - @Override - public IInventory getFertilizerInventory() { - return fertilizerInventory; - } - - public void drainCan(TankManager tankManager) { - FluidHelper.drainContainers(tankManager, this, SLOT_CAN); - } - - public boolean plantGermling(IFarmable germling, EntityPlayer player, World world, int x, int y, int z) { - for (int i = 0; i < germlingsInventory.getSizeInventory(); i++) { - ItemStack germlingStack = germlingsInventory.getStackInSlot(i); - if (germlingStack == null || !germling.isGermling(germlingStack)) { - continue; - } - - if (germling.plantSaplingAt(player, germlingStack, world, x, y, z)) { - germlingsInventory.decrStackSize(i, 1); - return true; - } - } - return false; - } - - public void addProduce(ItemStack produce) { - - if (acceptsAsGermling(produce)) { - produce.stackSize -= InventoryUtil.addStack(germlingsInventory, produce, true); - } - - if (produce.stackSize <= 0) { - return; - } - - if (acceptsAsResource(produce)) { - produce.stackSize -= InventoryUtil.addStack(resourcesInventory, produce, true); - } - - if (produce.stackSize <= 0) { - return; - } - - produce.stackSize -= InventoryUtil.addStack(productInventory, produce, true); - } - - public void stowHarvest(Iterable harvested, Stack pendingProduce) { - for (ItemStack harvest : harvested) { - if (harvest == null) { - continue; - } - - if (acceptsAsGermling(harvest)) { - harvest.stackSize -= InventoryUtil.addStack(germlingsInventory, harvest, true); - } - - if (harvest.stackSize <= 0) { - continue; - } - - harvest.stackSize -= InventoryUtil.addStack(productInventory, harvest, true); - - if (harvest.stackSize <= 0) { - continue; - } - - pendingProduce.push(harvest); - } - } - - public boolean tryAddPendingProduce(Stack pendingProduce) { - IInventory productInventory = getProductInventory(); - - ItemStack next = pendingProduce.peek(); - boolean added = InventoryUtil.tryAddStack(productInventory, next, true, true); - - if (added) { - pendingProduce.pop(); - } - - return added; - } - - public boolean useFertilizer() { - ItemStack fertilizer = getStackInSlot(SLOT_FERTILIZER); - if (fertilizer == null || fertilizer.stackSize <= 0) { - return false; - } - - if (!acceptsAsFertilizer(fertilizer)) { - return false; - } - - decrStackSize(SLOT_FERTILIZER, 1); - return true; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.multiblock; + +import forestry.api.farming.FarmDirection; +import forestry.api.farming.IFarmInventory; +import forestry.api.farming.IFarmLogic; +import forestry.api.farming.IFarmable; +import forestry.core.fluids.FluidHelper; +import forestry.core.fluids.TankManager; +import forestry.core.inventory.InventoryAdapterRestricted; +import forestry.core.inventory.wrappers.InventoryMapper; +import forestry.core.utils.InventoryUtil; +import forestry.core.utils.PlayerUtil; +import forestry.core.utils.SlotUtil; +import forestry.plugins.PluginCore; +import forestry.plugins.PluginManager; +import ic2.api.item.IC2Items; +import java.util.Stack; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraftforge.fluids.Fluid; + +public class InventoryFarm extends InventoryAdapterRestricted implements IFarmInventory { + public static final int SLOT_RESOURCES_1 = 0; + public static final int SLOT_RESOURCES_COUNT = 6; + public static final int SLOT_GERMLINGS_1 = 6; + public static final int SLOT_GERMLINGS_COUNT = 6; + public static final int SLOT_PRODUCTION_1 = 12; + public static final int SLOT_PRODUCTION_COUNT = 8; + + public static final int SLOT_FERTILIZER = 20; + public static final int SLOT_FERTILIZER_COUNT = 1; + public static final int SLOT_CAN = 21; + public static final int SLOT_CAN_COUNT = 1; + + public static final int SLOT_COUNT = SLOT_RESOURCES_COUNT + + SLOT_GERMLINGS_COUNT + + SLOT_PRODUCTION_COUNT + + SLOT_FERTILIZER_COUNT + + SLOT_CAN_COUNT; + + private final FarmController farmController; + + private final IInventory resourcesInventory; + private final IInventory germlingsInventory; + private final IInventory productInventory; + private final IInventory fertilizerInventory; + + public InventoryFarm(FarmController farmController) { + super(SLOT_COUNT, "Items", farmController.getAccessHandler()); + this.farmController = farmController; + + this.resourcesInventory = new InventoryMapper(this, SLOT_RESOURCES_1, SLOT_RESOURCES_COUNT); + this.germlingsInventory = new InventoryMapper(this, SLOT_GERMLINGS_1, SLOT_GERMLINGS_COUNT); + this.productInventory = new InventoryMapper(this, SLOT_PRODUCTION_1, SLOT_PRODUCTION_COUNT); + this.fertilizerInventory = new InventoryMapper(this, SLOT_FERTILIZER, SLOT_FERTILIZER_COUNT); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (SlotUtil.isSlotInRange(slotIndex, SLOT_FERTILIZER, SLOT_FERTILIZER_COUNT)) { + return acceptsAsFertilizer(itemStack); + } else if (SlotUtil.isSlotInRange(slotIndex, SLOT_GERMLINGS_1, SLOT_GERMLINGS_COUNT)) { + return acceptsAsGermling(itemStack); + } else if (SlotUtil.isSlotInRange(slotIndex, SLOT_RESOURCES_1, SLOT_RESOURCES_COUNT)) { + return acceptsAsResource(itemStack); + } else if (SlotUtil.isSlotInRange(slotIndex, SLOT_CAN, SLOT_CAN_COUNT)) { + Fluid fluid = FluidHelper.getFluidInContainer(itemStack); + return farmController.getTankManager().accepts(fluid); + } + return false; + } + + @Override + public boolean canExtractItem(int slotIndex, ItemStack stack, int side) { + return SlotUtil.isSlotInRange(slotIndex, SLOT_PRODUCTION_1, SLOT_PRODUCTION_COUNT); + } + + @Override + public boolean hasResources(ItemStack[] resources) { + return InventoryUtil.contains(resourcesInventory, resources); + } + + @Override + public void removeResources(ItemStack[] resources) { + EntityPlayer player = PlayerUtil.getPlayer( + farmController.getWorld(), farmController.getAccessHandler().getOwner()); + InventoryUtil.removeSets(resourcesInventory, 1, resources, player, false, true, false, true); + } + + @Override + public boolean acceptsAsGermling(ItemStack itemstack) { + if (itemstack == null) { + return false; + } + + for (FarmDirection farmDirection : FarmDirection.values()) { + IFarmLogic logic = farmController.getFarmLogic(farmDirection); + if (logic.isAcceptedGermling(itemstack)) { + return true; + } + } + + return false; + } + + @Override + public boolean acceptsAsResource(ItemStack itemstack) { + if (itemstack == null) { + return false; + } + + for (FarmDirection farmDirection : FarmDirection.values()) { + IFarmLogic logic = farmController.getFarmLogic(farmDirection); + if (logic.isAcceptedResource(itemstack)) { + return true; + } + } + + return false; + } + + @Override + public boolean acceptsAsFertilizer(ItemStack itemstack) { + if (itemstack == null) { + return false; + } + Item item = itemstack.getItem(); + if (PluginManager.Module.INDUSTRIALCRAFT.isEnabled()) { + Item ic2fert = IC2Items.getItem("fertilizer").getItem(); + if (ic2fert == item) { + return true; + } + } + + return PluginCore.items.fertilizerCompound == item; + } + + @Override + public IInventory getProductInventory() { + return productInventory; + } + + @Override + public IInventory getGermlingsInventory() { + return germlingsInventory; + } + + @Override + public IInventory getResourcesInventory() { + return resourcesInventory; + } + + @Override + public IInventory getFertilizerInventory() { + return fertilizerInventory; + } + + public void drainCan(TankManager tankManager) { + FluidHelper.drainContainers(tankManager, this, SLOT_CAN); + } + + public boolean plantGermling(IFarmable germling, EntityPlayer player, World world, int x, int y, int z) { + for (int i = 0; i < germlingsInventory.getSizeInventory(); i++) { + ItemStack germlingStack = germlingsInventory.getStackInSlot(i); + if (germlingStack == null || !germling.isGermling(germlingStack)) { + continue; + } + + if (germling.plantSaplingAt(player, germlingStack, world, x, y, z)) { + germlingsInventory.decrStackSize(i, 1); + return true; + } + } + return false; + } + + public void addProduce(ItemStack produce) { + + if (acceptsAsGermling(produce)) { + produce.stackSize -= InventoryUtil.addStack(germlingsInventory, produce, true); + } + + if (produce.stackSize <= 0) { + return; + } + + if (acceptsAsResource(produce)) { + produce.stackSize -= InventoryUtil.addStack(resourcesInventory, produce, true); + } + + if (produce.stackSize <= 0) { + return; + } + + produce.stackSize -= InventoryUtil.addStack(productInventory, produce, true); + } + + public void stowHarvest(Iterable harvested, Stack pendingProduce) { + for (ItemStack harvest : harvested) { + if (harvest == null) { + continue; + } + + if (acceptsAsGermling(harvest)) { + harvest.stackSize -= InventoryUtil.addStack(germlingsInventory, harvest, true); + } + + if (harvest.stackSize <= 0) { + continue; + } + + harvest.stackSize -= InventoryUtil.addStack(productInventory, harvest, true); + + if (harvest.stackSize <= 0) { + continue; + } + + pendingProduce.push(harvest); + } + } + + public boolean tryAddPendingProduce(Stack pendingProduce) { + IInventory productInventory = getProductInventory(); + + ItemStack next = pendingProduce.peek(); + boolean added = InventoryUtil.tryAddStack(productInventory, next, true, true); + + if (added) { + pendingProduce.pop(); + } + + return added; + } + + public boolean useFertilizer() { + ItemStack fertilizer = getStackInSlot(SLOT_FERTILIZER); + if (fertilizer == null || fertilizer.stackSize <= 0) { + return false; + } + + if (!acceptsAsFertilizer(fertilizer)) { + return false; + } + + decrStackSize(SLOT_FERTILIZER, 1); + return true; + } +} diff --git a/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java b/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java index 67075e14c..81b864b25 100644 --- a/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java +++ b/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java @@ -1,35 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.multiblock; - -import net.minecraft.world.World; - -import forestry.api.multiblock.IMultiblockLogicFarm; -import forestry.core.multiblock.MultiblockLogic; - -public class MultiblockLogicFarm extends MultiblockLogic implements IMultiblockLogicFarm { - public MultiblockLogicFarm() { - super(IFarmControllerInternal.class); - } - - @Override - public IFarmControllerInternal getController() { - if (super.isConnected()) { - return controller; - } else { - return FakeFarmController.instance; - } - } - - public IFarmControllerInternal createNewController(World world) { - return new FarmController(world); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.multiblock; + +import forestry.api.multiblock.IMultiblockLogicFarm; +import forestry.core.multiblock.MultiblockLogic; +import net.minecraft.world.World; + +public class MultiblockLogicFarm extends MultiblockLogic implements IMultiblockLogicFarm { + public MultiblockLogicFarm() { + super(IFarmControllerInternal.class); + } + + @Override + public IFarmControllerInternal getController() { + if (super.isConnected()) { + return controller; + } else { + return FakeFarmController.instance; + } + } + + public IFarmControllerInternal createNewController(World world) { + return new FarmController(world); + } +} diff --git a/src/main/java/forestry/farming/proxy/ProxyFarming.java b/src/main/java/forestry/farming/proxy/ProxyFarming.java index 9343ea393..e55db4057 100755 --- a/src/main/java/forestry/farming/proxy/ProxyFarming.java +++ b/src/main/java/forestry/farming/proxy/ProxyFarming.java @@ -12,6 +12,5 @@ package forestry.farming.proxy; public class ProxyFarming { - public void initializeRendering() { - } + public void initializeRendering() {} } diff --git a/src/main/java/forestry/farming/proxy/ProxyFarmingClient.java b/src/main/java/forestry/farming/proxy/ProxyFarmingClient.java index 4bb3b5a74..fc33c4b73 100644 --- a/src/main/java/forestry/farming/proxy/ProxyFarmingClient.java +++ b/src/main/java/forestry/farming/proxy/ProxyFarmingClient.java @@ -10,23 +10,21 @@ ******************************************************************************/ package forestry.farming.proxy; -import net.minecraft.item.Item; - -import net.minecraftforge.client.MinecraftForgeClient; - import cpw.mods.fml.client.registry.RenderingRegistry; - import forestry.farming.render.RenderFarmBlock; import forestry.farming.render.RenderFarmItem; import forestry.plugins.PluginFarming; +import net.minecraft.item.Item; +import net.minecraftforge.client.MinecraftForgeClient; public class ProxyFarmingClient extends ProxyFarming { - @Override - public void initializeRendering() { - PluginFarming.modelIdFarmBlock = RenderingRegistry.getNextAvailableRenderId(); + @Override + public void initializeRendering() { + PluginFarming.modelIdFarmBlock = RenderingRegistry.getNextAvailableRenderId(); - RenderingRegistry.registerBlockHandler(new RenderFarmBlock()); - MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(PluginFarming.blocks.farm), new RenderFarmItem()); - } + RenderingRegistry.registerBlockHandler(new RenderFarmBlock()); + MinecraftForgeClient.registerItemRenderer( + Item.getItemFromBlock(PluginFarming.blocks.farm), new RenderFarmItem()); + } } diff --git a/src/main/java/forestry/farming/render/EnumFarmBlockTexture.java b/src/main/java/forestry/farming/render/EnumFarmBlockTexture.java index e9630b71c..8305bfc5b 100644 --- a/src/main/java/forestry/farming/render/EnumFarmBlockTexture.java +++ b/src/main/java/forestry/farming/render/EnumFarmBlockTexture.java @@ -10,113 +10,109 @@ ******************************************************************************/ package forestry.farming.render; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.render.TextureManager; +import forestry.farming.blocks.BlockFarmType; import java.util.Arrays; import java.util.List; - import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IIcon; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.render.TextureManager; -import forestry.farming.blocks.BlockFarmType; - public enum EnumFarmBlockTexture { - BRICK_STONE(new ItemStack(Blocks.stonebrick, 1, 0)), - BRICK_MOSSY(new ItemStack(Blocks.stonebrick, 1, 1)), - BRICK_CRACKED(new ItemStack(Blocks.stonebrick, 1, 2)), - BRICK(new ItemStack(Blocks.brick_block)), - SANDSTONE_SMOOTH(new ItemStack(Blocks.sandstone, 1, 2)), - SANDSTONE_CHISELED(new ItemStack(Blocks.sandstone, 1, 1)), - BRICK_NETHER(new ItemStack(Blocks.nether_brick)), - BRICK_CHISELED(new ItemStack(Blocks.stonebrick, 1, 3)), - QUARTZ(new ItemStack(Blocks.quartz_block, 1, 0)), - QUARTZ_CHISELED(new ItemStack(Blocks.quartz_block, 1, 1)), - QUARTZ_LINES(new ItemStack(Blocks.quartz_block, 1, 2)); + BRICK_STONE(new ItemStack(Blocks.stonebrick, 1, 0)), + BRICK_MOSSY(new ItemStack(Blocks.stonebrick, 1, 1)), + BRICK_CRACKED(new ItemStack(Blocks.stonebrick, 1, 2)), + BRICK(new ItemStack(Blocks.brick_block)), + SANDSTONE_SMOOTH(new ItemStack(Blocks.sandstone, 1, 2)), + SANDSTONE_CHISELED(new ItemStack(Blocks.sandstone, 1, 1)), + BRICK_NETHER(new ItemStack(Blocks.nether_brick)), + BRICK_CHISELED(new ItemStack(Blocks.stonebrick, 1, 3)), + QUARTZ(new ItemStack(Blocks.quartz_block, 1, 0)), + QUARTZ_CHISELED(new ItemStack(Blocks.quartz_block, 1, 1)), + QUARTZ_LINES(new ItemStack(Blocks.quartz_block, 1, 2)); - private static final int TYPE_PLAIN = 0; - private static final int TYPE_REVERSE = 1; - private static final int TYPE_TOP = 2; - private static final int TYPE_BAND = 3; - private static final int TYPE_GEARS = 4; - private static final int TYPE_HATCH = 5; - private static final int TYPE_VALVE = 6; - private static final int TYPE_CONTROL = 7; + private static final int TYPE_PLAIN = 0; + private static final int TYPE_REVERSE = 1; + private static final int TYPE_TOP = 2; + private static final int TYPE_BAND = 3; + private static final int TYPE_GEARS = 4; + private static final int TYPE_HATCH = 5; + private static final int TYPE_VALVE = 6; + private static final int TYPE_CONTROL = 7; - @SideOnly(Side.CLIENT) - private static List icons; + @SideOnly(Side.CLIENT) + private static List icons; - @SideOnly(Side.CLIENT) - public static void registerIcons(IIconRegister register) { - icons = Arrays.asList( - TextureManager.registerTex(register, "farm/plain"), - TextureManager.registerTex(register, "farm/reverse"), - TextureManager.registerTex(register, "farm/top"), - TextureManager.registerTex(register, "farm/band"), - TextureManager.registerTex(register, "farm/gears"), - TextureManager.registerTex(register, "farm/hatch"), - TextureManager.registerTex(register, "farm/valve"), - TextureManager.registerTex(register, "farm/control") - ); - } + @SideOnly(Side.CLIENT) + public static void registerIcons(IIconRegister register) { + icons = Arrays.asList( + TextureManager.registerTex(register, "farm/plain"), + TextureManager.registerTex(register, "farm/reverse"), + TextureManager.registerTex(register, "farm/top"), + TextureManager.registerTex(register, "farm/band"), + TextureManager.registerTex(register, "farm/gears"), + TextureManager.registerTex(register, "farm/hatch"), + TextureManager.registerTex(register, "farm/valve"), + TextureManager.registerTex(register, "farm/control")); + } - private final ItemStack base; + private final ItemStack base; - EnumFarmBlockTexture(ItemStack base) { - this.base = base; - } + EnumFarmBlockTexture(ItemStack base) { + this.base = base; + } - @SideOnly(Side.CLIENT) - public static IIcon getIcon(BlockFarmType type, int side) { - switch (type) { - case BASIC: { - if (side == 2) { - return icons.get(TYPE_REVERSE); - } else if (side == 0 || side == 1) { - return icons.get(TYPE_TOP); - } else { - return icons.get(TYPE_PLAIN); - } - } - case BAND: - return icons.get(TYPE_BAND); - case GEARBOX: - return icons.get(TYPE_GEARS); - case HATCH: - return icons.get(TYPE_HATCH); - case VALVE: - return icons.get(TYPE_VALVE); - case CONTROL: - return icons.get(TYPE_CONTROL); - default: - return icons.get(TYPE_PLAIN); - } - } + @SideOnly(Side.CLIENT) + public static IIcon getIcon(BlockFarmType type, int side) { + switch (type) { + case BASIC: { + if (side == 2) { + return icons.get(TYPE_REVERSE); + } else if (side == 0 || side == 1) { + return icons.get(TYPE_TOP); + } else { + return icons.get(TYPE_PLAIN); + } + } + case BAND: + return icons.get(TYPE_BAND); + case GEARBOX: + return icons.get(TYPE_GEARS); + case HATCH: + return icons.get(TYPE_HATCH); + case VALVE: + return icons.get(TYPE_VALVE); + case CONTROL: + return icons.get(TYPE_CONTROL); + default: + return icons.get(TYPE_PLAIN); + } + } - public void saveToCompound(NBTTagCompound compound) { - compound.setInteger("FarmBlock", this.ordinal()); - } + public void saveToCompound(NBTTagCompound compound) { + compound.setInteger("FarmBlock", this.ordinal()); + } - public String getName() { - return base.getItem().getItemStackDisplayName(base); - } + public String getName() { + return base.getItem().getItemStackDisplayName(base); + } - public ItemStack getBase() { - return base; - } + public ItemStack getBase() { + return base; + } - public static EnumFarmBlockTexture getFromCompound(NBTTagCompound compound) { - if (compound != null) { - int farmBlockOrdinal = compound.getInteger("FarmBlock"); - if (farmBlockOrdinal < EnumFarmBlockTexture.values().length) { - return EnumFarmBlockTexture.values()[farmBlockOrdinal]; - } - } + public static EnumFarmBlockTexture getFromCompound(NBTTagCompound compound) { + if (compound != null) { + int farmBlockOrdinal = compound.getInteger("FarmBlock"); + if (farmBlockOrdinal < EnumFarmBlockTexture.values().length) { + return EnumFarmBlockTexture.values()[farmBlockOrdinal]; + } + } - return EnumFarmBlockTexture.BRICK_STONE; - } + return EnumFarmBlockTexture.BRICK_STONE; + } } diff --git a/src/main/java/forestry/farming/render/RenderFarmBlock.java b/src/main/java/forestry/farming/render/RenderFarmBlock.java index 67c65732f..182d37f70 100644 --- a/src/main/java/forestry/farming/render/RenderFarmBlock.java +++ b/src/main/java/forestry/farming/render/RenderFarmBlock.java @@ -10,53 +10,119 @@ ******************************************************************************/ package forestry.farming.render; +import forestry.core.render.RenderOverlayBlock; +import forestry.farming.blocks.BlockFarm; +import forestry.plugins.PluginFarming; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.world.IBlockAccess; -import forestry.core.render.RenderOverlayBlock; -import forestry.farming.blocks.BlockFarm; -import forestry.plugins.PluginFarming; - public class RenderFarmBlock extends RenderOverlayBlock { - @Override - public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { - } + @Override + public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) {} - @Override - public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { + @Override + public boolean renderWorldBlock( + IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { - // Render the plain block. - renderer.renderStandardBlock(block, x, y, z); - renderFarmOverlay(world, PluginFarming.blocks.farm, x, y, z, renderer); + // Render the plain block. + renderer.renderStandardBlock(block, x, y, z); + renderFarmOverlay(world, PluginFarming.blocks.farm, x, y, z, renderer); - return true; - } + return true; + } - private static void renderFarmOverlay(IBlockAccess world, BlockFarm block, int x, int y, int z, RenderBlocks renderer) { - int mixedBrightness = block.getMixedBrightnessForBlock(world, x, y, z); - int metadata = world.getBlockMetadata(x, y, z); + private static void renderFarmOverlay( + IBlockAccess world, BlockFarm block, int x, int y, int z, RenderBlocks renderer) { + int mixedBrightness = block.getMixedBrightnessForBlock(world, x, y, z); + int metadata = world.getBlockMetadata(x, y, z); - float adjR = 0.5f; - float adjG = 0.5f; - float adjB = 0.5f; + float adjR = 0.5f; + float adjG = 0.5f; + float adjB = 0.5f; - renderBottomFace(world, block, x, y, z, renderer, BlockFarm.getOverlayTextureForBlock(0, metadata), mixedBrightness, adjR, adjG, adjB); - renderTopFace(world, block, x, y, z, renderer, BlockFarm.getOverlayTextureForBlock(1, metadata), mixedBrightness, adjR, adjG, adjB); - renderEastFace(world, block, x, y, z, renderer, BlockFarm.getOverlayTextureForBlock(2, metadata), mixedBrightness, adjR, adjG, adjB); - renderWestFace(world, block, x, y, z, renderer, BlockFarm.getOverlayTextureForBlock(3, metadata), mixedBrightness, adjR, adjG, adjB); - renderNorthFace(world, block, x, y, z, renderer, BlockFarm.getOverlayTextureForBlock(4, metadata), mixedBrightness, adjR, adjG, adjB); - renderSouthFace(world, block, x, y, z, renderer, BlockFarm.getOverlayTextureForBlock(5, metadata), mixedBrightness, adjR, adjG, adjB); - } + renderBottomFace( + world, + block, + x, + y, + z, + renderer, + BlockFarm.getOverlayTextureForBlock(0, metadata), + mixedBrightness, + adjR, + adjG, + adjB); + renderTopFace( + world, + block, + x, + y, + z, + renderer, + BlockFarm.getOverlayTextureForBlock(1, metadata), + mixedBrightness, + adjR, + adjG, + adjB); + renderEastFace( + world, + block, + x, + y, + z, + renderer, + BlockFarm.getOverlayTextureForBlock(2, metadata), + mixedBrightness, + adjR, + adjG, + adjB); + renderWestFace( + world, + block, + x, + y, + z, + renderer, + BlockFarm.getOverlayTextureForBlock(3, metadata), + mixedBrightness, + adjR, + adjG, + adjB); + renderNorthFace( + world, + block, + x, + y, + z, + renderer, + BlockFarm.getOverlayTextureForBlock(4, metadata), + mixedBrightness, + adjR, + adjG, + adjB); + renderSouthFace( + world, + block, + x, + y, + z, + renderer, + BlockFarm.getOverlayTextureForBlock(5, metadata), + mixedBrightness, + adjR, + adjG, + adjB); + } - @Override - public boolean shouldRender3DInInventory(int modelId) { - return true; - } + @Override + public boolean shouldRender3DInInventory(int modelId) { + return true; + } - @Override - public int getRenderId() { - return PluginFarming.modelIdFarmBlock; - } + @Override + public int getRenderId() { + return PluginFarming.modelIdFarmBlock; + } } diff --git a/src/main/java/forestry/farming/render/RenderFarmItem.java b/src/main/java/forestry/farming/render/RenderFarmItem.java index 00de22e99..00ea42f5e 100644 --- a/src/main/java/forestry/farming/render/RenderFarmItem.java +++ b/src/main/java/forestry/farming/render/RenderFarmItem.java @@ -10,114 +10,111 @@ ******************************************************************************/ package forestry.farming.render; +import forestry.core.utils.ItemStackUtil; +import forestry.farming.blocks.BlockFarm; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.ItemStack; - import net.minecraftforge.client.IItemRenderer; - import org.lwjgl.opengl.GL11; -import forestry.core.utils.ItemStackUtil; -import forestry.farming.blocks.BlockFarm; - public class RenderFarmItem implements IItemRenderer { - private static void renderFarmBlock(RenderBlocks render, ItemStack item, float translateX, float translateY, float translateZ) { - Tessellator tessellator = Tessellator.instance; - BlockFarm block = (BlockFarm) ItemStackUtil.getBlock(item); - if (block == null) { - return; - } + private static void renderFarmBlock( + RenderBlocks render, ItemStack item, float translateX, float translateY, float translateZ) { + Tessellator tessellator = Tessellator.instance; + BlockFarm block = (BlockFarm) ItemStackUtil.getBlock(item); + if (block == null) { + return; + } - block.setBlockBoundsForItemRender(); - render.setRenderBoundsFromBlock(block); + block.setBlockBoundsForItemRender(); + render.setRenderBoundsFromBlock(block); - EnumFarmBlockTexture type = EnumFarmBlockTexture.getFromCompound(item.getTagCompound()); + EnumFarmBlockTexture type = EnumFarmBlockTexture.getFromCompound(item.getTagCompound()); - GL11.glTranslatef(translateX, translateY, translateZ); + GL11.glTranslatef(translateX, translateY, translateZ); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, -1F, 0.0F); - render.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, BlockFarm.getBlockTextureForSide(type, 0)); - render.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, BlockFarm.getOverlayTextureForBlock(0, item.getItemDamage())); - tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, -1F, 0.0F); + render.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, BlockFarm.getBlockTextureForSide(type, 0)); + render.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, BlockFarm.getOverlayTextureForBlock(0, item.getItemDamage())); + tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 1.0F, 0.0F); - render.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, BlockFarm.getBlockTextureForSide(type, 1)); - render.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, BlockFarm.getOverlayTextureForBlock(1, item.getItemDamage())); - tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + render.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, BlockFarm.getBlockTextureForSide(type, 1)); + render.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, BlockFarm.getOverlayTextureForBlock(1, item.getItemDamage())); + tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, -1F); - render.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, BlockFarm.getBlockTextureForSide(type, 2)); - render.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, BlockFarm.getOverlayTextureForBlock(2, item.getItemDamage())); - tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, -1F); + render.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, BlockFarm.getBlockTextureForSide(type, 2)); + render.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, BlockFarm.getOverlayTextureForBlock(2, item.getItemDamage())); + tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 0.0F, 1.0F); - render.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, BlockFarm.getBlockTextureForSide(type, 3)); - render.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, BlockFarm.getOverlayTextureForBlock(3, item.getItemDamage())); - tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 0.0F, 1.0F); + render.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, BlockFarm.getBlockTextureForSide(type, 3)); + render.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, BlockFarm.getOverlayTextureForBlock(3, item.getItemDamage())); + tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(-1F, 0.0F, 0.0F); - render.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, BlockFarm.getBlockTextureForSide(type, 4)); - render.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, BlockFarm.getOverlayTextureForBlock(4, item.getItemDamage())); - tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(-1F, 0.0F, 0.0F); + render.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, BlockFarm.getBlockTextureForSide(type, 4)); + render.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, BlockFarm.getOverlayTextureForBlock(4, item.getItemDamage())); + tessellator.draw(); - tessellator.startDrawingQuads(); - tessellator.setNormal(1.0F, 0.0F, 0.0F); - render.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, BlockFarm.getBlockTextureForSide(type, 5)); - render.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, BlockFarm.getOverlayTextureForBlock(5, item.getItemDamage())); - tessellator.draw(); + tessellator.startDrawingQuads(); + tessellator.setNormal(1.0F, 0.0F, 0.0F); + render.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, BlockFarm.getBlockTextureForSide(type, 5)); + render.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, BlockFarm.getOverlayTextureForBlock(5, item.getItemDamage())); + tessellator.draw(); - GL11.glTranslatef(0.5F, 0.5F, 0.5F); + GL11.glTranslatef(0.5F, 0.5F, 0.5F); - block.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - } + block.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - switch (type) { - case ENTITY: - case EQUIPPED_FIRST_PERSON: - case EQUIPPED: - case INVENTORY: - return true; - default: - return false; - } - } + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + switch (type) { + case ENTITY: + case EQUIPPED_FIRST_PERSON: + case EQUIPPED: + case INVENTORY: + return true; + default: + return false; + } + } - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { - return true; - } + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return true; + } - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - switch (type) { - case ENTITY: - renderFarmBlock((RenderBlocks) data[0], item, -0.5f, -0.5f, -0.5f); - break; - case EQUIPPED: - case EQUIPPED_FIRST_PERSON: - renderFarmBlock((RenderBlocks) data[0], item, 0f, 0f, 0f); - break; - case INVENTORY: - renderFarmBlock((RenderBlocks) data[0], item, -0.5f, -0.5f, -0.5f); - break; - default: - } - - GL11.glPopAttrib(); - } + switch (type) { + case ENTITY: + renderFarmBlock((RenderBlocks) data[0], item, -0.5f, -0.5f, -0.5f); + break; + case EQUIPPED: + case EQUIPPED_FIRST_PERSON: + renderFarmBlock((RenderBlocks) data[0], item, 0f, 0f, 0f); + break; + case INVENTORY: + renderFarmBlock((RenderBlocks) data[0], item, -0.5f, -0.5f, -0.5f); + break; + default: + } + GL11.glPopAttrib(); + } } diff --git a/src/main/java/forestry/farming/tiles/TileFarm.java b/src/main/java/forestry/farming/tiles/TileFarm.java index 39fdde0a3..ae8006168 100644 --- a/src/main/java/forestry/farming/tiles/TileFarm.java +++ b/src/main/java/forestry/farming/tiles/TileFarm.java @@ -10,14 +10,6 @@ ******************************************************************************/ package forestry.farming.tiles; -import java.io.IOException; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ChunkCoordinates; - import forestry.api.circuits.ICircuitSocketType; import forestry.api.core.IErrorLogic; import forestry.api.core.IErrorLogicSource; @@ -39,145 +31,159 @@ import forestry.farming.gui.ContainerFarm; import forestry.farming.gui.GuiFarm; import forestry.farming.multiblock.MultiblockLogicFarm; import forestry.farming.render.EnumFarmBlockTexture; +import java.io.IOException; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChunkCoordinates; -public abstract class TileFarm extends MultiblockTileEntityForestry implements IFarmComponent, IHintSource, ISocketable, IStreamableGui, IErrorLogicSource, IRestrictedAccess, ITitled { +public abstract class TileFarm extends MultiblockTileEntityForestry + implements IFarmComponent, + IHintSource, + ISocketable, + IStreamableGui, + IErrorLogicSource, + IRestrictedAccess, + ITitled { - private EnumFarmBlockTexture farmBlockTexture = EnumFarmBlockTexture.BRICK_STONE; + private EnumFarmBlockTexture farmBlockTexture = EnumFarmBlockTexture.BRICK_STONE; - protected TileFarm() { - super(new MultiblockLogicFarm()); - } + protected TileFarm() { + super(new MultiblockLogicFarm()); + } - @Override - public void onMachineAssembled(IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord) { - worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); - markDirty(); - } + @Override + public void onMachineAssembled( + IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord) { + worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); + markDirty(); + } - @Override - public void onMachineBroken() { - worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); - markDirty(); - } + @Override + public void onMachineBroken() { + worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); + markDirty(); + } - @Override - public IInventoryAdapter getInternalInventory() { - return getMultiblockLogic().getController().getInternalInventory(); - } + @Override + public IInventoryAdapter getInternalInventory() { + return getMultiblockLogic().getController().getInternalInventory(); + } - @Override - public boolean allowsAutomation() { - return false; - } + @Override + public boolean allowsAutomation() { + return false; + } - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - farmBlockTexture = EnumFarmBlockTexture.getFromCompound(nbttagcompound); - } + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + farmBlockTexture = EnumFarmBlockTexture.getFromCompound(nbttagcompound); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - farmBlockTexture.saveToCompound(nbttagcompound); - } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + farmBlockTexture.saveToCompound(nbttagcompound); + } - /* CONSTRUCTION MATERIAL */ + /* CONSTRUCTION MATERIAL */ - public void setFarmBlockTexture(EnumFarmBlockTexture farmBlockTexture) { - if (this.farmBlockTexture != farmBlockTexture) { - this.farmBlockTexture = farmBlockTexture; - worldObj.func_147479_m(xCoord, yCoord, zCoord); - } - } + public void setFarmBlockTexture(EnumFarmBlockTexture farmBlockTexture) { + if (this.farmBlockTexture != farmBlockTexture) { + this.farmBlockTexture = farmBlockTexture; + worldObj.func_147479_m(xCoord, yCoord, zCoord); + } + } - public EnumFarmBlockTexture getFarmBlockTexture() { - return farmBlockTexture; - } + public EnumFarmBlockTexture getFarmBlockTexture() { + return farmBlockTexture; + } - /* TILEFORESTRY */ + /* TILEFORESTRY */ - @Override - protected void encodeDescriptionPacket(NBTTagCompound packetData) { - super.encodeDescriptionPacket(packetData); - farmBlockTexture.saveToCompound(packetData); - } + @Override + protected void encodeDescriptionPacket(NBTTagCompound packetData) { + super.encodeDescriptionPacket(packetData); + farmBlockTexture.saveToCompound(packetData); + } - @Override - protected void decodeDescriptionPacket(NBTTagCompound packetData) { - super.decodeDescriptionPacket(packetData); - EnumFarmBlockTexture farmBlockTexture = EnumFarmBlockTexture.getFromCompound(packetData); - setFarmBlockTexture(farmBlockTexture); - } + @Override + protected void decodeDescriptionPacket(NBTTagCompound packetData) { + super.decodeDescriptionPacket(packetData); + EnumFarmBlockTexture farmBlockTexture = EnumFarmBlockTexture.getFromCompound(packetData); + setFarmBlockTexture(farmBlockTexture); + } - /* IHintSource */ - @Override - public List getHints() { - return Config.hints.get("farm"); - } + /* IHintSource */ + @Override + public List getHints() { + return Config.hints.get("farm"); + } - /* ISocketable */ - @Override - public int getSocketCount() { - return getMultiblockLogic().getController().getSocketCount(); - } + /* ISocketable */ + @Override + public int getSocketCount() { + return getMultiblockLogic().getController().getSocketCount(); + } - @Override - public ItemStack getSocket(int slot) { - return getMultiblockLogic().getController().getSocket(slot); - } + @Override + public ItemStack getSocket(int slot) { + return getMultiblockLogic().getController().getSocket(slot); + } - @Override - public void setSocket(int slot, ItemStack stack) { - getMultiblockLogic().getController().setSocket(slot, stack); - } + @Override + public void setSocket(int slot, ItemStack stack) { + getMultiblockLogic().getController().setSocket(slot, stack); + } - @Override - public ICircuitSocketType getSocketType() { - return getMultiblockLogic().getController().getSocketType(); - } + @Override + public ICircuitSocketType getSocketType() { + return getMultiblockLogic().getController().getSocketType(); + } - /* IStreamableGui */ - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - getMultiblockLogic().getController().writeGuiData(data); - } + /* IStreamableGui */ + @Override + public void writeGuiData(DataOutputStreamForestry data) throws IOException { + getMultiblockLogic().getController().writeGuiData(data); + } - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - getMultiblockLogic().getController().readGuiData(data); - } + @Override + public void readGuiData(DataInputStreamForestry data) throws IOException { + getMultiblockLogic().getController().readGuiData(data); + } - /* IErrorLogicSource */ - @Override - public IErrorLogic getErrorLogic() { - return getMultiblockLogic().getController().getErrorLogic(); - } + /* IErrorLogicSource */ + @Override + public IErrorLogic getErrorLogic() { + return getMultiblockLogic().getController().getErrorLogic(); + } - @Override - public IAccessHandler getAccessHandler() { - return getMultiblockLogic().getController().getAccessHandler(); - } + @Override + public IAccessHandler getAccessHandler() { + return getMultiblockLogic().getController().getAccessHandler(); + } - @Override - public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { - getMultiblockLogic().getController().onSwitchAccess(oldAccess, newAccess); - } + @Override + public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { + getMultiblockLogic().getController().onSwitchAccess(oldAccess, newAccess); + } - /* ITitled */ - @Override - public String getUnlocalizedTitle() { - return "for.gui.farm.title"; - } + /* ITitled */ + @Override + public String getUnlocalizedTitle() { + return "for.gui.farm.title"; + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiFarm(player, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiFarm(player, this); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerFarm(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerFarm(player.inventory, this); + } } diff --git a/src/main/java/forestry/farming/tiles/TileFarmControl.java b/src/main/java/forestry/farming/tiles/TileFarmControl.java index 2a517be2b..66a73a741 100644 --- a/src/main/java/forestry/farming/tiles/TileFarmControl.java +++ b/src/main/java/forestry/farming/tiles/TileFarmControl.java @@ -10,49 +10,49 @@ ******************************************************************************/ package forestry.farming.tiles; -import net.minecraft.world.World; - -import net.minecraftforge.common.util.ForgeDirection; - import forestry.api.farming.DefaultFarmListener; import forestry.api.farming.FarmDirection; import forestry.api.farming.IFarmListener; import forestry.api.farming.IFarmLogic; import forestry.api.multiblock.IFarmComponent; import forestry.core.utils.vect.Vect; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; public class TileFarmControl extends TileFarm implements IFarmComponent.Listener { - private final IFarmListener farmListener; + private final IFarmListener farmListener; - public TileFarmControl() { - this.farmListener = new ControlFarmListener(this); - } + public TileFarmControl() { + this.farmListener = new ControlFarmListener(this); + } - @Override - public IFarmListener getFarmListener() { - return farmListener; - } + @Override + public IFarmListener getFarmListener() { + return farmListener; + } - private static class ControlFarmListener extends DefaultFarmListener { - private final TileFarmControl tile; + private static class ControlFarmListener extends DefaultFarmListener { + private final TileFarmControl tile; - public ControlFarmListener(TileFarmControl tile) { - this.tile = tile; - } + public ControlFarmListener(TileFarmControl tile) { + this.tile = tile; + } - @Override - public boolean cancelTask(IFarmLogic logic, FarmDirection direction) { - return hasRedstoneSignal(direction.getForgeDirection()) || hasRedstoneSignal(ForgeDirection.UP) || hasRedstoneSignal(ForgeDirection.DOWN); - } + @Override + public boolean cancelTask(IFarmLogic logic, FarmDirection direction) { + return hasRedstoneSignal(direction.getForgeDirection()) + || hasRedstoneSignal(ForgeDirection.UP) + || hasRedstoneSignal(ForgeDirection.DOWN); + } - private boolean hasRedstoneSignal(ForgeDirection direction) { - Vect side = new Vect(tile).add(direction); - int dir = direction.getOpposite().ordinal(); - World world = tile.getWorldObj(); - - return world.getIndirectPowerLevelTo(side.x, side.y, side.z, dir) > 0 || world.isBlockProvidingPowerTo(side.x, side.y, side.z, dir) > 0; - } - } + private boolean hasRedstoneSignal(ForgeDirection direction) { + Vect side = new Vect(tile).add(direction); + int dir = direction.getOpposite().ordinal(); + World world = tile.getWorldObj(); + return world.getIndirectPowerLevelTo(side.x, side.y, side.z, dir) > 0 + || world.isBlockProvidingPowerTo(side.x, side.y, side.z, dir) > 0; + } + } } diff --git a/src/main/java/forestry/farming/tiles/TileFarmGearbox.java b/src/main/java/forestry/farming/tiles/TileFarmGearbox.java index 3f40ac3de..bd7c19f68 100644 --- a/src/main/java/forestry/farming/tiles/TileFarmGearbox.java +++ b/src/main/java/forestry/farming/tiles/TileFarmGearbox.java @@ -10,112 +10,107 @@ ******************************************************************************/ package forestry.farming.tiles; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.util.ForgeDirection; - import forestry.api.multiblock.IFarmComponent; import forestry.api.multiblock.IFarmController; import forestry.core.tiles.IPowerHandler; import forestry.energy.EnergyManager; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; public class TileFarmGearbox extends TileFarm implements IPowerHandler, IFarmComponent.Active { - private static final int WORK_CYCLES = 4; - private static final int ENERGY_PER_OPERATION = WORK_CYCLES * 50; + private static final int WORK_CYCLES = 4; + private static final int ENERGY_PER_OPERATION = WORK_CYCLES * 50; - private final EnergyManager energyManager; + private final EnergyManager energyManager; - private int activationDelay = 0; - private int previousDelays = 0; - private int workCounter; + private int activationDelay = 0; + private int previousDelays = 0; + private int workCounter; - public TileFarmGearbox() { - energyManager = new EnergyManager(200, 10000); - } + public TileFarmGearbox() { + energyManager = new EnergyManager(200, 10000); + } - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - energyManager.readFromNBT(nbttagcompound); + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + energyManager.readFromNBT(nbttagcompound); - activationDelay = nbttagcompound.getInteger("ActivationDelay"); - previousDelays = nbttagcompound.getInteger("PrevDelays"); - } + activationDelay = nbttagcompound.getInteger("ActivationDelay"); + previousDelays = nbttagcompound.getInteger("PrevDelays"); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - energyManager.writeToNBT(nbttagcompound); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + energyManager.writeToNBT(nbttagcompound); - nbttagcompound.setInteger("ActivationDelay", activationDelay); - nbttagcompound.setInteger("PrevDelays", previousDelays); - } + nbttagcompound.setInteger("ActivationDelay", activationDelay); + nbttagcompound.setInteger("PrevDelays", previousDelays); + } - @Override - public void updateServer(int tickCount) { - if (energyManager.getTotalEnergyStored() <= 0) { - return; - } + @Override + public void updateServer(int tickCount) { + if (energyManager.getTotalEnergyStored() <= 0) { + return; + } - if (activationDelay > 0) { - activationDelay--; - return; - } + if (activationDelay > 0) { + activationDelay--; + return; + } - // Hard limit to 4 cycles / second. - if (workCounter < WORK_CYCLES && energyManager.consumeEnergyToDoWork(WORK_CYCLES, ENERGY_PER_OPERATION)) { - workCounter++; - } + // Hard limit to 4 cycles / second. + if (workCounter < WORK_CYCLES && energyManager.consumeEnergyToDoWork(WORK_CYCLES, ENERGY_PER_OPERATION)) { + workCounter++; + } - if (workCounter >= WORK_CYCLES && (tickCount % 5 == 0)) { - IFarmController farmController = getMultiblockLogic().getController(); - if (farmController.doWork()) { - workCounter = 0; - previousDelays = 0; - } else { - // If the central TE doesn't have work, we add to the activation delay to throttle the CPU usage. - activationDelay = 10 * previousDelays < 120 ? 10 * previousDelays : 120; - previousDelays++; // First delay is free! - } - } - } + if (workCounter >= WORK_CYCLES && (tickCount % 5 == 0)) { + IFarmController farmController = getMultiblockLogic().getController(); + if (farmController.doWork()) { + workCounter = 0; + previousDelays = 0; + } else { + // If the central TE doesn't have work, we add to the activation delay to throttle the CPU usage. + activationDelay = 10 * previousDelays < 120 ? 10 * previousDelays : 120; + previousDelays++; // First delay is free! + } + } + } - @Override - public void updateClient(int tickCount) { + @Override + public void updateClient(int tickCount) {} - } + /* IPowerHandler */ + @Override + public EnergyManager getEnergyManager() { + return energyManager; + } - /* IPowerHandler */ - @Override - public EnergyManager getEnergyManager() { - return energyManager; - } + @Override + public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + return energyManager.receiveEnergy(from, maxReceive, simulate); + } - @Override - public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { - return energyManager.receiveEnergy(from, maxReceive, simulate); - } + @Override + public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { + return energyManager.extractEnergy(from, maxExtract, simulate); + } - @Override - public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { - return energyManager.extractEnergy(from, maxExtract, simulate); - } + @Override + public int getEnergyStored(ForgeDirection from) { + return energyManager.getEnergyStored(from); + } - @Override - public int getEnergyStored(ForgeDirection from) { - return energyManager.getEnergyStored(from); - } - - @Override - public int getMaxEnergyStored(ForgeDirection from) { - return energyManager.getMaxEnergyStored(from); - } - - @Override - public boolean canConnectEnergy(ForgeDirection from) { - return energyManager.canConnectEnergy(from); - } + @Override + public int getMaxEnergyStored(ForgeDirection from) { + return energyManager.getMaxEnergyStored(from); + } + @Override + public boolean canConnectEnergy(ForgeDirection from) { + return energyManager.canConnectEnergy(from); + } } diff --git a/src/main/java/forestry/farming/tiles/TileFarmHatch.java b/src/main/java/forestry/farming/tiles/TileFarmHatch.java index 68b5b4bec..aab3623af 100644 --- a/src/main/java/forestry/farming/tiles/TileFarmHatch.java +++ b/src/main/java/forestry/farming/tiles/TileFarmHatch.java @@ -10,82 +10,75 @@ ******************************************************************************/ package forestry.farming.tiles; -import java.util.Collection; -import java.util.Collections; - -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.statements.IStatementContainer; +import buildcraft.api.statements.ITriggerExternal; +import buildcraft.api.statements.ITriggerInternal; +import buildcraft.api.statements.ITriggerProvider; import cpw.mods.fml.common.Optional; - import forestry.api.multiblock.IFarmComponent; import forestry.core.inventory.AdjacentInventoryCache; import forestry.core.tiles.AdjacentTileCache; import forestry.core.utils.InventoryUtil; import forestry.farming.triggers.FarmingTriggers; - -import buildcraft.api.statements.IStatementContainer; -import buildcraft.api.statements.ITriggerExternal; -import buildcraft.api.statements.ITriggerInternal; -import buildcraft.api.statements.ITriggerProvider; +import java.util.Collection; +import java.util.Collections; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; @Optional.Interface(iface = "buildcraft.api.statements.ITriggerProvider", modid = "BuildCraftAPI|statements") public class TileFarmHatch extends TileFarm implements ISidedInventory, IFarmComponent.Active, ITriggerProvider { - private static final ForgeDirection[] dumpDirections = new ForgeDirection[]{ForgeDirection.DOWN}; + private static final ForgeDirection[] dumpDirections = new ForgeDirection[] {ForgeDirection.DOWN}; - private final AdjacentTileCache tileCache; - private final AdjacentInventoryCache inventoryCache; + private final AdjacentTileCache tileCache; + private final AdjacentInventoryCache inventoryCache; - public TileFarmHatch() { - this.tileCache = new AdjacentTileCache(this); - this.inventoryCache = new AdjacentInventoryCache(this, tileCache, new AdjacentInventoryCache.ITileFilter() { - @Override - public boolean matches(TileEntity tile) { - return !(tile instanceof TileFarm) && tile.yCoord < yCoord; - } - }); - } + public TileFarmHatch() { + this.tileCache = new AdjacentTileCache(this); + this.inventoryCache = new AdjacentInventoryCache(this, tileCache, new AdjacentInventoryCache.ITileFilter() { + @Override + public boolean matches(TileEntity tile) { + return !(tile instanceof TileFarm) && tile.yCoord < yCoord; + } + }); + } - @Override - public boolean allowsAutomation() { - return true; - } + @Override + public boolean allowsAutomation() { + return true; + } - @Override - public void updateServer(int tickCount) { - if (tickCount % 40 == 0) { - IInventory productInventory = getMultiblockLogic().getController().getFarmInventory().getProductInventory(); + @Override + public void updateServer(int tickCount) { + if (tickCount % 40 == 0) { + IInventory productInventory = + getMultiblockLogic().getController().getFarmInventory().getProductInventory(); - if (!InventoryUtil.moveOneItemToPipe(productInventory, tileCache, dumpDirections)) { - InventoryUtil.moveItemStack(productInventory, inventoryCache.getAdjacentInventories()); - } - } - } + if (!InventoryUtil.moveOneItemToPipe(productInventory, tileCache, dumpDirections)) { + InventoryUtil.moveItemStack(productInventory, inventoryCache.getAdjacentInventories()); + } + } + } - @Override - public void updateClient(int tickCount) { + @Override + public void updateClient(int tickCount) {} - } + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getInternalTriggers(IStatementContainer container) { + return Collections.emptyList(); + } - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getInternalTriggers(IStatementContainer container) { - return Collections.emptyList(); - } - - /* ITRIGGERPROVIDER */ - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { - if (!getMultiblockLogic().isConnected()) { - return Collections.emptyList(); - } - - return FarmingTriggers.allExternalTriggers; - } + /* ITRIGGERPROVIDER */ + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { + if (!getMultiblockLogic().isConnected()) { + return Collections.emptyList(); + } + return FarmingTriggers.allExternalTriggers; + } } diff --git a/src/main/java/forestry/farming/tiles/TileFarmPlain.java b/src/main/java/forestry/farming/tiles/TileFarmPlain.java index 458cba95d..47ea3066e 100644 --- a/src/main/java/forestry/farming/tiles/TileFarmPlain.java +++ b/src/main/java/forestry/farming/tiles/TileFarmPlain.java @@ -10,27 +10,27 @@ ******************************************************************************/ package forestry.farming.tiles; +import forestry.api.multiblock.IMultiblockController; import net.minecraft.util.ChunkCoordinates; -import forestry.api.multiblock.IMultiblockController; - public class TileFarmPlain extends TileFarm { - @Override - public void onMachineAssembled(IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord) { - super.onMachineAssembled(multiblockController, minCoord, maxCoord); + @Override + public void onMachineAssembled( + IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord) { + super.onMachineAssembled(multiblockController, minCoord, maxCoord); - // set band block meta - int bandY = maxCoord.posY - 1; - if (yCoord == bandY) { - this.worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 1, 2); - } - } + // set band block meta + int bandY = maxCoord.posY - 1; + if (yCoord == bandY) { + this.worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 1, 2); + } + } - @Override - public void onMachineBroken() { - super.onMachineBroken(); + @Override + public void onMachineBroken() { + super.onMachineBroken(); - // set band block meta back to normal - this.worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 2); - } + // set band block meta back to normal + this.worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 2); + } } diff --git a/src/main/java/forestry/farming/tiles/TileFarmValve.java b/src/main/java/forestry/farming/tiles/TileFarmValve.java index 8ea631a90..35ad8ff6f 100644 --- a/src/main/java/forestry/farming/tiles/TileFarmValve.java +++ b/src/main/java/forestry/farming/tiles/TileFarmValve.java @@ -10,50 +10,49 @@ ******************************************************************************/ package forestry.farming.tiles; +import forestry.core.fluids.ITankManager; +import forestry.core.tiles.ILiquidTankTile; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; -import forestry.core.fluids.ITankManager; -import forestry.core.tiles.ILiquidTankTile; - public class TileFarmValve extends TileFarm implements ILiquidTankTile, IFluidHandler { - /* ILIQUIDTANKCONTAINER */ - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - return getTankManager().fill(from, resource, doFill); - } + /* ILIQUIDTANKCONTAINER */ + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + return getTankManager().fill(from, resource, doFill); + } - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { - return getTankManager().drain(from, resource, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return getTankManager().drain(from, resource, doDrain); + } - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return getTankManager().drain(from, maxDrain, doDrain); - } + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return getTankManager().drain(from, maxDrain, doDrain); + } - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return getTankManager().canFill(from, fluid); - } + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return getTankManager().canFill(from, fluid); + } - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return getTankManager().canDrain(from, fluid); - } + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return getTankManager().canDrain(from, fluid); + } - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return getTankManager().getTankInfo(from); - } + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return getTankManager().getTankInfo(from); + } - @Override - public ITankManager getTankManager() { - return getMultiblockLogic().getController().getTankManager(); - } + @Override + public ITankManager getTankManager() { + return getMultiblockLogic().getController().getTankManager(); + } } diff --git a/src/main/java/forestry/farming/triggers/FarmingTriggers.java b/src/main/java/forestry/farming/triggers/FarmingTriggers.java index fb15d5120..cb72ead4c 100644 --- a/src/main/java/forestry/farming/triggers/FarmingTriggers.java +++ b/src/main/java/forestry/farming/triggers/FarmingTriggers.java @@ -10,36 +10,33 @@ ******************************************************************************/ package forestry.farming.triggers; +import buildcraft.api.statements.ITriggerExternal; +import forestry.core.triggers.Trigger; import java.util.Arrays; import java.util.List; -import forestry.core.triggers.Trigger; - -import buildcraft.api.statements.ITriggerExternal; - public class FarmingTriggers { - public static Trigger lowResourceLiquid50; - public static Trigger lowResourceLiquid25; - public static Trigger lowSoil128; - public static Trigger lowSoil64; - public static Trigger lowSoil32; - public static Trigger lowFertilizer50; - public static Trigger lowFertilizer25; - public static Trigger lowGermlings25; - public static Trigger lowGermlings10; - public static List allExternalTriggers; + public static Trigger lowResourceLiquid50; + public static Trigger lowResourceLiquid25; + public static Trigger lowSoil128; + public static Trigger lowSoil64; + public static Trigger lowSoil32; + public static Trigger lowFertilizer50; + public static Trigger lowFertilizer25; + public static Trigger lowGermlings25; + public static Trigger lowGermlings10; + public static List allExternalTriggers; - public static void initialize() { - allExternalTriggers = Arrays.asList( - lowResourceLiquid50 = new TriggerLowLiquid("lowLiquid.50", 0.5f), - lowResourceLiquid25 = new TriggerLowLiquid("lowLiquid.25", 0.25f), - lowSoil128 = new TriggerLowSoil(128), - lowSoil64 = new TriggerLowSoil(64), - lowSoil32 = new TriggerLowSoil(32), - lowFertilizer50 = new TriggerLowFertilizer("lowFertilizer.50", 0.5f), - lowFertilizer25 = new TriggerLowFertilizer("lowFertilizer.25", 0.25f), - lowGermlings25 = new TriggerLowGermlings("lowGermlings.25", 0.25f), - lowGermlings10 = new TriggerLowGermlings("lowGermlings.10", 0.1f) - ); - } + public static void initialize() { + allExternalTriggers = Arrays.asList( + lowResourceLiquid50 = new TriggerLowLiquid("lowLiquid.50", 0.5f), + lowResourceLiquid25 = new TriggerLowLiquid("lowLiquid.25", 0.25f), + lowSoil128 = new TriggerLowSoil(128), + lowSoil64 = new TriggerLowSoil(64), + lowSoil32 = new TriggerLowSoil(32), + lowFertilizer50 = new TriggerLowFertilizer("lowFertilizer.50", 0.5f), + lowFertilizer25 = new TriggerLowFertilizer("lowFertilizer.25", 0.25f), + lowGermlings25 = new TriggerLowGermlings("lowGermlings.25", 0.25f), + lowGermlings10 = new TriggerLowGermlings("lowGermlings.10", 0.1f)); + } } diff --git a/src/main/java/forestry/farming/triggers/TriggerLowFertilizer.java b/src/main/java/forestry/farming/triggers/TriggerLowFertilizer.java index 5017e140e..d43183fb6 100755 --- a/src/main/java/forestry/farming/triggers/TriggerLowFertilizer.java +++ b/src/main/java/forestry/farming/triggers/TriggerLowFertilizer.java @@ -10,40 +10,42 @@ ******************************************************************************/ package forestry.farming.triggers; -import net.minecraft.inventory.IInventory; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.statements.IStatementContainer; +import buildcraft.api.statements.IStatementParameter; import forestry.core.triggers.Trigger; import forestry.core.utils.InventoryUtil; import forestry.farming.tiles.TileFarmHatch; - -import buildcraft.api.statements.IStatementContainer; -import buildcraft.api.statements.IStatementParameter; +import net.minecraft.inventory.IInventory; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TriggerLowFertilizer extends Trigger { - private final float threshold; + private final float threshold; - public TriggerLowFertilizer(String tag, float threshold) { - super(tag, "lowFertilizer"); - this.threshold = threshold; - } + public TriggerLowFertilizer(String tag, float threshold) { + super(tag, "lowFertilizer"); + this.threshold = threshold; + } - @Override - public String getDescription() { - return super.getDescription() + " < " + threshold * 100 + "%"; - } + @Override + public String getDescription() { + return super.getDescription() + " < " + threshold * 100 + "%"; + } - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - if (!(tile instanceof TileFarmHatch)) { - return false; - } + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + if (!(tile instanceof TileFarmHatch)) { + return false; + } - TileFarmHatch tileHatch = (TileFarmHatch) tile; - IInventory fertilizerInventory = tileHatch.getMultiblockLogic().getController().getFarmInventory().getFertilizerInventory(); - return !InventoryUtil.containsPercent(fertilizerInventory, threshold); - } + TileFarmHatch tileHatch = (TileFarmHatch) tile; + IInventory fertilizerInventory = tileHatch + .getMultiblockLogic() + .getController() + .getFarmInventory() + .getFertilizerInventory(); + return !InventoryUtil.containsPercent(fertilizerInventory, threshold); + } } diff --git a/src/main/java/forestry/farming/triggers/TriggerLowGermlings.java b/src/main/java/forestry/farming/triggers/TriggerLowGermlings.java index 890edf293..21279907a 100644 --- a/src/main/java/forestry/farming/triggers/TriggerLowGermlings.java +++ b/src/main/java/forestry/farming/triggers/TriggerLowGermlings.java @@ -10,43 +10,45 @@ ******************************************************************************/ package forestry.farming.triggers; -import net.minecraft.inventory.IInventory; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.statements.IStatementContainer; +import buildcraft.api.statements.IStatementParameter; import forestry.core.triggers.Trigger; import forestry.core.utils.InventoryUtil; import forestry.farming.tiles.TileFarmHatch; - -import buildcraft.api.statements.IStatementContainer; -import buildcraft.api.statements.IStatementParameter; +import net.minecraft.inventory.IInventory; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TriggerLowGermlings extends Trigger { - private final float threshold; + private final float threshold; - public TriggerLowGermlings(String tag, float threshold) { - super(tag, "lowGermlings"); - this.threshold = threshold; - } + public TriggerLowGermlings(String tag, float threshold) { + super(tag, "lowGermlings"); + this.threshold = threshold; + } - @Override - public String getDescription() { - return super.getDescription() + " < " + threshold * 100 + "%"; - } + @Override + public String getDescription() { + return super.getDescription() + " < " + threshold * 100 + "%"; + } - /** - * Return true if the tile given in parameter activates the trigger, given the parameters. - */ - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - if (!(tile instanceof TileFarmHatch)) { - return false; - } + /** + * Return true if the tile given in parameter activates the trigger, given the parameters. + */ + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + if (!(tile instanceof TileFarmHatch)) { + return false; + } - TileFarmHatch tileHatch = (TileFarmHatch) tile; - IInventory germlingsInventory = tileHatch.getMultiblockLogic().getController().getFarmInventory().getGermlingsInventory(); - return !InventoryUtil.containsPercent(germlingsInventory, threshold); - } + TileFarmHatch tileHatch = (TileFarmHatch) tile; + IInventory germlingsInventory = tileHatch + .getMultiblockLogic() + .getController() + .getFarmInventory() + .getGermlingsInventory(); + return !InventoryUtil.containsPercent(germlingsInventory, threshold); + } } diff --git a/src/main/java/forestry/farming/triggers/TriggerLowLiquid.java b/src/main/java/forestry/farming/triggers/TriggerLowLiquid.java index 9d077ca8f..32bc44733 100755 --- a/src/main/java/forestry/farming/triggers/TriggerLowLiquid.java +++ b/src/main/java/forestry/farming/triggers/TriggerLowLiquid.java @@ -10,49 +10,48 @@ ******************************************************************************/ package forestry.farming.triggers; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.IFluidTank; - +import buildcraft.api.statements.IStatementContainer; +import buildcraft.api.statements.IStatementParameter; import forestry.core.fluids.ITankManager; import forestry.core.triggers.Trigger; import forestry.farming.tiles.TileFarmHatch; - -import buildcraft.api.statements.IStatementContainer; -import buildcraft.api.statements.IStatementParameter; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.IFluidTank; public class TriggerLowLiquid extends Trigger { - private final float threshold; + private final float threshold; - public TriggerLowLiquid(String tag, float threshold) { - super(tag, "lowLiquid"); - this.threshold = threshold; - } + public TriggerLowLiquid(String tag, float threshold) { + super(tag, "lowLiquid"); + this.threshold = threshold; + } - @Override - public String getDescription() { - return super.getDescription() + " < " + threshold * 100 + "%"; - } + @Override + public String getDescription() { + return super.getDescription() + " < " + threshold * 100 + "%"; + } - /** - * Return true if the tile given in parameter activates the trigger, given - * the parameters. - */ - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - if (!(tile instanceof TileFarmHatch)) { - return false; - } + /** + * Return true if the tile given in parameter activates the trigger, given + * the parameters. + */ + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + if (!(tile instanceof TileFarmHatch)) { + return false; + } - TileFarmHatch tileHatch = (TileFarmHatch) tile; - ITankManager tankManager = tileHatch.getMultiblockLogic().getController().getTankManager(); + TileFarmHatch tileHatch = (TileFarmHatch) tile; + ITankManager tankManager = + tileHatch.getMultiblockLogic().getController().getTankManager(); - IFluidTank tank = tankManager.getTank(0); - if (tank.getCapacity() == 0) { - return false; - } - return ((float) tank.getFluidAmount() / tank.getCapacity()) <= threshold; - } + IFluidTank tank = tankManager.getTank(0); + if (tank.getCapacity() == 0) { + return false; + } + return ((float) tank.getFluidAmount() / tank.getCapacity()) <= threshold; + } } diff --git a/src/main/java/forestry/farming/triggers/TriggerLowSoil.java b/src/main/java/forestry/farming/triggers/TriggerLowSoil.java index 26516be79..31a9edce7 100755 --- a/src/main/java/forestry/farming/triggers/TriggerLowSoil.java +++ b/src/main/java/forestry/farming/triggers/TriggerLowSoil.java @@ -10,77 +10,75 @@ ******************************************************************************/ package forestry.farming.triggers; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.statements.IStatementContainer; +import buildcraft.api.statements.IStatementParameter; +import buildcraft.api.statements.StatementParameterItemStack; import forestry.api.farming.IFarmInventory; import forestry.api.multiblock.IFarmController; import forestry.core.triggers.Trigger; import forestry.core.utils.InventoryUtil; import forestry.farming.tiles.TileFarmHatch; - -import buildcraft.api.statements.IStatementContainer; -import buildcraft.api.statements.IStatementParameter; -import buildcraft.api.statements.StatementParameterItemStack; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TriggerLowSoil extends Trigger { - private final int threshold; + private final int threshold; - public TriggerLowSoil(int threshold) { - super("lowSoil." + threshold, "lowSoil"); - this.threshold = threshold; - } + public TriggerLowSoil(int threshold) { + super("lowSoil." + threshold, "lowSoil"); + this.threshold = threshold; + } - @Override - public String getDescription() { - return super.getDescription() + " < " + threshold; - } + @Override + public String getDescription() { + return super.getDescription() + " < " + threshold; + } - @Override - public int maxParameters() { - return 1; - } + @Override + public int maxParameters() { + return 1; + } - @Override - public int minParameters() { - return 0; - } + @Override + public int minParameters() { + return 0; + } - @Override - public IStatementParameter createParameter(int index) { - return new StatementParameterItemStack(); - } + @Override + public IStatementParameter createParameter(int index) { + return new StatementParameterItemStack(); + } - /** - * Return true if the tile given in parameter activates the trigger, given - * the parameters. - */ - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - IStatementParameter parameter = null; - if (parameters.length > 0) { - parameter = parameters[0]; - } + /** + * Return true if the tile given in parameter activates the trigger, given + * the parameters. + */ + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + IStatementParameter parameter = null; + if (parameters.length > 0) { + parameter = parameters[0]; + } - if (!(tile instanceof TileFarmHatch)) { - return false; - } + if (!(tile instanceof TileFarmHatch)) { + return false; + } - TileFarmHatch tileHatch = (TileFarmHatch) tile; - IFarmController farmController = tileHatch.getMultiblockLogic().getController(); - IFarmInventory farmInventory = farmController.getFarmInventory(); - IInventory resourcesInventory = farmInventory.getResourcesInventory(); + TileFarmHatch tileHatch = (TileFarmHatch) tile; + IFarmController farmController = tileHatch.getMultiblockLogic().getController(); + IFarmInventory farmInventory = farmController.getFarmInventory(); + IInventory resourcesInventory = farmInventory.getResourcesInventory(); - if (parameter == null || parameter.getItemStack() == null) { - return !InventoryUtil.containsAmount(resourcesInventory, threshold); - } else { - ItemStack filter = parameter.getItemStack().copy(); - filter.stackSize = threshold; - return !InventoryUtil.contains(resourcesInventory, new ItemStack[]{filter}); - } - } + if (parameter == null || parameter.getItemStack() == null) { + return !InventoryUtil.containsAmount(resourcesInventory, threshold); + } else { + ItemStack filter = parameter.getItemStack().copy(); + filter.stackSize = threshold; + return !InventoryUtil.contains(resourcesInventory, new ItemStack[] {filter}); + } + } } diff --git a/src/main/java/forestry/food/BeverageEffect.java b/src/main/java/forestry/food/BeverageEffect.java index 2c11208b9..b5473fcb8 100755 --- a/src/main/java/forestry/food/BeverageEffect.java +++ b/src/main/java/forestry/food/BeverageEffect.java @@ -10,96 +10,94 @@ ******************************************************************************/ package forestry.food; +import forestry.api.food.BeverageManager; +import forestry.api.food.IBeverageEffect; +import forestry.core.utils.StringUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import forestry.api.food.BeverageManager; -import forestry.api.food.IBeverageEffect; -import forestry.core.utils.StringUtil; - public abstract class BeverageEffect implements IBeverageEffect { - public static final IBeverageEffect weakAlcoholic = new BeverageEffectDrunk(10, 0.2f); - public static final IBeverageEffect weakAntidote = new BeverageEffectAntidote(20, 0.5f); - public static final IBeverageEffect strongAntidote = new BeverageEffectAntidote(21, 1.0f); + public static final IBeverageEffect weakAlcoholic = new BeverageEffectDrunk(10, 0.2f); + public static final IBeverageEffect weakAntidote = new BeverageEffectAntidote(20, 0.5f); + public static final IBeverageEffect strongAntidote = new BeverageEffectAntidote(21, 1.0f); - private final int id; - protected String description; + private final int id; + protected String description; - protected BeverageEffect(int id) { - this.id = id; + protected BeverageEffect(int id) { + this.id = id; - if (BeverageManager.effectList[id] != null) { - throw new RuntimeException("Beverage effect slot " + id + " was already occupied by " + BeverageManager.effectList[id].toString() - + " when trying to add " + this.toString()); - } else { - BeverageManager.effectList[id] = this; - } - } + if (BeverageManager.effectList[id] != null) { + throw new RuntimeException("Beverage effect slot " + id + " was already occupied by " + + BeverageManager.effectList[id].toString() + " when trying to add " + this.toString()); + } else { + BeverageManager.effectList[id] = this; + } + } - public int getId() { - return this.id; - } + public int getId() { + return this.id; + } - protected String getLevel() { - return null; - } + protected String getLevel() { + return null; + } - @Override - public String getDescription() { - if (getLevel() != null) { - return StringUtil.localize(description) + " " + getLevel(); - } else { - return StringUtil.localize(description); - } - } + @Override + public String getDescription() { + if (getLevel() != null) { + return StringUtil.localize(description) + " " + getLevel(); + } else { + return StringUtil.localize(description); + } + } - public static List loadEffects(ItemStack stack) { - List effectsList = new ArrayList<>(); + public static List loadEffects(ItemStack stack) { + List effectsList = new ArrayList<>(); - NBTTagCompound nbttagcompound = stack.getTagCompound(); - if (nbttagcompound == null) { - return effectsList; - } + NBTTagCompound nbttagcompound = stack.getTagCompound(); + if (nbttagcompound == null) { + return effectsList; + } - if (nbttagcompound.hasKey("E")) { - int effectLength = nbttagcompound.getInteger("L"); - NBTTagList nbttaglist = nbttagcompound.getTagList("E", 10); - IBeverageEffect[] effects = new IBeverageEffect[effectLength]; - for (int i = 0; i < nbttaglist.tagCount(); i++) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - byte byte0 = nbttagcompound1.getByte("S"); - if (byte0 >= 0 && byte0 < effects.length) { - effects[byte0] = BeverageManager.effectList[nbttagcompound1.getInteger("ID")]; - } - } - effectsList = Arrays.asList(effects); - } + if (nbttagcompound.hasKey("E")) { + int effectLength = nbttagcompound.getInteger("L"); + NBTTagList nbttaglist = nbttagcompound.getTagList("E", 10); + IBeverageEffect[] effects = new IBeverageEffect[effectLength]; + for (int i = 0; i < nbttaglist.tagCount(); i++) { + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + byte byte0 = nbttagcompound1.getByte("S"); + if (byte0 >= 0 && byte0 < effects.length) { + effects[byte0] = BeverageManager.effectList[nbttagcompound1.getInteger("ID")]; + } + } + effectsList = Arrays.asList(effects); + } - return effectsList; - } + return effectsList; + } - public static void saveEffects(ItemStack stack, List effects) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); + public static void saveEffects(ItemStack stack, List effects) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); - NBTTagList nbttaglist = new NBTTagList(); - nbttagcompound.setInteger("L", effects.size()); - for (int i = 0; i < effects.size(); i++) { - IBeverageEffect effect = effects.get(i); - if (effect != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte("S", (byte) i); - nbttagcompound1.setInteger("ID", effect.getId()); - nbttaglist.appendTag(nbttagcompound1); - } - } - nbttagcompound.setTag("E", nbttaglist); + NBTTagList nbttaglist = new NBTTagList(); + nbttagcompound.setInteger("L", effects.size()); + for (int i = 0; i < effects.size(); i++) { + IBeverageEffect effect = effects.get(i); + if (effect != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setByte("S", (byte) i); + nbttagcompound1.setInteger("ID", effect.getId()); + nbttaglist.appendTag(nbttagcompound1); + } + } + nbttagcompound.setTag("E", nbttaglist); - stack.setTagCompound(nbttagcompound); - } + stack.setTagCompound(nbttagcompound); + } } diff --git a/src/main/java/forestry/food/BeverageEffectAntidote.java b/src/main/java/forestry/food/BeverageEffectAntidote.java index 8f1dd870b..ab9272f4b 100755 --- a/src/main/java/forestry/food/BeverageEffectAntidote.java +++ b/src/main/java/forestry/food/BeverageEffectAntidote.java @@ -16,33 +16,32 @@ import net.minecraft.world.World; public class BeverageEffectAntidote extends BeverageEffect { - private float chance = 0.2f; + private float chance = 0.2f; - public BeverageEffectAntidote(int id, float chance) { - super(id); - this.chance = chance; - this.description = "beverage.effect.antidote"; - } + public BeverageEffectAntidote(int id, float chance) { + super(id); + this.chance = chance; + this.description = "beverage.effect.antidote"; + } - @Override - public void doEffect(World world, EntityPlayer player) { + @Override + public void doEffect(World world, EntityPlayer player) { - if (world.rand.nextFloat() >= chance) { - return; - } + if (world.rand.nextFloat() >= chance) { + return; + } - player.removePotionEffect(Potion.poison.getId()); - } - - @Override - public String getLevel() { - if (chance > 0.5f) { - return "III"; - } else if (chance > 0.2f) { - return "II"; - } else { - return "I"; - } - } + player.removePotionEffect(Potion.poison.getId()); + } + @Override + public String getLevel() { + if (chance > 0.5f) { + return "III"; + } else if (chance > 0.2f) { + return "II"; + } else { + return "I"; + } + } } diff --git a/src/main/java/forestry/food/BeverageEffectDrunk.java b/src/main/java/forestry/food/BeverageEffectDrunk.java index f491a81e0..de63fd17d 100755 --- a/src/main/java/forestry/food/BeverageEffectDrunk.java +++ b/src/main/java/forestry/food/BeverageEffectDrunk.java @@ -17,21 +17,20 @@ import net.minecraft.world.World; public class BeverageEffectDrunk extends BeverageEffect { - private final PotionEffect drunkEffect; - private final float chance; + private final PotionEffect drunkEffect; + private final float chance; - public BeverageEffectDrunk(int id, float chance) { - super(id); - this.chance = chance; - this.description = "beverage.effect.alcoholic"; - this.drunkEffect = new PotionEffect(Potion.confusion.id, 25 * 20, 0); - } - - @Override - public void doEffect(World world, EntityPlayer player) { - if (world.rand.nextFloat() < chance) { - player.addPotionEffect(drunkEffect); - } - } + public BeverageEffectDrunk(int id, float chance) { + super(id); + this.chance = chance; + this.description = "beverage.effect.alcoholic"; + this.drunkEffect = new PotionEffect(Potion.confusion.id, 25 * 20, 0); + } + @Override + public void doEffect(World world, EntityPlayer player) { + if (world.rand.nextFloat() < chance) { + player.addPotionEffect(drunkEffect); + } + } } diff --git a/src/main/java/forestry/food/InfuserIngredient.java b/src/main/java/forestry/food/InfuserIngredient.java index b84d60f56..33c58a039 100644 --- a/src/main/java/forestry/food/InfuserIngredient.java +++ b/src/main/java/forestry/food/InfuserIngredient.java @@ -1,31 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.food; - -import net.minecraft.item.ItemStack; - -public class InfuserIngredient { - private final ItemStack ingredient; - private final String description; - - public InfuserIngredient(ItemStack ingredient, String description) { - this.ingredient = ingredient; - this.description = description; - } - - public ItemStack getIngredient() { - return ingredient; - } - - public String getDescription() { - return description; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.food; + +import net.minecraft.item.ItemStack; + +public class InfuserIngredient { + private final ItemStack ingredient; + private final String description; + + public InfuserIngredient(ItemStack ingredient, String description) { + this.ingredient = ingredient; + this.description = description; + } + + public ItemStack getIngredient() { + return ingredient; + } + + public String getDescription() { + return description; + } +} diff --git a/src/main/java/forestry/food/InfuserIngredientManager.java b/src/main/java/forestry/food/InfuserIngredientManager.java index 43edf4a02..ccf184c83 100644 --- a/src/main/java/forestry/food/InfuserIngredientManager.java +++ b/src/main/java/forestry/food/InfuserIngredientManager.java @@ -1,44 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.food; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.item.ItemStack; - -import forestry.api.food.IIngredientManager; - -public class InfuserIngredientManager implements IIngredientManager { - private final List ingredients = new ArrayList<>(); - - @Override - public void addIngredient(ItemStack ingredient, String description) { - this.ingredients.add(new InfuserIngredient(ingredient, description)); - } - - @Override - public String getDescription(ItemStack itemstack) { - if (itemstack == null) { - return null; - } - - for (InfuserIngredient ingredient : ingredients) { - if (ingredient.getIngredient().getItemDamage() < 0 && ingredient.getIngredient().getItem() == itemstack.getItem()) { - return ingredient.getDescription(); - } else if (ingredient.getIngredient().getItemDamage() >= 0 && ingredient.getIngredient().isItemEqual(itemstack)) { - return ingredient.getDescription(); - } - } - - return null; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.food; + +import forestry.api.food.IIngredientManager; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.item.ItemStack; + +public class InfuserIngredientManager implements IIngredientManager { + private final List ingredients = new ArrayList<>(); + + @Override + public void addIngredient(ItemStack ingredient, String description) { + this.ingredients.add(new InfuserIngredient(ingredient, description)); + } + + @Override + public String getDescription(ItemStack itemstack) { + if (itemstack == null) { + return null; + } + + for (InfuserIngredient ingredient : ingredients) { + if (ingredient.getIngredient().getItemDamage() < 0 + && ingredient.getIngredient().getItem() == itemstack.getItem()) { + return ingredient.getDescription(); + } else if (ingredient.getIngredient().getItemDamage() >= 0 + && ingredient.getIngredient().isItemEqual(itemstack)) { + return ingredient.getDescription(); + } + } + + return null; + } +} diff --git a/src/main/java/forestry/food/InfuserMixture.java b/src/main/java/forestry/food/InfuserMixture.java index afb9834ea..fea6164c6 100644 --- a/src/main/java/forestry/food/InfuserMixture.java +++ b/src/main/java/forestry/food/InfuserMixture.java @@ -1,99 +1,97 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.food; - -import net.minecraft.item.ItemStack; - -import forestry.api.food.IBeverageEffect; - -/** - * describes the itemstacks required to achieve a certain effect. - */ -public class InfuserMixture { - private final int meta; - private final ItemStack[] ingredients; - private final IBeverageEffect effect; - - public InfuserMixture(int meta, ItemStack ingredient, IBeverageEffect effect) { - this(meta, new ItemStack[]{ingredient}, effect); - } - - public InfuserMixture(int meta, ItemStack ingredients[], IBeverageEffect effect) { - this.meta = meta; - this.ingredients = ingredients; - this.effect = effect; - } - - public ItemStack[] getIngredients() { - return ingredients; - } - - public boolean isIngredient(ItemStack itemstack) { - for (ItemStack ingredient : ingredients) { - if (ingredient.getItemDamage() < 0 && ingredient.getItem() == itemstack.getItem()) { - return true; - } else if (ingredient.getItemDamage() >= 0 && ingredient.isItemEqual(itemstack)) { - return true; - } - } - - return false; - } - - public boolean matches(ItemStack[] res) { - - // No recipe without resource! - if (res == null || res.length <= 0) { - return false; - } - - boolean matchedAll = true; - - for (ItemStack stack : ingredients) { - boolean matched = false; - for (ItemStack matchStack : res) { - if (matchStack == null) { - continue; - } - - // Check item matching - if (stack.getItemDamage() < 0 && stack.getItem() == matchStack.getItem()) { - if (stack.stackSize <= matchStack.stackSize) { - matched = true; - break; - } - } else if (stack.getItemDamage() >= 0 && stack.isItemEqual(matchStack)) { - if (stack.stackSize <= matchStack.stackSize) { - matched = true; - break; - } - } - } - if (!matched) { - matchedAll = false; - } - } - return matchedAll; - - } - - public IBeverageEffect getEffect() { - return this.effect; - } - - public int getMeta() { - return meta; - } - - public int getWeight() { - return ingredients.length; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.food; + +import forestry.api.food.IBeverageEffect; +import net.minecraft.item.ItemStack; + +/** + * describes the itemstacks required to achieve a certain effect. + */ +public class InfuserMixture { + private final int meta; + private final ItemStack[] ingredients; + private final IBeverageEffect effect; + + public InfuserMixture(int meta, ItemStack ingredient, IBeverageEffect effect) { + this(meta, new ItemStack[] {ingredient}, effect); + } + + public InfuserMixture(int meta, ItemStack ingredients[], IBeverageEffect effect) { + this.meta = meta; + this.ingredients = ingredients; + this.effect = effect; + } + + public ItemStack[] getIngredients() { + return ingredients; + } + + public boolean isIngredient(ItemStack itemstack) { + for (ItemStack ingredient : ingredients) { + if (ingredient.getItemDamage() < 0 && ingredient.getItem() == itemstack.getItem()) { + return true; + } else if (ingredient.getItemDamage() >= 0 && ingredient.isItemEqual(itemstack)) { + return true; + } + } + + return false; + } + + public boolean matches(ItemStack[] res) { + + // No recipe without resource! + if (res == null || res.length <= 0) { + return false; + } + + boolean matchedAll = true; + + for (ItemStack stack : ingredients) { + boolean matched = false; + for (ItemStack matchStack : res) { + if (matchStack == null) { + continue; + } + + // Check item matching + if (stack.getItemDamage() < 0 && stack.getItem() == matchStack.getItem()) { + if (stack.stackSize <= matchStack.stackSize) { + matched = true; + break; + } + } else if (stack.getItemDamage() >= 0 && stack.isItemEqual(matchStack)) { + if (stack.stackSize <= matchStack.stackSize) { + matched = true; + break; + } + } + } + if (!matched) { + matchedAll = false; + } + } + return matchedAll; + } + + public IBeverageEffect getEffect() { + return this.effect; + } + + public int getMeta() { + return meta; + } + + public int getWeight() { + return ingredients.length; + } +} diff --git a/src/main/java/forestry/food/InfuserMixtureManager.java b/src/main/java/forestry/food/InfuserMixtureManager.java index b9d95b344..d164b28ec 100644 --- a/src/main/java/forestry/food/InfuserMixtureManager.java +++ b/src/main/java/forestry/food/InfuserMixtureManager.java @@ -1,99 +1,97 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.food; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import net.minecraft.item.ItemStack; - -import forestry.api.food.IBeverageEffect; -import forestry.api.food.IInfuserManager; - -/** - * contains the available mixtures. - */ -public class InfuserMixtureManager implements IInfuserManager { - - private final List mixtures = new ArrayList<>(); - - @Override - public void addMixture(int meta, ItemStack ingredient, IBeverageEffect effect) { - this.mixtures.add(new InfuserMixture(meta, ingredient, effect)); - } - - @Override - public void addMixture(int meta, ItemStack[] ingredients, IBeverageEffect effect) { - this.mixtures.add(new InfuserMixture(meta, ingredients, effect)); - } - - public boolean isIngredient(ItemStack itemstack) { - for (InfuserMixture ingredient : mixtures) { - if (ingredient.isIngredient(itemstack)) { - return true; - } - } - - return false; - } - - private InfuserMixture[] getMatchingMixtures(ItemStack[] ingredients) { - - ArrayList matches = new ArrayList<>(); - - for (InfuserMixture mixture : mixtures) { - if (mixture.matches(ingredients)) { - matches.add(mixture); - } - } - - return matches.toArray(new InfuserMixture[matches.size()]); - } - - @Override - public boolean hasMixtures(ItemStack[] ingredients) { - return getMatchingMixtures(ingredients).length > 0; - } - - @Override - public ItemStack[] getRequired(ItemStack[] ingredients) { - InfuserMixture[] mixtures = getMatchingMixtures(ingredients); - ArrayList required = new ArrayList<>(); - - for (InfuserMixture mixture : mixtures) { - required.addAll(Arrays.asList(mixture.getIngredients())); - } - - return required.toArray(new ItemStack[required.size()]); - } - - @Override - public ItemStack getSeasoned(ItemStack base, ItemStack[] ingredients) { - InfuserMixture[] mixtures = getMatchingMixtures(ingredients); - List effects = BeverageEffect.loadEffects(base); - - int weight = 0; - int meta = 0; - for (InfuserMixture mixture : mixtures) { - effects.add(mixture.getEffect()); - if (mixture.getWeight() > weight) { - weight = mixture.getWeight(); - meta = mixture.getMeta(); - } - } - - ItemStack seasoned = base.copy(); - seasoned.setItemDamage(meta); - BeverageEffect.saveEffects(seasoned, effects); - return seasoned; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.food; + +import forestry.api.food.IBeverageEffect; +import forestry.api.food.IInfuserManager; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import net.minecraft.item.ItemStack; + +/** + * contains the available mixtures. + */ +public class InfuserMixtureManager implements IInfuserManager { + + private final List mixtures = new ArrayList<>(); + + @Override + public void addMixture(int meta, ItemStack ingredient, IBeverageEffect effect) { + this.mixtures.add(new InfuserMixture(meta, ingredient, effect)); + } + + @Override + public void addMixture(int meta, ItemStack[] ingredients, IBeverageEffect effect) { + this.mixtures.add(new InfuserMixture(meta, ingredients, effect)); + } + + public boolean isIngredient(ItemStack itemstack) { + for (InfuserMixture ingredient : mixtures) { + if (ingredient.isIngredient(itemstack)) { + return true; + } + } + + return false; + } + + private InfuserMixture[] getMatchingMixtures(ItemStack[] ingredients) { + + ArrayList matches = new ArrayList<>(); + + for (InfuserMixture mixture : mixtures) { + if (mixture.matches(ingredients)) { + matches.add(mixture); + } + } + + return matches.toArray(new InfuserMixture[matches.size()]); + } + + @Override + public boolean hasMixtures(ItemStack[] ingredients) { + return getMatchingMixtures(ingredients).length > 0; + } + + @Override + public ItemStack[] getRequired(ItemStack[] ingredients) { + InfuserMixture[] mixtures = getMatchingMixtures(ingredients); + ArrayList required = new ArrayList<>(); + + for (InfuserMixture mixture : mixtures) { + required.addAll(Arrays.asList(mixture.getIngredients())); + } + + return required.toArray(new ItemStack[required.size()]); + } + + @Override + public ItemStack getSeasoned(ItemStack base, ItemStack[] ingredients) { + InfuserMixture[] mixtures = getMatchingMixtures(ingredients); + List effects = BeverageEffect.loadEffects(base); + + int weight = 0; + int meta = 0; + for (InfuserMixture mixture : mixtures) { + effects.add(mixture.getEffect()); + if (mixture.getWeight() > weight) { + weight = mixture.getWeight(); + meta = mixture.getMeta(); + } + } + + ItemStack seasoned = base.copy(); + seasoned.setItemDamage(meta); + BeverageEffect.saveEffects(seasoned, effects); + return seasoned; + } +} diff --git a/src/main/java/forestry/food/gui/ContainerInfuser.java b/src/main/java/forestry/food/gui/ContainerInfuser.java index 7cb029328..f46d50b49 100755 --- a/src/main/java/forestry/food/gui/ContainerInfuser.java +++ b/src/main/java/forestry/food/gui/ContainerInfuser.java @@ -10,28 +10,27 @@ ******************************************************************************/ package forestry.food.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.food.inventory.ItemInventoryInfuser; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerInfuser extends ContainerItemInventory { - public ContainerInfuser(InventoryPlayer inventoryplayer, ItemInventoryInfuser inventory) { - super(inventory, inventoryplayer, 8, 103); + public ContainerInfuser(InventoryPlayer inventoryplayer, ItemInventoryInfuser inventory) { + super(inventory, inventoryplayer, 8, 103); - // Input - this.addSlotToContainer(new SlotFiltered(inventory, 0, 152, 12)); + // Input + this.addSlotToContainer(new SlotFiltered(inventory, 0, 152, 12)); - // Output - this.addSlotToContainer(new SlotOutput(inventory, 1, 152, 72)); + // Output + this.addSlotToContainer(new SlotOutput(inventory, 1, 152, 72)); - // Ingredients - this.addSlotToContainer(new SlotFiltered(inventory, 2, 12, 12)); - this.addSlotToContainer(new SlotFiltered(inventory, 3, 12, 32)); - this.addSlotToContainer(new SlotFiltered(inventory, 4, 12, 52)); - this.addSlotToContainer(new SlotFiltered(inventory, 5, 12, 72)); - } + // Ingredients + this.addSlotToContainer(new SlotFiltered(inventory, 2, 12, 12)); + this.addSlotToContainer(new SlotFiltered(inventory, 3, 12, 32)); + this.addSlotToContainer(new SlotFiltered(inventory, 4, 12, 52)); + this.addSlotToContainer(new SlotFiltered(inventory, 5, 12, 72)); + } } diff --git a/src/main/java/forestry/food/gui/GuiInfuser.java b/src/main/java/forestry/food/gui/GuiInfuser.java index 1b55047ea..1b226b24a 100755 --- a/src/main/java/forestry/food/gui/GuiInfuser.java +++ b/src/main/java/forestry/food/gui/GuiInfuser.java @@ -10,45 +10,44 @@ ******************************************************************************/ package forestry.food.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.api.food.BeverageManager; import forestry.core.config.Constants; import forestry.core.gui.GuiForestry; import forestry.food.inventory.ItemInventoryInfuser; +import net.minecraft.entity.player.InventoryPlayer; public class GuiInfuser extends GuiForestry { - private int startX; - private int startY; + private int startX; + private int startY; - public GuiInfuser(InventoryPlayer inventoryplayer, ItemInventoryInfuser inventory) { - super(Constants.TEXTURE_PATH_GUI + "/infuser.png", new ContainerInfuser(inventoryplayer, inventory), inventory); + public GuiInfuser(InventoryPlayer inventoryplayer, ItemInventoryInfuser inventory) { + super(Constants.TEXTURE_PATH_GUI + "/infuser.png", new ContainerInfuser(inventoryplayer, inventory), inventory); - xSize = 176; - ySize = 185; - } + xSize = 176; + ySize = 185; + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - for (int l = 2; l < inventory.getSizeInventory(); l++) { - String description = BeverageManager.ingredientManager.getDescription(inventory.getStackInSlot(l)); - if (description == null) { - description = "(No effect)"; - } + for (int l = 2; l < inventory.getSizeInventory(); l++) { + String description = BeverageManager.ingredientManager.getDescription(inventory.getStackInSlot(l)); + if (description == null) { + description = "(No effect)"; + } - int row = (l - 2) * 20; - fontRendererObj.drawString(description, startX + 32, startY + 16 + row, fontColor.get("gui.screen")); - } - } + int row = (l - 2) * 20; + fontRendererObj.drawString(description, startX + 32, startY + 16 + row, fontColor.get("gui.screen")); + } + } - @Override - public void initGui() { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - startX = (this.width - this.xSize) / 2; - startY = (this.height - this.ySize) / 2; - } + startX = (this.width - this.xSize) / 2; + startY = (this.height - this.ySize) / 2; + } } diff --git a/src/main/java/forestry/food/inventory/ItemInventoryInfuser.java b/src/main/java/forestry/food/inventory/ItemInventoryInfuser.java index d51310136..c8d166c5e 100644 --- a/src/main/java/forestry/food/inventory/ItemInventoryInfuser.java +++ b/src/main/java/forestry/food/inventory/ItemInventoryInfuser.java @@ -1,104 +1,103 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.food.inventory; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.api.food.BeverageManager; -import forestry.core.inventory.ItemInventory; -import forestry.plugins.PluginFood; - -public class ItemInventoryInfuser extends ItemInventory { - private static final short inputSlot = 0; - private static final short outputSlot = 1; - private static final short ingredientSlot1 = 2; - private static final short ingredientSlotCount = 4; - - public ItemInventoryInfuser(EntityPlayer player, ItemStack itemStack) { - super(player, 6, itemStack); - } - - @Override - public void onSlotClick(EntityPlayer player) { - - // Need input - ItemStack input = getStackInSlot(inputSlot); - if (input == null) { - return; - } - - // Output slot may not be occupied - if (getStackInSlot(outputSlot) != null) { - return; - } - - // Need a valid base - if (PluginFood.items.beverage != input.getItem()) { - return; - } - - // Create the seasoned item - ItemStack[] ingredients = new ItemStack[4]; - for (int i = 0; i < 4; i++) { - ingredients[i] = getStackInSlot(i + ingredientSlot1); - } - - // Only continue if there is anything to season - if (!BeverageManager.infuserManager.hasMixtures(ingredients)) { - return; - } - - ItemStack seasoned = BeverageManager.infuserManager.getSeasoned(input, ingredients); - if (seasoned == null) { - return; - } - - // Remove required ingredients. - ItemStack[] toRemove = BeverageManager.infuserManager.getRequired(ingredients); - for (ItemStack templ : toRemove) { - ItemStack ghost = templ.copy(); - - for (int i = ingredientSlot1; i < this.getSizeInventory(); i++) { - ItemStack ingredient = getStackInSlot(i); - if (ingredient == null) { - continue; - } - if (ghost.stackSize <= 0) { - break; - } - - if ((ghost.getItemDamage() >= 0 && ingredient.isItemEqual(ghost)) - || (ghost.getItemDamage() < 0 && ghost.getItem() == ingredient.getItem())) { - ItemStack removed = decrStackSize(i, 1); - ghost.stackSize -= removed.stackSize; - } - } - } - decrStackSize(inputSlot, 1); - setInventorySlotContents(outputSlot, seasoned); - } - - @Override - public String getInventoryName() { - return "Infuser"; - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == inputSlot) { - return PluginFood.items.beverage == itemStack.getItem(); - } else if (slotIndex >= ingredientSlot1 && slotIndex < ingredientSlot1 + ingredientSlotCount) { - return BeverageManager.infuserManager.isIngredient(itemStack); - } - return false; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.food.inventory; + +import forestry.api.food.BeverageManager; +import forestry.core.inventory.ItemInventory; +import forestry.plugins.PluginFood; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class ItemInventoryInfuser extends ItemInventory { + private static final short inputSlot = 0; + private static final short outputSlot = 1; + private static final short ingredientSlot1 = 2; + private static final short ingredientSlotCount = 4; + + public ItemInventoryInfuser(EntityPlayer player, ItemStack itemStack) { + super(player, 6, itemStack); + } + + @Override + public void onSlotClick(EntityPlayer player) { + + // Need input + ItemStack input = getStackInSlot(inputSlot); + if (input == null) { + return; + } + + // Output slot may not be occupied + if (getStackInSlot(outputSlot) != null) { + return; + } + + // Need a valid base + if (PluginFood.items.beverage != input.getItem()) { + return; + } + + // Create the seasoned item + ItemStack[] ingredients = new ItemStack[4]; + for (int i = 0; i < 4; i++) { + ingredients[i] = getStackInSlot(i + ingredientSlot1); + } + + // Only continue if there is anything to season + if (!BeverageManager.infuserManager.hasMixtures(ingredients)) { + return; + } + + ItemStack seasoned = BeverageManager.infuserManager.getSeasoned(input, ingredients); + if (seasoned == null) { + return; + } + + // Remove required ingredients. + ItemStack[] toRemove = BeverageManager.infuserManager.getRequired(ingredients); + for (ItemStack templ : toRemove) { + ItemStack ghost = templ.copy(); + + for (int i = ingredientSlot1; i < this.getSizeInventory(); i++) { + ItemStack ingredient = getStackInSlot(i); + if (ingredient == null) { + continue; + } + if (ghost.stackSize <= 0) { + break; + } + + if ((ghost.getItemDamage() >= 0 && ingredient.isItemEqual(ghost)) + || (ghost.getItemDamage() < 0 && ghost.getItem() == ingredient.getItem())) { + ItemStack removed = decrStackSize(i, 1); + ghost.stackSize -= removed.stackSize; + } + } + } + decrStackSize(inputSlot, 1); + setInventorySlotContents(outputSlot, seasoned); + } + + @Override + public String getInventoryName() { + return "Infuser"; + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (slotIndex == inputSlot) { + return PluginFood.items.beverage == itemStack.getItem(); + } else if (slotIndex >= ingredientSlot1 && slotIndex < ingredientSlot1 + ingredientSlotCount) { + return BeverageManager.infuserManager.isIngredient(itemStack); + } + return false; + } +} diff --git a/src/main/java/forestry/food/items/EnumBeverage.java b/src/main/java/forestry/food/items/EnumBeverage.java index 7dfe47ab8..dc87a4572 100644 --- a/src/main/java/forestry/food/items/EnumBeverage.java +++ b/src/main/java/forestry/food/items/EnumBeverage.java @@ -1,103 +1,108 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.food.items; - -import java.awt.Color; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.util.IIcon; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.core.render.TextureManager; - -public enum EnumBeverage implements ItemBeverage.IBeverageInfo { - MEAD_SHORT("meadShort", "glass", new Color(0xec9a19), new Color(0xffffff), 1, 0.2f, true), - MEAD_CURATIVE("meadCurative", "glass", new Color(0xc5feff), new Color(0xffffff), 1, 0.2f, true), - MEAD("mead", "glass", new Color(0xcc6600), new Color(0xffffff), 10, 0.1f, true); - public static final EnumBeverage[] VALUES = values(); - - private final String name; - private final String iconType; - private final int primaryColor; - private final int secondaryColor; - - @SideOnly(Side.CLIENT) - private IIcon iconBottle; - @SideOnly(Side.CLIENT) - private IIcon iconContents; - - private final int heal; - private final float saturation; - private final boolean isAlwaysEdible; - - EnumBeverage(String name, String iconType, Color primaryColor, Color secondaryColor, int heal, float saturation, boolean isAlwaysEdible) { - this.name = name; - this.iconType = iconType; - this.primaryColor = primaryColor.getRGB(); - this.secondaryColor = secondaryColor.getRGB(); - this.heal = heal; - this.saturation = saturation; - this.isAlwaysEdible = isAlwaysEdible; - } - - @SideOnly(Side.CLIENT) - public void registerIcons(IIconRegister register) { - iconBottle = TextureManager.registerTex(register, "liquids/" + iconType + ".bottle"); - iconContents = TextureManager.registerTex(register, "liquids/" + iconType + ".contents"); - } - - @Override - public int getHeal() { - return heal; - } - - @Override - public float getSaturation() { - return saturation; - } - - @Override - public boolean isAlwaysEdible() { - return isAlwaysEdible; - } - - @Override - public String getName() { - return name; - } - - @Override - public int getPrimaryColor() { - return primaryColor; - } - - @Override - public int getSecondaryColor() { - return secondaryColor; - } - - @Override - public boolean isSecret() { - return false; - } - - @Override - public IIcon getIconBottle() { - return iconBottle; - } - - @Override - public IIcon getIconContents() { - return iconContents; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.food.items; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.core.render.TextureManager; +import java.awt.Color; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.util.IIcon; + +public enum EnumBeverage implements ItemBeverage.IBeverageInfo { + MEAD_SHORT("meadShort", "glass", new Color(0xec9a19), new Color(0xffffff), 1, 0.2f, true), + MEAD_CURATIVE("meadCurative", "glass", new Color(0xc5feff), new Color(0xffffff), 1, 0.2f, true), + MEAD("mead", "glass", new Color(0xcc6600), new Color(0xffffff), 10, 0.1f, true); + public static final EnumBeverage[] VALUES = values(); + + private final String name; + private final String iconType; + private final int primaryColor; + private final int secondaryColor; + + @SideOnly(Side.CLIENT) + private IIcon iconBottle; + + @SideOnly(Side.CLIENT) + private IIcon iconContents; + + private final int heal; + private final float saturation; + private final boolean isAlwaysEdible; + + EnumBeverage( + String name, + String iconType, + Color primaryColor, + Color secondaryColor, + int heal, + float saturation, + boolean isAlwaysEdible) { + this.name = name; + this.iconType = iconType; + this.primaryColor = primaryColor.getRGB(); + this.secondaryColor = secondaryColor.getRGB(); + this.heal = heal; + this.saturation = saturation; + this.isAlwaysEdible = isAlwaysEdible; + } + + @SideOnly(Side.CLIENT) + public void registerIcons(IIconRegister register) { + iconBottle = TextureManager.registerTex(register, "liquids/" + iconType + ".bottle"); + iconContents = TextureManager.registerTex(register, "liquids/" + iconType + ".contents"); + } + + @Override + public int getHeal() { + return heal; + } + + @Override + public float getSaturation() { + return saturation; + } + + @Override + public boolean isAlwaysEdible() { + return isAlwaysEdible; + } + + @Override + public String getName() { + return name; + } + + @Override + public int getPrimaryColor() { + return primaryColor; + } + + @Override + public int getSecondaryColor() { + return secondaryColor; + } + + @Override + public boolean isSecret() { + return false; + } + + @Override + public IIcon getIconBottle() { + return iconBottle; + } + + @Override + public IIcon getIconContents() { + return iconContents; + } +} diff --git a/src/main/java/forestry/food/items/ItemAmbrosia.java b/src/main/java/forestry/food/items/ItemAmbrosia.java index 0bbaed4ba..55dbc8ac2 100755 --- a/src/main/java/forestry/food/items/ItemAmbrosia.java +++ b/src/main/java/forestry/food/items/ItemAmbrosia.java @@ -10,23 +10,21 @@ ******************************************************************************/ package forestry.food.items; +import forestry.core.config.Constants; +import forestry.core.items.ItemForestryFood; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; -import forestry.core.config.Constants; -import forestry.core.items.ItemForestryFood; - public class ItemAmbrosia extends ItemForestryFood { - public ItemAmbrosia() { - super(Constants.FOOD_AMBROSIA_HEAL, 0.6f); - setAlwaysEdible(); - setPotionEffect(Potion.regeneration.id, 40, 0, 1.0F); - } - - @Override - public boolean hasEffect(ItemStack itemstack, int pass) { - return true; - } + public ItemAmbrosia() { + super(Constants.FOOD_AMBROSIA_HEAL, 0.6f); + setAlwaysEdible(); + setPotionEffect(Potion.regeneration.id, 40, 0, 1.0F); + } + @Override + public boolean hasEffect(ItemStack itemstack, int pass) { + return true; + } } diff --git a/src/main/java/forestry/food/items/ItemBeverage.java b/src/main/java/forestry/food/items/ItemBeverage.java index 29c90af85..662c87aac 100755 --- a/src/main/java/forestry/food/items/ItemBeverage.java +++ b/src/main/java/forestry/food/items/ItemBeverage.java @@ -10,8 +10,14 @@ ******************************************************************************/ package forestry.food.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.food.IBeverageEffect; +import forestry.core.config.Config; +import forestry.core.items.ItemForestryFood; +import forestry.core.items.ItemOverlay; +import forestry.food.BeverageEffect; import java.util.List; - import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; @@ -22,171 +28,162 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.food.IBeverageEffect; -import forestry.core.config.Config; -import forestry.core.items.ItemForestryFood; -import forestry.core.items.ItemOverlay; -import forestry.food.BeverageEffect; - public class ItemBeverage extends ItemForestryFood { - public interface IBeverageInfo extends ItemOverlay.IOverlayInfo { - int getHeal(); + public interface IBeverageInfo extends ItemOverlay.IOverlayInfo { + int getHeal(); - float getSaturation(); + float getSaturation(); - boolean isAlwaysEdible(); + boolean isAlwaysEdible(); - void registerIcons(IIconRegister register); + void registerIcons(IIconRegister register); - IIcon getIconBottle(); + IIcon getIconBottle(); - IIcon getIconContents(); - } + IIcon getIconContents(); + } - public final IBeverageInfo[] beverages; + public final IBeverageInfo[] beverages; - public ItemBeverage() { - super(1, 0.2f); - setMaxStackSize(8); - this.beverages = EnumBeverage.VALUES; - } + public ItemBeverage() { + super(1, 0.2f); + setMaxStackSize(8); + this.beverages = EnumBeverage.VALUES; + } - /** - * @return true if the item's stackTagCompound needs to be synchronized over SMP. - */ - @Override - public boolean getShareTag() { - return true; - } + /** + * @return true if the item's stackTagCompound needs to be synchronized over SMP. + */ + @Override + public boolean getShareTag() { + return true; + } - @Override - public ItemStack onEaten(ItemStack itemstack, World world, EntityPlayer entityplayer) { - List effects = BeverageEffect.loadEffects(itemstack); - ItemStack container = new ItemStack(Items.glass_bottle, 1); + @Override + public ItemStack onEaten(ItemStack itemstack, World world, EntityPlayer entityplayer) { + List effects = BeverageEffect.loadEffects(itemstack); + ItemStack container = new ItemStack(Items.glass_bottle, 1); - itemstack.stackSize--; - if (!entityplayer.inventory.addItemStackToInventory(container)) { - entityplayer.dropPlayerItemWithRandomChoice(container, false); - } else { - entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, container); - } - entityplayer.inventory.markDirty(); + itemstack.stackSize--; + if (!entityplayer.inventory.addItemStackToInventory(container)) { + entityplayer.dropPlayerItemWithRandomChoice(container, false); + } else { + entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, container); + } + entityplayer.inventory.markDirty(); - entityplayer.getFoodStats().func_151686_a(this, itemstack); - world.playSoundAtEntity(entityplayer, "random.burp", 0.5F, world.rand.nextFloat() * 0.1F + 0.9F); - if (world.isRemote) { - return itemstack; - } + entityplayer.getFoodStats().func_151686_a(this, itemstack); + world.playSoundAtEntity(entityplayer, "random.burp", 0.5F, world.rand.nextFloat() * 0.1F + 0.9F); + if (world.isRemote) { + return itemstack; + } - for (IBeverageEffect effect : effects) { - effect.doEffect(world, entityplayer); - } + for (IBeverageEffect effect : effects) { + effect.doEffect(world, entityplayer); + } - return itemstack; - } + return itemstack; + } - @Override - public int func_150905_g(ItemStack itemstack) { - int meta = itemstack.getItemDamage(); - IBeverageInfo beverage = beverages[meta]; - return beverage.getHeal(); - } + @Override + public int func_150905_g(ItemStack itemstack) { + int meta = itemstack.getItemDamage(); + IBeverageInfo beverage = beverages[meta]; + return beverage.getHeal(); + } - @Override - public float func_150906_h(ItemStack itemstack) { - int meta = itemstack.getItemDamage(); - IBeverageInfo beverage = beverages[meta]; - return beverage.getSaturation(); - } + @Override + public float func_150906_h(ItemStack itemstack) { + int meta = itemstack.getItemDamage(); + IBeverageInfo beverage = beverages[meta]; + return beverage.getSaturation(); + } - @Override - public int getMaxItemUseDuration(ItemStack itemstack) { - return 32; - } + @Override + public int getMaxItemUseDuration(ItemStack itemstack) { + return 32; + } - @Override - public EnumAction getItemUseAction(ItemStack itemstack) { - return EnumAction.drink; - } + @Override + public EnumAction getItemUseAction(ItemStack itemstack) { + return EnumAction.drink; + } - @Override - public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { + @Override + public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { - int meta = itemstack.getItemDamage(); - IBeverageInfo beverage = beverages[meta]; + int meta = itemstack.getItemDamage(); + IBeverageInfo beverage = beverages[meta]; - if (entityplayer.canEat(beverage.isAlwaysEdible())) { - entityplayer.setItemInUse(itemstack, getMaxItemUseDuration(itemstack)); - } - return itemstack; - } + if (entityplayer.canEat(beverage.isAlwaysEdible())) { + entityplayer.setItemInUse(itemstack, getMaxItemUseDuration(itemstack)); + } + return itemstack; + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - for (int i = 0; i < beverages.length; i++) { - if (Config.isDebug || !beverages[i].isSecret()) { - itemList.add(new ItemStack(this, 1, i)); - } - } - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + for (int i = 0; i < beverages.length; i++) { + if (Config.isDebug || !beverages[i].isSecret()) { + itemList.add(new ItemStack(this, 1, i)); + } + } + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { - List effects = BeverageEffect.loadEffects(itemstack); + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { + List effects = BeverageEffect.loadEffects(itemstack); - for (IBeverageEffect effect : effects) { - if (effect.getDescription() != null) { - list.add(effect.getDescription()); - } - } - } + for (IBeverageEffect effect : effects) { + if (effect.getDescription() != null) { + list.add(effect.getDescription()); + } + } + } - @Override - public String getUnlocalizedName(ItemStack stack) { - return super.getUnlocalizedName(stack) + "." + beverages[stack.getItemDamage()].getName(); - } + @Override + public String getUnlocalizedName(ItemStack stack) { + return super.getUnlocalizedName(stack) + "." + beverages[stack.getItemDamage()].getName(); + } - /* ICONS */ - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - for (IBeverageInfo info : beverages) { - info.registerIcons(register); - } - } + /* ICONS */ + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + for (IBeverageInfo info : beverages) { + info.registerIcons(register); + } + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamageForRenderPass(int i, int j) { - if (j > 0 && beverages[i].getSecondaryColor() != 0) { - return beverages[i].getIconBottle(); - } else { - return beverages[i].getIconContents(); - } - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamageForRenderPass(int i, int j) { + if (j > 0 && beverages[i].getSecondaryColor() != 0) { + return beverages[i].getIconBottle(); + } else { + return beverages[i].getIconContents(); + } + } - // Return true to enable color overlay - @Override - public boolean requiresMultipleRenderPasses() { - return true; - } + // Return true to enable color overlay + @Override + public boolean requiresMultipleRenderPasses() { + return true; + } - @Override - public int getColorFromItemStack(ItemStack itemstack, int j) { + @Override + public int getColorFromItemStack(ItemStack itemstack, int j) { - if (j == 0 || beverages[itemstack.getItemDamage()].getSecondaryColor() == 0) { - return beverages[itemstack.getItemDamage()].getPrimaryColor(); - } else { - return beverages[itemstack.getItemDamage()].getSecondaryColor(); - } - } + if (j == 0 || beverages[itemstack.getItemDamage()].getSecondaryColor() == 0) { + return beverages[itemstack.getItemDamage()].getPrimaryColor(); + } else { + return beverages[itemstack.getItemDamage()].getSecondaryColor(); + } + } - public ItemStack get(EnumBeverage beverage, int amount) { - return new ItemStack(this, amount, beverage.ordinal()); - } + public ItemStack get(EnumBeverage beverage, int amount) { + return new ItemStack(this, amount, beverage.ordinal()); + } } diff --git a/src/main/java/forestry/food/items/ItemInfuser.java b/src/main/java/forestry/food/items/ItemInfuser.java index 569e48748..45e1dd879 100644 --- a/src/main/java/forestry/food/items/ItemInfuser.java +++ b/src/main/java/forestry/food/items/ItemInfuser.java @@ -1,31 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.food.items; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.core.items.ItemWithGui; -import forestry.food.gui.ContainerInfuser; -import forestry.food.gui.GuiInfuser; -import forestry.food.inventory.ItemInventoryInfuser; - -public class ItemInfuser extends ItemWithGui { - @Override - public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { - return new GuiInfuser(player.inventory, new ItemInventoryInfuser(player, heldItem)); - } - - @Override - public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { - return new ContainerInfuser(player.inventory, new ItemInventoryInfuser(player, heldItem)); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.food.items; + +import forestry.core.items.ItemWithGui; +import forestry.food.gui.ContainerInfuser; +import forestry.food.gui.GuiInfuser; +import forestry.food.inventory.ItemInventoryInfuser; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class ItemInfuser extends ItemWithGui { + @Override + public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { + return new GuiInfuser(player.inventory, new ItemInventoryInfuser(player, heldItem)); + } + + @Override + public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { + return new ContainerInfuser(player.inventory, new ItemInventoryInfuser(player, heldItem)); + } +} diff --git a/src/main/java/forestry/food/items/ItemRegistryFood.java b/src/main/java/forestry/food/items/ItemRegistryFood.java index a0d61043d..590d52b58 100644 --- a/src/main/java/forestry/food/items/ItemRegistryFood.java +++ b/src/main/java/forestry/food/items/ItemRegistryFood.java @@ -1,42 +1,40 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.food.items; - -import java.util.Collections; - -import net.minecraft.item.ItemStack; - -import forestry.core.items.ItemForestryFood; -import forestry.core.items.ItemRegistry; -import forestry.food.BeverageEffect; - -public class ItemRegistryFood extends ItemRegistry { - public final ItemForestryFood honeyedSlice; - public final ItemBeverage beverage; - public final ItemForestryFood ambrosia; - public final ItemForestryFood honeyPot; - public final ItemInfuser infuser; - - public ItemRegistryFood() { - // / FOOD ITEMS - honeyedSlice = registerItem(new ItemForestryFood(8, 0.6f), "honeyedSlice"); - beverage = registerItem(new ItemBeverage(), "beverage"); - ambrosia = registerItem(new ItemAmbrosia().setIsDrink(), "ambrosia"); - honeyPot = registerItem(new ItemForestryFood(2, 0.2f).setIsDrink(), "honeyPot"); - - // / SEASONER - infuser = new ItemInfuser(); - registerItem(infuser, "infuser"); - - // Mead - BeverageEffect.saveEffects(new ItemStack(beverage), Collections.singletonList(BeverageEffect.weakAlcoholic)); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.food.items; + +import forestry.core.items.ItemForestryFood; +import forestry.core.items.ItemRegistry; +import forestry.food.BeverageEffect; +import java.util.Collections; +import net.minecraft.item.ItemStack; + +public class ItemRegistryFood extends ItemRegistry { + public final ItemForestryFood honeyedSlice; + public final ItemBeverage beverage; + public final ItemForestryFood ambrosia; + public final ItemForestryFood honeyPot; + public final ItemInfuser infuser; + + public ItemRegistryFood() { + // / FOOD ITEMS + honeyedSlice = registerItem(new ItemForestryFood(8, 0.6f), "honeyedSlice"); + beverage = registerItem(new ItemBeverage(), "beverage"); + ambrosia = registerItem(new ItemAmbrosia().setIsDrink(), "ambrosia"); + honeyPot = registerItem(new ItemForestryFood(2, 0.2f).setIsDrink(), "honeyPot"); + + // / SEASONER + infuser = new ItemInfuser(); + registerItem(infuser, "infuser"); + + // Mead + BeverageEffect.saveEffects(new ItemStack(beverage), Collections.singletonList(BeverageEffect.weakAlcoholic)); + } +} diff --git a/src/main/java/forestry/lepidopterology/ButterflySpawner.java b/src/main/java/forestry/lepidopterology/ButterflySpawner.java index bef7c44bf..140c7761a 100755 --- a/src/main/java/forestry/lepidopterology/ButterflySpawner.java +++ b/src/main/java/forestry/lepidopterology/ButterflySpawner.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.lepidopterology; -import net.minecraft.world.World; - import forestry.api.arboriculture.ILeafTickHandler; import forestry.api.arboriculture.ITree; import forestry.api.lepidopterology.ButterflyManager; @@ -19,46 +17,50 @@ import forestry.api.lepidopterology.IButterfly; import forestry.core.utils.Log; import forestry.lepidopterology.entities.EntityButterfly; import forestry.plugins.PluginLepidopterology; +import net.minecraft.world.World; public class ButterflySpawner implements ILeafTickHandler { - @Override - public boolean onRandomLeafTick(ITree tree, World world, int x, int y, int z, boolean isDestroyed) { - - if (world.rand.nextFloat() >= tree.getGenome().getSappiness() * tree.getGenome().getYield()) { - return false; - } + @Override + public boolean onRandomLeafTick(ITree tree, World world, int x, int y, int z, boolean isDestroyed) { - IButterfly spawn = ButterflyManager.butterflyRoot.getIndividualTemplates().get(world.rand.nextInt(ButterflyManager.butterflyRoot.getIndividualTemplates().size())); - if (world.rand.nextFloat() >= spawn.getGenome().getPrimary().getRarity() * 0.5f) { - return false; - } - - if (world.countEntities(EntityButterfly.class) > PluginLepidopterology.spawnConstraint) { - return false; - } - - if (!spawn.canSpawn(world, x, y, z)) { - return false; - } - - if (world.isAirBlock(x - 1, y, z)) { - attemptButterflySpawn(world, spawn, x - 1, y, z); - } else if (world.isAirBlock(x + 1, y, z)) { - attemptButterflySpawn(world, spawn, x + 1, y, z); - } else if (world.isAirBlock(x, y, z - 1)) { - attemptButterflySpawn(world, spawn, x, y, z - 1); - } else if (world.isAirBlock(x, y, z + 1)) { - attemptButterflySpawn(world, spawn, x, y, z + 1); - } - - return false; - } + if (world.rand.nextFloat() + >= tree.getGenome().getSappiness() * tree.getGenome().getYield()) { + return false; + } - private static void attemptButterflySpawn(World world, IButterfly butterfly, double x, double y, double z) { - if (ButterflyManager.butterflyRoot.spawnButterflyInWorld(world, butterfly.copy(), x, y + 0.1f, z) != null) { - Log.finest("Spawned a butterfly '%s' at %s/%s/%s.", butterfly.getDisplayName(), x, y, z); - } - } + IButterfly spawn = ButterflyManager.butterflyRoot + .getIndividualTemplates() + .get(world.rand.nextInt( + ButterflyManager.butterflyRoot.getIndividualTemplates().size())); + if (world.rand.nextFloat() >= spawn.getGenome().getPrimary().getRarity() * 0.5f) { + return false; + } + if (world.countEntities(EntityButterfly.class) > PluginLepidopterology.spawnConstraint) { + return false; + } + + if (!spawn.canSpawn(world, x, y, z)) { + return false; + } + + if (world.isAirBlock(x - 1, y, z)) { + attemptButterflySpawn(world, spawn, x - 1, y, z); + } else if (world.isAirBlock(x + 1, y, z)) { + attemptButterflySpawn(world, spawn, x + 1, y, z); + } else if (world.isAirBlock(x, y, z - 1)) { + attemptButterflySpawn(world, spawn, x, y, z - 1); + } else if (world.isAirBlock(x, y, z + 1)) { + attemptButterflySpawn(world, spawn, x, y, z + 1); + } + + return false; + } + + private static void attemptButterflySpawn(World world, IButterfly butterfly, double x, double y, double z) { + if (ButterflyManager.butterflyRoot.spawnButterflyInWorld(world, butterfly.copy(), x, y + 0.1f, z) != null) { + Log.finest("Spawned a butterfly '%s' at %s/%s/%s.", butterfly.getDisplayName(), x, y, z); + } + } } diff --git a/src/main/java/forestry/lepidopterology/blocks/BlockLepidopterology.java b/src/main/java/forestry/lepidopterology/blocks/BlockLepidopterology.java index f7fc83c9b..1bf84aec7 100644 --- a/src/main/java/forestry/lepidopterology/blocks/BlockLepidopterology.java +++ b/src/main/java/forestry/lepidopterology/blocks/BlockLepidopterology.java @@ -1,21 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.blocks; - -import forestry.api.core.Tabs; -import forestry.core.blocks.BlockBase; - -public class BlockLepidopterology extends BlockBase { - public BlockLepidopterology() { - super(true); - setCreativeTab(Tabs.tabLepidopterology); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.blocks; + +import forestry.api.core.Tabs; +import forestry.core.blocks.BlockBase; + +public class BlockLepidopterology extends BlockBase { + public BlockLepidopterology() { + super(true); + setCreativeTab(Tabs.tabLepidopterology); + } +} diff --git a/src/main/java/forestry/lepidopterology/blocks/BlockLepidopterologyType.java b/src/main/java/forestry/lepidopterology/blocks/BlockLepidopterologyType.java index ba06df2bb..c2659ff95 100644 --- a/src/main/java/forestry/lepidopterology/blocks/BlockLepidopterologyType.java +++ b/src/main/java/forestry/lepidopterology/blocks/BlockLepidopterologyType.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.blocks; - -import forestry.core.blocks.IMachinePropertiesTESR; -import forestry.core.proxy.Proxies; -import forestry.core.render.IBlockRenderer; -import forestry.core.tiles.TileForestry; -import forestry.lepidopterology.tiles.TileLepidopteristChest; - -public enum BlockLepidopterologyType implements IMachinePropertiesTESR { - LEPICHEST(TileLepidopteristChest.class, "LepiChest") { - @Override - public IBlockRenderer getRenderer() { - return Proxies.render.getRenderChest("lepichest"); - } - }; - - public static final BlockLepidopterologyType[] VALUES = values(); - - private final String teIdent; - private final Class teClass; - - BlockLepidopterologyType(Class teClass, String teName) { - this.teIdent = "forestry." + teName; - this.teClass = teClass; - } - - @Override - public int getMeta() { - return ordinal(); - } - - @Override - public String getTeIdent() { - return teIdent; - } - - @Override - public Class getTeClass() { - return teClass; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.blocks; + +import forestry.core.blocks.IMachinePropertiesTESR; +import forestry.core.proxy.Proxies; +import forestry.core.render.IBlockRenderer; +import forestry.core.tiles.TileForestry; +import forestry.lepidopterology.tiles.TileLepidopteristChest; + +public enum BlockLepidopterologyType implements IMachinePropertiesTESR { + LEPICHEST(TileLepidopteristChest.class, "LepiChest") { + @Override + public IBlockRenderer getRenderer() { + return Proxies.render.getRenderChest("lepichest"); + } + }; + + public static final BlockLepidopterologyType[] VALUES = values(); + + private final String teIdent; + private final Class teClass; + + BlockLepidopterologyType(Class teClass, String teName) { + this.teIdent = "forestry." + teName; + this.teClass = teClass; + } + + @Override + public int getMeta() { + return ordinal(); + } + + @Override + public String getTeIdent() { + return teIdent; + } + + @Override + public Class getTeClass() { + return teClass; + } +} diff --git a/src/main/java/forestry/lepidopterology/blocks/BlockRegistryLepidopterology.java b/src/main/java/forestry/lepidopterology/blocks/BlockRegistryLepidopterology.java index cddbeddda..e99493e3d 100644 --- a/src/main/java/forestry/lepidopterology/blocks/BlockRegistryLepidopterology.java +++ b/src/main/java/forestry/lepidopterology/blocks/BlockRegistryLepidopterology.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.blocks; - -import forestry.core.blocks.BlockRegistry; -import forestry.core.items.ItemBlockForestry; - -public class BlockRegistryLepidopterology extends BlockRegistry { - public final BlockLepidopterology lepidopterology; - - public BlockRegistryLepidopterology() { - lepidopterology = registerBlock(new BlockLepidopterology(), ItemBlockForestry.class, "lepidopterology"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.blocks; + +import forestry.core.blocks.BlockRegistry; +import forestry.core.items.ItemBlockForestry; + +public class BlockRegistryLepidopterology extends BlockRegistry { + public final BlockLepidopterology lepidopterology; + + public BlockRegistryLepidopterology() { + lepidopterology = registerBlock(new BlockLepidopterology(), ItemBlockForestry.class, "lepidopterology"); + } +} diff --git a/src/main/java/forestry/lepidopterology/commands/CommandButterfly.java b/src/main/java/forestry/lepidopterology/commands/CommandButterfly.java index 58559e863..5766e89c0 100644 --- a/src/main/java/forestry/lepidopterology/commands/CommandButterfly.java +++ b/src/main/java/forestry/lepidopterology/commands/CommandButterfly.java @@ -10,50 +10,47 @@ ******************************************************************************/ package forestry.lepidopterology.commands; -import net.minecraft.command.ICommandSender; -import net.minecraft.world.World; - import forestry.core.commands.CommandHelpers; import forestry.core.commands.SubCommand; import forestry.lepidopterology.entities.EntityButterfly; +import net.minecraft.command.ICommandSender; +import net.minecraft.world.World; /** * @author CovertJaguar */ public class CommandButterfly extends SubCommand { - public CommandButterfly() { - super("butterfly"); - addAlias("bfly"); - addChildCommand(new CommandButterflyKill()); - } + public CommandButterfly() { + super("butterfly"); + addAlias("bfly"); + addChildCommand(new CommandButterflyKill()); + } - public static class CommandButterflyKill extends SubCommand { + public static class CommandButterflyKill extends SubCommand { - public CommandButterflyKill() { - super("kill"); - addAlias("killall"); - setPermLevel(PermLevel.ADMIN); - } + public CommandButterflyKill() { + super("kill"); + addAlias("killall"); + setPermLevel(PermLevel.ADMIN); + } - @Override - public void processSubCommand(ICommandSender sender, String[] args) { - if (args.length > 1) { - CommandHelpers.throwWrongUsage(sender, this); - } - - World world = CommandHelpers.getWorld(sender, this, args, 0); - if (world == null) { - CommandHelpers.throwWrongUsage(sender, this); - } else { - for (Object entity : world.loadedEntityList) { - if (entity instanceof EntityButterfly) { - ((EntityButterfly) entity).setDead(); - } - } - } - } - - } + @Override + public void processSubCommand(ICommandSender sender, String[] args) { + if (args.length > 1) { + CommandHelpers.throwWrongUsage(sender, this); + } + World world = CommandHelpers.getWorld(sender, this, args, 0); + if (world == null) { + CommandHelpers.throwWrongUsage(sender, this); + } else { + for (Object entity : world.loadedEntityList) { + if (entity instanceof EntityButterfly) { + ((EntityButterfly) entity).setDead(); + } + } + } + } + } } diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyBase.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyBase.java index 1c8e3ddc6..eb408d90a 100755 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyBase.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyBase.java @@ -17,53 +17,53 @@ import net.minecraft.util.Vec3; public abstract class AIButterflyBase extends EntityAIBase { - protected final EntityButterfly entity; + protected final EntityButterfly entity; - protected AIButterflyBase(EntityButterfly entity) { - this.entity = entity; - } + protected AIButterflyBase(EntityButterfly entity) { + this.entity = entity; + } - protected Vec3 getRandomDestination() { - if (entity.isInWater()) { - return getRandomDestinationUpwards(); - } + protected Vec3 getRandomDestination() { + if (entity.isInWater()) { + return getRandomDestinationUpwards(); + } - Vec3 randomTarget = RandomPositionGenerator.findRandomTargetBlockAwayFrom(entity, 16, 7, - Vec3.createVectorHelper(entity.posX, entity.posY, entity.posZ)); + Vec3 randomTarget = RandomPositionGenerator.findRandomTargetBlockAwayFrom( + entity, 16, 7, Vec3.createVectorHelper(entity.posX, entity.posY, entity.posZ)); - if (randomTarget == null) { - return null; - } + if (randomTarget == null) { + return null; + } - if (validateDestination(randomTarget, false)) { - return randomTarget; - } else { - return null; - } - } + if (validateDestination(randomTarget, false)) { + return randomTarget; + } else { + return null; + } + } - protected Vec3 getRandomDestinationUpwards() { - Vec3 destination = Vec3.createVectorHelper(entity.posX, entity.posY + entity.getRNG().nextInt(10) + 2, entity.posZ); - if (validateDestination(destination, true)) { - return destination; - } else { - return null; - } - } - - private boolean validateDestination(Vec3 dest, boolean allowFluids) { - if (dest.yCoord < 1) { - return false; - } - Block block = entity.worldObj.getBlock((int) dest.xCoord, (int) dest.yCoord, (int) dest.zCoord); - if (!allowFluids && block.getMaterial().isLiquid()) { - return false; - } - // getBlocksMovement is a bad name, getAllowsMovement would be a better name. - if (!block.getBlocksMovement(entity.worldObj, (int) dest.xCoord, (int) dest.yCoord, (int) dest.zCoord)) { - return false; - } - return entity.getButterfly().isAcceptedEnvironment(entity.worldObj, dest.xCoord, dest.yCoord, dest.zCoord); - } + protected Vec3 getRandomDestinationUpwards() { + Vec3 destination = Vec3.createVectorHelper( + entity.posX, entity.posY + entity.getRNG().nextInt(10) + 2, entity.posZ); + if (validateDestination(destination, true)) { + return destination; + } else { + return null; + } + } + private boolean validateDestination(Vec3 dest, boolean allowFluids) { + if (dest.yCoord < 1) { + return false; + } + Block block = entity.worldObj.getBlock((int) dest.xCoord, (int) dest.yCoord, (int) dest.zCoord); + if (!allowFluids && block.getMaterial().isLiquid()) { + return false; + } + // getBlocksMovement is a bad name, getAllowsMovement would be a better name. + if (!block.getBlocksMovement(entity.worldObj, (int) dest.xCoord, (int) dest.yCoord, (int) dest.zCoord)) { + return false; + } + return entity.getButterfly().isAcceptedEnvironment(entity.worldObj, dest.xCoord, dest.yCoord, dest.zCoord); + } } diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyFlee.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyFlee.java index afca7746a..4adfaf53b 100755 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyFlee.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyFlee.java @@ -14,36 +14,37 @@ import net.minecraft.entity.player.EntityPlayer; public class AIButterflyFlee extends AIButterflyMovement { - public AIButterflyFlee(EntityButterfly entity) { - super(entity); - setMutexBits(3); - } + public AIButterflyFlee(EntityButterfly entity) { + super(entity); + setMutexBits(3); + } - @Override - public boolean shouldExecute() { + @Override + public boolean shouldExecute() { - EntityPlayer player = entity.worldObj.getClosestPlayerToEntity(entity, entity.getButterfly().getGenome().getPrimary().getFlightDistance()); + EntityPlayer player = entity.worldObj.getClosestPlayerToEntity( + entity, entity.getButterfly().getGenome().getPrimary().getFlightDistance()); - if (player == null || player.isSneaking()) { - return false; - } + if (player == null || player.isSneaking()) { + return false; + } - if (!entity.getEntitySenses().canSee(player)) { - return false; - } + if (!entity.getEntitySenses().canSee(player)) { + return false; + } - flightTarget = getRandomDestination(); - if (flightTarget == null) { - return false; - } + flightTarget = getRandomDestination(); + if (flightTarget == null) { + return false; + } - if (player.getDistanceSq(flightTarget.xCoord, flightTarget.yCoord, flightTarget.zCoord) < player.getDistanceSqToEntity(entity)) { - return false; - } - - entity.setDestination(flightTarget); - entity.setState(EnumButterflyState.FLYING); - return true; - } + if (player.getDistanceSq(flightTarget.xCoord, flightTarget.yCoord, flightTarget.zCoord) + < player.getDistanceSqToEntity(entity)) { + return false; + } + entity.setDestination(flightTarget); + entity.setState(EnumButterflyState.FLYING); + return true; + } } diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyInteract.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyInteract.java index a1d1ba225..cf6f132cb 100755 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyInteract.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyInteract.java @@ -14,52 +14,50 @@ import net.minecraft.util.ChunkCoordinates; public abstract class AIButterflyInteract extends AIButterflyBase { - protected ChunkCoordinates rest; + protected ChunkCoordinates rest; - private boolean canInteract = false; - private boolean hasInteracted = false; + private boolean canInteract = false; + private boolean hasInteracted = false; - protected AIButterflyInteract(EntityButterfly entity) { - super(entity); - setMutexBits(3); - } + protected AIButterflyInteract(EntityButterfly entity) { + super(entity); + setMutexBits(3); + } - @Override - public boolean shouldExecute() { - if (entity.getState() != EnumButterflyState.RESTING) { - return false; - } + @Override + public boolean shouldExecute() { + if (entity.getState() != EnumButterflyState.RESTING) { + return false; + } - rest = new ChunkCoordinates((int) entity.posX, ((int) Math.floor(entity.posY)) - 1, (int) entity.posZ); - if (entity.worldObj.isAirBlock(rest.posX, rest.posY, rest.posZ)) { - return false; - } + rest = new ChunkCoordinates((int) entity.posX, ((int) Math.floor(entity.posY)) - 1, (int) entity.posZ); + if (entity.worldObj.isAirBlock(rest.posX, rest.posY, rest.posZ)) { + return false; + } - canInteract = canInteract(); + canInteract = canInteract(); - return canInteract; - } + return canInteract; + } - protected abstract boolean canInteract(); + protected abstract boolean canInteract(); - @Override - public boolean continueExecuting() { - return canInteract && !hasInteracted; - } + @Override + public boolean continueExecuting() { + return canInteract && !hasInteracted; + } - @Override - public void startExecuting() { - } + @Override + public void startExecuting() {} - @Override - public void resetTask() { - canInteract = false; - hasInteracted = false; - rest = null; - } - - protected void setHasInteracted() { - hasInteracted = true; - } + @Override + public void resetTask() { + canInteract = false; + hasInteracted = false; + rest = null; + } + protected void setHasInteracted() { + hasInteracted = true; + } } diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyMate.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyMate.java index 0d9f362f1..3e900b84d 100644 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyMate.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyMate.java @@ -17,47 +17,49 @@ import forestry.plugins.PluginLepidopterology; public class AIButterflyMate extends AIButterflyInteract { - public AIButterflyMate(EntityButterfly entity) { - super(entity); - } + public AIButterflyMate(EntityButterfly entity) { + super(entity); + } - /** - * Should lay egg? - */ - @Override - protected boolean canInteract() { - if (entity.cooldownEgg > 0) { - return false; - } + /** + * Should lay egg? + */ + @Override + protected boolean canInteract() { + if (entity.cooldownEgg > 0) { + return false; + } - if (entity.getButterfly().getMate() == null) { - return false; - } + if (entity.getButterfly().getMate() == null) { + return false; + } - if (entity.worldObj.countEntities(EntityButterfly.class) > PluginLepidopterology.spawnConstraint) { - return false; - } + if (entity.worldObj.countEntities(EntityButterfly.class) > PluginLepidopterology.spawnConstraint) { + return false; + } - return GeneticsUtil.canNurse(entity.getButterfly(), entity.worldObj, rest.posX, rest.posY, rest.posZ); - } - - @Override - public void updateTask() { - if (continueExecuting()) { - IPollinatable tile = GeneticsUtil.getOrCreatePollinatable(null, entity.worldObj, rest.posX, rest.posY, rest.posZ); - if (tile instanceof IButterflyNursery) { - IButterflyNursery nursery = (IButterflyNursery) tile; - if (nursery.canNurse(entity.getButterfly())) { - nursery.setCaterpillar(entity.getButterfly().spawnCaterpillar(nursery)); - // Log.finest("A butterfly '%s' laid an egg at %s/%s/%s.", entity.getButterfly().getIdent(), rest.posX, rest.posY, rest.posZ); - if (entity.getRNG().nextFloat() < 1.0f / entity.getButterfly().getGenome().getFertility()) { - entity.setHealth(0); - } - } - } - setHasInteracted(); - entity.cooldownEgg = EntityButterfly.COOLDOWNS; - } - } + return GeneticsUtil.canNurse(entity.getButterfly(), entity.worldObj, rest.posX, rest.posY, rest.posZ); + } + @Override + public void updateTask() { + if (continueExecuting()) { + IPollinatable tile = + GeneticsUtil.getOrCreatePollinatable(null, entity.worldObj, rest.posX, rest.posY, rest.posZ); + if (tile instanceof IButterflyNursery) { + IButterflyNursery nursery = (IButterflyNursery) tile; + if (nursery.canNurse(entity.getButterfly())) { + nursery.setCaterpillar(entity.getButterfly().spawnCaterpillar(nursery)); + // Log.finest("A butterfly '%s' laid an egg at %s/%s/%s.", entity.getButterfly().getIdent(), + // rest.posX, rest.posY, rest.posZ); + if (entity.getRNG().nextFloat() + < 1.0f / entity.getButterfly().getGenome().getFertility()) { + entity.setHealth(0); + } + } + } + setHasInteracted(); + entity.cooldownEgg = EntityButterfly.COOLDOWNS; + } + } } diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyMovement.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyMovement.java index 3c69e7bc8..b964c358e 100644 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyMovement.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyMovement.java @@ -17,54 +17,53 @@ import net.minecraft.util.Vec3; */ public abstract class AIButterflyMovement extends AIButterflyBase { - protected Vec3 flightTarget; + protected Vec3 flightTarget; - protected AIButterflyMovement(EntityButterfly entity) { - super(entity); - } + protected AIButterflyMovement(EntityButterfly entity) { + super(entity); + } - @Override - public boolean continueExecuting() { - if (entity.getState() != EnumButterflyState.FLYING) { - return false; - } - if (flightTarget == null) { - return false; - } - // Abort if the flight target changed on us. - if (entity.getDestination() == null || !entity.getDestination().equals(flightTarget)) { - return false; - } + @Override + public boolean continueExecuting() { + if (entity.getState() != EnumButterflyState.FLYING) { + return false; + } + if (flightTarget == null) { + return false; + } + // Abort if the flight target changed on us. + if (entity.getDestination() == null || !entity.getDestination().equals(flightTarget)) { + return false; + } - // Continue if we have not yet reached the destination. - if (entity.getDestination().squareDistanceTo(entity.posX, entity.posY, entity.posZ) > 2.0f) { - return true; - } + // Continue if we have not yet reached the destination. + if (entity.getDestination().squareDistanceTo(entity.posX, entity.posY, entity.posZ) > 2.0f) { + return true; + } - entity.setDestination(null); - return false; - } + entity.setDestination(null); + return false; + } - @Override - public void updateTask() { - // Reset destination if we did collide. - if (entity.isInWater()) { - flightTarget = getRandomDestinationUpwards(); - } else if (entity.isCollided) { - flightTarget = entity.getRNG().nextBoolean() ? getRandomDestination() : null; - } else if (entity.worldObj.rand.nextInt(300) == 0) { - flightTarget = getRandomDestination(); - } - entity.setDestination(flightTarget); - entity.changeExhaustion(1); - } + @Override + public void updateTask() { + // Reset destination if we did collide. + if (entity.isInWater()) { + flightTarget = getRandomDestinationUpwards(); + } else if (entity.isCollided) { + flightTarget = entity.getRNG().nextBoolean() ? getRandomDestination() : null; + } else if (entity.worldObj.rand.nextInt(300) == 0) { + flightTarget = getRandomDestination(); + } + entity.setDestination(flightTarget); + entity.changeExhaustion(1); + } - @Override - public void startExecuting() { - } + @Override + public void startExecuting() {} - @Override - public void resetTask() { - flightTarget = null; - } + @Override + public void resetTask() { + flightTarget = null; + } } diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyPollinate.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyPollinate.java index a94acdc2d..d764da36c 100644 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyPollinate.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyPollinate.java @@ -18,51 +18,60 @@ import forestry.plugins.PluginLepidopterology; public class AIButterflyPollinate extends AIButterflyInteract { - public AIButterflyPollinate(EntityButterfly entity) { - super(entity); - } + public AIButterflyPollinate(EntityButterfly entity) { + super(entity); + } - /** - * Should pollinate? - */ - @Override - protected boolean canInteract() { - if (entity.cooldownPollination > 0 || !PluginLepidopterology.isPollinationAllowed()) { - return false; - } + /** + * Should pollinate? + */ + @Override + protected boolean canInteract() { + if (entity.cooldownPollination > 0 || !PluginLepidopterology.isPollinationAllowed()) { + return false; + } - ICheckPollinatable checkPollinatable = GeneticsUtil.getCheckPollinatable(entity.worldObj, rest.posX, rest.posY, rest.posZ); - if (checkPollinatable == null) { - return false; - } + ICheckPollinatable checkPollinatable = + GeneticsUtil.getCheckPollinatable(entity.worldObj, rest.posX, rest.posY, rest.posZ); + if (checkPollinatable == null) { + return false; + } - if (!entity.getButterfly().getGenome().getFlowerProvider().isAcceptedPollinatable(entity.worldObj, new FakePollinatable(checkPollinatable))) { - return false; - } + if (!entity.getButterfly() + .getGenome() + .getFlowerProvider() + .isAcceptedPollinatable(entity.worldObj, new FakePollinatable(checkPollinatable))) { + return false; + } - return entity.getPollen() == null || checkPollinatable.canMateWith(entity.getPollen()); - } - - @Override - public void updateTask() { - if (continueExecuting()) { - ICheckPollinatable checkPollinatable = GeneticsUtil.getCheckPollinatable(entity.worldObj, rest.posX, rest.posY, rest.posZ); - if (checkPollinatable != null) { - if (entity.getPollen() == null) { - entity.setPollen(checkPollinatable.getPollen()); - // Log.finest("A butterfly '%s' grabbed a pollen '%s' at %s/%s/%s.", entity.getButterfly().getIdent(), entity.getPollen().getIdent(), rest.posX, rest.posY, rest.posZ); - } else if (checkPollinatable.canMateWith(entity.getPollen())) { - IPollinatable realPollinatable = GeneticsUtil.getOrCreatePollinatable(null, entity.worldObj, rest.posX, rest.posY, rest.posZ); - if (realPollinatable != null) { - realPollinatable.mateWith(entity.getPollen()); - // Log.finest("A butterfly '%s' unloaded pollen '%s' at %s/%s/%s.", entity.getButterfly().getIdent(), entity.getPollen().getIdent(), rest.posX, rest.posY, rest.posZ); - entity.setPollen(null); - } - } - } - setHasInteracted(); - entity.cooldownPollination = EntityButterfly.COOLDOWNS; - } - } + return entity.getPollen() == null || checkPollinatable.canMateWith(entity.getPollen()); + } + @Override + public void updateTask() { + if (continueExecuting()) { + ICheckPollinatable checkPollinatable = + GeneticsUtil.getCheckPollinatable(entity.worldObj, rest.posX, rest.posY, rest.posZ); + if (checkPollinatable != null) { + if (entity.getPollen() == null) { + entity.setPollen(checkPollinatable.getPollen()); + // Log.finest("A butterfly '%s' grabbed a pollen '%s' at %s/%s/%s.", + // entity.getButterfly().getIdent(), entity.getPollen().getIdent(), rest.posX, rest.posY, + // rest.posZ); + } else if (checkPollinatable.canMateWith(entity.getPollen())) { + IPollinatable realPollinatable = GeneticsUtil.getOrCreatePollinatable( + null, entity.worldObj, rest.posX, rest.posY, rest.posZ); + if (realPollinatable != null) { + realPollinatable.mateWith(entity.getPollen()); + // Log.finest("A butterfly '%s' unloaded pollen '%s' at %s/%s/%s.", + // entity.getButterfly().getIdent(), entity.getPollen().getIdent(), rest.posX, rest.posY, + // rest.posZ); + entity.setPollen(null); + } + } + } + setHasInteracted(); + entity.cooldownPollination = EntityButterfly.COOLDOWNS; + } + } } diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyRest.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyRest.java index 7e7beaa66..ca7898884 100755 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyRest.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyRest.java @@ -16,99 +16,95 @@ import net.minecraft.block.BlockFlower; import net.minecraft.block.BlockWall; import net.minecraft.block.IGrowable; import net.minecraft.block.material.Material; - import net.minecraftforge.common.IPlantable; public class AIButterflyRest extends AIButterflyBase { - public AIButterflyRest(EntityButterfly entity) { - super(entity); - setMutexBits(3); - } + public AIButterflyRest(EntityButterfly entity) { + super(entity); + setMutexBits(3); + } - @Override - public boolean shouldExecute() { + @Override + public boolean shouldExecute() { - if (entity.getExhaustion() < EntityButterfly.EXHAUSTION_REST - && entity.canFly()) { - return false; - } + if (entity.getExhaustion() < EntityButterfly.EXHAUSTION_REST && entity.canFly()) { + return false; + } - int x = (int) entity.posX; - int y = ((int) Math.floor(entity.posY)); - int z = (int) entity.posZ; + int x = (int) entity.posX; + int y = ((int) Math.floor(entity.posY)); + int z = (int) entity.posZ; - if (!canLand(x, y, z)) { - return false; - } + if (!canLand(x, y, z)) { + return false; + } - y--; - if (entity.worldObj.isAirBlock(x, y, z)) { - return false; - } - if (entity.worldObj.getBlock(x, y, z).getMaterial().isLiquid()) { - return false; - } - if (!entity.getButterfly().isAcceptedEnvironment(entity.worldObj, x, y, z)) { - return false; - } + y--; + if (entity.worldObj.isAirBlock(x, y, z)) { + return false; + } + if (entity.worldObj.getBlock(x, y, z).getMaterial().isLiquid()) { + return false; + } + if (!entity.getButterfly().isAcceptedEnvironment(entity.worldObj, x, y, z)) { + return false; + } - entity.setDestination(null); - entity.setState(EnumButterflyState.RESTING); - return true; - } + entity.setDestination(null); + entity.setState(EnumButterflyState.RESTING); + return true; + } - @Override - public boolean continueExecuting() { - if (entity.getExhaustion() <= 0 && entity.canFly()) { - return false; - } - return !entity.isInWater(); - } + @Override + public boolean continueExecuting() { + if (entity.getExhaustion() <= 0 && entity.canFly()) { + return false; + } + return !entity.isInWater(); + } - @Override - public void startExecuting() { - } + @Override + public void startExecuting() {} - @Override - public void resetTask() { - } + @Override + public void resetTask() {} - @Override - public void updateTask() { - entity.changeExhaustion(-1); - } + @Override + public void updateTask() { + entity.changeExhaustion(-1); + } - private boolean canLand(int x, int y, int z) { - Block block = entity.worldObj.getBlock(x, y, z); - // getBlocksMovement is a bad name, allowsMovement would be a better name. - if (!block.getBlocksMovement(entity.worldObj, x, y, z)) { - return false; - } - if (isPlant(block)) { - return true; - } - block = entity.worldObj.getBlock(x, y - 1, z); - return isRest(block) || block.isLeaves(entity.worldObj, x, y - 1, z); - } + private boolean canLand(int x, int y, int z) { + Block block = entity.worldObj.getBlock(x, y, z); + // getBlocksMovement is a bad name, allowsMovement would be a better name. + if (!block.getBlocksMovement(entity.worldObj, x, y, z)) { + return false; + } + if (isPlant(block)) { + return true; + } + block = entity.worldObj.getBlock(x, y - 1, z); + return isRest(block) || block.isLeaves(entity.worldObj, x, y - 1, z); + } - private static boolean isRest(Block block) { - if (block instanceof BlockFence) { - return true; - } - return block instanceof BlockWall; - } + private static boolean isRest(Block block) { + if (block instanceof BlockFence) { + return true; + } + return block instanceof BlockWall; + } - private static boolean isPlant(Block block) { - if (block instanceof BlockFlower) { - return true; - } else if (block instanceof IPlantable) { - return true; - } else if (block instanceof IGrowable) { - return true; - } else if (block.getMaterial() == Material.plants) { - return true; - } - return false; - } + private static boolean isPlant(Block block) { + if (block instanceof BlockFlower) { + return true; + } else if (block instanceof IPlantable) { + return true; + } else if (block instanceof IGrowable) { + return true; + } else if (block.getMaterial() == Material.plants) { + return true; + } + return false; + } } diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyRise.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyRise.java index 2294d947a..8dc7bd5d6 100644 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyRise.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyRise.java @@ -12,65 +12,65 @@ package forestry.lepidopterology.entities; public class AIButterflyRise extends AIButterflyMovement { - public AIButterflyRise(EntityButterfly entity) { - super(entity); - setMutexBits(1); - } + public AIButterflyRise(EntityButterfly entity) { + super(entity); + setMutexBits(1); + } - @Override - public boolean shouldExecute() { - if (entity.getDestination() != null) { - return false; - } + @Override + public boolean shouldExecute() { + if (entity.getDestination() != null) { + return false; + } - if (!entity.isCollidedHorizontally && entity.getRNG().nextInt(64) != 0) { - return false; - } + if (!entity.isCollidedHorizontally && entity.getRNG().nextInt(64) != 0) { + return false; + } - flightTarget = getRandomDestinationUpwards(); - if (flightTarget == null) { - if (entity.getState().doesMovement) { - entity.setState(EnumButterflyState.HOVER); - } - return false; - } + flightTarget = getRandomDestinationUpwards(); + if (flightTarget == null) { + if (entity.getState().doesMovement) { + entity.setState(EnumButterflyState.HOVER); + } + return false; + } - entity.setDestination(flightTarget); - entity.setState(EnumButterflyState.RISING); - return true; - } + entity.setDestination(flightTarget); + entity.setState(EnumButterflyState.RISING); + return true; + } - @Override - public boolean continueExecuting() { - if (entity.getState() != EnumButterflyState.RISING) { - return false; - } - if (flightTarget == null) { - return false; - } - // Abort if the flight target changed on us. - if (entity.getDestination() == null || !entity.getDestination().equals(flightTarget)) { - return false; - } + @Override + public boolean continueExecuting() { + if (entity.getState() != EnumButterflyState.RISING) { + return false; + } + if (flightTarget == null) { + return false; + } + // Abort if the flight target changed on us. + if (entity.getDestination() == null || !entity.getDestination().equals(flightTarget)) { + return false; + } - // Continue if we have not yet reached the destination. - if (entity.getDestination().squareDistanceTo(entity.posX, entity.posY, entity.posZ) > 2.0f) { - return true; - } + // Continue if we have not yet reached the destination. + if (entity.getDestination().squareDistanceTo(entity.posX, entity.posY, entity.posZ) > 2.0f) { + return true; + } - entity.setDestination(null); - return false; - } + entity.setDestination(null); + return false; + } - @Override - public void updateTask() { - if (entity.isInWater()) { - flightTarget = getRandomDestinationUpwards(); - } else if (entity.isCollidedVertically && entity.getRNG().nextInt(62) == 0) { - flightTarget = null; - } + @Override + public void updateTask() { + if (entity.isInWater()) { + flightTarget = getRandomDestinationUpwards(); + } else if (entity.isCollidedVertically && entity.getRNG().nextInt(62) == 0) { + flightTarget = null; + } - entity.setDestination(flightTarget); - entity.changeExhaustion(1); - } + entity.setDestination(flightTarget); + entity.changeExhaustion(1); + } } diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyWander.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyWander.java index d99eda4ad..b19e28b6a 100755 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyWander.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyWander.java @@ -12,28 +12,28 @@ package forestry.lepidopterology.entities; public class AIButterflyWander extends AIButterflyMovement { - public AIButterflyWander(EntityButterfly entity) { - super(entity); - setMutexBits(1); - } + public AIButterflyWander(EntityButterfly entity) { + super(entity); + setMutexBits(1); + } - @Override - public boolean shouldExecute() { + @Override + public boolean shouldExecute() { - if (entity.getDestination() != null) { - return false; - } + if (entity.getDestination() != null) { + return false; + } - flightTarget = getRandomDestination(); - if (flightTarget == null) { - if (entity.getState().doesMovement) { - entity.setState(EnumButterflyState.HOVER); - } - return false; - } + flightTarget = getRandomDestination(); + if (flightTarget == null) { + if (entity.getState().doesMovement) { + entity.setState(EnumButterflyState.HOVER); + } + return false; + } - entity.setDestination(flightTarget); - entity.setState(EnumButterflyState.FLYING); - return true; - } + entity.setDestination(flightTarget); + entity.setState(EnumButterflyState.FLYING); + return true; + } } diff --git a/src/main/java/forestry/lepidopterology/entities/EntityButterfly.java b/src/main/java/forestry/lepidopterology/entities/EntityButterfly.java index 7f28e12ef..bebe25c00 100755 --- a/src/main/java/forestry/lepidopterology/entities/EntityButterfly.java +++ b/src/main/java/forestry/lepidopterology/entities/EntityButterfly.java @@ -10,6 +10,25 @@ ******************************************************************************/ package forestry.lepidopterology.entities; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.arboriculture.EnumGermlingType; +import forestry.api.arboriculture.TreeManager; +import forestry.api.core.IToolScoop; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.ISpeciesRoot; +import forestry.api.lepidopterology.ButterflyManager; +import forestry.api.lepidopterology.EnumFlutterType; +import forestry.api.lepidopterology.IAlleleButterflySpecies; +import forestry.api.lepidopterology.IButterfly; +import forestry.api.lepidopterology.IButterflyGenome; +import forestry.api.lepidopterology.IButterflyRoot; +import forestry.api.lepidopterology.IEntityButterfly; +import forestry.api.lepidopterology.ILepidopteristTracker; +import forestry.core.utils.ItemStackUtil; +import forestry.lepidopterology.genetics.Butterfly; import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.block.BlockFlower; @@ -31,501 +50,477 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; - import net.minecraftforge.common.IPlantable; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.arboriculture.EnumGermlingType; -import forestry.api.arboriculture.TreeManager; -import forestry.api.core.IToolScoop; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.ISpeciesRoot; -import forestry.api.lepidopterology.ButterflyManager; -import forestry.api.lepidopterology.EnumFlutterType; -import forestry.api.lepidopterology.IAlleleButterflySpecies; -import forestry.api.lepidopterology.IButterfly; -import forestry.api.lepidopterology.IButterflyGenome; -import forestry.api.lepidopterology.IButterflyRoot; -import forestry.api.lepidopterology.IEntityButterfly; -import forestry.api.lepidopterology.ILepidopteristTracker; -import forestry.core.utils.ItemStackUtil; -import forestry.lepidopterology.genetics.Butterfly; - public class EntityButterfly extends EntityCreature implements IEntityButterfly { - /* CONSTANTS */ - public static final int COOLDOWNS = 1500; - - private static final int DATAWATCHER_ID_SPECIES = 16; - private static final int DATAWATCHER_ID_SIZE = 17; - private static final int DATAWATCHER_ID_STATE = 18; - - private static final float DEFAULT_BUTTERFLY_SIZE = 0.75f; - private static final EnumButterflyState DEFAULT_STATE = EnumButterflyState.FLYING; - - public static final int EXHAUSTION_REST = 1000; - public static final int EXHAUSTION_CONSUMPTION = 100 * EXHAUSTION_REST; - public static final int MAX_LIFESPAN = 24000 * 7; // one minecraft week in ticks - private int maximumHomeDistance = 64; - - private Vec3 flightTarget; - private int exhaustion; - private IButterfly contained; - private IIndividual pollen; - - public int cooldownPollination = 0; - public int cooldownEgg = 0; - - // Client Rendering - private IAlleleButterflySpecies species; - private float size = DEFAULT_BUTTERFLY_SIZE; - private EnumButterflyState state = DEFAULT_STATE; - - /* CONSTRUCTOR */ - public EntityButterfly(World world) { - super(world); - setDefaults(); - } - - public EntityButterfly(World world, IButterfly butterfly, int x, int y, int z) { - super(world); - setDefaults(); - setIndividual(butterfly); - setHomeArea(x, y, z, maximumHomeDistance); - } - - @Override - protected void entityInit() { - super.entityInit(); - - dataWatcher.addObject(DATAWATCHER_ID_SPECIES, ""); - dataWatcher.addObject(DATAWATCHER_ID_SIZE, (int) (DEFAULT_BUTTERFLY_SIZE * 100)); - dataWatcher.addObject(DATAWATCHER_ID_STATE, (byte) DEFAULT_STATE.ordinal()); - } - - private void setDefaults() { - tasks.addTask(8, new AIButterflyFlee(this)); - tasks.addTask(9, new AIButterflyMate(this)); - tasks.addTask(10, new AIButterflyPollinate(this)); - tasks.addTask(11, new AIButterflyRest(this)); - tasks.addTask(12, new AIButterflyRise(this)); - tasks.addTask(12, new AIButterflyWander(this)); - } - - @Override - public EntityCreature getEntity() { - return this; - } - - /* SAVING & LOADING */ - @Override - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - - NBTTagCompound bio = new NBTTagCompound(); - if (contained != null) - contained.writeToNBT(bio); - - nbttagcompound.setTag("BTFLY", bio); - - if (pollen != null) { - NBTTagCompound pln = new NBTTagCompound(); - pollen.writeToNBT(pln); - nbttagcompound.setTag("PLN", pln); - } - - nbttagcompound.setByte("STATE", (byte) getState().ordinal()); - nbttagcompound.setInteger("EXH", exhaustion); - } - - @Override - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - - IButterfly butterfly = null; - if (nbttagcompound.hasKey("BTFLY")) { - butterfly = new Butterfly((NBTTagCompound) nbttagcompound.getTag("BTFLY")); - } - setIndividual(butterfly); - - if (nbttagcompound.hasKey("PLN")) { - pollen = TreeManager.treeRoot.getMember((NBTTagCompound) nbttagcompound.getTag("PLN")); - } - - EnumButterflyState state = EnumButterflyState.VALUES[nbttagcompound.getByte("STATE")]; - setState(state); - exhaustion = nbttagcompound.getInteger("EXH"); - } - - public float getWingFlap(float partialTicktime) { - return getState().getWingFlap(this, species.getUID().hashCode(), partialTicktime); - } - - /* STATE - Used for AI and rendering */ - public void setState(EnumButterflyState state) { - if (this.state != state) { - this.state = state; - if (!worldObj.isRemote) { - dataWatcher.updateObject(DATAWATCHER_ID_STATE, (byte) state.ordinal()); - } - } - } - - public EnumButterflyState getState() { - return state; - } - - public float getSize() { - return size; - } - - public float getSpeed() { - return contained.getGenome().getSpeed(); - } - - /* DESTINATION */ - public Vec3 getDestination() { - return flightTarget; - } - - public void setDestination(Vec3 destination) { - flightTarget = destination; - } - - @Override - public float getBlockPathWeight(int x, int y, int z) { - float weight = 0.0f; - final ChunkCoordinates home = getHomePosition(); - double distanceToHome = home.getDistanceSquared(x, y, z); - - if(!isWithinHomeDistanceFromPosition(distanceToHome)){ - - weight -= 7.5f + 0.005 * (distanceToHome / 4); - } - - if (!getButterfly().isAcceptedEnvironment(worldObj, x, y, z)) { - weight -= 15.0f; - } - - if (!worldObj.getEntitiesWithinAABB(EntityButterfly.class, AxisAlignedBB.getBoundingBox(x, y, z, x + 1, y + 1, z + 1)).isEmpty()) { - weight -= 1.0f; - } - - int depth = getFluidDepth(x, z); - if (depth > 0) { - weight -= 0.1f * depth; - } else { - Block block = worldObj.getBlock(x, y, z); - if (block instanceof BlockFlower) { - weight += 2.0f; - } else if (block instanceof IPlantable) { - weight += 1.5f; - } else if (block instanceof IGrowable) { - weight += 1.0f; - } else if (block.getMaterial() == Material.plants) { - weight += 1.0f; - } - - block = worldObj.getBlock(x, y - 1, z); - if (block.isLeaves(worldObj, x, y - 1, z)) { - weight += 2.5f; - } else if (block instanceof BlockFence) { - weight += 1.0f; - } else if (block instanceof BlockWall) { - weight += 1.0f; - } - } - - weight += worldObj.getLightBrightness(x, y, z); - return weight; - } - - private boolean isWithinHomeDistanceFromPosition(double distanceToHome) { - return distanceToHome < (maximumHomeDistance * maximumHomeDistance); - } - - private int getFluidDepth(int x, int z) { - Chunk chunk = worldObj.getChunkFromBlockCoords(x, z); - int xx = x & 15; - int zz = z & 15; - int depth = 0; - for (int y = chunk.getTopFilledSegment() + 15; y > 0; --y) { - Block block = chunk.getBlock(xx, y, zz); - if (block.getMaterial().isLiquid()) { - depth++; - } else if (!block.isAir(worldObj, x, y, z)) { - break; - } - } - - return depth; - } - - /* POLLEN */ - @Override - public IIndividual getPollen() { - return pollen; - } - - @Override - public void setPollen(IIndividual pollen) { - this.pollen = pollen; - } - - public boolean isRenderable() { - return species != null; - } - - /* EXHAUSTION */ - @Override - public void changeExhaustion(int change) { - exhaustion = exhaustion + change > 0 ? exhaustion + change : 0; - } - - @Override - public int getExhaustion() { - return exhaustion; - } - - /* FLYING ABILITY */ - public boolean canFly() { - return contained.canTakeFlight(worldObj, posX, posY, posZ); - } - - public void setIndividual(IButterfly butterfly) { - if (butterfly == null) { - butterfly = ButterflyManager.butterflyRoot.templateAsIndividual(ButterflyManager.butterflyRoot.getDefaultTemplate()); - } - contained = butterfly; - - IButterflyGenome genome = contained.getGenome(); - - isImmuneToFire = genome.getFireResist(); - size = genome.getSize(); - setSize(size, 0.4f); - species = genome.getPrimary(); - - if (!worldObj.isRemote) { - dataWatcher.updateObject(DATAWATCHER_ID_SIZE, (int) (size * 100)); - dataWatcher.updateObject(DATAWATCHER_ID_SPECIES, species.getUID()); - } else { - textureResource = new ResourceLocation(species.getEntityTexture()); - } - } - - @Override - public IButterfly getButterfly() { - return contained; - } - - @Override - public IEntityLivingData onSpawnWithEgg(IEntityLivingData data) { - if (!worldObj.isRemote) { - setIndividual(contained); - } - return data; - } - - @Override - public String getCommandSenderName() { - if (species == null) { - return super.getCommandSenderName(); - } - return species.getName(); - } - - @Override - public boolean getCanSpawnHere() { - return true; - } - - @Override - public int getMaxInPortalTime() { - return 1000; - } - - @SideOnly(Side.CLIENT) - private ResourceLocation textureResource; - - @SideOnly(Side.CLIENT) - public ResourceLocation getTexture() { - return textureResource; - } - - @Override - public boolean canBePushed() { - return false; - } - - @Override - protected void collideWithEntity(Entity other) { - } - - @Override - protected boolean isAIEnabled() { - return true; - } - - @Override - protected boolean canDespawn() { - return ticksExisted > MAX_LIFESPAN; - } - - /* INTERACTION */ - @Override - public boolean interact(EntityPlayer player) { - if (isDead) { - return false; - } - - ItemStack heldItem = player.getHeldItem(); - if (heldItem == null) { - return false; - } - - if (!(heldItem.getItem() instanceof IToolScoop)) { - return false; - } - - if (!worldObj.isRemote) { - IButterflyRoot root = contained.getGenome().getPrimary().getRoot(); - ILepidopteristTracker tracker = root.getBreedingTracker(worldObj, player.getGameProfile()); - ItemStack itemStack = root.getMemberStack(contained.copy(), EnumFlutterType.BUTTERFLY.ordinal()); - - tracker.registerCatch(contained); - ItemStackUtil.dropItemStackAsEntity(itemStack, worldObj, posX, posY, posZ); - setDead(); - } else { - player.swingItem(); - } - return true; - } - - /* LOOT */ - @Override - protected void dropFewItems(boolean playerKill, int lootLevel) { - for (ItemStack stack : contained.getLootDrop(this, playerKill, lootLevel)) { - ItemStackUtil.dropItemStackAsEntity(stack, worldObj, posX, posY, posZ); - } - - // Drop pollen if any - IIndividual pollen = getPollen(); - if (pollen != null) { - ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(pollen.getClass()); - ItemStack pollenStack = root.getMemberStack(pollen, EnumGermlingType.POLLEN.ordinal()); - ItemStackUtil.dropItemStackAsEntity(pollenStack, worldObj, posX, posY, posZ); - } - } - - /* UPDATING */ - @Override - public void onUpdate() { - super.onUpdate(); - - // Update stuff client side - if (worldObj.isRemote) { - if (species == null) { - String speciesUid = dataWatcher.getWatchableObjectString(DATAWATCHER_ID_SPECIES); - IAllele allele = AlleleManager.alleleRegistry.getAllele(speciesUid); - if (allele instanceof IAlleleButterflySpecies) { - species = (IAlleleButterflySpecies) allele; - textureResource = new ResourceLocation(species.getEntityTexture()); - size = dataWatcher.getWatchableObjectInt(DATAWATCHER_ID_SIZE) / 100f; - } - } - - int stateOrdinal = dataWatcher.getWatchableObjectByte(DATAWATCHER_ID_STATE); - if (state == null || state.ordinal() != stateOrdinal) { - setState(EnumButterflyState.VALUES[stateOrdinal]); - } - } - - motionY *= 0.6000000238418579d; - - // Make sure we die if the butterfly hasn't rested in a long, long time. - if (exhaustion > EXHAUSTION_CONSUMPTION && getRNG().nextInt(20) == 0) { - attackEntityFrom(DamageSource.generic, 1); - } - - if (ticksExisted > MAX_LIFESPAN) { - attackEntityFrom(DamageSource.generic, 1); - } - - // Reduce cooldowns - if (cooldownEgg > 0) { - cooldownEgg--; - } - if (cooldownPollination > 0) { - cooldownPollination--; - } - } - - @Override - protected void updateAITasks() { - super.updateAITasks(); - - if (getState().doesMovement && flightTarget != null) { - double diffX = flightTarget.xCoord + 0.5d - posX; - double diffY = flightTarget.yCoord + 0.1d - posY; - double diffZ = flightTarget.zCoord + 0.5d - posZ; - - motionX += (Math.signum(diffX) * 0.5d - motionX) * 0.10000000149011612d; - motionY += (Math.signum(diffY) * 0.699999988079071d - motionY) * 0.10000000149011612d; - motionZ += (Math.signum(diffZ) * 0.5d - motionZ) * 0.10000000149011612d; - - float horizontal = (float) ((Math.atan2(motionZ, motionX) * 180d) / Math.PI) - 90f; - rotationYaw += MathHelper.wrapAngleTo180_float(horizontal - rotationYaw); - - setMoveForward(contained.getGenome().getSpeed()); - } - } - - @Override - protected boolean canTriggerWalking() { - return false; - } - - @Override - protected void fall(float par1) { - } - - @Override - protected void updateFallState(double par1, boolean par3) { - } - - @Override - public boolean doesEntityNotTriggerPressurePlate() { - return true; - } - - @Override - public float getSwingProgress(float partialTicktime) { - float flap = swingProgress - prevSwingProgress; - if (flap < 0.0F) { - ++flap; - } - - return prevSwingProgress + flap * partialTicktime; - - } - - @Override - protected float getSoundVolume() { - return 0.1F; - } - - @Override - public ItemStack getPickedResult(MovingObjectPosition target) { - if (species == null) { - return null; - } - IButterflyRoot root = species.getRoot(); - IAllele[] template = root.getTemplate(species.getUID()); - IButterfly butterfly = root.templateAsIndividual(template); - return root.getMemberStack(butterfly, EnumFlutterType.BUTTERFLY.ordinal()); - } + /* CONSTANTS */ + public static final int COOLDOWNS = 1500; + + private static final int DATAWATCHER_ID_SPECIES = 16; + private static final int DATAWATCHER_ID_SIZE = 17; + private static final int DATAWATCHER_ID_STATE = 18; + + private static final float DEFAULT_BUTTERFLY_SIZE = 0.75f; + private static final EnumButterflyState DEFAULT_STATE = EnumButterflyState.FLYING; + + public static final int EXHAUSTION_REST = 1000; + public static final int EXHAUSTION_CONSUMPTION = 100 * EXHAUSTION_REST; + public static final int MAX_LIFESPAN = 24000 * 7; // one minecraft week in ticks + private int maximumHomeDistance = 64; + + private Vec3 flightTarget; + private int exhaustion; + private IButterfly contained; + private IIndividual pollen; + + public int cooldownPollination = 0; + public int cooldownEgg = 0; + + // Client Rendering + private IAlleleButterflySpecies species; + private float size = DEFAULT_BUTTERFLY_SIZE; + private EnumButterflyState state = DEFAULT_STATE; + + /* CONSTRUCTOR */ + public EntityButterfly(World world) { + super(world); + setDefaults(); + } + + public EntityButterfly(World world, IButterfly butterfly, int x, int y, int z) { + super(world); + setDefaults(); + setIndividual(butterfly); + setHomeArea(x, y, z, maximumHomeDistance); + } + + @Override + protected void entityInit() { + super.entityInit(); + + dataWatcher.addObject(DATAWATCHER_ID_SPECIES, ""); + dataWatcher.addObject(DATAWATCHER_ID_SIZE, (int) (DEFAULT_BUTTERFLY_SIZE * 100)); + dataWatcher.addObject(DATAWATCHER_ID_STATE, (byte) DEFAULT_STATE.ordinal()); + } + + private void setDefaults() { + tasks.addTask(8, new AIButterflyFlee(this)); + tasks.addTask(9, new AIButterflyMate(this)); + tasks.addTask(10, new AIButterflyPollinate(this)); + tasks.addTask(11, new AIButterflyRest(this)); + tasks.addTask(12, new AIButterflyRise(this)); + tasks.addTask(12, new AIButterflyWander(this)); + } + + @Override + public EntityCreature getEntity() { + return this; + } + + /* SAVING & LOADING */ + @Override + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + + NBTTagCompound bio = new NBTTagCompound(); + if (contained != null) contained.writeToNBT(bio); + + nbttagcompound.setTag("BTFLY", bio); + + if (pollen != null) { + NBTTagCompound pln = new NBTTagCompound(); + pollen.writeToNBT(pln); + nbttagcompound.setTag("PLN", pln); + } + + nbttagcompound.setByte("STATE", (byte) getState().ordinal()); + nbttagcompound.setInteger("EXH", exhaustion); + } + + @Override + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + + IButterfly butterfly = null; + if (nbttagcompound.hasKey("BTFLY")) { + butterfly = new Butterfly((NBTTagCompound) nbttagcompound.getTag("BTFLY")); + } + setIndividual(butterfly); + + if (nbttagcompound.hasKey("PLN")) { + pollen = TreeManager.treeRoot.getMember((NBTTagCompound) nbttagcompound.getTag("PLN")); + } + + EnumButterflyState state = EnumButterflyState.VALUES[nbttagcompound.getByte("STATE")]; + setState(state); + exhaustion = nbttagcompound.getInteger("EXH"); + } + + public float getWingFlap(float partialTicktime) { + return getState().getWingFlap(this, species.getUID().hashCode(), partialTicktime); + } + + /* STATE - Used for AI and rendering */ + public void setState(EnumButterflyState state) { + if (this.state != state) { + this.state = state; + if (!worldObj.isRemote) { + dataWatcher.updateObject(DATAWATCHER_ID_STATE, (byte) state.ordinal()); + } + } + } + + public EnumButterflyState getState() { + return state; + } + + public float getSize() { + return size; + } + + public float getSpeed() { + return contained.getGenome().getSpeed(); + } + + /* DESTINATION */ + public Vec3 getDestination() { + return flightTarget; + } + + public void setDestination(Vec3 destination) { + flightTarget = destination; + } + + @Override + public float getBlockPathWeight(int x, int y, int z) { + float weight = 0.0f; + final ChunkCoordinates home = getHomePosition(); + double distanceToHome = home.getDistanceSquared(x, y, z); + + if (!isWithinHomeDistanceFromPosition(distanceToHome)) { + + weight -= 7.5f + 0.005 * (distanceToHome / 4); + } + + if (!getButterfly().isAcceptedEnvironment(worldObj, x, y, z)) { + weight -= 15.0f; + } + + if (!worldObj.getEntitiesWithinAABB( + EntityButterfly.class, AxisAlignedBB.getBoundingBox(x, y, z, x + 1, y + 1, z + 1)) + .isEmpty()) { + weight -= 1.0f; + } + + int depth = getFluidDepth(x, z); + if (depth > 0) { + weight -= 0.1f * depth; + } else { + Block block = worldObj.getBlock(x, y, z); + if (block instanceof BlockFlower) { + weight += 2.0f; + } else if (block instanceof IPlantable) { + weight += 1.5f; + } else if (block instanceof IGrowable) { + weight += 1.0f; + } else if (block.getMaterial() == Material.plants) { + weight += 1.0f; + } + + block = worldObj.getBlock(x, y - 1, z); + if (block.isLeaves(worldObj, x, y - 1, z)) { + weight += 2.5f; + } else if (block instanceof BlockFence) { + weight += 1.0f; + } else if (block instanceof BlockWall) { + weight += 1.0f; + } + } + + weight += worldObj.getLightBrightness(x, y, z); + return weight; + } + + private boolean isWithinHomeDistanceFromPosition(double distanceToHome) { + return distanceToHome < (maximumHomeDistance * maximumHomeDistance); + } + + private int getFluidDepth(int x, int z) { + Chunk chunk = worldObj.getChunkFromBlockCoords(x, z); + int xx = x & 15; + int zz = z & 15; + int depth = 0; + for (int y = chunk.getTopFilledSegment() + 15; y > 0; --y) { + Block block = chunk.getBlock(xx, y, zz); + if (block.getMaterial().isLiquid()) { + depth++; + } else if (!block.isAir(worldObj, x, y, z)) { + break; + } + } + + return depth; + } + + /* POLLEN */ + @Override + public IIndividual getPollen() { + return pollen; + } + + @Override + public void setPollen(IIndividual pollen) { + this.pollen = pollen; + } + + public boolean isRenderable() { + return species != null; + } + + /* EXHAUSTION */ + @Override + public void changeExhaustion(int change) { + exhaustion = exhaustion + change > 0 ? exhaustion + change : 0; + } + + @Override + public int getExhaustion() { + return exhaustion; + } + + /* FLYING ABILITY */ + public boolean canFly() { + return contained.canTakeFlight(worldObj, posX, posY, posZ); + } + + public void setIndividual(IButterfly butterfly) { + if (butterfly == null) { + butterfly = ButterflyManager.butterflyRoot.templateAsIndividual( + ButterflyManager.butterflyRoot.getDefaultTemplate()); + } + contained = butterfly; + + IButterflyGenome genome = contained.getGenome(); + + isImmuneToFire = genome.getFireResist(); + size = genome.getSize(); + setSize(size, 0.4f); + species = genome.getPrimary(); + + if (!worldObj.isRemote) { + dataWatcher.updateObject(DATAWATCHER_ID_SIZE, (int) (size * 100)); + dataWatcher.updateObject(DATAWATCHER_ID_SPECIES, species.getUID()); + } else { + textureResource = new ResourceLocation(species.getEntityTexture()); + } + } + + @Override + public IButterfly getButterfly() { + return contained; + } + + @Override + public IEntityLivingData onSpawnWithEgg(IEntityLivingData data) { + if (!worldObj.isRemote) { + setIndividual(contained); + } + return data; + } + + @Override + public String getCommandSenderName() { + if (species == null) { + return super.getCommandSenderName(); + } + return species.getName(); + } + + @Override + public boolean getCanSpawnHere() { + return true; + } + + @Override + public int getMaxInPortalTime() { + return 1000; + } + + @SideOnly(Side.CLIENT) + private ResourceLocation textureResource; + + @SideOnly(Side.CLIENT) + public ResourceLocation getTexture() { + return textureResource; + } + + @Override + public boolean canBePushed() { + return false; + } + + @Override + protected void collideWithEntity(Entity other) {} + + @Override + protected boolean isAIEnabled() { + return true; + } + + @Override + protected boolean canDespawn() { + return ticksExisted > MAX_LIFESPAN; + } + + /* INTERACTION */ + @Override + public boolean interact(EntityPlayer player) { + if (isDead) { + return false; + } + + ItemStack heldItem = player.getHeldItem(); + if (heldItem == null) { + return false; + } + + if (!(heldItem.getItem() instanceof IToolScoop)) { + return false; + } + + if (!worldObj.isRemote) { + IButterflyRoot root = contained.getGenome().getPrimary().getRoot(); + ILepidopteristTracker tracker = root.getBreedingTracker(worldObj, player.getGameProfile()); + ItemStack itemStack = root.getMemberStack(contained.copy(), EnumFlutterType.BUTTERFLY.ordinal()); + + tracker.registerCatch(contained); + ItemStackUtil.dropItemStackAsEntity(itemStack, worldObj, posX, posY, posZ); + setDead(); + } else { + player.swingItem(); + } + return true; + } + + /* LOOT */ + @Override + protected void dropFewItems(boolean playerKill, int lootLevel) { + for (ItemStack stack : contained.getLootDrop(this, playerKill, lootLevel)) { + ItemStackUtil.dropItemStackAsEntity(stack, worldObj, posX, posY, posZ); + } + + // Drop pollen if any + IIndividual pollen = getPollen(); + if (pollen != null) { + ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(pollen.getClass()); + ItemStack pollenStack = root.getMemberStack(pollen, EnumGermlingType.POLLEN.ordinal()); + ItemStackUtil.dropItemStackAsEntity(pollenStack, worldObj, posX, posY, posZ); + } + } + + /* UPDATING */ + @Override + public void onUpdate() { + super.onUpdate(); + + // Update stuff client side + if (worldObj.isRemote) { + if (species == null) { + String speciesUid = dataWatcher.getWatchableObjectString(DATAWATCHER_ID_SPECIES); + IAllele allele = AlleleManager.alleleRegistry.getAllele(speciesUid); + if (allele instanceof IAlleleButterflySpecies) { + species = (IAlleleButterflySpecies) allele; + textureResource = new ResourceLocation(species.getEntityTexture()); + size = dataWatcher.getWatchableObjectInt(DATAWATCHER_ID_SIZE) / 100f; + } + } + + int stateOrdinal = dataWatcher.getWatchableObjectByte(DATAWATCHER_ID_STATE); + if (state == null || state.ordinal() != stateOrdinal) { + setState(EnumButterflyState.VALUES[stateOrdinal]); + } + } + + motionY *= 0.6000000238418579d; + + // Make sure we die if the butterfly hasn't rested in a long, long time. + if (exhaustion > EXHAUSTION_CONSUMPTION && getRNG().nextInt(20) == 0) { + attackEntityFrom(DamageSource.generic, 1); + } + + if (ticksExisted > MAX_LIFESPAN) { + attackEntityFrom(DamageSource.generic, 1); + } + + // Reduce cooldowns + if (cooldownEgg > 0) { + cooldownEgg--; + } + if (cooldownPollination > 0) { + cooldownPollination--; + } + } + + @Override + protected void updateAITasks() { + super.updateAITasks(); + + if (getState().doesMovement && flightTarget != null) { + double diffX = flightTarget.xCoord + 0.5d - posX; + double diffY = flightTarget.yCoord + 0.1d - posY; + double diffZ = flightTarget.zCoord + 0.5d - posZ; + + motionX += (Math.signum(diffX) * 0.5d - motionX) * 0.10000000149011612d; + motionY += (Math.signum(diffY) * 0.699999988079071d - motionY) * 0.10000000149011612d; + motionZ += (Math.signum(diffZ) * 0.5d - motionZ) * 0.10000000149011612d; + + float horizontal = (float) ((Math.atan2(motionZ, motionX) * 180d) / Math.PI) - 90f; + rotationYaw += MathHelper.wrapAngleTo180_float(horizontal - rotationYaw); + + setMoveForward(contained.getGenome().getSpeed()); + } + } + + @Override + protected boolean canTriggerWalking() { + return false; + } + + @Override + protected void fall(float par1) {} + + @Override + protected void updateFallState(double par1, boolean par3) {} + + @Override + public boolean doesEntityNotTriggerPressurePlate() { + return true; + } + + @Override + public float getSwingProgress(float partialTicktime) { + float flap = swingProgress - prevSwingProgress; + if (flap < 0.0F) { + ++flap; + } + + return prevSwingProgress + flap * partialTicktime; + } + + @Override + protected float getSoundVolume() { + return 0.1F; + } + + @Override + public ItemStack getPickedResult(MovingObjectPosition target) { + if (species == null) { + return null; + } + IButterflyRoot root = species.getRoot(); + IAllele[] template = root.getTemplate(species.getUID()); + IButterfly butterfly = root.templateAsIndividual(template); + return root.getMemberStack(butterfly, EnumFlutterType.BUTTERFLY.ordinal()); + } } diff --git a/src/main/java/forestry/lepidopterology/entities/EnumButterflyState.java b/src/main/java/forestry/lepidopterology/entities/EnumButterflyState.java index b5c272954..4765e94c3 100644 --- a/src/main/java/forestry/lepidopterology/entities/EnumButterflyState.java +++ b/src/main/java/forestry/lepidopterology/entities/EnumButterflyState.java @@ -1,38 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.entities; - -import forestry.lepidopterology.render.RenderButterflyItem; - -public enum EnumButterflyState { - - FLYING(true), GLIDING(true), RISING(true), RESTING(false), HOVER(false); - - public static final EnumButterflyState[] VALUES = values(); - - public final boolean doesMovement; - - EnumButterflyState(boolean doesMovement) { - this.doesMovement = doesMovement; - } - - public float getWingFlap(EntityButterfly entity, long offset, float partialTicktime) { - if (this == RESTING || this == HOVER) { - long systemTime = System.currentTimeMillis(); - long flapping = systemTime + offset; - float flap = (float) (flapping % 1000) / 1000; // 0 to 1 - - return RenderButterflyItem.getIrregularWingYaw(flapping, flap); - } else { - return entity.ticksExisted + partialTicktime; - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.entities; + +import forestry.lepidopterology.render.RenderButterflyItem; + +public enum EnumButterflyState { + FLYING(true), + GLIDING(true), + RISING(true), + RESTING(false), + HOVER(false); + + public static final EnumButterflyState[] VALUES = values(); + + public final boolean doesMovement; + + EnumButterflyState(boolean doesMovement) { + this.doesMovement = doesMovement; + } + + public float getWingFlap(EntityButterfly entity, long offset, float partialTicktime) { + if (this == RESTING || this == HOVER) { + long systemTime = System.currentTimeMillis(); + long flapping = systemTime + offset; + float flap = (float) (flapping % 1000) / 1000; // 0 to 1 + + return RenderButterflyItem.getIrregularWingYaw(flapping, flap); + } else { + return entity.ticksExisted + partialTicktime; + } + } +} diff --git a/src/main/java/forestry/lepidopterology/genetics/AlleleButterflyEffect.java b/src/main/java/forestry/lepidopterology/genetics/AlleleButterflyEffect.java index 47f7e5e73..18a78a651 100644 --- a/src/main/java/forestry/lepidopterology/genetics/AlleleButterflyEffect.java +++ b/src/main/java/forestry/lepidopterology/genetics/AlleleButterflyEffect.java @@ -19,30 +19,29 @@ import forestry.core.genetics.alleles.AlleleCategorized; public class AlleleButterflyEffect extends AlleleCategorized implements IAlleleButterflyEffect { - public static IAlleleButterflyEffect butterflyNone; + public static IAlleleButterflyEffect butterflyNone; - public static void createAlleles() { - butterflyNone = new AlleleButterflyEffectNone(); - AlleleManager.alleleRegistry.registerAllele(butterflyNone, EnumButterflyChromosome.EFFECT); - } + public static void createAlleles() { + butterflyNone = new AlleleButterflyEffectNone(); + AlleleManager.alleleRegistry.registerAllele(butterflyNone, EnumButterflyChromosome.EFFECT); + } - protected AlleleButterflyEffect(String valueName, boolean isDominant) { - super("forestry", "bf", valueName, isDominant); - } + protected AlleleButterflyEffect(String valueName, boolean isDominant) { + super("forestry", "bf", valueName, isDominant); + } - @Override - public boolean isCombinable() { - return true; - } + @Override + public boolean isCombinable() { + return true; + } - @Override - public IEffectData validateStorage(IEffectData storedData) { - return null; - } - - @Override - public IEffectData doEffect(IEntityButterfly butterfly, IEffectData storedData) { - return storedData; - } + @Override + public IEffectData validateStorage(IEffectData storedData) { + return null; + } + @Override + public IEffectData doEffect(IEntityButterfly butterfly, IEffectData storedData) { + return storedData; + } } diff --git a/src/main/java/forestry/lepidopterology/genetics/AlleleButterflyEffectNone.java b/src/main/java/forestry/lepidopterology/genetics/AlleleButterflyEffectNone.java index 079f29b60..881412a39 100644 --- a/src/main/java/forestry/lepidopterology/genetics/AlleleButterflyEffectNone.java +++ b/src/main/java/forestry/lepidopterology/genetics/AlleleButterflyEffectNone.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.genetics; - -public class AlleleButterflyEffectNone extends AlleleButterflyEffect { - public AlleleButterflyEffectNone() { - super("none", false); - } - - @Override - public String getUnlocalizedName() { - return "for.lepidopterology.effect.none"; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.genetics; + +public class AlleleButterflyEffectNone extends AlleleButterflyEffect { + public AlleleButterflyEffectNone() { + super("none", false); + } + + @Override + public String getUnlocalizedName() { + return "for.lepidopterology.effect.none"; + } +} diff --git a/src/main/java/forestry/lepidopterology/genetics/AlleleButterflySpecies.java b/src/main/java/forestry/lepidopterology/genetics/AlleleButterflySpecies.java index fd5444778..76d308e8e 100755 --- a/src/main/java/forestry/lepidopterology/genetics/AlleleButterflySpecies.java +++ b/src/main/java/forestry/lepidopterology/genetics/AlleleButterflySpecies.java @@ -10,22 +10,9 @@ ******************************************************************************/ package forestry.lepidopterology.genetics; -import java.awt.Color; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.BiomeDictionary; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.core.IIconProvider; import forestry.api.genetics.IClassification; import forestry.api.genetics.IIndividual; @@ -34,147 +21,164 @@ import forestry.api.lepidopterology.EnumFlutterType; import forestry.api.lepidopterology.IAlleleButterflySpeciesCustom; import forestry.api.lepidopterology.IButterflyRoot; import forestry.core.genetics.alleles.AlleleSpecies; +import java.awt.Color; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraftforge.common.BiomeDictionary; public class AlleleButterflySpecies extends AlleleSpecies implements IAlleleButterflySpeciesCustom { - private final String texture; - private final Color serumColour; - private float rarity = 0.1f; - private float flightDistance = 5.0f; - private boolean isActualNocturnal = false; + private final String texture; + private final Color serumColour; + private float rarity = 0.1f; + private float flightDistance = 5.0f; + private boolean isActualNocturnal = false; - private final EnumSet spawnBiomes = EnumSet.noneOf(BiomeDictionary.Type.class); + private final EnumSet spawnBiomes = EnumSet.noneOf(BiomeDictionary.Type.class); - private final Map butterflyLoot = new HashMap<>(); - private final Map caterpillarLoot = new HashMap<>(); + private final Map butterflyLoot = new HashMap<>(); + private final Map caterpillarLoot = new HashMap<>(); - public AlleleButterflySpecies(String uid, String unlocalizedName, String authority, String unlocalizedDescription, String texturePath, boolean isDominant, IClassification branch, String binomial, Color serumColour) { - super(uid, unlocalizedName, authority, unlocalizedDescription, isDominant, branch, binomial); - this.serumColour = serumColour; - this.texture = texturePath; - } + public AlleleButterflySpecies( + String uid, + String unlocalizedName, + String authority, + String unlocalizedDescription, + String texturePath, + boolean isDominant, + IClassification branch, + String binomial, + Color serumColour) { + super(uid, unlocalizedName, authority, unlocalizedDescription, isDominant, branch, binomial); + this.serumColour = serumColour; + this.texture = texturePath; + } - @Override - public IButterflyRoot getRoot() { - return ButterflyManager.butterflyRoot; - } + @Override + public IButterflyRoot getRoot() { + return ButterflyManager.butterflyRoot; + } - public AlleleButterflySpecies setRarity(float rarity) { - this.rarity = rarity; - return this; - } + public AlleleButterflySpecies setRarity(float rarity) { + this.rarity = rarity; + return this; + } - public AlleleButterflySpecies setFlightDistance(float flightDistance) { - this.flightDistance = flightDistance; - return this; - } + public AlleleButterflySpecies setFlightDistance(float flightDistance) { + this.flightDistance = flightDistance; + return this; + } - public AlleleButterflySpecies setNocturnal() { - this.isActualNocturnal = true; - return this; - } + public AlleleButterflySpecies setNocturnal() { + this.isActualNocturnal = true; + return this; + } - public AlleleButterflySpecies addSpawnBiomes(EnumSet biomeTags) { - spawnBiomes.addAll(biomeTags); - return this; - } + public AlleleButterflySpecies addSpawnBiomes(EnumSet biomeTags) { + spawnBiomes.addAll(biomeTags); + return this; + } - public AlleleButterflySpecies addSpawnBiome(BiomeDictionary.Type biomeTag) { - spawnBiomes.add(biomeTag); - return this; - } + public AlleleButterflySpecies addSpawnBiome(BiomeDictionary.Type biomeTag) { + spawnBiomes.add(biomeTag); + return this; + } - @Override - @SideOnly(Side.CLIENT) - public IIconProvider getIconProvider() { - return null; - } + @Override + @SideOnly(Side.CLIENT) + public IIconProvider getIconProvider() { + return null; + } - @Override - public String getEntityTexture() { - return texture; - } + @Override + public String getEntityTexture() { + return texture; + } - @Override - public EnumSet getSpawnBiomes() { - return spawnBiomes; - } + @Override + public EnumSet getSpawnBiomes() { + return spawnBiomes; + } - @Override - public boolean strictSpawnMatch() { - return false; - } + @Override + public boolean strictSpawnMatch() { + return false; + } - /* RESEARCH */ - @Override - public int getComplexity() { - return (int) ((1.35f / rarity) * 1.5); - } + /* RESEARCH */ + @Override + public int getComplexity() { + return (int) ((1.35f / rarity) * 1.5); + } - @Override - public float getResearchSuitability(ItemStack itemstack) { - if (itemstack == null) { - return 0f; - } + @Override + public float getResearchSuitability(ItemStack itemstack) { + if (itemstack == null) { + return 0f; + } - if (itemstack.getItem() == Items.glass_bottle) { - return 0.9f; - } + if (itemstack.getItem() == Items.glass_bottle) { + return 0.9f; + } - for (ItemStack stack : butterflyLoot.keySet()) { - if (stack.isItemEqual(itemstack)) { - return 1.0f; - } - } - for (ItemStack stack : caterpillarLoot.keySet()) { - if (stack.isItemEqual(itemstack)) { - return 1.0f; - } - } + for (ItemStack stack : butterflyLoot.keySet()) { + if (stack.isItemEqual(itemstack)) { + return 1.0f; + } + } + for (ItemStack stack : caterpillarLoot.keySet()) { + if (stack.isItemEqual(itemstack)) { + return 1.0f; + } + } - return super.getResearchSuitability(itemstack); - } + return super.getResearchSuitability(itemstack); + } - @Override - public ItemStack[] getResearchBounty(World world, GameProfile researcher, IIndividual individual, int bountyLevel) { - return new ItemStack[]{getRoot().getMemberStack(individual.copy(), EnumFlutterType.SERUM.ordinal())}; - } + @Override + public ItemStack[] getResearchBounty(World world, GameProfile researcher, IIndividual individual, int bountyLevel) { + return new ItemStack[] {getRoot().getMemberStack(individual.copy(), EnumFlutterType.SERUM.ordinal())}; + } - /* OTHER */ - @Override - public boolean isSecret() { - return rarity < 0.8f; - } + /* OTHER */ + @Override + public boolean isSecret() { + return rarity < 0.8f; + } - @Override - public float getRarity() { - return rarity; - } + @Override + public float getRarity() { + return rarity; + } - @Override - public float getFlightDistance() { - return flightDistance; - } + @Override + public float getFlightDistance() { + return flightDistance; + } - @Override - public boolean isNocturnal() { - return isActualNocturnal; - } + @Override + public boolean isNocturnal() { + return isActualNocturnal; + } - @Override - public Map getButterflyLoot() { - return butterflyLoot; - } + @Override + public Map getButterflyLoot() { + return butterflyLoot; + } - @Override - public Map getCaterpillarLoot() { - return caterpillarLoot; - } + @Override + public Map getCaterpillarLoot() { + return caterpillarLoot; + } - @Override - public int getIconColour(int renderPass) { - if (renderPass > 0) { - return 0xffffff; - } - return serumColour.getRGB() & 0xffffff; - } + @Override + public int getIconColour(int renderPass) { + if (renderPass > 0) { + return 0xffffff; + } + return serumColour.getRGB() & 0xffffff; + } } diff --git a/src/main/java/forestry/lepidopterology/genetics/BranchButterflies.java b/src/main/java/forestry/lepidopterology/genetics/BranchButterflies.java index 375a01392..891ab1708 100644 --- a/src/main/java/forestry/lepidopterology/genetics/BranchButterflies.java +++ b/src/main/java/forestry/lepidopterology/genetics/BranchButterflies.java @@ -1,21 +1,20 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.genetics; - -import java.util.Locale; - -import forestry.core.genetics.Branch; - -public class BranchButterflies extends Branch { - public BranchButterflies(String scientific) { - super("moth." + scientific.toLowerCase(Locale.ENGLISH), scientific); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.genetics; + +import forestry.core.genetics.Branch; +import java.util.Locale; + +public class BranchButterflies extends Branch { + public BranchButterflies(String scientific) { + super("moth." + scientific.toLowerCase(Locale.ENGLISH), scientific); + } +} diff --git a/src/main/java/forestry/lepidopterology/genetics/Butterfly.java b/src/main/java/forestry/lepidopterology/genetics/Butterfly.java index 555415f7d..d5e9f9071 100755 --- a/src/main/java/forestry/lepidopterology/genetics/Butterfly.java +++ b/src/main/java/forestry/lepidopterology/genetics/Butterfly.java @@ -10,21 +10,6 @@ ******************************************************************************/ package forestry.lepidopterology.genetics; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Random; - -import net.minecraft.entity.EntityCreature; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.world.World; -import net.minecraft.world.biome.BiomeGenBase; - -import net.minecraftforge.common.BiomeDictionary; - import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; import forestry.api.genetics.AlleleManager; @@ -45,268 +30,302 @@ import forestry.core.genetics.Chromosome; import forestry.core.genetics.GenericRatings; import forestry.core.genetics.IndividualLiving; import forestry.core.utils.StringUtil; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Random; +import net.minecraft.entity.EntityCreature; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; +import net.minecraftforge.common.BiomeDictionary; public class Butterfly extends IndividualLiving implements IButterfly { - private static final Random rand = new Random(); + private static final Random rand = new Random(); - private IButterflyGenome genome; - private IButterflyGenome mate; + private IButterflyGenome genome; + private IButterflyGenome mate; - /* CONSTRUCTOR */ - public Butterfly(NBTTagCompound nbttagcompound) { - readFromNBT(nbttagcompound); - } + /* CONSTRUCTOR */ + public Butterfly(NBTTagCompound nbttagcompound) { + readFromNBT(nbttagcompound); + } - public Butterfly(IButterflyGenome genome) { - super(genome.getLifespan()); - this.genome = genome; - } + public Butterfly(IButterflyGenome genome) { + super(genome.getLifespan()); + this.genome = genome; + } - @Override - public void addTooltip(List list) { - IAlleleButterflySpecies primary = genome.getPrimary(); - IAlleleButterflySpecies secondary = genome.getSecondary(); - if (!isPureBred(EnumButterflyChromosome.SPECIES)) { - list.add(EnumChatFormatting.BLUE + StringUtil.localize("butterflies.hybrid").replaceAll("%PRIMARY", primary.getName()).replaceAll("%SECONDARY", secondary.getName())); - } + @Override + public void addTooltip(List list) { + IAlleleButterflySpecies primary = genome.getPrimary(); + IAlleleButterflySpecies secondary = genome.getSecondary(); + if (!isPureBred(EnumButterflyChromosome.SPECIES)) { + list.add(EnumChatFormatting.BLUE + + StringUtil.localize("butterflies.hybrid") + .replaceAll("%PRIMARY", primary.getName()) + .replaceAll("%SECONDARY", secondary.getName())); + } - if (getMate() != null) { - list.add(EnumChatFormatting.RED + StringUtil.localize("gui.fecundated").toUpperCase(Locale.ENGLISH)); - } - list.add(EnumChatFormatting.YELLOW + genome.getActiveAllele(EnumButterflyChromosome.SIZE).getName()); - list.add(EnumChatFormatting.DARK_GREEN + genome.getActiveAllele(EnumButterflyChromosome.SPEED).getName()); - list.add(genome.getActiveAllele(EnumButterflyChromosome.LIFESPAN).getName() + ' ' + StringUtil.localize("gui.life")); + if (getMate() != null) { + list.add(EnumChatFormatting.RED + + StringUtil.localize("gui.fecundated").toUpperCase(Locale.ENGLISH)); + } + list.add(EnumChatFormatting.YELLOW + + genome.getActiveAllele(EnumButterflyChromosome.SIZE).getName()); + list.add(EnumChatFormatting.DARK_GREEN + + genome.getActiveAllele(EnumButterflyChromosome.SPEED).getName()); + list.add(genome.getActiveAllele(EnumButterflyChromosome.LIFESPAN).getName() + + ' ' + + StringUtil.localize("gui.life")); - IAlleleTolerance tempTolerance = (IAlleleTolerance) getGenome().getActiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE); - list.add(EnumChatFormatting.GREEN + "T: " + AlleleManager.climateHelper.toDisplay(genome.getPrimary().getTemperature()) + " / " + tempTolerance.getName()); + IAlleleTolerance tempTolerance = + (IAlleleTolerance) getGenome().getActiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE); + list.add(EnumChatFormatting.GREEN + "T: " + + AlleleManager.climateHelper.toDisplay(genome.getPrimary().getTemperature()) + " / " + + tempTolerance.getName()); - IAlleleTolerance humidTolerance = (IAlleleTolerance) getGenome().getActiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE); - list.add(EnumChatFormatting.GREEN + "H: " + AlleleManager.climateHelper.toDisplay(genome.getPrimary().getHumidity()) + " / " + humidTolerance.getName()); + IAlleleTolerance humidTolerance = + (IAlleleTolerance) getGenome().getActiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE); + list.add(EnumChatFormatting.GREEN + "H: " + + AlleleManager.climateHelper.toDisplay(genome.getPrimary().getHumidity()) + " / " + + humidTolerance.getName()); - list.add(EnumChatFormatting.RED + GenericRatings.rateActivityTime(genome.getNocturnal(), genome.getPrimary().isNocturnal())); + list.add(EnumChatFormatting.RED + + GenericRatings.rateActivityTime( + genome.getNocturnal(), genome.getPrimary().isNocturnal())); - if (genome.getTolerantFlyer()) { - list.add(EnumChatFormatting.WHITE + StringUtil.localize("gui.flyer.tooltip")); - } - } + if (genome.getTolerantFlyer()) { + list.add(EnumChatFormatting.WHITE + StringUtil.localize("gui.flyer.tooltip")); + } + } - /* SAVING & LOADING */ - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { + /* SAVING & LOADING */ + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { - if (nbttagcompound == null) { - this.genome = ButterflyManager.butterflyRoot.templateAsGenome(ButterflyManager.butterflyRoot.getDefaultTemplate()); - return; - } + if (nbttagcompound == null) { + this.genome = ButterflyManager.butterflyRoot.templateAsGenome( + ButterflyManager.butterflyRoot.getDefaultTemplate()); + return; + } - super.readFromNBT(nbttagcompound); + super.readFromNBT(nbttagcompound); - if (nbttagcompound.hasKey("Genome")) { - genome = new ButterflyGenome(nbttagcompound.getCompoundTag("Genome")); - } else { - genome = ButterflyManager.butterflyRoot.templateAsGenome(ButterflyManager.butterflyRoot.getDefaultTemplate()); - } - if (nbttagcompound.hasKey("Mate")) { - mate = new ButterflyGenome(nbttagcompound.getCompoundTag("Mate")); - } + if (nbttagcompound.hasKey("Genome")) { + genome = new ButterflyGenome(nbttagcompound.getCompoundTag("Genome")); + } else { + genome = ButterflyManager.butterflyRoot.templateAsGenome( + ButterflyManager.butterflyRoot.getDefaultTemplate()); + } + if (nbttagcompound.hasKey("Mate")) { + mate = new ButterflyGenome(nbttagcompound.getCompoundTag("Mate")); + } + } - } + @Override + public IButterfly copy() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + this.writeToNBT(nbttagcompound); + return new Butterfly(nbttagcompound); + } + @Override + public IButterflyGenome getGenome() { + return genome; + } - @Override - public IButterfly copy() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - this.writeToNBT(nbttagcompound); - return new Butterfly(nbttagcompound); - } + @Override + public IButterflyGenome getMate() { + return mate; + } - @Override - public IButterflyGenome getGenome() { - return genome; - } + @Override + public boolean canSpawn(World world, double x, double y, double z) { + if (!canFly(world)) { + return false; + } - @Override - public IButterflyGenome getMate() { - return mate; - } + BiomeGenBase biome = world.getBiomeGenForCoordsBody((int) x, (int) z); + if (getGenome().getPrimary().getSpawnBiomes().size() > 0) { + boolean noneMatched = true; - @Override - public boolean canSpawn(World world, double x, double y, double z) { - if (!canFly(world)) { - return false; - } + if (getGenome().getPrimary().strictSpawnMatch()) { + BiomeDictionary.Type[] types = BiomeDictionary.getTypesForBiome(biome); + if (types.length == 1 + && getGenome().getPrimary().getSpawnBiomes().contains(types[0])) { + noneMatched = false; + } + } else { + for (BiomeDictionary.Type type : getGenome().getPrimary().getSpawnBiomes()) { + if (BiomeDictionary.isBiomeOfType(biome, type)) { + noneMatched = false; + break; + } + } + } - BiomeGenBase biome = world.getBiomeGenForCoordsBody((int) x, (int) z); - if (getGenome().getPrimary().getSpawnBiomes().size() > 0) { - boolean noneMatched = true; + if (noneMatched) { + return false; + } + } - if (getGenome().getPrimary().strictSpawnMatch()) { - BiomeDictionary.Type[] types = BiomeDictionary.getTypesForBiome(biome); - if (types.length == 1 && getGenome().getPrimary().getSpawnBiomes().contains(types[0])) { - noneMatched = false; - } - } else { - for (BiomeDictionary.Type type : getGenome().getPrimary().getSpawnBiomes()) { - if (BiomeDictionary.isBiomeOfType(biome, type)) { - noneMatched = false; - break; - } - } - } + return isAcceptedEnvironment(world, x, y, z); + } - if (noneMatched) { - return false; - } - } + @Override + public boolean canTakeFlight(World world, double x, double y, double z) { + if (!canFly(world)) { + return false; + } + return isAcceptedEnvironment(world, x, y, z); + } - return isAcceptedEnvironment(world, x, y, z); - } + private boolean canFly(World world) { + if (world.isRaining() && !getGenome().getTolerantFlyer()) { + return false; + } + return isActiveThisTime(world.isDaytime()); + } - @Override - public boolean canTakeFlight(World world, double x, double y, double z) { - if (!canFly(world)) { - return false; - } - return isAcceptedEnvironment(world, x, y, z); - } + @Override + public boolean isAcceptedEnvironment(World world, double x, double y, double z) { + return isAcceptedEnvironment(world, (int) x, (int) y, (int) z); + } - private boolean canFly(World world) { - if (world.isRaining() && !getGenome().getTolerantFlyer()) { - return false; - } - return isActiveThisTime(world.isDaytime()); - } + private boolean isAcceptedEnvironment(World world, int x, int y, int z) { + BiomeGenBase biome = world.getBiomeGenForCoords(x, z); + EnumTemperature biomeTemperature = EnumTemperature.getFromBiome(biome, x, y, z); + EnumHumidity biomeHumidity = EnumHumidity.getFromValue(biome.rainfall); + return AlleleManager.climateHelper.isWithinLimits( + biomeTemperature, + biomeHumidity, + getGenome().getPrimary().getTemperature(), + getGenome().getToleranceTemp(), + getGenome().getPrimary().getHumidity(), + getGenome().getToleranceHumid()); + } - @Override - public boolean isAcceptedEnvironment(World world, double x, double y, double z) { - return isAcceptedEnvironment(world, (int) x, (int) y, (int) z); - } + @Override + public IButterfly spawnCaterpillar(IButterflyNursery nursery) { + // We need a mated queen to produce offspring. + if (mate == null) { + return null; + } - private boolean isAcceptedEnvironment(World world, int x, int y, int z) { - BiomeGenBase biome = world.getBiomeGenForCoords(x, z); - EnumTemperature biomeTemperature = EnumTemperature.getFromBiome(biome, x, y, z); - EnumHumidity biomeHumidity = EnumHumidity.getFromValue(biome.rainfall); - return AlleleManager.climateHelper.isWithinLimits(biomeTemperature, biomeHumidity, - getGenome().getPrimary().getTemperature(), getGenome().getToleranceTemp(), - getGenome().getPrimary().getHumidity(), getGenome().getToleranceHumid()); - } + IChromosome[] chromosomes = new IChromosome[genome.getChromosomes().length]; + IChromosome[] parent1 = genome.getChromosomes(); + IChromosome[] parent2 = mate.getChromosomes(); - @Override - public IButterfly spawnCaterpillar(IButterflyNursery nursery) { - // We need a mated queen to produce offspring. - if (mate == null) { - return null; - } + // Check for mutation. Replace one of the parents with the mutation + // template if mutation occured. + IChromosome[] mutated1 = mutateSpecies(nursery, genome, mate); + if (mutated1 != null) { + parent1 = mutated1; + } + IChromosome[] mutated2 = mutateSpecies(nursery, mate, genome); + if (mutated2 != null) { + parent2 = mutated2; + } - IChromosome[] chromosomes = new IChromosome[genome.getChromosomes().length]; - IChromosome[] parent1 = genome.getChromosomes(); - IChromosome[] parent2 = mate.getChromosomes(); + for (int i = 0; i < parent1.length; i++) { + if (parent1[i] != null && parent2[i] != null) { + chromosomes[i] = Chromosome.inheritChromosome(rand, parent1[i], parent2[i]); + } + } - // Check for mutation. Replace one of the parents with the mutation - // template if mutation occured. - IChromosome[] mutated1 = mutateSpecies(nursery, genome, mate); - if (mutated1 != null) { - parent1 = mutated1; - } - IChromosome[] mutated2 = mutateSpecies(nursery, mate, genome); - if (mutated2 != null) { - parent2 = mutated2; - } + return new Butterfly(new ButterflyGenome(chromosomes)); + } - for (int i = 0; i < parent1.length; i++) { - if (parent1[i] != null && parent2[i] != null) { - chromosomes[i] = Chromosome.inheritChromosome(rand, parent1[i], parent2[i]); - } - } + private static IChromosome[] mutateSpecies(IButterflyNursery nursery, IGenome genomeOne, IGenome genomeTwo) { - return new Butterfly(new ButterflyGenome(chromosomes)); - } + IChromosome[] parent1 = genomeOne.getChromosomes(); + IChromosome[] parent2 = genomeTwo.getChromosomes(); - private static IChromosome[] mutateSpecies(IButterflyNursery nursery, IGenome genomeOne, IGenome genomeTwo) { + IGenome genome0; + IGenome genome1; + IAllele allele0; + IAllele allele1; - IChromosome[] parent1 = genomeOne.getChromosomes(); - IChromosome[] parent2 = genomeTwo.getChromosomes(); + if (rand.nextBoolean()) { + allele0 = parent1[EnumButterflyChromosome.SPECIES.ordinal()].getPrimaryAllele(); + allele1 = parent2[EnumButterflyChromosome.SPECIES.ordinal()].getSecondaryAllele(); - IGenome genome0; - IGenome genome1; - IAllele allele0; - IAllele allele1; + genome0 = genomeOne; + genome1 = genomeTwo; + } else { + allele0 = parent2[EnumButterflyChromosome.SPECIES.ordinal()].getPrimaryAllele(); + allele1 = parent1[EnumButterflyChromosome.SPECIES.ordinal()].getSecondaryAllele(); - if (rand.nextBoolean()) { - allele0 = parent1[EnumButterflyChromosome.SPECIES.ordinal()].getPrimaryAllele(); - allele1 = parent2[EnumButterflyChromosome.SPECIES.ordinal()].getSecondaryAllele(); + genome0 = genomeTwo; + genome1 = genomeOne; + } - genome0 = genomeOne; - genome1 = genomeTwo; - } else { - allele0 = parent2[EnumButterflyChromosome.SPECIES.ordinal()].getPrimaryAllele(); - allele1 = parent1[EnumButterflyChromosome.SPECIES.ordinal()].getSecondaryAllele(); + for (IButterflyMutation mutation : ButterflyManager.butterflyRoot.getMutations(true)) { + float chance = mutation.getChance(nursery, allele0, allele1, genome0, genome1); + if (chance > rand.nextFloat() * 100) { + return ButterflyManager.butterflyRoot.templateAsChromosomes(mutation.getTemplate()); + } + } - genome0 = genomeTwo; - genome1 = genomeOne; - } + return null; + } - for (IButterflyMutation mutation : ButterflyManager.butterflyRoot.getMutations(true)) { - float chance = mutation.getChance(nursery, allele0, allele1, genome0, genome1); - if (chance > rand.nextFloat() * 100) { - return ButterflyManager.butterflyRoot.templateAsChromosomes(mutation.getTemplate()); - } - } + private boolean isActiveThisTime(boolean isDayTime) { + if (getGenome().getNocturnal()) { + return true; + } - return null; - } + return isDayTime != getGenome().getPrimary().isNocturnal(); + } - private boolean isActiveThisTime(boolean isDayTime) { - if (getGenome().getNocturnal()) { - return true; - } + @Override + public float getSize() { + return getGenome().getSize(); + } - return isDayTime != getGenome().getPrimary().isNocturnal(); - } + @Override + public void mate(IIndividual individual) { + if (!(individual instanceof IButterfly)) { + return; + } - @Override - public float getSize() { - return getGenome().getSize(); - } + mate = ((IButterfly) individual).getGenome(); + } - @Override - public void mate(IIndividual individual) { - if (!(individual instanceof IButterfly)) { - return; - } + @Override + public ItemStack[] getLootDrop(IEntityButterfly entity, boolean playerKill, int lootLevel) { + ArrayList drop = new ArrayList<>(); - mate = ((IButterfly) individual).getGenome(); - } + EntityCreature creature = entity.getEntity(); + float metabolism = (float) getGenome().getMetabolism() / 10; - @Override - public ItemStack[] getLootDrop(IEntityButterfly entity, boolean playerKill, int lootLevel) { - ArrayList drop = new ArrayList<>(); + for (Map.Entry entry : + getGenome().getPrimary().getButterflyLoot().entrySet()) { + if (creature.worldObj.rand.nextFloat() < entry.getValue() * metabolism) { + drop.add(entry.getKey().copy()); + } + } - EntityCreature creature = entity.getEntity(); - float metabolism = (float) getGenome().getMetabolism() / 10; + return drop.toArray(new ItemStack[drop.size()]); + } - for (Map.Entry entry : getGenome().getPrimary().getButterflyLoot().entrySet()) { - if (creature.worldObj.rand.nextFloat() < entry.getValue() * metabolism) { - drop.add(entry.getKey().copy()); - } - } + @Override + public ItemStack[] getCaterpillarDrop(IButterflyNursery nursery, boolean playerKill, int lootLevel) { + ArrayList drop = new ArrayList<>(); + float metabolism = (float) getGenome().getMetabolism() / 10; - return drop.toArray(new ItemStack[drop.size()]); - } - - @Override - public ItemStack[] getCaterpillarDrop(IButterflyNursery nursery, boolean playerKill, int lootLevel) { - ArrayList drop = new ArrayList<>(); - float metabolism = (float) getGenome().getMetabolism() / 10; - - for (Map.Entry entry : getGenome().getPrimary().getCaterpillarLoot().entrySet()) { - if (rand.nextFloat() < entry.getValue() * metabolism) { - drop.add(entry.getKey().copy()); - } - } - - return drop.toArray(new ItemStack[drop.size()]); - } + for (Map.Entry entry : + getGenome().getPrimary().getCaterpillarLoot().entrySet()) { + if (rand.nextFloat() < entry.getValue() * metabolism) { + drop.add(entry.getKey().copy()); + } + } + return drop.toArray(new ItemStack[drop.size()]); + } } diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyBranchDefinition.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyBranchDefinition.java index aa596b25c..6d1db82bf 100644 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyBranchDefinition.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyBranchDefinition.java @@ -1,128 +1,145 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.genetics; - -import java.util.Arrays; - -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IAlleleRegistry; -import forestry.api.genetics.IClassification; -import forestry.api.lepidopterology.EnumButterflyChromosome; -import forestry.core.genetics.IBranchDefinition; -import forestry.core.genetics.alleles.AlleleHelper; -import forestry.core.genetics.alleles.EnumAllele; - -public enum ButterflyBranchDefinition implements IBranchDefinition { - Anthocharis, - Attacus, - Bassarona, - Batesia, - Celastrina, - Cethosia, - Chiasmia, - Colias, - Danaus, - Gonepteryx, - Greta, - Heliconius, - Morpho, - Myscelia, - Opisthograptis, - Papilio, - Parantica, - Pararge, - Pieris, - Polygonia, - Pontia, - Protographium, - Siproeta, - Speyeria; - - private static IAllele[] defaultTemplate; - - private final IClassification branch; - - ButterflyBranchDefinition() { - branch = new BranchButterflies(name()); - } - - @Override - public IAllele[] getTemplate() { - if (defaultTemplate == null) { - defaultTemplate = new IAllele[EnumButterflyChromosome.values().length]; - - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALL); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWEST); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.METABOLISM, 3); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.FERTILITY, 3); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.NONE); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.NONE); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.NOCTURNAL, false); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.TOLERANT_FLYER, false); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.FIRE_RESIST, false); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.VANILLA); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.EFFECT, AlleleButterflyEffect.butterflyNone); - } - return Arrays.copyOf(defaultTemplate, defaultTemplate.length); - } - - @Override - public IClassification getBranch() { - return branch; - } - - public static void createAlleles() { - IAlleleRegistry alleleRegistry = AlleleManager.alleleRegistry; - - alleleRegistry.getClassification("class.insecta").addMemberGroup( - alleleRegistry.createAndRegisterClassification(IClassification.EnumClassLevel.ORDER, "lepidoptera", "Lepidoptera", - alleleRegistry.createAndRegisterClassification(IClassification.EnumClassLevel.FAMILY, "geometridae", "Geometridae", - Opisthograptis.getBranch(), - Chiasmia.getBranch() - ), - alleleRegistry.createAndRegisterClassification(IClassification.EnumClassLevel.FAMILY, "saturniidae", "Saturniidae", - Attacus.getBranch() - ), - alleleRegistry.createAndRegisterClassification(IClassification.EnumClassLevel.FAMILY, "pieridae", "Pieridae", - Pieris.getBranch(), - Gonepteryx.getBranch(), - Anthocharis.getBranch(), - Colias.getBranch(), - Pontia.getBranch(), - Celastrina.getBranch() - ), - alleleRegistry.createAndRegisterClassification(IClassification.EnumClassLevel.FAMILY, "nymphalidae", "Nymphalidae", - Pararge.getBranch(), - Polygonia.getBranch(), - Morpho.getBranch(), - Greta.getBranch(), - Batesia.getBranch(), - Myscelia.getBranch(), - Danaus.getBranch(), - Bassarona.getBranch(), - Parantica.getBranch(), - Heliconius.getBranch(), - Siproeta.getBranch(), - Cethosia.getBranch(), - Speyeria.getBranch() - ), - alleleRegistry.createAndRegisterClassification(IClassification.EnumClassLevel.FAMILY, "lycaenidae", "Lycaenidae"), - alleleRegistry.createAndRegisterClassification(IClassification.EnumClassLevel.FAMILY, "papilionidae", "Papilionidae", - Papilio.getBranch(), - Protographium.getBranch() - ), - alleleRegistry.createAndRegisterClassification(IClassification.EnumClassLevel.FAMILY, "notchidae", "Notchidae") - ) - ); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.genetics; + +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IAlleleRegistry; +import forestry.api.genetics.IClassification; +import forestry.api.lepidopterology.EnumButterflyChromosome; +import forestry.core.genetics.IBranchDefinition; +import forestry.core.genetics.alleles.AlleleHelper; +import forestry.core.genetics.alleles.EnumAllele; +import java.util.Arrays; + +public enum ButterflyBranchDefinition implements IBranchDefinition { + Anthocharis, + Attacus, + Bassarona, + Batesia, + Celastrina, + Cethosia, + Chiasmia, + Colias, + Danaus, + Gonepteryx, + Greta, + Heliconius, + Morpho, + Myscelia, + Opisthograptis, + Papilio, + Parantica, + Pararge, + Pieris, + Polygonia, + Pontia, + Protographium, + Siproeta, + Speyeria; + + private static IAllele[] defaultTemplate; + + private final IClassification branch; + + ButterflyBranchDefinition() { + branch = new BranchButterflies(name()); + } + + @Override + public IAllele[] getTemplate() { + if (defaultTemplate == null) { + defaultTemplate = new IAllele[EnumButterflyChromosome.values().length]; + + AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALL); + AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWEST); + AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); + AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.METABOLISM, 3); + AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.FERTILITY, 3); + AlleleHelper.instance.set( + defaultTemplate, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.NONE); + AlleleHelper.instance.set( + defaultTemplate, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.NONE); + AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.NOCTURNAL, false); + AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.TOLERANT_FLYER, false); + AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.FIRE_RESIST, false); + AlleleHelper.instance.set( + defaultTemplate, EnumButterflyChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.VANILLA); + AlleleHelper.instance.set( + defaultTemplate, EnumButterflyChromosome.EFFECT, AlleleButterflyEffect.butterflyNone); + } + return Arrays.copyOf(defaultTemplate, defaultTemplate.length); + } + + @Override + public IClassification getBranch() { + return branch; + } + + public static void createAlleles() { + IAlleleRegistry alleleRegistry = AlleleManager.alleleRegistry; + + alleleRegistry + .getClassification("class.insecta") + .addMemberGroup(alleleRegistry.createAndRegisterClassification( + IClassification.EnumClassLevel.ORDER, + "lepidoptera", + "Lepidoptera", + alleleRegistry.createAndRegisterClassification( + IClassification.EnumClassLevel.FAMILY, + "geometridae", + "Geometridae", + Opisthograptis.getBranch(), + Chiasmia.getBranch()), + alleleRegistry.createAndRegisterClassification( + IClassification.EnumClassLevel.FAMILY, + "saturniidae", + "Saturniidae", + Attacus.getBranch()), + alleleRegistry.createAndRegisterClassification( + IClassification.EnumClassLevel.FAMILY, + "pieridae", + "Pieridae", + Pieris.getBranch(), + Gonepteryx.getBranch(), + Anthocharis.getBranch(), + Colias.getBranch(), + Pontia.getBranch(), + Celastrina.getBranch()), + alleleRegistry.createAndRegisterClassification( + IClassification.EnumClassLevel.FAMILY, + "nymphalidae", + "Nymphalidae", + Pararge.getBranch(), + Polygonia.getBranch(), + Morpho.getBranch(), + Greta.getBranch(), + Batesia.getBranch(), + Myscelia.getBranch(), + Danaus.getBranch(), + Bassarona.getBranch(), + Parantica.getBranch(), + Heliconius.getBranch(), + Siproeta.getBranch(), + Cethosia.getBranch(), + Speyeria.getBranch()), + alleleRegistry.createAndRegisterClassification( + IClassification.EnumClassLevel.FAMILY, "lycaenidae", "Lycaenidae"), + alleleRegistry.createAndRegisterClassification( + IClassification.EnumClassLevel.FAMILY, + "papilionidae", + "Papilionidae", + Papilio.getBranch(), + Protographium.getBranch()), + alleleRegistry.createAndRegisterClassification( + IClassification.EnumClassLevel.FAMILY, "notchidae", "Notchidae"))); + } +} diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyDefinition.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyDefinition.java index 4192987bf..64d2ff90e 100644 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyDefinition.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyDefinition.java @@ -1,367 +1,378 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.genetics; - -import java.awt.Color; -import java.util.Arrays; -import java.util.Locale; - -import net.minecraft.item.ItemStack; - -import forestry.api.core.EnumHumidity; -import forestry.api.core.EnumTemperature; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IClassification; -import forestry.api.lepidopterology.ButterflyManager; -import forestry.api.lepidopterology.EnumButterflyChromosome; -import forestry.api.lepidopterology.EnumFlutterType; -import forestry.api.lepidopterology.IAlleleButterflySpeciesCustom; -import forestry.api.lepidopterology.IButterfly; -import forestry.api.lepidopterology.IButterflyGenome; -import forestry.core.config.Constants; -import forestry.core.genetics.alleles.AlleleHelper; -import forestry.core.genetics.alleles.EnumAllele; - -public enum ButterflyDefinition implements IButterflyDefinition { - CabbageWhite(ButterflyBranchDefinition.Pieris, "cabbageWhite", "rapae", new Color(0xccffee), true, 1.0f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); - } - }, - Brimstone(ButterflyBranchDefinition.Gonepteryx, "brimstone", "rhamni", new Color(0xf0ee38), true, 1.0f), - Aurora(ButterflyBranchDefinition.Anthocharis, "orangeTip", "cardamines", new Color(0xe34f05), true, 0.5f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); - } - }, - Postillion(ButterflyBranchDefinition.Colias, "postillion", "croceus", new Color(0xd77e04), true, 0.5f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOW); - } - }, - PalaenoSulphur(ButterflyBranchDefinition.Colias, "palaenoSulphur", "palaeno", new Color(0xf8fba3), true, 0.4f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); - } - }, - Reseda(ButterflyBranchDefinition.Pontia, "reseda", "edusa", new Color(0x747d48), true, 0.3f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); - } - }, - SpringAzure(ButterflyBranchDefinition.Celastrina, "springAzure", "argiolus", new Color(0xb8cae2), true, 0.3f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - } - }, - GozoraAzure(ButterflyBranchDefinition.Celastrina, "gozoraAzure", "gozora", new Color(0x6870e7), true, 0.2f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - } - }, - CitrusSwallow(ButterflyBranchDefinition.Papilio, "swallowtailC", "demodocus", new Color(0xeae389), false, 1.0f) { - @Override - protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { - species.setTemperature(EnumTemperature.WARM) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 10); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.METABOLISM, 8); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - } - }, - EmeraldPeacock(ButterflyBranchDefinition.Papilio, "emeraldPeacock", "palinurus", new Color(0x7cfe80), true, 0.1f) { - @Override - protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { - species.setTemperature(EnumTemperature.WARM) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 5); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - } - }, - ThoasSwallow(ButterflyBranchDefinition.Papilio, "swallowtailT", "thoas", new Color(0xeac783), false, 0.2f) { - @Override - protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { - species.setTemperature(EnumTemperature.WARM) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); - } - }, - Spicebush(ButterflyBranchDefinition.Papilio, "swallowtailS", "troilus", new Color(0xeefeff), true, 0.5f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); - } - }, - BlackSwallow(ButterflyBranchDefinition.Papilio, "swallowtailB", "polyxenes", new Color(0xeac783), true, 1.0f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOW); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - } - }, - ZebraSwallow(ButterflyBranchDefinition.Protographium, "swallowtailZ", "marcellus", new Color(0xeafeff), true, 0.5f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); - } - }, - Glasswing(ButterflyBranchDefinition.Greta, "glasswing", "oto", new Color(0x583732), true, 0.1f) { - @Override - protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { - species.setTemperature(EnumTemperature.WARM); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 5); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - } - }, - SpeckledWood(ButterflyBranchDefinition.Pararge, "speckledWood", "aegeria", new Color(0x947245), true, 1.0f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); - } - }, - MSpeckledWood(ButterflyBranchDefinition.Pararge, "speckledWoodM", "xiphia", new Color(0x402919), true, 0.5f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); - } - }, - CSpeckledWood(ButterflyBranchDefinition.Pararge, "speckledWoodC", "xiphioides", new Color(0x51372a), true, 0.5f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); - } - }, - MBlueMorpho(ButterflyBranchDefinition.Morpho, "blueMorphoM", "menelaus", new Color(0x72e1fd), true, 0.5f) { - @Override - protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { - species.setTemperature(EnumTemperature.WARM) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); - } - }, - PBlueMorpho(ButterflyBranchDefinition.Morpho, "blueMorphoP", "peleides", new Color(0x6ecce8), true, 0.25f) { - @Override - protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { - species.setTemperature(EnumTemperature.WARM) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); - } - }, - RBlueMorpho(ButterflyBranchDefinition.Morpho, "blueMorphoR", "rhetenor", new Color(0x00bef8), true, 0.1f) { - @Override - protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { - species.setTemperature(EnumTemperature.WARM) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); - } - }, - Comma(ButterflyBranchDefinition.Polygonia, "comma", "c-album", new Color(0xf89505), true, 0.3f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); - } - }, - Batesia(ButterflyBranchDefinition.Batesia, "paintedBeauty", "hypochlora", new Color(0xfe7763), true, 0.3f) { - @Override - protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { - species.setTemperature(EnumTemperature.WARM) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); - } - }, - BlueWing(ButterflyBranchDefinition.Myscelia, "blueWing", "ethusa", new Color(0x3a93cc), true, 0.3f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.METABOLISM, 5); - } - }, - Monarch(ButterflyBranchDefinition.Danaus, "monarch", "plexippus", new Color(0xffa722), true, 0.2f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); - } - }, - BlueDuke(ButterflyBranchDefinition.Bassarona, "blueDuke", "durga", new Color(0x304240), true, 0.5f) { - @Override - protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { - species.setTemperature(EnumTemperature.COLD); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); - } - }, - GlassyTiger(ButterflyBranchDefinition.Parantica, "glassyTiger", "aglea", new Color(0x5b3935), true, 0.3f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); - } - }, - Postman(ButterflyBranchDefinition.Heliconius, "postman", "melpomene", new Color(0xf7302d), true, 0.3f), - Malachite(ButterflyBranchDefinition.Siproeta, "malachite", "stelenes", new Color(0xbdff53), true, 0.5f) { - @Override - protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { - species.setTemperature(EnumTemperature.WARM) - .setHumidity(EnumHumidity.DAMP); - } - - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - } - }, - LLacewing(ButterflyBranchDefinition.Cethosia, "leopardLacewing", "cyane", new Color(0xfb8a06), true, 0.7f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.UP_1); - } - }, - DianaFrit(ButterflyBranchDefinition.Speyeria, "dianaFritillary", "diana", new Color(0xffac05), true, 0.6f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); - } - }; - - private final IAlleleButterflySpeciesCustom species; - private final ButterflyBranchDefinition branch; - private IAllele[] template; - private IButterflyGenome genome; - - ButterflyDefinition(ButterflyBranchDefinition branchDefinition, String speciesName, String binomial, Color serumColor, boolean dominant, float rarity) { - this.branch = branchDefinition; - - String uid = "lepi" + name(); - IClassification parent = branch.getBranch().getParent(); - String unlocalizedName = "for.butterflies.species." + parent.getUID().substring((parent.getLevel().name().toLowerCase(Locale.ENGLISH)).length() + 1) + '.' + speciesName; - String unlocalizedDescription = "for.description." + uid; - - String texture = "forestry:" + Constants.TEXTURE_PATH_ENTITIES + "/butterflies/" + uid + ".png"; - - species = ButterflyManager.butterflyFactory.createSpecies("forestry." + uid, unlocalizedName, "Sengir", unlocalizedDescription, texture, dominant, branchDefinition.getBranch(), binomial, serumColor); - species.setRarity(rarity); - } - - public static void initButterflies() { - for (ButterflyDefinition butterfly : values()) { - butterfly.init(); - } - } - - private void init() { - setSpeciesProperties(species); - - template = branch.getTemplate(); - AlleleHelper.instance.set(template, EnumButterflyChromosome.SPECIES, species); - setAlleles(template); - - genome = ButterflyManager.butterflyRoot.templateAsGenome(template); - - ButterflyManager.butterflyRoot.registerTemplate(template); - } - - protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { - - } - - protected void setAlleles(IAllele[] alleles) { - - } - - @Override - public final IAllele[] getTemplate() { - return Arrays.copyOf(template, template.length); - } - - @Override - public final IButterflyGenome getGenome() { - return genome; - } - - @Override - public final IButterfly getIndividual() { - return new Butterfly(genome); - } - - @Override - public final ItemStack getMemberStack(EnumFlutterType flutterType) { - IButterfly butterfly = getIndividual(); - return ButterflyManager.butterflyRoot.getMemberStack(butterfly, flutterType.ordinal()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.genetics; + +import forestry.api.core.EnumHumidity; +import forestry.api.core.EnumTemperature; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IClassification; +import forestry.api.lepidopterology.ButterflyManager; +import forestry.api.lepidopterology.EnumButterflyChromosome; +import forestry.api.lepidopterology.EnumFlutterType; +import forestry.api.lepidopterology.IAlleleButterflySpeciesCustom; +import forestry.api.lepidopterology.IButterfly; +import forestry.api.lepidopterology.IButterflyGenome; +import forestry.core.config.Constants; +import forestry.core.genetics.alleles.AlleleHelper; +import forestry.core.genetics.alleles.EnumAllele; +import java.awt.Color; +import java.util.Arrays; +import java.util.Locale; +import net.minecraft.item.ItemStack; + +public enum ButterflyDefinition implements IButterflyDefinition { + CabbageWhite(ButterflyBranchDefinition.Pieris, "cabbageWhite", "rapae", new Color(0xccffee), true, 1.0f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + } + }, + Brimstone(ButterflyBranchDefinition.Gonepteryx, "brimstone", "rhamni", new Color(0xf0ee38), true, 1.0f), + Aurora(ButterflyBranchDefinition.Anthocharis, "orangeTip", "cardamines", new Color(0xe34f05), true, 0.5f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); + } + }, + Postillion(ButterflyBranchDefinition.Colias, "postillion", "croceus", new Color(0xd77e04), true, 0.5f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOW); + } + }, + PalaenoSulphur(ButterflyBranchDefinition.Colias, "palaenoSulphur", "palaeno", new Color(0xf8fba3), true, 0.4f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + } + }, + Reseda(ButterflyBranchDefinition.Pontia, "reseda", "edusa", new Color(0x747d48), true, 0.3f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + } + }, + SpringAzure(ButterflyBranchDefinition.Celastrina, "springAzure", "argiolus", new Color(0xb8cae2), true, 0.3f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + } + }, + GozoraAzure(ButterflyBranchDefinition.Celastrina, "gozoraAzure", "gozora", new Color(0x6870e7), true, 0.2f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + } + }, + CitrusSwallow(ButterflyBranchDefinition.Papilio, "swallowtailC", "demodocus", new Color(0xeae389), false, 1.0f) { + @Override + protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { + species.setTemperature(EnumTemperature.WARM).setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 10); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.METABOLISM, 8); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); + AlleleHelper.instance.set( + alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + } + }, + EmeraldPeacock(ButterflyBranchDefinition.Papilio, "emeraldPeacock", "palinurus", new Color(0x7cfe80), true, 0.1f) { + @Override + protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { + species.setTemperature(EnumTemperature.WARM).setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 5); + AlleleHelper.instance.set( + alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + } + }, + ThoasSwallow(ButterflyBranchDefinition.Papilio, "swallowtailT", "thoas", new Color(0xeac783), false, 0.2f) { + @Override + protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { + species.setTemperature(EnumTemperature.WARM).setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); + } + }, + Spicebush(ButterflyBranchDefinition.Papilio, "swallowtailS", "troilus", new Color(0xeefeff), true, 0.5f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + } + }, + BlackSwallow(ButterflyBranchDefinition.Papilio, "swallowtailB", "polyxenes", new Color(0xeac783), true, 1.0f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOW); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); + AlleleHelper.instance.set( + alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + } + }, + ZebraSwallow( + ButterflyBranchDefinition.Protographium, "swallowtailZ", "marcellus", new Color(0xeafeff), true, 0.5f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + } + }, + Glasswing(ButterflyBranchDefinition.Greta, "glasswing", "oto", new Color(0x583732), true, 0.1f) { + @Override + protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { + species.setTemperature(EnumTemperature.WARM); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 5); + AlleleHelper.instance.set( + alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + } + }, + SpeckledWood(ButterflyBranchDefinition.Pararge, "speckledWood", "aegeria", new Color(0x947245), true, 1.0f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); + } + }, + MSpeckledWood(ButterflyBranchDefinition.Pararge, "speckledWoodM", "xiphia", new Color(0x402919), true, 0.5f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); + } + }, + CSpeckledWood(ButterflyBranchDefinition.Pararge, "speckledWoodC", "xiphioides", new Color(0x51372a), true, 0.5f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); + } + }, + MBlueMorpho(ButterflyBranchDefinition.Morpho, "blueMorphoM", "menelaus", new Color(0x72e1fd), true, 0.5f) { + @Override + protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { + species.setTemperature(EnumTemperature.WARM).setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGER); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); + } + }, + PBlueMorpho(ButterflyBranchDefinition.Morpho, "blueMorphoP", "peleides", new Color(0x6ecce8), true, 0.25f) { + @Override + protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { + species.setTemperature(EnumTemperature.WARM).setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGER); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); + } + }, + RBlueMorpho(ButterflyBranchDefinition.Morpho, "blueMorphoR", "rhetenor", new Color(0x00bef8), true, 0.1f) { + @Override + protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { + species.setTemperature(EnumTemperature.WARM).setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGER); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); + } + }, + Comma(ButterflyBranchDefinition.Polygonia, "comma", "c-album", new Color(0xf89505), true, 0.3f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + } + }, + Batesia(ButterflyBranchDefinition.Batesia, "paintedBeauty", "hypochlora", new Color(0xfe7763), true, 0.3f) { + @Override + protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { + species.setTemperature(EnumTemperature.WARM).setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); + } + }, + BlueWing(ButterflyBranchDefinition.Myscelia, "blueWing", "ethusa", new Color(0x3a93cc), true, 0.3f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.METABOLISM, 5); + } + }, + Monarch(ButterflyBranchDefinition.Danaus, "monarch", "plexippus", new Color(0xffa722), true, 0.2f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + } + }, + BlueDuke(ButterflyBranchDefinition.Bassarona, "blueDuke", "durga", new Color(0x304240), true, 0.5f) { + @Override + protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { + species.setTemperature(EnumTemperature.COLD); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set( + alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + } + }, + GlassyTiger(ButterflyBranchDefinition.Parantica, "glassyTiger", "aglea", new Color(0x5b3935), true, 0.3f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + } + }, + Postman(ButterflyBranchDefinition.Heliconius, "postman", "melpomene", new Color(0xf7302d), true, 0.3f), + Malachite(ButterflyBranchDefinition.Siproeta, "malachite", "stelenes", new Color(0xbdff53), true, 0.5f) { + @Override + protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { + species.setTemperature(EnumTemperature.WARM).setHumidity(EnumHumidity.DAMP); + } + + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + AlleleHelper.instance.set( + alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + } + }, + LLacewing(ButterflyBranchDefinition.Cethosia, "leopardLacewing", "cyane", new Color(0xfb8a06), true, 0.7f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set( + alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.UP_1); + } + }, + DianaFrit(ButterflyBranchDefinition.Speyeria, "dianaFritillary", "diana", new Color(0xffac05), true, 0.6f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); + } + }; + + private final IAlleleButterflySpeciesCustom species; + private final ButterflyBranchDefinition branch; + private IAllele[] template; + private IButterflyGenome genome; + + ButterflyDefinition( + ButterflyBranchDefinition branchDefinition, + String speciesName, + String binomial, + Color serumColor, + boolean dominant, + float rarity) { + this.branch = branchDefinition; + + String uid = "lepi" + name(); + IClassification parent = branch.getBranch().getParent(); + String unlocalizedName = "for.butterflies.species." + + parent.getUID().substring((parent.getLevel().name().toLowerCase(Locale.ENGLISH)).length() + 1) + '.' + + speciesName; + String unlocalizedDescription = "for.description." + uid; + + String texture = "forestry:" + Constants.TEXTURE_PATH_ENTITIES + "/butterflies/" + uid + ".png"; + + species = ButterflyManager.butterflyFactory.createSpecies( + "forestry." + uid, + unlocalizedName, + "Sengir", + unlocalizedDescription, + texture, + dominant, + branchDefinition.getBranch(), + binomial, + serumColor); + species.setRarity(rarity); + } + + public static void initButterflies() { + for (ButterflyDefinition butterfly : values()) { + butterfly.init(); + } + } + + private void init() { + setSpeciesProperties(species); + + template = branch.getTemplate(); + AlleleHelper.instance.set(template, EnumButterflyChromosome.SPECIES, species); + setAlleles(template); + + genome = ButterflyManager.butterflyRoot.templateAsGenome(template); + + ButterflyManager.butterflyRoot.registerTemplate(template); + } + + protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) {} + + protected void setAlleles(IAllele[] alleles) {} + + @Override + public final IAllele[] getTemplate() { + return Arrays.copyOf(template, template.length); + } + + @Override + public final IButterflyGenome getGenome() { + return genome; + } + + @Override + public final IButterfly getIndividual() { + return new Butterfly(genome); + } + + @Override + public final ItemStack getMemberStack(EnumFlutterType flutterType) { + IButterfly butterfly = getIndividual(); + return ButterflyManager.butterflyRoot.getMemberStack(butterfly, flutterType.ordinal()); + } +} diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyFactory.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyFactory.java index 45afe55a7..db70c424b 100644 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyFactory.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyFactory.java @@ -1,28 +1,45 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.genetics; - -import java.awt.Color; - -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IClassification; -import forestry.api.lepidopterology.EnumButterflyChromosome; -import forestry.api.lepidopterology.IAlleleButterflySpeciesCustom; -import forestry.api.lepidopterology.IButterflyFactory; - -public class ButterflyFactory implements IButterflyFactory { - @Override - public IAlleleButterflySpeciesCustom createSpecies(String uid, String unlocalizedName, String authority, String unlocalizedDescription, String texturePath, boolean isDominant, IClassification branch, String binomial, Color serumColour) { - IAlleleButterflySpeciesCustom species = new AlleleButterflySpecies(uid, unlocalizedName, authority, unlocalizedDescription, texturePath, isDominant, branch, binomial, serumColour); - AlleleManager.alleleRegistry.registerAllele(species, EnumButterflyChromosome.SPECIES); - return species; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.genetics; + +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IClassification; +import forestry.api.lepidopterology.EnumButterflyChromosome; +import forestry.api.lepidopterology.IAlleleButterflySpeciesCustom; +import forestry.api.lepidopterology.IButterflyFactory; +import java.awt.Color; + +public class ButterflyFactory implements IButterflyFactory { + @Override + public IAlleleButterflySpeciesCustom createSpecies( + String uid, + String unlocalizedName, + String authority, + String unlocalizedDescription, + String texturePath, + boolean isDominant, + IClassification branch, + String binomial, + Color serumColour) { + IAlleleButterflySpeciesCustom species = new AlleleButterflySpecies( + uid, + unlocalizedName, + authority, + unlocalizedDescription, + texturePath, + isDominant, + branch, + binomial, + serumColour); + AlleleManager.alleleRegistry.registerAllele(species, EnumButterflyChromosome.SPECIES); + return species; + } +} diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyGenome.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyGenome.java index 4e134c7c9..3547e897b 100755 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyGenome.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyGenome.java @@ -10,9 +10,6 @@ ******************************************************************************/ package forestry.lepidopterology.genetics; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import forestry.api.genetics.EnumTolerance; import forestry.api.genetics.IAlleleFloat; import forestry.api.genetics.IAlleleFlowers; @@ -29,106 +26,108 @@ import forestry.api.lepidopterology.IButterflyGenome; import forestry.core.genetics.Genome; import forestry.core.genetics.alleles.AlleleBoolean; import forestry.core.genetics.alleles.AlleleTolerance; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; public class ButterflyGenome extends Genome implements IButterflyGenome { - /* CONSTRUCTOR */ - public ButterflyGenome(NBTTagCompound nbttagcompound) { - super(nbttagcompound); - } + /* CONSTRUCTOR */ + public ButterflyGenome(NBTTagCompound nbttagcompound) { + super(nbttagcompound); + } - public ButterflyGenome(IChromosome[] chromosomes) { - super(chromosomes); - } + public ButterflyGenome(IChromosome[] chromosomes) { + super(chromosomes); + } - // NBT RETRIEVAL - public static IAlleleButterflySpecies getSpecies(ItemStack itemStack) { - if (!ButterflyManager.butterflyRoot.isMember(itemStack)) { - return null; - } - - IAlleleSpecies species = getSpeciesDirectly(itemStack); - if (species instanceof IAlleleButterflySpecies) { - return (IAlleleButterflySpecies) species; - } + // NBT RETRIEVAL + public static IAlleleButterflySpecies getSpecies(ItemStack itemStack) { + if (!ButterflyManager.butterflyRoot.isMember(itemStack)) { + return null; + } - return (IAlleleButterflySpecies) getActiveAllele(itemStack, EnumButterflyChromosome.SPECIES, ButterflyManager.butterflyRoot); - } + IAlleleSpecies species = getSpeciesDirectly(itemStack); + if (species instanceof IAlleleButterflySpecies) { + return (IAlleleButterflySpecies) species; + } - /* SPECIES */ - @Override - public IAlleleButterflySpecies getPrimary() { - return (IAlleleButterflySpecies) getActiveAllele(EnumButterflyChromosome.SPECIES); - } + return (IAlleleButterflySpecies) + getActiveAllele(itemStack, EnumButterflyChromosome.SPECIES, ButterflyManager.butterflyRoot); + } - @Override - public IAlleleButterflySpecies getSecondary() { - return (IAlleleButterflySpecies) getInactiveAllele(EnumButterflyChromosome.SPECIES); - } + /* SPECIES */ + @Override + public IAlleleButterflySpecies getPrimary() { + return (IAlleleButterflySpecies) getActiveAllele(EnumButterflyChromosome.SPECIES); + } - @Override - public float getSize() { - return ((IAlleleFloat) getActiveAllele(EnumButterflyChromosome.SIZE)).getValue(); - } - - @Override - public int getLifespan() { - return ((IAlleleInteger) getActiveAllele(EnumButterflyChromosome.LIFESPAN)).getValue(); - } - - @Override - public float getSpeed() { - return ((IAlleleFloat) getActiveAllele(EnumButterflyChromosome.SPEED)).getValue(); - } + @Override + public IAlleleButterflySpecies getSecondary() { + return (IAlleleButterflySpecies) getInactiveAllele(EnumButterflyChromosome.SPECIES); + } - @Override - public int getMetabolism() { - return ((IAlleleInteger) getActiveAllele(EnumButterflyChromosome.METABOLISM)).getValue(); - } + @Override + public float getSize() { + return ((IAlleleFloat) getActiveAllele(EnumButterflyChromosome.SIZE)).getValue(); + } - @Override - public int getFertility() { - return ((IAlleleInteger) getActiveAllele(EnumButterflyChromosome.FERTILITY)).getValue(); - } + @Override + public int getLifespan() { + return ((IAlleleInteger) getActiveAllele(EnumButterflyChromosome.LIFESPAN)).getValue(); + } - @Override - public EnumTolerance getToleranceTemp() { - return ((AlleleTolerance) getActiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE)).getValue(); - } + @Override + public float getSpeed() { + return ((IAlleleFloat) getActiveAllele(EnumButterflyChromosome.SPEED)).getValue(); + } - @Override - public EnumTolerance getToleranceHumid() { - return ((AlleleTolerance) getActiveAllele(EnumButterflyChromosome.HUMIDITY_TOLERANCE)).getValue(); - } + @Override + public int getMetabolism() { + return ((IAlleleInteger) getActiveAllele(EnumButterflyChromosome.METABOLISM)).getValue(); + } - @Override - public boolean getNocturnal() { - return ((AlleleBoolean) getActiveAllele(EnumButterflyChromosome.NOCTURNAL)).getValue(); - } + @Override + public int getFertility() { + return ((IAlleleInteger) getActiveAllele(EnumButterflyChromosome.FERTILITY)).getValue(); + } - @Override - public boolean getTolerantFlyer() { - return ((AlleleBoolean) getActiveAllele(EnumButterflyChromosome.TOLERANT_FLYER)).getValue(); - } + @Override + public EnumTolerance getToleranceTemp() { + return ((AlleleTolerance) getActiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE)).getValue(); + } - @Override - public boolean getFireResist() { - return ((AlleleBoolean) getActiveAllele(EnumButterflyChromosome.FIRE_RESIST)).getValue(); - } + @Override + public EnumTolerance getToleranceHumid() { + return ((AlleleTolerance) getActiveAllele(EnumButterflyChromosome.HUMIDITY_TOLERANCE)).getValue(); + } - @Override - public IFlowerProvider getFlowerProvider() { - return ((IAlleleFlowers) getActiveAllele(EnumButterflyChromosome.FLOWER_PROVIDER)).getProvider(); - } + @Override + public boolean getNocturnal() { + return ((AlleleBoolean) getActiveAllele(EnumButterflyChromosome.NOCTURNAL)).getValue(); + } - @Override - public IAlleleButterflyEffect getEffect() { - return (IAlleleButterflyEffect) getActiveAllele(EnumButterflyChromosome.EFFECT); - } + @Override + public boolean getTolerantFlyer() { + return ((AlleleBoolean) getActiveAllele(EnumButterflyChromosome.TOLERANT_FLYER)).getValue(); + } - @Override - public ISpeciesRoot getSpeciesRoot() { - return ButterflyManager.butterflyRoot; - } + @Override + public boolean getFireResist() { + return ((AlleleBoolean) getActiveAllele(EnumButterflyChromosome.FIRE_RESIST)).getValue(); + } + @Override + public IFlowerProvider getFlowerProvider() { + return ((IAlleleFlowers) getActiveAllele(EnumButterflyChromosome.FLOWER_PROVIDER)).getProvider(); + } + + @Override + public IAlleleButterflyEffect getEffect() { + return (IAlleleButterflyEffect) getActiveAllele(EnumButterflyChromosome.EFFECT); + } + + @Override + public ISpeciesRoot getSpeciesRoot() { + return ButterflyManager.butterflyRoot; + } } diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyHelper.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyHelper.java index b2a47748a..f00af4dab 100755 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyHelper.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyHelper.java @@ -10,18 +10,7 @@ ******************************************************************************/ package forestry.lepidopterology.genetics; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Map.Entry; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; import forestry.api.genetics.IChromosomeType; @@ -40,220 +29,227 @@ import forestry.core.genetics.SpeciesRoot; import forestry.core.utils.EntityUtil; import forestry.lepidopterology.entities.EntityButterfly; import forestry.plugins.PluginLepidopterology; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Map.Entry; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; public class ButterflyHelper extends SpeciesRoot implements IButterflyRoot { - private static int butterflySpeciesCount = -1; - public static final String UID = "rootButterflies"; + private static int butterflySpeciesCount = -1; + public static final String UID = "rootButterflies"; - @Override - public String getUID() { - return UID; - } + @Override + public String getUID() { + return UID; + } - @Override - public Class getMemberClass() { - return IButterfly.class; - } + @Override + public Class getMemberClass() { + return IButterfly.class; + } - @Override - public int getSpeciesCount() { - if (butterflySpeciesCount < 0) { - butterflySpeciesCount = 0; - for (Entry entry : AlleleManager.alleleRegistry.getRegisteredAlleles().entrySet()) { - if (entry.getValue() instanceof IAlleleButterflySpecies) { - if (((IAlleleButterflySpecies) entry.getValue()).isCounted()) { - butterflySpeciesCount++; - } - } - } - } + @Override + public int getSpeciesCount() { + if (butterflySpeciesCount < 0) { + butterflySpeciesCount = 0; + for (Entry entry : + AlleleManager.alleleRegistry.getRegisteredAlleles().entrySet()) { + if (entry.getValue() instanceof IAlleleButterflySpecies) { + if (((IAlleleButterflySpecies) entry.getValue()).isCounted()) { + butterflySpeciesCount++; + } + } + } + } - return butterflySpeciesCount; - } + return butterflySpeciesCount; + } - @Override - public boolean isMember(ItemStack stack) { - return getType(stack) != EnumFlutterType.NONE; - } + @Override + public boolean isMember(ItemStack stack) { + return getType(stack) != EnumFlutterType.NONE; + } - @Override - public EnumFlutterType getType(ItemStack stack) { - if (stack == null) { - return EnumFlutterType.NONE; - } + @Override + public EnumFlutterType getType(ItemStack stack) { + if (stack == null) { + return EnumFlutterType.NONE; + } - Item item = stack.getItem(); - if (PluginLepidopterology.items.butterflyGE == item) { - return EnumFlutterType.BUTTERFLY; - } else if (PluginLepidopterology.items.serumGE == item) { - return EnumFlutterType.SERUM; - } else if (PluginLepidopterology.items.caterpillarGE == item) { - return EnumFlutterType.CATERPILLAR; - } else { - return EnumFlutterType.NONE; - } - } + Item item = stack.getItem(); + if (PluginLepidopterology.items.butterflyGE == item) { + return EnumFlutterType.BUTTERFLY; + } else if (PluginLepidopterology.items.serumGE == item) { + return EnumFlutterType.SERUM; + } else if (PluginLepidopterology.items.caterpillarGE == item) { + return EnumFlutterType.CATERPILLAR; + } else { + return EnumFlutterType.NONE; + } + } - @Override - public boolean isMember(ItemStack stack, int type) { - return getType(stack).ordinal() == type; - } + @Override + public boolean isMember(ItemStack stack, int type) { + return getType(stack).ordinal() == type; + } - @Override - public boolean isMember(IIndividual individual) { - return individual instanceof IButterfly; - } + @Override + public boolean isMember(IIndividual individual) { + return individual instanceof IButterfly; + } - @Override - public IButterfly getMember(ItemStack stack) { - if (!stack.hasTagCompound()) { - return null; - } - if (!isMember(stack)) { - return null; - } + @Override + public IButterfly getMember(ItemStack stack) { + if (!stack.hasTagCompound()) { + return null; + } + if (!isMember(stack)) { + return null; + } - return new Butterfly(stack.getTagCompound()); - } + return new Butterfly(stack.getTagCompound()); + } - @Override - public IButterfly getMember(NBTTagCompound compound) { - return new Butterfly(compound); - } + @Override + public IButterfly getMember(NBTTagCompound compound) { + return new Butterfly(compound); + } - @Override - public ItemStack getMemberStack(IIndividual butterfly, int type) { + @Override + public ItemStack getMemberStack(IIndividual butterfly, int type) { - Item butterflyItem; - switch (EnumFlutterType.VALUES[type]) { - case SERUM: - butterflyItem = PluginLepidopterology.items.serumGE; - break; - case CATERPILLAR: - butterflyItem = PluginLepidopterology.items.caterpillarGE; - break; - case BUTTERFLY: - default: - butterflyItem = PluginLepidopterology.items.butterflyGE; - break; - } + Item butterflyItem; + switch (EnumFlutterType.VALUES[type]) { + case SERUM: + butterflyItem = PluginLepidopterology.items.serumGE; + break; + case CATERPILLAR: + butterflyItem = PluginLepidopterology.items.caterpillarGE; + break; + case BUTTERFLY: + default: + butterflyItem = PluginLepidopterology.items.butterflyGE; + break; + } - NBTTagCompound nbttagcompound = new NBTTagCompound(); - butterfly.writeToNBT(nbttagcompound); - ItemStack stack = new ItemStack(butterflyItem); - stack.setTagCompound(nbttagcompound); - return stack; + NBTTagCompound nbttagcompound = new NBTTagCompound(); + butterfly.writeToNBT(nbttagcompound); + ItemStack stack = new ItemStack(butterflyItem); + stack.setTagCompound(nbttagcompound); + return stack; + } - } + @Override + public EntityButterfly spawnButterflyInWorld(World world, IButterfly butterfly, double x, double y, double z) { + return EntityUtil.spawnEntity(world, new EntityButterfly(world, butterfly, (int) x, (int) y, (int) z), x, y, z); + } - @Override - public EntityButterfly spawnButterflyInWorld(World world, IButterfly butterfly, double x, double y, double z) { - return EntityUtil.spawnEntity(world, new EntityButterfly(world, butterfly, (int)x, (int)y, (int)z), x, y, z); - } + @Override + public boolean isMated(ItemStack stack) { + IButterfly butterfly = getMember(stack); + if (butterfly == null) { + return false; + } - @Override - public boolean isMated(ItemStack stack) { - IButterfly butterfly = getMember(stack); - if (butterfly == null) { - return false; - } + return butterfly.getMate() != null; + } - return butterfly.getMate() != null; - } + /* GENOME CONVERSIONS */ + @Override + public IButterfly templateAsIndividual(IAllele[] template) { + return new Butterfly(templateAsGenome(template)); + } - /* GENOME CONVERSIONS */ - @Override - public IButterfly templateAsIndividual(IAllele[] template) { - return new Butterfly(templateAsGenome(template)); - } + @Override + public IButterfly templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive) { + return new Butterfly(templateAsGenome(templateActive, templateInactive)); + } - @Override - public IButterfly templateAsIndividual(IAllele[] templateActive, IAllele[] templateInactive) { - return new Butterfly(templateAsGenome(templateActive, templateInactive)); - } + @Override + public IButterflyGenome templateAsGenome(IAllele[] template) { + return new ButterflyGenome(templateAsChromosomes(template)); + } - @Override - public IButterflyGenome templateAsGenome(IAllele[] template) { - return new ButterflyGenome(templateAsChromosomes(template)); - } + @Override + public IButterflyGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive) { + return new ButterflyGenome(templateAsChromosomes(templateActive, templateInactive)); + } - @Override - public IButterflyGenome templateAsGenome(IAllele[] templateActive, IAllele[] templateInactive) { - return new ButterflyGenome(templateAsChromosomes(templateActive, templateInactive)); - } + /* TEMPLATES */ + private static final ArrayList butterflyTemplates = new ArrayList<>(); - /* TEMPLATES */ - private static final ArrayList butterflyTemplates = new ArrayList<>(); + @Override + public ArrayList getIndividualTemplates() { + return butterflyTemplates; + } - @Override - public ArrayList getIndividualTemplates() { - return butterflyTemplates; - } + @Override + public IAllele[] getDefaultTemplate() { + return MothDefinition.Brimstone.getTemplate(); + } - @Override - public IAllele[] getDefaultTemplate() { - return MothDefinition.Brimstone.getTemplate(); - } + @Override + public void registerTemplate(String identifier, IAllele[] template) { + butterflyTemplates.add(ButterflyManager.butterflyRoot.templateAsIndividual(template)); + speciesTemplates.put(identifier, template); + } - @Override - public void registerTemplate(String identifier, IAllele[] template) { - butterflyTemplates.add(ButterflyManager.butterflyRoot.templateAsIndividual(template)); - speciesTemplates.put(identifier, template); - } + /* MUTATIONS */ + private static final ArrayList butterflyMutations = new ArrayList<>(); - /* MUTATIONS */ - private static final ArrayList butterflyMutations = new ArrayList<>(); + @Override + public void registerMutation(IMutation mutation) { + if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getTemplate()[0].getUID())) { + return; + } + if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getAllele0().getUID())) { + return; + } + if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getAllele1().getUID())) { + return; + } - @Override - public void registerMutation(IMutation mutation) { - if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getTemplate()[0].getUID())) { - return; - } - if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getAllele0().getUID())) { - return; - } - if (AlleleManager.alleleRegistry.isBlacklisted(mutation.getAllele1().getUID())) { - return; - } + butterflyMutations.add((IButterflyMutation) mutation); + } - butterflyMutations.add((IButterflyMutation) mutation); - } + @Override + public Collection getMutations(boolean shuffle) { + if (shuffle) { + Collections.shuffle(butterflyMutations); + } + return butterflyMutations; + } - @Override - public Collection getMutations(boolean shuffle) { - if (shuffle) { - Collections.shuffle(butterflyMutations); - } - return butterflyMutations; - } + /* BREEDING TRACKER */ + @Override + public ILepidopteristTracker getBreedingTracker(World world, GameProfile player) { + String filename = "LepidopteristTracker." + (player == null ? "common" : player.getId()); + LepidopteristTracker tracker = (LepidopteristTracker) world.loadItemData(LepidopteristTracker.class, filename); - /* BREEDING TRACKER */ - @Override - public ILepidopteristTracker getBreedingTracker(World world, GameProfile player) { - String filename = "LepidopteristTracker." + (player == null ? "common" : player.getId()); - LepidopteristTracker tracker = (LepidopteristTracker) world.loadItemData(LepidopteristTracker.class, filename); + // Create a tracker if there is none yet. + if (tracker == null) { + tracker = new LepidopteristTracker(filename); + world.setItemData(filename, tracker); + } - // Create a tracker if there is none yet. - if (tracker == null) { - tracker = new LepidopteristTracker(filename); - world.setItemData(filename, tracker); - } + tracker.setUsername(player); + tracker.setWorld(world); - tracker.setUsername(player); - tracker.setWorld(world); + return tracker; + } - return tracker; - } - - @Override - public IChromosomeType[] getKaryotype() { - return EnumButterflyChromosome.values(); - } - - @Override - public IChromosomeType getKaryotypeKey() { - return EnumButterflyChromosome.SPECIES; - } + @Override + public IChromosomeType[] getKaryotype() { + return EnumButterflyChromosome.values(); + } + @Override + public IChromosomeType getKaryotypeKey() { + return EnumButterflyChromosome.SPECIES; + } } diff --git a/src/main/java/forestry/lepidopterology/genetics/IButterflyDefinition.java b/src/main/java/forestry/lepidopterology/genetics/IButterflyDefinition.java index 9e7685831..6a5e0c563 100644 --- a/src/main/java/forestry/lepidopterology/genetics/IButterflyDefinition.java +++ b/src/main/java/forestry/lepidopterology/genetics/IButterflyDefinition.java @@ -1,28 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.genetics; - -import net.minecraft.item.ItemStack; - -import forestry.api.lepidopterology.EnumFlutterType; -import forestry.api.lepidopterology.IButterfly; -import forestry.api.lepidopterology.IButterflyGenome; -import forestry.core.genetics.IGeneticDefinition; - -public interface IButterflyDefinition extends IGeneticDefinition { - @Override - IButterflyGenome getGenome(); - - @Override - IButterfly getIndividual(); - - ItemStack getMemberStack(EnumFlutterType flutterType); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.genetics; + +import forestry.api.lepidopterology.EnumFlutterType; +import forestry.api.lepidopterology.IButterfly; +import forestry.api.lepidopterology.IButterflyGenome; +import forestry.core.genetics.IGeneticDefinition; +import net.minecraft.item.ItemStack; + +public interface IButterflyDefinition extends IGeneticDefinition { + @Override + IButterflyGenome getGenome(); + + @Override + IButterfly getIndividual(); + + ItemStack getMemberStack(EnumFlutterType flutterType); +} diff --git a/src/main/java/forestry/lepidopterology/genetics/LepidopteristTracker.java b/src/main/java/forestry/lepidopterology/genetics/LepidopteristTracker.java index b830828b9..477d85d1b 100755 --- a/src/main/java/forestry/lepidopterology/genetics/LepidopteristTracker.java +++ b/src/main/java/forestry/lepidopterology/genetics/LepidopteristTracker.java @@ -10,40 +10,37 @@ ******************************************************************************/ package forestry.lepidopterology.genetics; -import net.minecraft.entity.player.EntityPlayer; - import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.IIndividual; import forestry.api.lepidopterology.ButterflyManager; import forestry.api.lepidopterology.IButterfly; import forestry.api.lepidopterology.ILepidopteristTracker; import forestry.core.genetics.BreedingTracker; +import net.minecraft.entity.player.EntityPlayer; public class LepidopteristTracker extends BreedingTracker implements ILepidopteristTracker { - /** Required for creation from map storage */ - public LepidopteristTracker(String s) { - super(s); - } + /** Required for creation from map storage */ + public LepidopteristTracker(String s) { + super(s); + } - @Override - protected IBreedingTracker getBreedingTracker(EntityPlayer player) { - return ButterflyManager.butterflyRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); - } + @Override + protected IBreedingTracker getBreedingTracker(EntityPlayer player) { + return ButterflyManager.butterflyRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); + } - @Override - protected String speciesRootUID() { - return ButterflyHelper.UID; - } + @Override + protected String speciesRootUID() { + return ButterflyHelper.UID; + } - @Override - public void registerPickup(IIndividual individual) { - } - - @Override - public void registerCatch(IButterfly butterfly) { - registerSpecies(butterfly.getGenome().getPrimary()); - registerSpecies(butterfly.getGenome().getSecondary()); - } + @Override + public void registerPickup(IIndividual individual) {} + @Override + public void registerCatch(IButterfly butterfly) { + registerSpecies(butterfly.getGenome().getPrimary()); + registerSpecies(butterfly.getGenome().getSecondary()); + } } diff --git a/src/main/java/forestry/lepidopterology/genetics/MothDefinition.java b/src/main/java/forestry/lepidopterology/genetics/MothDefinition.java index e9ca5868a..4d90b8d23 100644 --- a/src/main/java/forestry/lepidopterology/genetics/MothDefinition.java +++ b/src/main/java/forestry/lepidopterology/genetics/MothDefinition.java @@ -1,112 +1,123 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.genetics; - -import java.awt.Color; -import java.util.Arrays; -import java.util.Locale; - -import net.minecraft.item.ItemStack; - -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IClassification; -import forestry.api.lepidopterology.ButterflyManager; -import forestry.api.lepidopterology.EnumButterflyChromosome; -import forestry.api.lepidopterology.EnumFlutterType; -import forestry.api.lepidopterology.IAlleleButterflySpeciesCustom; -import forestry.api.lepidopterology.IButterfly; -import forestry.api.lepidopterology.IButterflyGenome; -import forestry.core.config.Constants; -import forestry.core.genetics.alleles.AlleleHelper; -import forestry.core.genetics.alleles.EnumAllele; - -public enum MothDefinition implements IButterflyDefinition { - Brimstone(ButterflyBranchDefinition.Opisthograptis, "brimstone", "luteolata", new Color(0xffea40), true, 1.0f), - LatticedHeath(ButterflyBranchDefinition.Chiasmia, "latticeHeath", "clathrata", new Color(0xf2f0be), true, 0.5f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLEST); - } - }, - Atlas(ButterflyBranchDefinition.Attacus, "atlas", "atlas", new Color(0xd96e3d), false, 0.1f) { - @Override - protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGEST); - } - }; - - private final IAlleleButterflySpeciesCustom species; - private final ButterflyBranchDefinition branch; - private IAllele[] template; - private IButterflyGenome genome; - - MothDefinition(ButterflyBranchDefinition branchDefinition, String speciesName, String binomial, Color serumColor, boolean dominant, float rarity) { - branch = branchDefinition; - - String uid = "moth" + name(); - IClassification parent = branch.getBranch().getParent(); - String unlocalizedName = "for.butterflies.species." + parent.getUID().substring((parent.getLevel().name().toLowerCase(Locale.ENGLISH)).length() + 1) + '.' + speciesName; - String unlocalizedDescription = "for.description." + uid; - - String texture = "forestry:" + Constants.TEXTURE_PATH_ENTITIES + "/butterflies/" + uid + ".png"; - - species = ButterflyManager.butterflyFactory.createSpecies("forestry." + uid, unlocalizedName, "Sengir", unlocalizedDescription, texture, dominant, branchDefinition.getBranch(), binomial, serumColor); - species.setRarity(rarity); - species.setNocturnal(); - } - - public static void initMoths() { - for (MothDefinition butterfly : values()) { - butterfly.init(); - } - } - - private void init() { - setSpeciesProperties(species); - - template = branch.getTemplate(); - AlleleHelper.instance.set(template, EnumButterflyChromosome.SPECIES, species); - setAlleles(template); - - genome = ButterflyManager.butterflyRoot.templateAsGenome(template); - - ButterflyManager.butterflyRoot.registerTemplate(template); - } - - protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) { - - } - - protected void setAlleles(IAllele[] alleles) { - - } - - @Override - public final IAllele[] getTemplate() { - return Arrays.copyOf(template, template.length); - } - - @Override - public final IButterflyGenome getGenome() { - return genome; - } - - @Override - public final IButterfly getIndividual() { - return new Butterfly(genome); - } - - @Override - public final ItemStack getMemberStack(EnumFlutterType flutterType) { - IButterfly butterfly = getIndividual(); - return ButterflyManager.butterflyRoot.getMemberStack(butterfly, flutterType.ordinal()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.genetics; + +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IClassification; +import forestry.api.lepidopterology.ButterflyManager; +import forestry.api.lepidopterology.EnumButterflyChromosome; +import forestry.api.lepidopterology.EnumFlutterType; +import forestry.api.lepidopterology.IAlleleButterflySpeciesCustom; +import forestry.api.lepidopterology.IButterfly; +import forestry.api.lepidopterology.IButterflyGenome; +import forestry.core.config.Constants; +import forestry.core.genetics.alleles.AlleleHelper; +import forestry.core.genetics.alleles.EnumAllele; +import java.awt.Color; +import java.util.Arrays; +import java.util.Locale; +import net.minecraft.item.ItemStack; + +public enum MothDefinition implements IButterflyDefinition { + Brimstone(ButterflyBranchDefinition.Opisthograptis, "brimstone", "luteolata", new Color(0xffea40), true, 1.0f), + LatticedHeath(ButterflyBranchDefinition.Chiasmia, "latticeHeath", "clathrata", new Color(0xf2f0be), true, 0.5f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLEST); + } + }, + Atlas(ButterflyBranchDefinition.Attacus, "atlas", "atlas", new Color(0xd96e3d), false, 0.1f) { + @Override + protected void setAlleles(IAllele[] alleles) { + AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGEST); + } + }; + + private final IAlleleButterflySpeciesCustom species; + private final ButterflyBranchDefinition branch; + private IAllele[] template; + private IButterflyGenome genome; + + MothDefinition( + ButterflyBranchDefinition branchDefinition, + String speciesName, + String binomial, + Color serumColor, + boolean dominant, + float rarity) { + branch = branchDefinition; + + String uid = "moth" + name(); + IClassification parent = branch.getBranch().getParent(); + String unlocalizedName = "for.butterflies.species." + + parent.getUID().substring((parent.getLevel().name().toLowerCase(Locale.ENGLISH)).length() + 1) + '.' + + speciesName; + String unlocalizedDescription = "for.description." + uid; + + String texture = "forestry:" + Constants.TEXTURE_PATH_ENTITIES + "/butterflies/" + uid + ".png"; + + species = ButterflyManager.butterflyFactory.createSpecies( + "forestry." + uid, + unlocalizedName, + "Sengir", + unlocalizedDescription, + texture, + dominant, + branchDefinition.getBranch(), + binomial, + serumColor); + species.setRarity(rarity); + species.setNocturnal(); + } + + public static void initMoths() { + for (MothDefinition butterfly : values()) { + butterfly.init(); + } + } + + private void init() { + setSpeciesProperties(species); + + template = branch.getTemplate(); + AlleleHelper.instance.set(template, EnumButterflyChromosome.SPECIES, species); + setAlleles(template); + + genome = ButterflyManager.butterflyRoot.templateAsGenome(template); + + ButterflyManager.butterflyRoot.registerTemplate(template); + } + + protected void setSpeciesProperties(IAlleleButterflySpeciesCustom species) {} + + protected void setAlleles(IAllele[] alleles) {} + + @Override + public final IAllele[] getTemplate() { + return Arrays.copyOf(template, template.length); + } + + @Override + public final IButterflyGenome getGenome() { + return genome; + } + + @Override + public final IButterfly getIndividual() { + return new Butterfly(genome); + } + + @Override + public final ItemStack getMemberStack(EnumFlutterType flutterType) { + IButterfly butterfly = getIndividual(); + return ButterflyManager.butterflyRoot.getMemberStack(butterfly, flutterType.ordinal()); + } +} diff --git a/src/main/java/forestry/lepidopterology/gui/GuiFlutterlyzer.java b/src/main/java/forestry/lepidopterology/gui/GuiFlutterlyzer.java index 3a769a0e4..474645f5d 100755 --- a/src/main/java/forestry/lepidopterology/gui/GuiFlutterlyzer.java +++ b/src/main/java/forestry/lepidopterology/gui/GuiFlutterlyzer.java @@ -10,11 +10,6 @@ ******************************************************************************/ package forestry.lepidopterology.gui; -import java.util.ArrayList; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAlleleFlowers; import forestry.api.genetics.IAlleleInteger; @@ -31,228 +26,330 @@ import forestry.core.utils.StringUtil; import forestry.lepidopterology.genetics.ButterflyGenome; import forestry.lepidopterology.inventory.ItemInventoryFlutterlyzer; import forestry.plugins.PluginLepidopterology; +import java.util.ArrayList; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; public class GuiFlutterlyzer extends GuiAlyzer { - public GuiFlutterlyzer(EntityPlayer player, ItemInventoryFlutterlyzer inventory) { - super(ButterflyManager.butterflyRoot, player, new ContainerAlyzer(inventory, player), inventory, "gui.flutterlyzer"); + public GuiFlutterlyzer(EntityPlayer player, ItemInventoryFlutterlyzer inventory) { + super( + ButterflyManager.butterflyRoot, + player, + new ContainerAlyzer(inventory, player), + inventory, + "gui.flutterlyzer"); - ArrayList butterflyList = new ArrayList<>(); - PluginLepidopterology.items.butterflyGE.addCreativeItems(butterflyList, false); - for (ItemStack butterflyStack : butterflyList) { - IAlleleButterflySpecies species = ButterflyGenome.getSpecies(butterflyStack); - if (species != null) { - iconStacks.put(species.getUID(), butterflyStack); - } - } - } + ArrayList butterflyList = new ArrayList<>(); + PluginLepidopterology.items.butterflyGE.addCreativeItems(butterflyList, false); + for (ItemStack butterflyStack : butterflyList) { + IAlleleButterflySpecies species = ButterflyGenome.getSpecies(butterflyStack); + if (species != null) { + iconStacks.put(species.getUID(), butterflyStack); + } + } + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - int page = 0; - IButterfly butterfly = null; - for (int k = 1; k < ItemInventoryFlutterlyzer.SLOT_ANALYZE_5 + 1; k++) { - if (k == ItemInventoryFlutterlyzer.SLOT_ENERGY) { - continue; - } + int page = 0; + IButterfly butterfly = null; + for (int k = 1; k < ItemInventoryFlutterlyzer.SLOT_ANALYZE_5 + 1; k++) { + if (k == ItemInventoryFlutterlyzer.SLOT_ENERGY) { + continue; + } - if (inventory.getStackInSlot(k) == null) { - continue; - } - butterfly = ButterflyManager.butterflyRoot.getMember(inventory.getStackInSlot(k)); - if (butterfly == null || !butterfly.isAnalyzed()) { - continue; - } + if (inventory.getStackInSlot(k) == null) { + continue; + } + butterfly = ButterflyManager.butterflyRoot.getMember(inventory.getStackInSlot(k)); + if (butterfly == null || !butterfly.isAnalyzed()) { + continue; + } - page = k; - break; - } + page = k; + break; + } - switch (page) { - case 1: - drawAnalyticsPage1(butterfly); - break; - case 2: - drawAnalyticsPage2(butterfly); - break; - case 3: - drawAnalyticsPage3(butterfly); - break; - case 4: - drawAnalyticsPageMutations(butterfly); - break; - case 6: - drawAnalyticsPageClassification(butterfly); - break; - default: - drawAnalyticsOverview(); - } + switch (page) { + case 1: + drawAnalyticsPage1(butterfly); + break; + case 2: + drawAnalyticsPage2(butterfly); + break; + case 3: + drawAnalyticsPage3(butterfly); + break; + case 4: + drawAnalyticsPageMutations(butterfly); + break; + case 6: + drawAnalyticsPageClassification(butterfly); + break; + default: + drawAnalyticsOverview(); + } + } - } + private void drawAnalyticsPage1(IButterfly butterfly) { + textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); - private void drawAnalyticsPage1(IButterfly butterfly) { - textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); + textLayout.drawLine(StringUtil.localize("gui.active"), COLUMN_1); + textLayout.drawLine(StringUtil.localize("gui.inactive"), COLUMN_2); - textLayout.drawLine(StringUtil.localize("gui.active"), COLUMN_1); - textLayout.drawLine(StringUtil.localize("gui.inactive"), COLUMN_2); + textLayout.newLine(); + textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); + drawSpeciesRow(StringUtil.localize("gui.species"), butterfly, EnumButterflyChromosome.SPECIES, null, null); + textLayout.newLine(); - drawSpeciesRow(StringUtil.localize("gui.species"), butterfly, EnumButterflyChromosome.SPECIES, null, null); - textLayout.newLine(); + drawRow( + StringUtil.localize("gui.size"), + butterfly + .getGenome() + .getActiveAllele(EnumButterflyChromosome.SIZE) + .getName(), + butterfly + .getGenome() + .getInactiveAllele(EnumButterflyChromosome.SIZE) + .getName(), + butterfly, + EnumButterflyChromosome.SPEED); + textLayout.newLine(); - drawRow(StringUtil.localize("gui.size"), butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.SIZE).getName(), - butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.SIZE).getName(), butterfly, EnumButterflyChromosome.SPEED); - textLayout.newLine(); + drawRow( + StringUtil.localize("gui.lifespan"), + butterfly + .getGenome() + .getActiveAllele(EnumButterflyChromosome.LIFESPAN) + .getName(), + butterfly + .getGenome() + .getInactiveAllele(EnumButterflyChromosome.LIFESPAN) + .getName(), + butterfly, + EnumButterflyChromosome.LIFESPAN); + textLayout.newLine(); - drawRow(StringUtil.localize("gui.lifespan"), butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.LIFESPAN).getName(), - butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.LIFESPAN).getName(), butterfly, - EnumButterflyChromosome.LIFESPAN); - textLayout.newLine(); + drawRow( + StringUtil.localize("gui.speed"), + butterfly + .getGenome() + .getActiveAllele(EnumButterflyChromosome.SPEED) + .getName(), + butterfly + .getGenome() + .getInactiveAllele(EnumButterflyChromosome.SPEED) + .getName(), + butterfly, + EnumButterflyChromosome.SPEED); + textLayout.newLine(); - drawRow(StringUtil.localize("gui.speed"), butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.SPEED).getName(), - butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.SPEED).getName(), butterfly, EnumButterflyChromosome.SPEED); - textLayout.newLine(); + drawRow( + StringUtil.localize("gui.metabolism"), + GenericRatings.rateMetabolism(butterfly.getGenome().getMetabolism()), + GenericRatings.rateMetabolism( + ((IAlleleInteger) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.METABOLISM)) + .getValue()), + butterfly, + EnumButterflyChromosome.METABOLISM); + textLayout.newLine(); - drawRow(StringUtil.localize("gui.metabolism"), GenericRatings.rateMetabolism(butterfly.getGenome().getMetabolism()), - GenericRatings.rateMetabolism(((IAlleleInteger) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.METABOLISM)).getValue()), butterfly, EnumButterflyChromosome.METABOLISM); - textLayout.newLine(); + textLayout.drawLine(StringUtil.localize("gui.fertility"), COLUMN_0); + drawFertilityInfo( + butterfly.getGenome().getFertility(), + COLUMN_1, + getColorCoding(butterfly + .getGenome() + .getActiveAllele(EnumButterflyChromosome.FERTILITY) + .isDominant()), + 8); + drawFertilityInfo( + ((IAlleleInteger) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.FERTILITY)) + .getValue(), + COLUMN_2, + getColorCoding(butterfly + .getGenome() + .getInactiveAllele(EnumButterflyChromosome.FERTILITY) + .isDominant()), + 8); - textLayout.drawLine(StringUtil.localize("gui.fertility"), COLUMN_0); - drawFertilityInfo(butterfly.getGenome().getFertility(), COLUMN_1, getColorCoding(butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.FERTILITY) - .isDominant()), 8); - drawFertilityInfo(((IAlleleInteger) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.FERTILITY)).getValue(), COLUMN_2, getColorCoding(butterfly - .getGenome().getInactiveAllele(EnumButterflyChromosome.FERTILITY).isDominant()), 8); + textLayout.newLine(); - textLayout.newLine(); + drawRow( + StringUtil.localize("gui.flowers"), + butterfly.getGenome().getFlowerProvider().getDescription(), + ((IAlleleFlowers) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.FLOWER_PROVIDER)) + .getProvider() + .getDescription(), + butterfly, + EnumButterflyChromosome.FLOWER_PROVIDER); + textLayout.newLine(); - drawRow(StringUtil.localize("gui.flowers"), butterfly.getGenome().getFlowerProvider().getDescription(), - ((IAlleleFlowers) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.FLOWER_PROVIDER)).getProvider() - .getDescription(), butterfly, EnumButterflyChromosome.FLOWER_PROVIDER); - textLayout.newLine(); + drawRow( + StringUtil.localize("gui.effect"), + butterfly.getGenome().getEffect().getName(), + butterfly + .getGenome() + .getInactiveAllele(EnumButterflyChromosome.EFFECT) + .getName(), + butterfly, + EnumButterflyChromosome.EFFECT); - drawRow(StringUtil.localize("gui.effect"), butterfly.getGenome().getEffect().getName(), - butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.EFFECT).getName(), butterfly, - EnumButterflyChromosome.EFFECT); + textLayout.newLine(); - textLayout.newLine(); + textLayout.endPage(); + } - textLayout.endPage(); - } + private void drawAnalyticsPage2(IButterfly butterfly) { + textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); - private void drawAnalyticsPage2(IButterfly butterfly) { - textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); + textLayout.drawLine(StringUtil.localize("gui.active"), COLUMN_1); + textLayout.drawLine(StringUtil.localize("gui.inactive"), COLUMN_2); - textLayout.drawLine(StringUtil.localize("gui.active"), COLUMN_1); - textLayout.drawLine(StringUtil.localize("gui.inactive"), COLUMN_2); + textLayout.newLine(); + textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); + drawRow( + StringUtil.localize("gui.climate"), + AlleleManager.climateHelper.toDisplay( + butterfly.getGenome().getPrimary().getTemperature()), + AlleleManager.climateHelper.toDisplay( + butterfly.getGenome().getPrimary().getTemperature()), + butterfly, + EnumButterflyChromosome.SPECIES); + textLayout.newLine(); - drawRow(StringUtil.localize("gui.climate"), AlleleManager.climateHelper.toDisplay(butterfly.getGenome().getPrimary().getTemperature()), - AlleleManager.climateHelper.toDisplay(butterfly.getGenome().getPrimary().getTemperature()), butterfly, EnumButterflyChromosome.SPECIES); - textLayout.newLine(); + IAlleleTolerance tempToleranceActive = + (IAlleleTolerance) butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE); + IAlleleTolerance tempToleranceInactive = (IAlleleTolerance) + butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE); + textLayout.drawLine(" " + StringUtil.localize("gui.tolerance"), COLUMN_0); + drawToleranceInfo(tempToleranceActive, COLUMN_1); + drawToleranceInfo(tempToleranceInactive, COLUMN_2); - IAlleleTolerance tempToleranceActive = (IAlleleTolerance) butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE); - IAlleleTolerance tempToleranceInactive = (IAlleleTolerance) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE); - textLayout.drawLine(" " + StringUtil.localize("gui.tolerance"), COLUMN_0); - drawToleranceInfo(tempToleranceActive, COLUMN_1); - drawToleranceInfo(tempToleranceInactive, COLUMN_2); + textLayout.newLine(); - textLayout.newLine(); + drawRow( + StringUtil.localize("gui.humidity"), + AlleleManager.climateHelper.toDisplay( + butterfly.getGenome().getPrimary().getHumidity()), + AlleleManager.climateHelper.toDisplay( + butterfly.getGenome().getPrimary().getHumidity()), + butterfly, + EnumButterflyChromosome.SPECIES); + textLayout.newLine(); - drawRow(StringUtil.localize("gui.humidity"), AlleleManager.climateHelper.toDisplay(butterfly.getGenome().getPrimary().getHumidity()), - AlleleManager.climateHelper.toDisplay(butterfly.getGenome().getPrimary().getHumidity()), butterfly, EnumButterflyChromosome.SPECIES); - textLayout.newLine(); + IAlleleTolerance humidToleranceActive = + (IAlleleTolerance) butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.HUMIDITY_TOLERANCE); + IAlleleTolerance humidToleranceInactive = + (IAlleleTolerance) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.HUMIDITY_TOLERANCE); + textLayout.drawLine(" " + StringUtil.localize("gui.tolerance"), COLUMN_0); + drawToleranceInfo(humidToleranceActive, COLUMN_1); + drawToleranceInfo(humidToleranceInactive, COLUMN_2); - IAlleleTolerance humidToleranceActive = (IAlleleTolerance) butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.HUMIDITY_TOLERANCE); - IAlleleTolerance humidToleranceInactive = (IAlleleTolerance) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.HUMIDITY_TOLERANCE); - textLayout.drawLine(" " + StringUtil.localize("gui.tolerance"), COLUMN_0); - drawToleranceInfo(humidToleranceActive, COLUMN_1); - drawToleranceInfo(humidToleranceInactive, COLUMN_2); + textLayout.newLine(); + textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); + String yes = StringUtil.localize("yes"); + String no = StringUtil.localize("no"); - String yes = StringUtil.localize("yes"); - String no = StringUtil.localize("no"); + String diurnal0, diurnal1, nocturnal0, nocturnal1; + if (butterfly.getGenome().getNocturnal()) { + nocturnal0 = diurnal0 = yes; + } else { + nocturnal0 = butterfly.getGenome().getPrimary().isNocturnal() ? yes : no; + diurnal0 = !butterfly.getGenome().getPrimary().isNocturnal() ? yes : no; + } + if (((AlleleBoolean) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.NOCTURNAL)).getValue()) { + nocturnal1 = diurnal1 = yes; + } else { + nocturnal1 = butterfly.getGenome().getSecondary().isNocturnal() ? yes : no; + diurnal1 = !butterfly.getGenome().getSecondary().isNocturnal() ? yes : no; + } - String diurnal0, diurnal1, nocturnal0, nocturnal1; - if (butterfly.getGenome().getNocturnal()) { - nocturnal0 = diurnal0 = yes; - } else { - nocturnal0 = butterfly.getGenome().getPrimary().isNocturnal() ? yes : no; - diurnal0 = !butterfly.getGenome().getPrimary().isNocturnal() ? yes : no; - } - if (((AlleleBoolean) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.NOCTURNAL)).getValue()) { - nocturnal1 = diurnal1 = yes; - } else { - nocturnal1 = butterfly.getGenome().getSecondary().isNocturnal() ? yes : no; - diurnal1 = !butterfly.getGenome().getSecondary().isNocturnal() ? yes : no; - } + textLayout.drawLine(StringUtil.localize("gui.diurnal"), COLUMN_0); + textLayout.drawLine(diurnal0, COLUMN_1, getColorCoding(false)); + textLayout.drawLine(diurnal1, COLUMN_2, getColorCoding(false)); + textLayout.newLine(); - textLayout.drawLine(StringUtil.localize("gui.diurnal"), COLUMN_0); - textLayout.drawLine(diurnal0, COLUMN_1, getColorCoding(false)); - textLayout.drawLine(diurnal1, COLUMN_2, getColorCoding(false)); - textLayout.newLine(); + textLayout.drawLine(StringUtil.localize("gui.nocturnal"), COLUMN_0); + textLayout.drawLine(nocturnal0, COLUMN_1, getColorCoding(false)); + textLayout.drawLine(nocturnal1, COLUMN_2, getColorCoding(false)); + textLayout.newLine(); - textLayout.drawLine(StringUtil.localize("gui.nocturnal"), COLUMN_0); - textLayout.drawLine(nocturnal0, COLUMN_1, getColorCoding(false)); - textLayout.drawLine(nocturnal1, COLUMN_2, getColorCoding(false)); - textLayout.newLine(); + String primary = StringUtil.readableBoolean(butterfly.getGenome().getTolerantFlyer(), yes, no); + String secondary = StringUtil.readableBoolean( + ((AlleleBoolean) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.TOLERANT_FLYER)) + .getValue(), + yes, + no); - String primary = StringUtil.readableBoolean(butterfly.getGenome().getTolerantFlyer(), yes, no); - String secondary = StringUtil.readableBoolean(((AlleleBoolean) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.TOLERANT_FLYER)).getValue(), yes, - no); + drawRow( + StringUtil.localize("gui.flyer"), + primary, + secondary, + butterfly, + EnumButterflyChromosome.TOLERANT_FLYER); + textLayout.newLine(); - drawRow(StringUtil.localize("gui.flyer"), primary, secondary, butterfly, EnumButterflyChromosome.TOLERANT_FLYER); - textLayout.newLine(); + primary = StringUtil.readableBoolean(butterfly.getGenome().getFireResist(), yes, no); + secondary = StringUtil.readableBoolean( + ((AlleleBoolean) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.FIRE_RESIST)) + .getValue(), + yes, + no); - primary = StringUtil.readableBoolean(butterfly.getGenome().getFireResist(), yes, no); - secondary = StringUtil.readableBoolean(((AlleleBoolean) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.FIRE_RESIST)).getValue(), yes, - no); + drawRow( + StringUtil.localize("gui.fireresist"), + primary, + secondary, + butterfly, + EnumButterflyChromosome.FIRE_RESIST); - drawRow(StringUtil.localize("gui.fireresist"), primary, secondary, butterfly, EnumButterflyChromosome.FIRE_RESIST); + textLayout.endPage(); + } - textLayout.endPage(); - } + private void drawAnalyticsPage3(IButterfly butterfly) { - private void drawAnalyticsPage3(IButterfly butterfly) { + textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); - textLayout.startPage(COLUMN_0, COLUMN_1, COLUMN_2); + textLayout.drawLine(StringUtil.localize("gui.loot.butterfly") + ":", COLUMN_0); + textLayout.newLine(); - textLayout.drawLine(StringUtil.localize("gui.loot.butterfly") + ":", COLUMN_0); - textLayout.newLine(); + int x = COLUMN_0; + for (ItemStack stack : + butterfly.getGenome().getPrimary().getButterflyLoot().keySet()) { + itemRender.renderItemIntoGUI( + fontRendererObj, mc.renderEngine, stack, guiLeft + x, guiTop + textLayout.getLineY()); + x += 18; + if (x > 148) { + x = COLUMN_0; + textLayout.newLine(); + } + } - int x = COLUMN_0; - for (ItemStack stack : butterfly.getGenome().getPrimary().getButterflyLoot().keySet()) { - itemRender.renderItemIntoGUI(fontRendererObj, mc.renderEngine, stack, guiLeft + x, guiTop + textLayout.getLineY()); - x += 18; - if (x > 148) { - x = COLUMN_0; - textLayout.newLine(); - } - } + textLayout.newLine(); + textLayout.newLine(); - textLayout.newLine(); - textLayout.newLine(); + textLayout.drawLine(StringUtil.localize("gui.loot.caterpillar") + ":", COLUMN_0); + textLayout.newLine(); - textLayout.drawLine(StringUtil.localize("gui.loot.caterpillar") + ":", COLUMN_0); - textLayout.newLine(); + x = COLUMN_0; + for (ItemStack stack : + butterfly.getGenome().getPrimary().getCaterpillarLoot().keySet()) { + itemRender.renderItemIntoGUI( + fontRendererObj, mc.renderEngine, stack, guiLeft + x, guiTop + textLayout.getLineY()); + x += 18; + if (x > 148) { + x = COLUMN_0; + textLayout.newLine(); + } + } - x = COLUMN_0; - for (ItemStack stack : butterfly.getGenome().getPrimary().getCaterpillarLoot().keySet()) { - itemRender.renderItemIntoGUI(fontRendererObj, mc.renderEngine, stack, guiLeft + x, guiTop + textLayout.getLineY()); - x += 18; - if (x > 148) { - x = COLUMN_0; - textLayout.newLine(); - } - } - - textLayout.endPage(); - } + textLayout.endPage(); + } } diff --git a/src/main/java/forestry/lepidopterology/inventory/ItemInventoryFlutterlyzer.java b/src/main/java/forestry/lepidopterology/inventory/ItemInventoryFlutterlyzer.java index 1b9d3d6fe..d5a461e7e 100644 --- a/src/main/java/forestry/lepidopterology/inventory/ItemInventoryFlutterlyzer.java +++ b/src/main/java/forestry/lepidopterology/inventory/ItemInventoryFlutterlyzer.java @@ -1,34 +1,32 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.inventory; - -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.api.lepidopterology.ButterflyManager; -import forestry.core.config.Config; -import forestry.core.gui.IHintSource; -import forestry.core.inventory.ItemInventoryAlyzer; - -public class ItemInventoryFlutterlyzer extends ItemInventoryAlyzer implements IHintSource { - - public ItemInventoryFlutterlyzer(EntityPlayer player, ItemStack itemStack) { - super(ButterflyManager.butterflyRoot, player, itemStack); - } - - /* IHintSource */ - @Override - public List getHints() { - return Config.hints.get("flutterlyzer"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.inventory; + +import forestry.api.lepidopterology.ButterflyManager; +import forestry.core.config.Config; +import forestry.core.gui.IHintSource; +import forestry.core.inventory.ItemInventoryAlyzer; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class ItemInventoryFlutterlyzer extends ItemInventoryAlyzer implements IHintSource { + + public ItemInventoryFlutterlyzer(EntityPlayer player, ItemStack itemStack) { + super(ButterflyManager.butterflyRoot, player, itemStack); + } + + /* IHintSource */ + @Override + public List getHints() { + return Config.hints.get("flutterlyzer"); + } +} diff --git a/src/main/java/forestry/lepidopterology/items/ItemButterflyGE.java b/src/main/java/forestry/lepidopterology/items/ItemButterflyGE.java index a1cb0f79a..3952314ed 100755 --- a/src/main/java/forestry/lepidopterology/items/ItemButterflyGE.java +++ b/src/main/java/forestry/lepidopterology/items/ItemButterflyGE.java @@ -10,22 +10,8 @@ ******************************************************************************/ package forestry.lepidopterology.items; -import java.util.List; -import java.util.Random; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.core.Tabs; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAlleleSpecies; @@ -43,203 +29,241 @@ import forestry.core.utils.EntityUtil; import forestry.lepidopterology.entities.EntityButterfly; import forestry.lepidopterology.genetics.ButterflyGenome; import forestry.plugins.PluginLepidopterology; +import java.util.List; +import java.util.Random; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; public class ItemButterflyGE extends ItemGE { - private static final Random rand = new Random(); + private static final Random rand = new Random(); - private final EnumFlutterType type; + private final EnumFlutterType type; - public ItemButterflyGE(EnumFlutterType type) { - super(Tabs.tabLepidopterology); - this.type = type; - } + public ItemButterflyGE(EnumFlutterType type) { + super(Tabs.tabLepidopterology); + this.type = type; + } - @Override - protected int getDefaultPrimaryColour() { - return 0; - } + @Override + protected int getDefaultPrimaryColour() { + return 0; + } - @Override - protected int getDefaultSecondaryColour() { - return 0; - } + @Override + protected int getDefaultSecondaryColour() { + return 0; + } - @Override - public IButterfly getIndividual(ItemStack itemstack) { - return ButterflyManager.butterflyRoot.getMember(itemstack); - } + @Override + public IButterfly getIndividual(ItemStack itemstack) { + return ButterflyManager.butterflyRoot.getMember(itemstack); + } - @Override - protected IAlleleSpecies getSpecies(ItemStack itemStack) { - return ButterflyGenome.getSpecies(itemStack); - } + @Override + protected IAlleleSpecies getSpecies(ItemStack itemStack) { + return ButterflyGenome.getSpecies(itemStack); + } - @Override - public String getItemStackDisplayName(ItemStack itemstack) { + @Override + public String getItemStackDisplayName(ItemStack itemstack) { - if (itemstack.getTagCompound() == null) { - return "???"; - } + if (itemstack.getTagCompound() == null) { + return "???"; + } - IButterfly butterfly = ButterflyManager.butterflyRoot.getMember(itemstack); - if (butterfly == null) { - return "???"; - } + IButterfly butterfly = ButterflyManager.butterflyRoot.getMember(itemstack); + if (butterfly == null) { + return "???"; + } - return butterfly.getDisplayName(); - } + return butterfly.getDisplayName(); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - addCreativeItems(itemList, true); - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + addCreativeItems(itemList, true); + } - public void addCreativeItems(List itemList, boolean hideSecrets) { + public void addCreativeItems(List itemList, boolean hideSecrets) { - for (IIndividual individual : ButterflyManager.butterflyRoot.getIndividualTemplates()) { - // Don't show secret butterflies unless ordered to. - if (hideSecrets && individual.isSecret() && !Config.isDebug) { - continue; - } + for (IIndividual individual : ButterflyManager.butterflyRoot.getIndividualTemplates()) { + // Don't show secret butterflies unless ordered to. + if (hideSecrets && individual.isSecret() && !Config.isDebug) { + continue; + } - itemList.add(ButterflyManager.butterflyRoot.getMemberStack(individual, type.ordinal())); - } - } + itemList.add(ButterflyManager.butterflyRoot.getMemberStack(individual, type.ordinal())); + } + } - @Override - public boolean onEntityItemUpdate(EntityItem entityItem) { - if (type != EnumFlutterType.BUTTERFLY) { - return false; - } - if (entityItem.worldObj.isRemote || entityItem.ticksExisted < 80) { - return false; - } - if (rand.nextInt(24) != 0) { - return false; - } + @Override + public boolean onEntityItemUpdate(EntityItem entityItem) { + if (type != EnumFlutterType.BUTTERFLY) { + return false; + } + if (entityItem.worldObj.isRemote || entityItem.ticksExisted < 80) { + return false; + } + if (rand.nextInt(24) != 0) { + return false; + } - IButterfly butterfly = ButterflyManager.butterflyRoot.getMember(entityItem.getEntityItem()); - if (butterfly == null) { - return false; - } + IButterfly butterfly = ButterflyManager.butterflyRoot.getMember(entityItem.getEntityItem()); + if (butterfly == null) { + return false; + } - if (!butterfly.canTakeFlight(entityItem.worldObj, entityItem.posX, entityItem.posY, entityItem.posZ)) { - return false; - } + if (!butterfly.canTakeFlight(entityItem.worldObj, entityItem.posX, entityItem.posY, entityItem.posZ)) { + return false; + } - if (entityItem.worldObj.countEntities(EntityButterfly.class) > PluginLepidopterology.entityConstraint) { - return false; - } + if (entityItem.worldObj.countEntities(EntityButterfly.class) > PluginLepidopterology.entityConstraint) { + return false; + } - if (EntityUtil.spawnEntity(entityItem.worldObj, new EntityButterfly(entityItem.worldObj, butterfly, (int)entityItem.posX, (int)entityItem.posY, (int)entityItem.posZ), entityItem.posX, entityItem.posY, entityItem.posZ) != null) { - if (entityItem.getEntityItem().stackSize > 1) { - entityItem.getEntityItem().stackSize--; - } else { - entityItem.setDead(); - } - return true; - } + if (EntityUtil.spawnEntity( + entityItem.worldObj, + new EntityButterfly( + entityItem.worldObj, butterfly, (int) entityItem.posX, (int) entityItem.posY, (int) + entityItem.posZ), + entityItem.posX, + entityItem.posY, + entityItem.posZ) + != null) { + if (entityItem.getEntityItem().stackSize > 1) { + entityItem.getEntityItem().stackSize--; + } else { + entityItem.setDead(); + } + return true; + } - return false; - } + return false; + } - /* ICONS FOR SERUMS */ - @Override - public int getColorFromItemStack(ItemStack itemstack, int renderPass) { - if (!itemstack.hasTagCompound()) { - return super.getColorFromItemStack(itemstack, renderPass); - } + /* ICONS FOR SERUMS */ + @Override + public int getColorFromItemStack(ItemStack itemstack, int renderPass) { + if (!itemstack.hasTagCompound()) { + return super.getColorFromItemStack(itemstack, renderPass); + } - return getColourFromSpecies(AlleleManager.alleleRegistry.getIndividual(itemstack).getGenome().getPrimary(), renderPass); - } + return getColourFromSpecies( + AlleleManager.alleleRegistry + .getIndividual(itemstack) + .getGenome() + .getPrimary(), + renderPass); + } - @Override - public int getColourFromSpecies(IAlleleSpecies species, int renderPass) { - if (species != null) { - return species.getIconColour(renderPass); - } else { - return 0xffffff; - } + @Override + public int getColourFromSpecies(IAlleleSpecies species, int renderPass) { + if (species != null) { + return species.getIconColour(renderPass); + } else { + return 0xffffff; + } + } - } + @Override + public boolean requiresMultipleRenderPasses() { + return true; + } - @Override - public boolean requiresMultipleRenderPasses() { - return true; - } + @Override + public int getRenderPasses(int metadata) { + return 2; + } - @Override - public int getRenderPasses(int metadata) { - return 2; - } + /* ICONS */ + @SideOnly(Side.CLIENT) + private IIcon[] icons; - /* ICONS */ - @SideOnly(Side.CLIENT) - private IIcon[] icons; + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + icons = new IIcon[2]; + switch (this.type) { + case CATERPILLAR: + icons[0] = TextureManager.registerTex(register, "caterpillar.body"); + icons[1] = TextureManager.registerTex(register, "caterpillar.body2"); + break; + default: + icons[0] = TextureManager.registerTex(register, "liquids/jar.contents"); + icons[1] = TextureManager.registerTex(register, "liquids/jar.bottle"); + } + } - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - icons = new IIcon[2]; - switch (this.type) { - case CATERPILLAR: - icons[0] = TextureManager.registerTex(register, "caterpillar.body"); - icons[1] = TextureManager.registerTex(register, "caterpillar.body2"); - break; - default: - icons[0] = TextureManager.registerTex(register, "liquids/jar.contents"); - icons[1] = TextureManager.registerTex(register, "liquids/jar.bottle"); - } - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamageForRenderPass(int i, int j) { + if (j > 0) { + return icons[1]; + } else { + return icons[0]; + } + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamageForRenderPass(int i, int j) { - if (j > 0) { - return icons[1]; - } else { - return icons[0]; - } - } + @Override + public boolean onItemUse( + ItemStack itemstack, + EntityPlayer player, + World world, + int x, + int y, + int z, + int par7, + float facingX, + float facingY, + float facingZ) { - @Override - public boolean onItemUse(ItemStack itemstack, EntityPlayer player, World world, int x, int y, int z, int par7, float facingX, float facingY, float facingZ) { + if (world.isRemote) { + return false; + } - if (world.isRemote) { - return false; - } + IButterfly flutter = ButterflyManager.butterflyRoot.getMember(itemstack); + if (flutter == null) { + return false; + } - IButterfly flutter = ButterflyManager.butterflyRoot.getMember(itemstack); - if (flutter == null) { - return false; - } + if (type == EnumFlutterType.CATERPILLAR) { - if (type == EnumFlutterType.CATERPILLAR) { + TileEntity target = world.getTileEntity(x, y, z); + if (!(target instanceof IButterflyNursery)) { + return false; + } - TileEntity target = world.getTileEntity(x, y, z); - if (!(target instanceof IButterflyNursery)) { - return false; - } - - IButterflyNursery pollinatable = (IButterflyNursery) target; - if (!pollinatable.canNurse(flutter)) { - return false; - } - - pollinatable.setCaterpillar(flutter); - Proxies.common.sendFXSignal(PacketFXSignal.VisualFXType.BLOCK_DESTROY, PacketFXSignal.SoundFXType.LEAF, world, x, y, z, - world.getBlock(x, y, z), 0); - if (!player.capabilities.isCreativeMode) { - itemstack.stackSize--; - } - return true; - - } else { - return false; - } - } + IButterflyNursery pollinatable = (IButterflyNursery) target; + if (!pollinatable.canNurse(flutter)) { + return false; + } + pollinatable.setCaterpillar(flutter); + Proxies.common.sendFXSignal( + PacketFXSignal.VisualFXType.BLOCK_DESTROY, + PacketFXSignal.SoundFXType.LEAF, + world, + x, + y, + z, + world.getBlock(x, y, z), + 0); + if (!player.capabilities.isCreativeMode) { + itemstack.stackSize--; + } + return true; + } else { + return false; + } + } } diff --git a/src/main/java/forestry/lepidopterology/items/ItemFlutterlyzer.java b/src/main/java/forestry/lepidopterology/items/ItemFlutterlyzer.java index 8245ab483..4a21a92f4 100644 --- a/src/main/java/forestry/lepidopterology/items/ItemFlutterlyzer.java +++ b/src/main/java/forestry/lepidopterology/items/ItemFlutterlyzer.java @@ -1,36 +1,35 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.items; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.api.core.Tabs; -import forestry.core.gui.ContainerAlyzer; -import forestry.core.items.ItemWithGui; -import forestry.lepidopterology.gui.GuiFlutterlyzer; -import forestry.lepidopterology.inventory.ItemInventoryFlutterlyzer; - -public class ItemFlutterlyzer extends ItemWithGui { - public ItemFlutterlyzer() { - setCreativeTab(Tabs.tabLepidopterology); - } - - @Override - public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { - return new GuiFlutterlyzer(player, new ItemInventoryFlutterlyzer(player, heldItem)); - } - - @Override - public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { - return new ContainerAlyzer(new ItemInventoryFlutterlyzer(player, heldItem), player); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.items; + +import forestry.api.core.Tabs; +import forestry.core.gui.ContainerAlyzer; +import forestry.core.items.ItemWithGui; +import forestry.lepidopterology.gui.GuiFlutterlyzer; +import forestry.lepidopterology.inventory.ItemInventoryFlutterlyzer; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class ItemFlutterlyzer extends ItemWithGui { + public ItemFlutterlyzer() { + setCreativeTab(Tabs.tabLepidopterology); + } + + @Override + public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { + return new GuiFlutterlyzer(player, new ItemInventoryFlutterlyzer(player, heldItem)); + } + + @Override + public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { + return new ContainerAlyzer(new ItemInventoryFlutterlyzer(player, heldItem), player); + } +} diff --git a/src/main/java/forestry/lepidopterology/items/ItemRegistryLepidopterology.java b/src/main/java/forestry/lepidopterology/items/ItemRegistryLepidopterology.java index a8972166c..541b6a268 100644 --- a/src/main/java/forestry/lepidopterology/items/ItemRegistryLepidopterology.java +++ b/src/main/java/forestry/lepidopterology/items/ItemRegistryLepidopterology.java @@ -1,28 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.lepidopterology.items; - -import forestry.api.lepidopterology.EnumFlutterType; -import forestry.core.items.ItemRegistry; - -public class ItemRegistryLepidopterology extends ItemRegistry { - public final ItemFlutterlyzer flutterlyzer; - public final ItemButterflyGE butterflyGE; - public final ItemButterflyGE serumGE; - public final ItemButterflyGE caterpillarGE; - - public ItemRegistryLepidopterology() { - flutterlyzer = registerItem(new ItemFlutterlyzer(), "flutterlyzer"); - butterflyGE = registerItem(new ItemButterflyGE(EnumFlutterType.BUTTERFLY), "butterflyGE"); - serumGE = registerItem(new ItemButterflyGE(EnumFlutterType.SERUM), "serumGE"); - caterpillarGE = registerItem(new ItemButterflyGE(EnumFlutterType.CATERPILLAR), "caterpillarGE"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.lepidopterology.items; + +import forestry.api.lepidopterology.EnumFlutterType; +import forestry.core.items.ItemRegistry; + +public class ItemRegistryLepidopterology extends ItemRegistry { + public final ItemFlutterlyzer flutterlyzer; + public final ItemButterflyGE butterflyGE; + public final ItemButterflyGE serumGE; + public final ItemButterflyGE caterpillarGE; + + public ItemRegistryLepidopterology() { + flutterlyzer = registerItem(new ItemFlutterlyzer(), "flutterlyzer"); + butterflyGE = registerItem(new ItemButterflyGE(EnumFlutterType.BUTTERFLY), "butterflyGE"); + serumGE = registerItem(new ItemButterflyGE(EnumFlutterType.SERUM), "serumGE"); + caterpillarGE = registerItem(new ItemButterflyGE(EnumFlutterType.CATERPILLAR), "caterpillarGE"); + } +} diff --git a/src/main/java/forestry/lepidopterology/proxy/ProxyLepidopterology.java b/src/main/java/forestry/lepidopterology/proxy/ProxyLepidopterology.java index e8014caf8..e799dfea6 100755 --- a/src/main/java/forestry/lepidopterology/proxy/ProxyLepidopterology.java +++ b/src/main/java/forestry/lepidopterology/proxy/ProxyLepidopterology.java @@ -12,6 +12,5 @@ package forestry.lepidopterology.proxy; public class ProxyLepidopterology { - public void initializeRendering() { - } + public void initializeRendering() {} } diff --git a/src/main/java/forestry/lepidopterology/proxy/ProxyLepidopterologyClient.java b/src/main/java/forestry/lepidopterology/proxy/ProxyLepidopterologyClient.java index d294508f4..679e1ff0e 100644 --- a/src/main/java/forestry/lepidopterology/proxy/ProxyLepidopterologyClient.java +++ b/src/main/java/forestry/lepidopterology/proxy/ProxyLepidopterologyClient.java @@ -10,20 +10,18 @@ ******************************************************************************/ package forestry.lepidopterology.proxy; -import net.minecraftforge.client.MinecraftForgeClient; - import cpw.mods.fml.client.registry.RenderingRegistry; - import forestry.lepidopterology.entities.EntityButterfly; import forestry.lepidopterology.render.RenderButterflyEntity; import forestry.lepidopterology.render.RenderButterflyItem; import forestry.plugins.PluginLepidopterology; +import net.minecraftforge.client.MinecraftForgeClient; public class ProxyLepidopterologyClient extends ProxyLepidopterology { - @Override - public void initializeRendering() { - RenderingRegistry.registerEntityRenderingHandler(EntityButterfly.class, new RenderButterflyEntity()); - MinecraftForgeClient.registerItemRenderer(PluginLepidopterology.items.butterflyGE, new RenderButterflyItem()); - } + @Override + public void initializeRendering() { + RenderingRegistry.registerEntityRenderingHandler(EntityButterfly.class, new RenderButterflyEntity()); + MinecraftForgeClient.registerItemRenderer(PluginLepidopterology.items.butterflyGE, new RenderButterflyItem()); + } } diff --git a/src/main/java/forestry/lepidopterology/recipes/MatingRecipe.java b/src/main/java/forestry/lepidopterology/recipes/MatingRecipe.java index e6bb545d9..27c20fab0 100644 --- a/src/main/java/forestry/lepidopterology/recipes/MatingRecipe.java +++ b/src/main/java/forestry/lepidopterology/recipes/MatingRecipe.java @@ -10,76 +10,79 @@ ******************************************************************************/ package forestry.lepidopterology.recipes; +import forestry.api.lepidopterology.ButterflyManager; +import forestry.api.lepidopterology.EnumFlutterType; +import forestry.api.lepidopterology.IButterfly; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.World; -import forestry.api.lepidopterology.ButterflyManager; -import forestry.api.lepidopterology.EnumFlutterType; -import forestry.api.lepidopterology.IButterfly; - public class MatingRecipe implements IRecipe { - private final ItemStack unknown; - private ItemStack cached; - - public MatingRecipe() { - unknown = ButterflyManager.butterflyRoot.getMemberStack(ButterflyManager.butterflyRoot.getIndividualTemplates().get(0), EnumFlutterType.BUTTERFLY.ordinal()); - } - - @Override - public boolean matches(InventoryCrafting crafting, World world) { - - boolean mated = true; - int butterflies = 0; - int sera = 0; - - for (int i = 0; i < crafting.getSizeInventory(); i++) { - if (ButterflyManager.butterflyRoot.isMember(crafting.getStackInSlot(i), EnumFlutterType.BUTTERFLY.ordinal())) { - butterflies++; - mated = ButterflyManager.butterflyRoot.isMated(crafting.getStackInSlot(i)); - cached = crafting.getStackInSlot(i); - } else if (ButterflyManager.butterflyRoot.isMember(crafting.getStackInSlot(i), EnumFlutterType.SERUM.ordinal())) { - sera++; - } - } - - return !mated && butterflies == 1 && sera == 1; - } + private final ItemStack unknown; + private ItemStack cached; - @Override - public ItemStack getRecipeOutput() { - if (cached != null) { - return cached; - } else { - return unknown; - } - } + public MatingRecipe() { + unknown = ButterflyManager.butterflyRoot.getMemberStack( + ButterflyManager.butterflyRoot.getIndividualTemplates().get(0), EnumFlutterType.BUTTERFLY.ordinal()); + } - @Override - public ItemStack getCraftingResult(InventoryCrafting crafting) { - IButterfly butterfly = null; - IButterfly serum = null; - for (int i = 0; i < crafting.getSizeInventory(); i++) { - if (ButterflyManager.butterflyRoot.isMember(crafting.getStackInSlot(i), EnumFlutterType.BUTTERFLY.ordinal())) { - butterfly = ButterflyManager.butterflyRoot.getMember(crafting.getStackInSlot(i)); - } else if (ButterflyManager.butterflyRoot.isMember(crafting.getStackInSlot(i), EnumFlutterType.SERUM.ordinal())) { - serum = ButterflyManager.butterflyRoot.getMember(crafting.getStackInSlot(i)); - } - } - if (butterfly == null || serum == null) { - return null; - } - - IButterfly mated = butterfly.copy(); - mated.mate(serum); - return ButterflyManager.butterflyRoot.getMemberStack(mated, EnumFlutterType.BUTTERFLY.ordinal()); - } + @Override + public boolean matches(InventoryCrafting crafting, World world) { - @Override - public int getRecipeSize() { - return 2; - } + boolean mated = true; + int butterflies = 0; + int sera = 0; + for (int i = 0; i < crafting.getSizeInventory(); i++) { + if (ButterflyManager.butterflyRoot.isMember( + crafting.getStackInSlot(i), EnumFlutterType.BUTTERFLY.ordinal())) { + butterflies++; + mated = ButterflyManager.butterflyRoot.isMated(crafting.getStackInSlot(i)); + cached = crafting.getStackInSlot(i); + } else if (ButterflyManager.butterflyRoot.isMember( + crafting.getStackInSlot(i), EnumFlutterType.SERUM.ordinal())) { + sera++; + } + } + + return !mated && butterflies == 1 && sera == 1; + } + + @Override + public ItemStack getRecipeOutput() { + if (cached != null) { + return cached; + } else { + return unknown; + } + } + + @Override + public ItemStack getCraftingResult(InventoryCrafting crafting) { + IButterfly butterfly = null; + IButterfly serum = null; + for (int i = 0; i < crafting.getSizeInventory(); i++) { + if (ButterflyManager.butterflyRoot.isMember( + crafting.getStackInSlot(i), EnumFlutterType.BUTTERFLY.ordinal())) { + butterfly = ButterflyManager.butterflyRoot.getMember(crafting.getStackInSlot(i)); + } else if (ButterflyManager.butterflyRoot.isMember( + crafting.getStackInSlot(i), EnumFlutterType.SERUM.ordinal())) { + serum = ButterflyManager.butterflyRoot.getMember(crafting.getStackInSlot(i)); + } + } + if (butterfly == null || serum == null) { + return null; + } + + IButterfly mated = butterfly.copy(); + mated.mate(serum); + return ButterflyManager.butterflyRoot.getMemberStack(mated, EnumFlutterType.BUTTERFLY.ordinal()); + } + + @Override + public int getRecipeSize() { + return 2; + } } diff --git a/src/main/java/forestry/lepidopterology/render/ModelButterfly.java b/src/main/java/forestry/lepidopterology/render/ModelButterfly.java index e8371c0b8..e344c8fc7 100755 --- a/src/main/java/forestry/lepidopterology/render/ModelButterfly.java +++ b/src/main/java/forestry/lepidopterology/render/ModelButterfly.java @@ -14,89 +14,86 @@ import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; - import org.lwjgl.opengl.GL11; public class ModelButterfly extends ModelBase { - private final ModelRenderer wingRight; - private final ModelRenderer eyeRight; - private final ModelRenderer eyeLeft; - private final ModelRenderer wingLeft; - private final ModelRenderer body; + private final ModelRenderer wingRight; + private final ModelRenderer eyeRight; + private final ModelRenderer eyeLeft; + private final ModelRenderer wingLeft; + private final ModelRenderer body; - private float scale; + private float scale; - public ModelButterfly() { - textureWidth = 64; - textureHeight = 32; + public ModelButterfly() { + textureWidth = 64; + textureHeight = 32; - wingRight = new ModelRenderer(this, 0, 0); - wingRight.addBox(-7F, 0F, -6F, 7, 1, 13); - wingRight.setRotationPoint(-0.5F, 0.5F, 0F); - wingRight.setTextureSize(64, 32); - wingRight.mirror = true; - setRotation(wingRight, 0F, 0F, 0F); - eyeRight = new ModelRenderer(this, 40, 9); - eyeRight.addBox(0F, 0F, 0F, 1, 1, 1); - eyeRight.setRotationPoint(-1.1F, -0.5F, -4.5F); - eyeRight.setTextureSize(64, 32); - eyeRight.mirror = true; - setRotation(eyeRight, 0F, 0F, 0F); - eyeLeft = new ModelRenderer(this, 40, 7); - eyeLeft.addBox(0F, 0F, 0F, 1, 1, 1); - eyeLeft.setRotationPoint(0.1F, -0.5F, -4.5F); - eyeLeft.setTextureSize(64, 32); - eyeLeft.mirror = true; - setRotation(eyeLeft, 0F, 0F, 0F); - wingLeft = new ModelRenderer(this, 0, 14); - wingLeft.addBox(0F, 0F, -6F, 7, 1, 13); - wingLeft.setRotationPoint(0.5F, 0.5F, 0F); - wingLeft.setTextureSize(64, 32); - wingLeft.mirror = true; - setRotation(wingLeft, 0F, 0F, 0F); - body = new ModelRenderer(this, 40, 0); - body.addBox(0F, 0F, -4F, 1, 1, 6); - body.setRotationPoint(0F, 0F, 0F); - body.setTextureSize(64, 32); - body.mirror = true; - setRotation(body, 0F, 0F, 0.7853982F); - } + wingRight = new ModelRenderer(this, 0, 0); + wingRight.addBox(-7F, 0F, -6F, 7, 1, 13); + wingRight.setRotationPoint(-0.5F, 0.5F, 0F); + wingRight.setTextureSize(64, 32); + wingRight.mirror = true; + setRotation(wingRight, 0F, 0F, 0F); + eyeRight = new ModelRenderer(this, 40, 9); + eyeRight.addBox(0F, 0F, 0F, 1, 1, 1); + eyeRight.setRotationPoint(-1.1F, -0.5F, -4.5F); + eyeRight.setTextureSize(64, 32); + eyeRight.mirror = true; + setRotation(eyeRight, 0F, 0F, 0F); + eyeLeft = new ModelRenderer(this, 40, 7); + eyeLeft.addBox(0F, 0F, 0F, 1, 1, 1); + eyeLeft.setRotationPoint(0.1F, -0.5F, -4.5F); + eyeLeft.setTextureSize(64, 32); + eyeLeft.mirror = true; + setRotation(eyeLeft, 0F, 0F, 0F); + wingLeft = new ModelRenderer(this, 0, 14); + wingLeft.addBox(0F, 0F, -6F, 7, 1, 13); + wingLeft.setRotationPoint(0.5F, 0.5F, 0F); + wingLeft.setTextureSize(64, 32); + wingLeft.mirror = true; + setRotation(wingLeft, 0F, 0F, 0F); + body = new ModelRenderer(this, 40, 0); + body.addBox(0F, 0F, -4F, 1, 1, 6); + body.setRotationPoint(0F, 0F, 0F); + body.setTextureSize(64, 32); + body.mirror = true; + setRotation(body, 0F, 0F, 0.7853982F); + } - public void setScale(float scale) { - this.scale = scale; - } + public void setScale(float scale) { + this.scale = scale; + } - @Override - public void render(Entity entity, float f, float f1, float swing, float f3, float f4, float f5) { - super.render(entity, f, f1, swing, f3, f4, f5); + @Override + public void render(Entity entity, float f, float f1, float swing, float f3, float f4, float f5) { + super.render(entity, f, f1, swing, f3, f4, f5); - //body.rotateAngleX = ((float)Math.PI / 4F) + MathHelper.cos(swing * 0.1F) * 0.15F; - //body.rotateAngleY = 0.0F; - wingRight.rotateAngleZ = MathHelper.cos(swing * 1.3F) * (float) Math.PI * 0.25F; - wingLeft.rotateAngleZ = -wingRight.rotateAngleZ; + // body.rotateAngleX = ((float)Math.PI / 4F) + MathHelper.cos(swing * 0.1F) * 0.15F; + // body.rotateAngleY = 0.0F; + wingRight.rotateAngleZ = MathHelper.cos(swing * 1.3F) * (float) Math.PI * 0.25F; + wingLeft.rotateAngleZ = -wingRight.rotateAngleZ; - GL11.glPushMatrix(); - GL11.glScalef(scale, scale, scale); - GL11.glTranslatef(0.0F, (20.0f / scale) * f5, 0.0F); - wingRight.render(f5); - eyeRight.render(f5); - eyeLeft.render(f5); - wingLeft.render(f5); - body.render(f5); - GL11.glPopMatrix(); + GL11.glPushMatrix(); + GL11.glScalef(scale, scale, scale); + GL11.glTranslatef(0.0F, (20.0f / scale) * f5, 0.0F); + wingRight.render(f5); + eyeRight.render(f5); + eyeLeft.render(f5); + wingLeft.render(f5); + body.render(f5); + GL11.glPopMatrix(); + } - } - - private static void setRotation(ModelRenderer model, float x, float y, float z) { - model.rotateAngleX = x; - model.rotateAngleY = y; - model.rotateAngleZ = z; - } - - @Override - public void setRotationAngles(float f, float f1, float swing, float f3, float f4, float f5, Entity entity) { - super.setRotationAngles(f, f1, swing, f3, f4, f5, entity); - } + private static void setRotation(ModelRenderer model, float x, float y, float z) { + model.rotateAngleX = x; + model.rotateAngleY = y; + model.rotateAngleZ = z; + } + @Override + public void setRotationAngles(float f, float f1, float swing, float f3, float f4, float f5, Entity entity) { + super.setRotationAngles(f, f1, swing, f3, f4, f5, entity); + } } diff --git a/src/main/java/forestry/lepidopterology/render/RenderButterflyEntity.java b/src/main/java/forestry/lepidopterology/render/RenderButterflyEntity.java index 22e505af1..8f261b512 100644 --- a/src/main/java/forestry/lepidopterology/render/RenderButterflyEntity.java +++ b/src/main/java/forestry/lepidopterology/render/RenderButterflyEntity.java @@ -10,44 +10,43 @@ ******************************************************************************/ package forestry.lepidopterology.render; +import forestry.lepidopterology.entities.EntityButterfly; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.ResourceLocation; -import forestry.lepidopterology.entities.EntityButterfly; - public class RenderButterflyEntity extends RenderLiving { - private final ModelButterfly butterflyModel; + private final ModelButterfly butterflyModel; - public RenderButterflyEntity() { - super(new ModelButterfly(), 0.25f); - butterflyModel = (ModelButterfly) mainModel; - } + public RenderButterflyEntity() { + super(new ModelButterfly(), 0.25f); + butterflyModel = (ModelButterfly) mainModel; + } - private void renderButterfly(EntityButterfly entity, double x, double y, double z, float light, float partialTickTime) { - if (!entity.isRenderable()) { - return; - } + private void renderButterfly( + EntityButterfly entity, double x, double y, double z, float light, float partialTickTime) { + if (!entity.isRenderable()) { + return; + } - butterflyModel.setScale(entity.getSize()); - super.doRender(entity, x, y, z, light, partialTickTime); - } + butterflyModel.setScale(entity.getSize()); + super.doRender(entity, x, y, z, light, partialTickTime); + } - @Override - public void doRender(Entity entity, double x, double y, double z, float light, float partialTickTime) { - this.renderButterfly((EntityButterfly) entity, x, y, z, light, partialTickTime); - } + @Override + public void doRender(Entity entity, double x, double y, double z, float light, float partialTickTime) { + this.renderButterfly((EntityButterfly) entity, x, y, z, light, partialTickTime); + } - @Override - protected ResourceLocation getEntityTexture(Entity entity) { - return ((EntityButterfly) entity).getTexture(); - } - - @Override - protected float handleRotationFloat(EntityLivingBase entity, float partialTickTime) { - return ((EntityButterfly) entity).getWingFlap(partialTickTime); - } + @Override + protected ResourceLocation getEntityTexture(Entity entity) { + return ((EntityButterfly) entity).getTexture(); + } + @Override + protected float handleRotationFloat(EntityLivingBase entity, float partialTickTime) { + return ((EntityButterfly) entity).getWingFlap(partialTickTime); + } } diff --git a/src/main/java/forestry/lepidopterology/render/RenderButterflyItem.java b/src/main/java/forestry/lepidopterology/render/RenderButterflyItem.java index fe1dd0a65..89040a21f 100644 --- a/src/main/java/forestry/lepidopterology/render/RenderButterflyItem.java +++ b/src/main/java/forestry/lepidopterology/render/RenderButterflyItem.java @@ -10,215 +10,208 @@ ******************************************************************************/ package forestry.lepidopterology.render; +import forestry.api.lepidopterology.ButterflyManager; +import forestry.api.lepidopterology.IButterfly; +import forestry.core.proxy.Proxies; +import forestry.lepidopterology.entities.EntityButterfly; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.item.ItemStack; - import net.minecraftforge.client.IItemRenderer; - import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import forestry.api.lepidopterology.ButterflyManager; -import forestry.api.lepidopterology.IButterfly; -import forestry.core.proxy.Proxies; -import forestry.lepidopterology.entities.EntityButterfly; - public class RenderButterflyItem implements IItemRenderer { - private final ModelButterfly model; - private EntityButterfly entity; - - public RenderButterflyItem() { - model = new ModelButterfly(); - } - - private static float getWingYaw(IButterfly butterfly) { - float wingYaw = 1f; + private final ModelButterfly model; + private EntityButterfly entity; - if (butterfly.isAlive()) { - long systemTime = System.currentTimeMillis(); - long flapping = systemTime + butterfly.getIdent().hashCode(); - float flap = (float) (flapping % 1024) / 1024; // 0 to 1 + public RenderButterflyItem() { + model = new ModelButterfly(); + } - wingYaw = getIrregularWingYaw(flapping, flap); + private static float getWingYaw(IButterfly butterfly) { + float wingYaw = 1f; - } + if (butterfly.isAlive()) { + long systemTime = System.currentTimeMillis(); + long flapping = systemTime + butterfly.getIdent().hashCode(); + float flap = (float) (flapping % 1024) / 1024; // 0 to 1 - return wingYaw; - } - - public static float getIrregularWingYaw(long flapping, float flap) { - long irregular = flapping / 1024; - float wingYaw; - - if (irregular % 11 == 0) { - wingYaw = 0.75f; - } else { - if (irregular % 7 == 0) { - flap *= 4; - flap = flap % 1; - } else if (irregular % 19 == 0) { - flap *= 6; - flap = flap % 1; - } - wingYaw = getRegularWingYaw(flap); - } - - return wingYaw; - } - - private static float getRegularWingYaw(float flap) { - return flap < 0.5 ? 0.75f + flap : 1.75f - flap; - } - - private IButterfly initButterfly(ItemStack item) { - IButterfly butterfly = ButterflyManager.butterflyRoot.getMember(item); - if (butterfly == null) { - butterfly = ButterflyManager.butterflyRoot.templateAsIndividual(ButterflyManager.butterflyRoot.getDefaultTemplate()); - } - - if (entity == null) { - entity = new EntityButterfly(Proxies.common.getRenderWorld(), butterfly, 0, 0, 0); - } else { - entity.setIndividual(butterfly); - } - - return butterfly; - } - - private void renderButterflyItem(IButterfly butterfly, float translateX, float translateY, float translateZ) { - float yaw = 1; - float pitch = 1; - - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_COLOR_MATERIAL); + wingYaw = getIrregularWingYaw(flapping, flap); + } - GL11.glPushMatrix(); + return wingYaw; + } - if (RenderItem.renderInFrame) { - //GL11.glScalef(-2.0f, 2.0f, 2.0f); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F); - GL11.glRotatef(-90.0F, 1.0F, 0.0F, 0.0F); - GL11.glScalef(1.1f, 1f, 1f); + public static float getIrregularWingYaw(long flapping, float flap) { + long irregular = flapping / 1024; + float wingYaw; - GL11.glTranslatef(0, -0.7f, 0.2f); + if (irregular % 11 == 0) { + wingYaw = 0.75f; + } else { + if (irregular % 7 == 0) { + flap *= 4; + flap = flap % 1; + } else if (irregular % 19 == 0) { + flap *= 6; + flap = flap % 1; + } + wingYaw = getRegularWingYaw(flap); + } - entity.renderYawOffset = 0; - entity.rotationYaw = 0; - entity.rotationPitch = 0; - entity.rotationYawHead = entity.rotationYaw; + return wingYaw; + } - RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, 1.0f); + private static float getRegularWingYaw(float flap) { + return flap < 0.5 ? 0.75f + flap : 1.75f - flap; + } - } else { - GL11.glTranslatef(translateX, translateY, translateZ); + private IButterfly initButterfly(ItemStack item) { + IButterfly butterfly = ButterflyManager.butterflyRoot.getMember(item); + if (butterfly == null) { + butterfly = ButterflyManager.butterflyRoot.templateAsIndividual( + ButterflyManager.butterflyRoot.getDefaultTemplate()); + } - GL11.glScalef(-2.0f, 2.0f, 2.0f); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glRotatef(-135.0F, 0.0F, 1.0F, 0.0F); - GL11.glRotatef(-((float) Math.atan((double) (pitch / 40.0F))) * 20.0F, 1.0F, 0.0F, 0.0F); + if (entity == null) { + entity = new EntityButterfly(Proxies.common.getRenderWorld(), butterfly, 0, 0, 0); + } else { + entity.setIndividual(butterfly); + } - entity.renderYawOffset = (float) Math.atan((double) (yaw / 40.0F)) * 20.0F; - entity.rotationYaw = (float) Math.atan((double) (yaw / 40.0F)) * 40.0F; - entity.rotationPitch = -((float) Math.atan((double) (pitch / 40.0F))) * 20.0F; - entity.rotationYawHead = entity.rotationYaw; + return butterfly; + } - RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, getWingYaw(butterfly)); + private void renderButterflyItem(IButterfly butterfly, float translateX, float translateY, float translateZ) { + float yaw = 1; + float pitch = 1; - } + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_COLOR_MATERIAL); - GL11.glPopMatrix(); + GL11.glPushMatrix(); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GL11.glDisable(GL11.GL_TEXTURE_2D); - OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); - GL11.glPopAttrib(); + if (RenderItem.renderInFrame) { + // GL11.glScalef(-2.0f, 2.0f, 2.0f); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F); + GL11.glRotatef(-90.0F, 1.0F, 0.0F, 0.0F); + GL11.glScalef(1.1f, 1f, 1f); - } - - private void renderButterflyInInventory(IButterfly butterfly) { + GL11.glTranslatef(0, -0.7f, 0.2f); - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_COLOR_MATERIAL); - RenderHelper.enableStandardItemLighting(); - GL11.glPushMatrix(); + entity.renderYawOffset = 0; + entity.rotationYaw = 0; + entity.rotationPitch = 0; + entity.rotationYawHead = entity.rotationYaw; - GL11.glTranslatef(0f, -0.25f, 0f); - GL11.glScalef(-2.0f, 2.0f, 2.0f); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glRotatef(135.0F, 0.0F, 1.0F, 0.0F); - GL11.glRotatef(-35.0F, 1.0F, 0.0F, 0.0F); - GL11.glScalef(1.1f, 1f, 1f); + RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, 1.0f); - entity.renderYawOffset = 0; - entity.rotationYaw = 0; - entity.rotationPitch = 0; - entity.rotationYawHead = entity.rotationYaw; + } else { + GL11.glTranslatef(translateX, translateY, translateZ); - RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, getWingYaw(butterfly)); + GL11.glScalef(-2.0f, 2.0f, 2.0f); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glRotatef(-135.0F, 0.0F, 1.0F, 0.0F); + GL11.glRotatef(-((float) Math.atan((double) (pitch / 40.0F))) * 20.0F, 1.0F, 0.0F, 0.0F); - GL11.glPopMatrix(); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GL11.glDisable(GL11.GL_TEXTURE_2D); - OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); - GL11.glPopAttrib(); + entity.renderYawOffset = (float) Math.atan((double) (yaw / 40.0F)) * 20.0F; + entity.rotationYaw = (float) Math.atan((double) (yaw / 40.0F)) * 40.0F; + entity.rotationPitch = -((float) Math.atan((double) (pitch / 40.0F))) * 20.0F; + entity.rotationYawHead = entity.rotationYaw; - } - - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - switch (type) { - case ENTITY: - case EQUIPPED: - case EQUIPPED_FIRST_PERSON: - case INVENTORY: - return true; - default: - return false; - } - } + RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, getWingYaw(butterfly)); + } - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { - switch (helper) { - case ENTITY_BOBBING: - case ENTITY_ROTATION: - return false; - default: - return true; - } - } + GL11.glPopMatrix(); - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GL11.glDisable(GL11.GL_TEXTURE_2D); + OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); + GL11.glPopAttrib(); + } - switch (type) { - case ENTITY: - renderButterflyItem(initButterfly(item), 0f, -0.5f, 0f); - break; - case EQUIPPED: - renderButterflyItem(initButterfly(item), 0.5f, -0.9f, 1.0f); - break; - case EQUIPPED_FIRST_PERSON: - renderButterflyItem(initButterfly(item), 0.5f, -0.9f, 1.0f); - break; - case INVENTORY: - renderButterflyInInventory(initButterfly(item)); - break; - default: - } - } + private void renderButterflyInInventory(IButterfly butterfly) { + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_COLOR_MATERIAL); + RenderHelper.enableStandardItemLighting(); + GL11.glPushMatrix(); + + GL11.glTranslatef(0f, -0.25f, 0f); + GL11.glScalef(-2.0f, 2.0f, 2.0f); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glRotatef(135.0F, 0.0F, 1.0F, 0.0F); + GL11.glRotatef(-35.0F, 1.0F, 0.0F, 0.0F); + GL11.glScalef(1.1f, 1f, 1f); + + entity.renderYawOffset = 0; + entity.rotationYaw = 0; + entity.rotationPitch = 0; + entity.rotationYawHead = entity.rotationYaw; + + RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, getWingYaw(butterfly)); + + GL11.glPopMatrix(); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GL11.glDisable(GL11.GL_TEXTURE_2D); + OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); + GL11.glPopAttrib(); + } + + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + switch (type) { + case ENTITY: + case EQUIPPED: + case EQUIPPED_FIRST_PERSON: + case INVENTORY: + return true; + default: + return false; + } + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + switch (helper) { + case ENTITY_BOBBING: + case ENTITY_ROTATION: + return false; + default: + return true; + } + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + + switch (type) { + case ENTITY: + renderButterflyItem(initButterfly(item), 0f, -0.5f, 0f); + break; + case EQUIPPED: + renderButterflyItem(initButterfly(item), 0.5f, -0.9f, 1.0f); + break; + case EQUIPPED_FIRST_PERSON: + renderButterflyItem(initButterfly(item), 0.5f, -0.9f, 1.0f); + break; + case INVENTORY: + renderButterflyInInventory(initButterfly(item)); + break; + default: + } + } } diff --git a/src/main/java/forestry/lepidopterology/tiles/TileLepidopteristChest.java b/src/main/java/forestry/lepidopterology/tiles/TileLepidopteristChest.java index 083405cb2..b31116a45 100644 --- a/src/main/java/forestry/lepidopterology/tiles/TileLepidopteristChest.java +++ b/src/main/java/forestry/lepidopterology/tiles/TileLepidopteristChest.java @@ -14,7 +14,7 @@ import forestry.api.lepidopterology.ButterflyManager; import forestry.core.tiles.TileNaturalistChest; public class TileLepidopteristChest extends TileNaturalistChest { - public TileLepidopteristChest() { - super(ButterflyManager.butterflyRoot); - } + public TileLepidopteristChest() { + super(ButterflyManager.butterflyRoot); + } } diff --git a/src/main/java/forestry/mail/EnumDeliveryState.java b/src/main/java/forestry/mail/EnumDeliveryState.java index b038f79e7..3a84f3f9c 100755 --- a/src/main/java/forestry/mail/EnumDeliveryState.java +++ b/src/main/java/forestry/mail/EnumDeliveryState.java @@ -10,20 +10,25 @@ ******************************************************************************/ package forestry.mail; +import forestry.api.mail.IPostalState; import java.util.Locale; -import forestry.api.mail.IPostalState; - public enum EnumDeliveryState implements IPostalState { - OK, NO_MAILBOX, NOT_MAILABLE, ALREADY_MAILED, NOT_POSTPAID, MAILBOX_FULL, RESPONSE_NOT_MAILABLE; + OK, + NO_MAILBOX, + NOT_MAILABLE, + ALREADY_MAILED, + NOT_POSTPAID, + MAILBOX_FULL, + RESPONSE_NOT_MAILABLE; - @Override - public boolean isOk() { - return this == OK; - } + @Override + public boolean isOk() { + return this == OK; + } - @Override - public String getIdentifier() { - return this.toString().toLowerCase(Locale.ENGLISH); - } + @Override + public String getIdentifier() { + return this.toString().toLowerCase(Locale.ENGLISH); + } } diff --git a/src/main/java/forestry/mail/EnumStationState.java b/src/main/java/forestry/mail/EnumStationState.java index 652d1dddf..3ea45aa11 100755 --- a/src/main/java/forestry/mail/EnumStationState.java +++ b/src/main/java/forestry/mail/EnumStationState.java @@ -10,20 +10,24 @@ ******************************************************************************/ package forestry.mail; +import forestry.api.mail.IPostalState; import java.util.Locale; -import forestry.api.mail.IPostalState; - public enum EnumStationState implements IPostalState { - OK, INSUFFICIENT_OFFER, INSUFFICIENT_TRADE_GOOD, INSUFFICIENT_BUFFER, INSUFFICIENT_PAPER, INSUFFICIENT_STAMPS; + OK, + INSUFFICIENT_OFFER, + INSUFFICIENT_TRADE_GOOD, + INSUFFICIENT_BUFFER, + INSUFFICIENT_PAPER, + INSUFFICIENT_STAMPS; - @Override - public boolean isOk() { - return this == OK; - } + @Override + public boolean isOk() { + return this == OK; + } - @Override - public String getIdentifier() { - return this.toString().toLowerCase(Locale.ENGLISH); - } + @Override + public String getIdentifier() { + return this.toString().toLowerCase(Locale.ENGLISH); + } } diff --git a/src/main/java/forestry/mail/EventHandlerMailAlert.java b/src/main/java/forestry/mail/EventHandlerMailAlert.java index d03c6b168..b2eb85b69 100644 --- a/src/main/java/forestry/mail/EventHandlerMailAlert.java +++ b/src/main/java/forestry/mail/EventHandlerMailAlert.java @@ -10,39 +10,37 @@ ******************************************************************************/ package forestry.mail; -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; - import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; - import forestry.core.proxy.Proxies; import forestry.mail.gui.GuiMailboxInfo; import forestry.mail.network.packets.PacketPOBoxInfoUpdate; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; public class EventHandlerMailAlert { - @SubscribeEvent - public void onRenderTick(TickEvent.RenderTickEvent event) { - if (event.phase != Phase.END) { - return; - } + @SubscribeEvent + public void onRenderTick(TickEvent.RenderTickEvent event) { + if (event.phase != Phase.END) { + return; + } - if (Minecraft.getMinecraft().theWorld != null && GuiMailboxInfo.instance.hasPOBoxInfo()) { - GuiMailboxInfo.instance.render(); - } - } + if (Minecraft.getMinecraft().theWorld != null && GuiMailboxInfo.instance.hasPOBoxInfo()) { + GuiMailboxInfo.instance.render(); + } + } - @SubscribeEvent - public void handlePlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { - EntityPlayer player = event.player; - if (player != null) { - MailAddress address = new MailAddress(player.getGameProfile()); - POBox pobox = PostRegistry.getOrCreatePOBox(player.worldObj, address); - if (pobox != null) { - Proxies.net.sendToPlayer(new PacketPOBoxInfoUpdate(pobox.getPOBoxInfo()), player); - } - } - } + @SubscribeEvent + public void handlePlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { + EntityPlayer player = event.player; + if (player != null) { + MailAddress address = new MailAddress(player.getGameProfile()); + POBox pobox = PostRegistry.getOrCreatePOBox(player.worldObj, address); + if (pobox != null) { + Proxies.net.sendToPlayer(new PacketPOBoxInfoUpdate(pobox.getPOBoxInfo()), player); + } + } + } } diff --git a/src/main/java/forestry/mail/Letter.java b/src/main/java/forestry/mail/Letter.java index 9b6863d51..e49e03a8d 100755 --- a/src/main/java/forestry/mail/Letter.java +++ b/src/main/java/forestry/mail/Letter.java @@ -10,313 +10,310 @@ ******************************************************************************/ package forestry.mail; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import forestry.api.mail.ILetter; import forestry.api.mail.IMailAddress; import forestry.api.mail.IStamps; import forestry.core.inventory.InventoryAdapter; import forestry.core.utils.InventoryUtil; import forestry.core.utils.StringUtil; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import org.apache.commons.lang3.StringUtils; public class Letter implements ILetter { - public static final short SLOT_ATTACHMENT_1 = 0; - public static final short SLOT_ATTACHMENT_COUNT = 18; - public static final short SLOT_POSTAGE_1 = 18; - public static final short SLOT_POSTAGE_COUNT = 4; + public static final short SLOT_ATTACHMENT_1 = 0; + public static final short SLOT_ATTACHMENT_COUNT = 18; + public static final short SLOT_POSTAGE_1 = 18; + public static final short SLOT_POSTAGE_COUNT = 4; - private boolean isProcessed = false; + private boolean isProcessed = false; - private IMailAddress sender; - private IMailAddress[] recipient; + private IMailAddress sender; + private IMailAddress[] recipient; - private String text; - private final InventoryAdapter inventory = new InventoryAdapter(22, "INV"); + private String text; + private final InventoryAdapter inventory = new InventoryAdapter(22, "INV"); - public Letter(IMailAddress sender, IMailAddress recipient) { - this.sender = sender; - this.recipient = new IMailAddress[]{recipient}; - } + public Letter(IMailAddress sender, IMailAddress recipient) { + this.sender = sender; + this.recipient = new IMailAddress[] {recipient}; + } - public Letter(NBTTagCompound nbttagcompound) { - if (nbttagcompound != null) { - readFromNBT(nbttagcompound); - } - } + public Letter(NBTTagCompound nbttagcompound) { + if (nbttagcompound != null) { + readFromNBT(nbttagcompound); + } + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { - this.isProcessed = nbttagcompound.getBoolean("PRC"); - this.sender = MailAddress.loadFromNBT(nbttagcompound.getCompoundTag("SDR")); + this.isProcessed = nbttagcompound.getBoolean("PRC"); + this.sender = MailAddress.loadFromNBT(nbttagcompound.getCompoundTag("SDR")); - int recipientCount = nbttagcompound.getShort("CRC"); - this.recipient = new MailAddress[recipientCount]; - for (int i = 0; i < recipientCount; i++) { - this.recipient[i] = MailAddress.loadFromNBT(nbttagcompound.getCompoundTag("RC" + i)); - } + int recipientCount = nbttagcompound.getShort("CRC"); + this.recipient = new MailAddress[recipientCount]; + for (int i = 0; i < recipientCount; i++) { + this.recipient[i] = MailAddress.loadFromNBT(nbttagcompound.getCompoundTag("RC" + i)); + } - this.text = nbttagcompound.getString("TXT"); + this.text = nbttagcompound.getString("TXT"); - this.inventory.readFromNBT(nbttagcompound); - } + this.inventory.readFromNBT(nbttagcompound); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setBoolean("PRC", isProcessed); + nbttagcompound.setBoolean("PRC", isProcessed); - NBTTagCompound subcompound = new NBTTagCompound(); - this.sender.writeToNBT(subcompound); - nbttagcompound.setTag("SDR", subcompound); + NBTTagCompound subcompound = new NBTTagCompound(); + this.sender.writeToNBT(subcompound); + nbttagcompound.setTag("SDR", subcompound); - nbttagcompound.setShort("CRC", (short) recipient.length); - for (int i = 0; i < recipient.length; i++) { - subcompound = new NBTTagCompound(); - this.recipient[i].writeToNBT(subcompound); - nbttagcompound.setTag("RC" + i, subcompound); - } + nbttagcompound.setShort("CRC", (short) recipient.length); + for (int i = 0; i < recipient.length; i++) { + subcompound = new NBTTagCompound(); + this.recipient[i].writeToNBT(subcompound); + nbttagcompound.setTag("RC" + i, subcompound); + } - nbttagcompound.setString("TXT", this.text); + nbttagcompound.setString("TXT", this.text); - inventory.writeToNBT(nbttagcompound); - } + inventory.writeToNBT(nbttagcompound); + } - @Override - public ItemStack[] getPostage() { - return InventoryUtil.getStacks(inventory, SLOT_POSTAGE_1, SLOT_POSTAGE_COUNT); - } + @Override + public ItemStack[] getPostage() { + return InventoryUtil.getStacks(inventory, SLOT_POSTAGE_1, SLOT_POSTAGE_COUNT); + } - @Override - public ItemStack[] getAttachments() { - return InventoryUtil.getStacks(inventory, SLOT_ATTACHMENT_1, SLOT_ATTACHMENT_COUNT); - } + @Override + public ItemStack[] getAttachments() { + return InventoryUtil.getStacks(inventory, SLOT_ATTACHMENT_1, SLOT_ATTACHMENT_COUNT); + } - @Override - public int countAttachments() { - int count = 0; - for (ItemStack stack : getAttachments()) { - if (stack != null) { - count++; - } - } + @Override + public int countAttachments() { + int count = 0; + for (ItemStack stack : getAttachments()) { + if (stack != null) { + count++; + } + } - return count; - } + return count; + } - @Override - public void addAttachment(ItemStack itemstack) { - InventoryUtil.tryAddStack(inventory, itemstack, false); - } + @Override + public void addAttachment(ItemStack itemstack) { + InventoryUtil.tryAddStack(inventory, itemstack, false); + } - @Override - public void addAttachments(ItemStack[] itemstacks) { - for (ItemStack stack : itemstacks) { - addAttachment(stack); - } - } + @Override + public void addAttachments(ItemStack[] itemstacks) { + for (ItemStack stack : itemstacks) { + addAttachment(stack); + } + } - @Override - public void invalidatePostage() { - for (int i = SLOT_POSTAGE_1; i < SLOT_POSTAGE_1 + SLOT_POSTAGE_COUNT; i++) { - inventory.setInventorySlotContents(i, null); - } - } + @Override + public void invalidatePostage() { + for (int i = SLOT_POSTAGE_1; i < SLOT_POSTAGE_1 + SLOT_POSTAGE_COUNT; i++) { + inventory.setInventorySlotContents(i, null); + } + } - @Override - public void setProcessed(boolean flag) { - this.isProcessed = flag; - } + @Override + public void setProcessed(boolean flag) { + this.isProcessed = flag; + } - @Override - public boolean isProcessed() { - return this.isProcessed; - } + @Override + public boolean isProcessed() { + return this.isProcessed; + } - @Override - public boolean isMailable() { - // Can't resend an already sent letter - // Requires at least one recipient - return !isProcessed && recipient != null && recipient.length > 0; - } + @Override + public boolean isMailable() { + // Can't resend an already sent letter + // Requires at least one recipient + return !isProcessed && recipient != null && recipient.length > 0; + } - @Override - public boolean isPostPaid() { + @Override + public boolean isPostPaid() { - int posted = 0; + int posted = 0; - for (ItemStack stamp : getPostage()) { - if (stamp == null) { - continue; - } - if (!(stamp.getItem() instanceof IStamps)) { - continue; - } + for (ItemStack stamp : getPostage()) { + if (stamp == null) { + continue; + } + if (!(stamp.getItem() instanceof IStamps)) { + continue; + } - posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.stackSize; - } + posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.stackSize; + } - return posted >= requiredPostage(); - } + return posted >= requiredPostage(); + } - @Override - public int requiredPostage() { + @Override + public int requiredPostage() { - int required = 1; - for (ItemStack attach : getAttachments()) { - if (attach != null) { - required++; - } - } + int required = 1; + for (ItemStack attach : getAttachments()) { + if (attach != null) { + required++; + } + } - return required; - } + return required; + } - @Override - public void addStamps(ItemStack stamps) { - InventoryUtil.tryAddStack(inventory, stamps, SLOT_POSTAGE_1, 4, false); - } + @Override + public void addStamps(ItemStack stamps) { + InventoryUtil.tryAddStack(inventory, stamps, SLOT_POSTAGE_1, 4, false); + } - @Override - public boolean hasRecipient() { - if (getRecipients().length <= 0) { - return false; - } + @Override + public boolean hasRecipient() { + if (getRecipients().length <= 0) { + return false; + } - IMailAddress recipient = getRecipients()[0]; - if (recipient == null) { - return false; - } + IMailAddress recipient = getRecipients()[0]; + if (recipient == null) { + return false; + } - return !StringUtils.isBlank(recipient.getName()); - } + return !StringUtils.isBlank(recipient.getName()); + } - @Override - public void setSender(IMailAddress address) { - this.sender = address; - } + @Override + public void setSender(IMailAddress address) { + this.sender = address; + } - @Override - public IMailAddress getSender() { - return sender; - } + @Override + public IMailAddress getSender() { + return sender; + } - @Override - public void setRecipient(IMailAddress address) { - if (address == null) { - this.recipient = new IMailAddress[]{}; - } else { - this.recipient = new IMailAddress[]{address}; - } - } + @Override + public void setRecipient(IMailAddress address) { + if (address == null) { + this.recipient = new IMailAddress[] {}; + } else { + this.recipient = new IMailAddress[] {address}; + } + } - @Override - public IMailAddress[] getRecipients() { - return recipient; - } + @Override + public IMailAddress[] getRecipients() { + return recipient; + } - @Override - public String getRecipientString() { - StringBuilder recipientString = new StringBuilder(); - for (IMailAddress address : recipient) { - if (recipientString.length() > 0) { - recipientString.append(", "); - } - recipientString.append(address.getName()); - } + @Override + public String getRecipientString() { + StringBuilder recipientString = new StringBuilder(); + for (IMailAddress address : recipient) { + if (recipientString.length() > 0) { + recipientString.append(", "); + } + recipientString.append(address.getName()); + } - return recipientString.toString(); - } + return recipientString.toString(); + } - @Override - public void setText(String text) { - this.text = text; - } + @Override + public void setText(String text) { + this.text = text; + } - @Override - public String getText() { - return text; - } + @Override + public String getText() { + return text; + } - @Override - public void addTooltip(List list) { - if (this.sender != null && StringUtils.isNotBlank(this.sender.getName())) { - list.add(StringUtil.localize("gui.mail.from") + ": " + this.sender.getName()); - } - if (this.recipient != null && this.recipient.length > 0) { - list.add(StringUtil.localize("gui.mail.to") + ": " + this.getRecipientString()); - } - } + @Override + public void addTooltip(List list) { + if (this.sender != null && StringUtils.isNotBlank(this.sender.getName())) { + list.add(StringUtil.localize("gui.mail.from") + ": " + this.sender.getName()); + } + if (this.recipient != null && this.recipient.length > 0) { + list.add(StringUtil.localize("gui.mail.to") + ": " + this.getRecipientString()); + } + } - // / IINVENTORY - @Override - public int getSizeInventory() { - return inventory.getSizeInventory(); - } + // / IINVENTORY + @Override + public int getSizeInventory() { + return inventory.getSizeInventory(); + } - @Override - public ItemStack getStackInSlot(int var1) { - return inventory.getStackInSlot(var1); - } + @Override + public ItemStack getStackInSlot(int var1) { + return inventory.getStackInSlot(var1); + } - @Override - public ItemStack decrStackSize(int var1, int var2) { - return inventory.decrStackSize(var1, var2); - } + @Override + public ItemStack decrStackSize(int var1, int var2) { + return inventory.decrStackSize(var1, var2); + } - @Override - public ItemStack getStackInSlotOnClosing(int var1) { - return inventory.getStackInSlotOnClosing(var1); - } + @Override + public ItemStack getStackInSlotOnClosing(int var1) { + return inventory.getStackInSlotOnClosing(var1); + } - @Override - public void setInventorySlotContents(int var1, ItemStack var2) { - inventory.setInventorySlotContents(var1, var2); - } + @Override + public void setInventorySlotContents(int var1, ItemStack var2) { + inventory.setInventorySlotContents(var1, var2); + } - @Override - public String getInventoryName() { - return inventory.getInventoryName(); - } + @Override + public String getInventoryName() { + return inventory.getInventoryName(); + } - @Override - public int getInventoryStackLimit() { - return inventory.getInventoryStackLimit(); - } + @Override + public int getInventoryStackLimit() { + return inventory.getInventoryStackLimit(); + } - @Override - public void markDirty() { - inventory.markDirty(); - } + @Override + public void markDirty() { + inventory.markDirty(); + } - @Override - public boolean isUseableByPlayer(EntityPlayer var1) { - return true; - } + @Override + public boolean isUseableByPlayer(EntityPlayer var1) { + return true; + } - @Override - public void openInventory() { - inventory.openInventory(); - } + @Override + public void openInventory() { + inventory.openInventory(); + } - @Override - public void closeInventory() { - inventory.closeInventory(); - } + @Override + public void closeInventory() { + inventory.closeInventory(); + } - @Override - public boolean hasCustomInventoryName() { - return inventory.hasCustomInventoryName(); - } + @Override + public boolean hasCustomInventoryName() { + return inventory.hasCustomInventoryName(); + } - @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) { - return inventory.isItemValidForSlot(i, itemstack); - } + @Override + public boolean isItemValidForSlot(int i, ItemStack itemstack) { + return inventory.isItemValidForSlot(i, itemstack); + } } diff --git a/src/main/java/forestry/mail/LetterProperties.java b/src/main/java/forestry/mail/LetterProperties.java index 54fe96ef9..fbe2cd200 100644 --- a/src/main/java/forestry/mail/LetterProperties.java +++ b/src/main/java/forestry/mail/LetterProperties.java @@ -1,150 +1,152 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail; - -import java.util.List; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.mail.ILetter; -import forestry.core.render.TextureManager; -import forestry.plugins.PluginMail; - -public class LetterProperties { - private enum State { - FRESH, STAMPED, OPENED, EMPTIED - } - - private enum Size { - EMPTY, SMALL, BIG - } - - public static ItemStack createStampedLetterStack(ILetter letter) { - Size size = getSize(letter); - int meta = encodeMeta(State.STAMPED, size); - return new ItemStack(PluginMail.items.letters, 1, meta); - } - - public static void closeLetter(ItemStack parent, ILetter letter) { - State state = getState(parent.getItemDamage()); - Size size = getSize(parent.getItemDamage()); - - switch (state) { - case OPENED: - if (letter.countAttachments() <= 0) { - state = State.EMPTIED; - } - break; - case FRESH: - case STAMPED: - if (letter.isMailable() && letter.isPostPaid()) { - state = State.STAMPED; - } else { - state = State.FRESH; - } - size = getSize(letter); - break; - case EMPTIED: - } - - int meta = encodeMeta(state, size); - parent.setItemDamage(meta); - - letter.writeToNBT(parent.getTagCompound()); - } - - public static void openLetter(ItemStack parent) { - int oldMeta = parent.getItemDamage(); - State state = getState(oldMeta); - if (state == State.FRESH || state == State.STAMPED) { - Size size = getSize(oldMeta); - int newMeta = encodeMeta(State.OPENED, size); - parent.setItemDamage(newMeta); - } - } - - /* ICONS */ - @SideOnly(Side.CLIENT) - private static IIcon[][] icons; - - @SideOnly(Side.CLIENT) - public static void registerIcons(IIconRegister register) { - icons = new IIcon[3][4]; - for (int i = 0; i < 3; i++) { - icons[i][0] = TextureManager.registerTex(register, "mail/letter." + i + ".fresh"); - icons[i][1] = TextureManager.registerTex(register, "mail/letter." + i + ".stamped"); - icons[i][2] = TextureManager.registerTex(register, "mail/letter." + i + ".opened"); - icons[i][3] = TextureManager.registerTex(register, "mail/letter." + i + ".emptied"); - } - } - - @SuppressWarnings("unchecked") - public static void getSubItems(Item item, CreativeTabs tab, List list) { - for (State state : State.values()) { - for (Size size : Size.values()) { - int meta = encodeMeta(state, size); - ItemStack letter = new ItemStack(item, 1, meta); - list.add(letter); - } - } - } - - @SideOnly(Side.CLIENT) - public static IIcon getIconFromDamage(int damage) { - State state = getState(damage); - Size size = getSize(damage); - - return icons[size.ordinal()][state.ordinal()]; - } - - private static State getState(int meta) { - int ordinal = meta & 0x0f; - State[] values = State.values(); - if (ordinal >= values.length) { - ordinal = 0; - } - return values[ordinal]; - } - - private static Size getSize(int meta) { - int ordinal = meta >> 4; - Size[] values = Size.values(); - if (ordinal >= values.length) { - ordinal = 0; - } - return values[ordinal]; - } - - private static int encodeMeta(State state, Size size) { - int meta = size.ordinal() << 4; - meta |= state.ordinal(); - return meta; - } - - private static Size getSize(ILetter letter) { - int count = letter.countAttachments(); - - if (count > 5) { - return Size.BIG; - } else if (count > 1) { - return Size.SMALL; - } else { - return Size.EMPTY; - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.mail.ILetter; +import forestry.core.render.TextureManager; +import forestry.plugins.PluginMail; +import java.util.List; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; + +public class LetterProperties { + private enum State { + FRESH, + STAMPED, + OPENED, + EMPTIED + } + + private enum Size { + EMPTY, + SMALL, + BIG + } + + public static ItemStack createStampedLetterStack(ILetter letter) { + Size size = getSize(letter); + int meta = encodeMeta(State.STAMPED, size); + return new ItemStack(PluginMail.items.letters, 1, meta); + } + + public static void closeLetter(ItemStack parent, ILetter letter) { + State state = getState(parent.getItemDamage()); + Size size = getSize(parent.getItemDamage()); + + switch (state) { + case OPENED: + if (letter.countAttachments() <= 0) { + state = State.EMPTIED; + } + break; + case FRESH: + case STAMPED: + if (letter.isMailable() && letter.isPostPaid()) { + state = State.STAMPED; + } else { + state = State.FRESH; + } + size = getSize(letter); + break; + case EMPTIED: + } + + int meta = encodeMeta(state, size); + parent.setItemDamage(meta); + + letter.writeToNBT(parent.getTagCompound()); + } + + public static void openLetter(ItemStack parent) { + int oldMeta = parent.getItemDamage(); + State state = getState(oldMeta); + if (state == State.FRESH || state == State.STAMPED) { + Size size = getSize(oldMeta); + int newMeta = encodeMeta(State.OPENED, size); + parent.setItemDamage(newMeta); + } + } + + /* ICONS */ + @SideOnly(Side.CLIENT) + private static IIcon[][] icons; + + @SideOnly(Side.CLIENT) + public static void registerIcons(IIconRegister register) { + icons = new IIcon[3][4]; + for (int i = 0; i < 3; i++) { + icons[i][0] = TextureManager.registerTex(register, "mail/letter." + i + ".fresh"); + icons[i][1] = TextureManager.registerTex(register, "mail/letter." + i + ".stamped"); + icons[i][2] = TextureManager.registerTex(register, "mail/letter." + i + ".opened"); + icons[i][3] = TextureManager.registerTex(register, "mail/letter." + i + ".emptied"); + } + } + + @SuppressWarnings("unchecked") + public static void getSubItems(Item item, CreativeTabs tab, List list) { + for (State state : State.values()) { + for (Size size : Size.values()) { + int meta = encodeMeta(state, size); + ItemStack letter = new ItemStack(item, 1, meta); + list.add(letter); + } + } + } + + @SideOnly(Side.CLIENT) + public static IIcon getIconFromDamage(int damage) { + State state = getState(damage); + Size size = getSize(damage); + + return icons[size.ordinal()][state.ordinal()]; + } + + private static State getState(int meta) { + int ordinal = meta & 0x0f; + State[] values = State.values(); + if (ordinal >= values.length) { + ordinal = 0; + } + return values[ordinal]; + } + + private static Size getSize(int meta) { + int ordinal = meta >> 4; + Size[] values = Size.values(); + if (ordinal >= values.length) { + ordinal = 0; + } + return values[ordinal]; + } + + private static int encodeMeta(State state, Size size) { + int meta = size.ordinal() << 4; + meta |= state.ordinal(); + return meta; + } + + private static Size getSize(ILetter letter) { + int count = letter.countAttachments(); + + if (count > 5) { + return Size.BIG; + } else if (count > 1) { + return Size.SMALL; + } else { + return Size.EMPTY; + } + } +} diff --git a/src/main/java/forestry/mail/MailAddress.java b/src/main/java/forestry/mail/MailAddress.java index e4873e3c3..6cc8709fb 100644 --- a/src/main/java/forestry/mail/MailAddress.java +++ b/src/main/java/forestry/mail/MailAddress.java @@ -10,148 +10,145 @@ ******************************************************************************/ package forestry.mail; -import java.util.Locale; -import java.util.UUID; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTUtil; - import com.mojang.authlib.GameProfile; - import forestry.api.core.INBTTagable; import forestry.api.mail.EnumAddressee; import forestry.api.mail.IMailAddress; import forestry.core.utils.PlayerUtil; +import java.util.Locale; +import java.util.UUID; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTUtil; public class MailAddress implements INBTTagable, IMailAddress { - private static final GameProfile invalidGameProfile = new GameProfile(new UUID(0, 0), ""); + private static final GameProfile invalidGameProfile = new GameProfile(new UUID(0, 0), ""); - private EnumAddressee type; - private GameProfile gameProfile; // gameProfile is a fake GameProfile for traders, and real for players + private EnumAddressee type; + private GameProfile gameProfile; // gameProfile is a fake GameProfile for traders, and real for players - public MailAddress() { - this.type = EnumAddressee.PLAYER; - this.gameProfile = invalidGameProfile; - } + public MailAddress() { + this.type = EnumAddressee.PLAYER; + this.gameProfile = invalidGameProfile; + } - public MailAddress(GameProfile gameProfile) { - if (gameProfile == null) { - throw new IllegalArgumentException("gameProfile must not be null"); - } + public MailAddress(GameProfile gameProfile) { + if (gameProfile == null) { + throw new IllegalArgumentException("gameProfile must not be null"); + } - this.type = EnumAddressee.PLAYER; - this.gameProfile = gameProfile; - } + this.type = EnumAddressee.PLAYER; + this.gameProfile = gameProfile; + } - public MailAddress(String name) { - if (name == null) { - throw new IllegalArgumentException("name must not be null"); - } + public MailAddress(String name) { + if (name == null) { + throw new IllegalArgumentException("name must not be null"); + } - this.type = EnumAddressee.TRADER; - this.gameProfile = new GameProfile(null, name); - } + this.type = EnumAddressee.TRADER; + this.gameProfile = new GameProfile(null, name); + } - public MailAddress(IMailAddress address) { - this.type = address.getType(); - if (type == EnumAddressee.TRADER) { - String name = address.getName(); - this.gameProfile = new GameProfile(null, name); - } else if (type == EnumAddressee.PLAYER) { - this.gameProfile = address.getPlayerProfile(); - } - } + public MailAddress(IMailAddress address) { + this.type = address.getType(); + if (type == EnumAddressee.TRADER) { + String name = address.getName(); + this.gameProfile = new GameProfile(null, name); + } else if (type == EnumAddressee.PLAYER) { + this.gameProfile = address.getPlayerProfile(); + } + } - public static MailAddress loadFromNBT(NBTTagCompound nbttagcompound) { - MailAddress address = new MailAddress(); - address.readFromNBT(nbttagcompound); - return address; - } + public static MailAddress loadFromNBT(NBTTagCompound nbttagcompound) { + MailAddress address = new MailAddress(); + address.readFromNBT(nbttagcompound); + return address; + } - @Override - public EnumAddressee getType() { - return type; - } + @Override + public EnumAddressee getType() { + return type; + } - @Override - public String getName() { - return gameProfile.getName(); - } + @Override + public String getName() { + return gameProfile.getName(); + } - @Override - public boolean isValid() { - return gameProfile.getName() != null && !PlayerUtil.isSameGameProfile(gameProfile, invalidGameProfile); - } + @Override + public boolean isValid() { + return gameProfile.getName() != null && !PlayerUtil.isSameGameProfile(gameProfile, invalidGameProfile); + } - @Override - public boolean isPlayer() { - return type == EnumAddressee.PLAYER; - } + @Override + public boolean isPlayer() { + return type == EnumAddressee.PLAYER; + } - @Override - public boolean isTrader() { - return type == EnumAddressee.TRADER; - } + @Override + public boolean isTrader() { + return type == EnumAddressee.TRADER; + } - @Override - public GameProfile getPlayerProfile() { - if (!this.isPlayer()) { - return null; - } - return gameProfile; - } + @Override + public GameProfile getPlayerProfile() { + if (!this.isPlayer()) { + return null; + } + return gameProfile; + } - @Override - public int hashCode() { - return gameProfile.getName().hashCode(); - } + @Override + public int hashCode() { + return gameProfile.getName().hashCode(); + } - @Override - public boolean equals(Object o) { - if (!(o instanceof MailAddress)) { - return false; - } + @Override + public boolean equals(Object o) { + if (!(o instanceof MailAddress)) { + return false; + } - MailAddress address = (MailAddress) o; - return PlayerUtil.isSameGameProfile(address.gameProfile, gameProfile); - } + MailAddress address = (MailAddress) o; + return PlayerUtil.isSameGameProfile(address.gameProfile, gameProfile); + } - @Override - public String toString() { - String name = getName().toLowerCase(Locale.ENGLISH); - if (isPlayer()) { - return type + "-" + name + '-' + gameProfile.getId(); - } else { - return type + "-" + name; - } - } + @Override + public String toString() { + String name = getName().toLowerCase(Locale.ENGLISH); + if (isPlayer()) { + return type + "-" + name + '-' + gameProfile.getId(); + } else { + return type + "-" + name; + } + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - type = null; - if (nbttagcompound.hasKey("TP")) { - String typeName = nbttagcompound.getString("TP"); - type = EnumAddressee.fromString(typeName); - } + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + type = null; + if (nbttagcompound.hasKey("TP")) { + String typeName = nbttagcompound.getString("TP"); + type = EnumAddressee.fromString(typeName); + } - if (type == null) { - type = EnumAddressee.PLAYER; - gameProfile = invalidGameProfile; - } else if (nbttagcompound.hasKey("profile")) { - NBTTagCompound profileTag = nbttagcompound.getCompoundTag("profile"); - gameProfile = NBTUtil.func_152459_a(profileTag); - } - } + if (type == null) { + type = EnumAddressee.PLAYER; + gameProfile = invalidGameProfile; + } else if (nbttagcompound.hasKey("profile")) { + NBTTagCompound profileTag = nbttagcompound.getCompoundTag("profile"); + gameProfile = NBTUtil.func_152459_a(profileTag); + } + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setString("TP", type.toString()); + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setString("TP", type.toString()); - if (gameProfile != null) { - NBTTagCompound profileNbt = new NBTTagCompound(); - NBTUtil.func_152460_a(profileNbt, gameProfile); - nbttagcompound.setTag("profile", profileNbt); - } - } + if (gameProfile != null) { + NBTTagCompound profileNbt = new NBTTagCompound(); + NBTUtil.func_152460_a(profileNbt, gameProfile); + nbttagcompound.setTag("profile", profileNbt); + } + } } diff --git a/src/main/java/forestry/mail/POBox.java b/src/main/java/forestry/mail/POBox.java index aa63809ec..6c6a41c47 100755 --- a/src/main/java/forestry/mail/POBox.java +++ b/src/main/java/forestry/mail/POBox.java @@ -10,153 +10,149 @@ ******************************************************************************/ package forestry.mail; +import forestry.api.mail.ILetter; +import forestry.api.mail.IMailAddress; +import forestry.api.mail.PostManager; +import forestry.core.inventory.InventoryAdapter; +import forestry.core.utils.InventoryUtil; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.WorldSavedData; -import forestry.api.mail.ILetter; -import forestry.api.mail.IMailAddress; -import forestry.api.mail.PostManager; -import forestry.core.inventory.InventoryAdapter; -import forestry.core.utils.InventoryUtil; - public class POBox extends WorldSavedData implements IInventory { - public static final String SAVE_NAME = "POBox_"; - public static final short SLOT_SIZE = 84; + public static final String SAVE_NAME = "POBox_"; + public static final short SLOT_SIZE = 84; - private IMailAddress address; - private final InventoryAdapter letters = new InventoryAdapter(SLOT_SIZE, "Letters").disableAutomation(); + private IMailAddress address; + private final InventoryAdapter letters = new InventoryAdapter(SLOT_SIZE, "Letters").disableAutomation(); - public POBox(IMailAddress address) { - super(SAVE_NAME + address); - if (!address.isPlayer()) { - throw new IllegalArgumentException("POBox address must be a player"); - } - this.address = address; - } + public POBox(IMailAddress address) { + super(SAVE_NAME + address); + if (!address.isPlayer()) { + throw new IllegalArgumentException("POBox address must be a player"); + } + this.address = address; + } - public POBox(String savename) { - super(savename); - } + public POBox(String savename) { + super(savename); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - if (nbttagcompound.hasKey("address")) { - this.address = MailAddress.loadFromNBT(nbttagcompound.getCompoundTag("address")); - } - letters.readFromNBT(nbttagcompound); - } + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + if (nbttagcompound.hasKey("address")) { + this.address = MailAddress.loadFromNBT(nbttagcompound.getCompoundTag("address")); + } + letters.readFromNBT(nbttagcompound); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - if (this.address != null) { - NBTTagCompound nbt = new NBTTagCompound(); - this.address.writeToNBT(nbt); - nbttagcompound.setTag("address", nbt); - } - letters.writeToNBT(nbttagcompound); - } + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + if (this.address != null) { + NBTTagCompound nbt = new NBTTagCompound(); + this.address.writeToNBT(nbt); + nbttagcompound.setTag("address", nbt); + } + letters.writeToNBT(nbttagcompound); + } - public boolean storeLetter(ItemStack letterstack) { - ILetter letter = PostManager.postRegistry.getLetter(letterstack); + public boolean storeLetter(ItemStack letterstack) { + ILetter letter = PostManager.postRegistry.getLetter(letterstack); - // Mark letter as processed - letter.setProcessed(true); - letter.invalidatePostage(); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - letter.writeToNBT(nbttagcompound); - letterstack.setTagCompound(nbttagcompound); + // Mark letter as processed + letter.setProcessed(true); + letter.invalidatePostage(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + letter.writeToNBT(nbttagcompound); + letterstack.setTagCompound(nbttagcompound); - this.markDirty(); + this.markDirty(); - return InventoryUtil.tryAddStack(letters, letterstack, true); - } + return InventoryUtil.tryAddStack(letters, letterstack, true); + } - public POBoxInfo getPOBoxInfo() { - int playerLetters = 0; - int tradeLetters = 0; - for (int i = 0; i < letters.getSizeInventory(); i++) { - if (letters.getStackInSlot(i) == null) { - continue; - } - ILetter letter = new Letter(letters.getStackInSlot(i).getTagCompound()); - if (letter.getSender().isPlayer()) { - playerLetters++; - } else { - tradeLetters++; - } - } + public POBoxInfo getPOBoxInfo() { + int playerLetters = 0; + int tradeLetters = 0; + for (int i = 0; i < letters.getSizeInventory(); i++) { + if (letters.getStackInSlot(i) == null) { + continue; + } + ILetter letter = new Letter(letters.getStackInSlot(i).getTagCompound()); + if (letter.getSender().isPlayer()) { + playerLetters++; + } else { + tradeLetters++; + } + } - return new POBoxInfo(playerLetters, tradeLetters); - } + return new POBoxInfo(playerLetters, tradeLetters); + } - /* IINVENTORY */ - @Override - public void markDirty() { - super.markDirty(); - letters.markDirty(); - } + /* IINVENTORY */ + @Override + public void markDirty() { + super.markDirty(); + letters.markDirty(); + } - @Override - public void setInventorySlotContents(int var1, ItemStack var2) { - this.markDirty(); - letters.setInventorySlotContents(var1, var2); - } + @Override + public void setInventorySlotContents(int var1, ItemStack var2) { + this.markDirty(); + letters.setInventorySlotContents(var1, var2); + } - @Override - public int getSizeInventory() { - return letters.getSizeInventory(); - } + @Override + public int getSizeInventory() { + return letters.getSizeInventory(); + } - @Override - public ItemStack getStackInSlot(int var1) { - return letters.getStackInSlot(var1); - } + @Override + public ItemStack getStackInSlot(int var1) { + return letters.getStackInSlot(var1); + } - @Override - public ItemStack decrStackSize(int var1, int var2) { - return letters.decrStackSize(var1, var2); - } + @Override + public ItemStack decrStackSize(int var1, int var2) { + return letters.decrStackSize(var1, var2); + } - @Override - public ItemStack getStackInSlotOnClosing(int var1) { - return letters.getStackInSlotOnClosing(var1); - } + @Override + public ItemStack getStackInSlotOnClosing(int var1) { + return letters.getStackInSlotOnClosing(var1); + } - @Override - public String getInventoryName() { - return letters.getInventoryName(); - } + @Override + public String getInventoryName() { + return letters.getInventoryName(); + } - @Override - public int getInventoryStackLimit() { - return letters.getInventoryStackLimit(); - } + @Override + public int getInventoryStackLimit() { + return letters.getInventoryStackLimit(); + } - @Override - public boolean isUseableByPlayer(EntityPlayer var1) { - return letters.isUseableByPlayer(var1); - } + @Override + public boolean isUseableByPlayer(EntityPlayer var1) { + return letters.isUseableByPlayer(var1); + } - @Override - public void openInventory() { - } + @Override + public void openInventory() {} - @Override - public void closeInventory() { - } + @Override + public void closeInventory() {} - @Override - public boolean hasCustomInventoryName() { - return true; - } - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) { - return letters.isItemValidForSlot(i, itemstack); - } + @Override + public boolean hasCustomInventoryName() { + return true; + } + @Override + public boolean isItemValidForSlot(int i, ItemStack itemstack) { + return letters.isItemValidForSlot(i, itemstack); + } } diff --git a/src/main/java/forestry/mail/POBoxInfo.java b/src/main/java/forestry/mail/POBoxInfo.java index 422905e1c..de94071d9 100755 --- a/src/main/java/forestry/mail/POBoxInfo.java +++ b/src/main/java/forestry/mail/POBoxInfo.java @@ -11,15 +11,15 @@ package forestry.mail; public class POBoxInfo { - public final int playerLetters; - public final int tradeLetters; + public final int playerLetters; + public final int tradeLetters; - public POBoxInfo(int playerLetters, int tradeLetters) { - this.playerLetters = playerLetters; - this.tradeLetters = tradeLetters; - } + public POBoxInfo(int playerLetters, int tradeLetters) { + this.playerLetters = playerLetters; + this.tradeLetters = tradeLetters; + } - public boolean hasMail() { - return playerLetters > 0 || tradeLetters > 0; - } + public boolean hasMail() { + return playerLetters > 0 || tradeLetters > 0; + } } diff --git a/src/main/java/forestry/mail/PostOffice.java b/src/main/java/forestry/mail/PostOffice.java index f6d8d2eda..72fa46572 100755 --- a/src/main/java/forestry/mail/PostOffice.java +++ b/src/main/java/forestry/mail/PostOffice.java @@ -10,14 +10,6 @@ ******************************************************************************/ package forestry.mail; -import java.io.File; -import java.util.LinkedHashMap; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; -import net.minecraft.world.WorldSavedData; - import forestry.api.mail.EnumPostage; import forestry.api.mail.ILetter; import forestry.api.mail.IMailAddress; @@ -29,171 +21,177 @@ import forestry.api.mail.ITradeStation; import forestry.api.mail.PostManager; import forestry.mail.items.EnumStampDefinition; import forestry.plugins.PluginMail; +import java.io.File; +import java.util.LinkedHashMap; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import net.minecraft.world.WorldSavedData; public class PostOffice extends WorldSavedData implements IPostOffice { - // / CONSTANTS - public static final String SAVE_NAME = "ForestryMail"; - private final int[] collectedPostage = new int[EnumPostage.values().length]; + // / CONSTANTS + public static final String SAVE_NAME = "ForestryMail"; + private final int[] collectedPostage = new int[EnumPostage.values().length]; - // CONSTRUCTORS - public PostOffice() { - super(SAVE_NAME); - } - - public PostOffice(String s) { - super(s); - } + // CONSTRUCTORS + public PostOffice() { + super(SAVE_NAME); + } - public void setWorld(World world) { - refreshActiveTradeStations(world); - } + public PostOffice(String s) { + super(s); + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - for (int i = 0; i < collectedPostage.length; i++) { - if (nbttagcompound.hasKey("CPS" + i)) { - collectedPostage[i] = nbttagcompound.getInteger("CPS" + i); - } - } - } + public void setWorld(World world) { + refreshActiveTradeStations(world); + } - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - for (int i = 0; i < collectedPostage.length; i++) { - nbttagcompound.setInteger("CPS" + i, collectedPostage[i]); - } - } + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + for (int i = 0; i < collectedPostage.length; i++) { + if (nbttagcompound.hasKey("CPS" + i)) { + collectedPostage[i] = nbttagcompound.getInteger("CPS" + i); + } + } + } - /* TRADE STATION MANAGMENT */ - private LinkedHashMap activeTradeStations; + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + for (int i = 0; i < collectedPostage.length; i++) { + nbttagcompound.setInteger("CPS" + i, collectedPostage[i]); + } + } - @Override - public LinkedHashMap getActiveTradeStations(World world) { - return this.activeTradeStations; - } + /* TRADE STATION MANAGMENT */ + private LinkedHashMap activeTradeStations; - private void refreshActiveTradeStations(World world) { - activeTradeStations = new LinkedHashMap<>(); - if (world == null || world.getSaveHandler() == null) { - return; - } - File worldSave = world.getSaveHandler().getMapFileFromName("dummy"); - if (worldSave == null) { - return; - } - File file = worldSave.getParentFile(); - if (!file.exists() || !file.isDirectory()) { - return; - } + @Override + public LinkedHashMap getActiveTradeStations(World world) { + return this.activeTradeStations; + } - for (String str : file.list()) { - if (!str.startsWith(TradeStation.SAVE_NAME)) { - continue; - } - if (!str.endsWith(".dat")) { - continue; - } + private void refreshActiveTradeStations(World world) { + activeTradeStations = new LinkedHashMap<>(); + if (world == null || world.getSaveHandler() == null) { + return; + } + File worldSave = world.getSaveHandler().getMapFileFromName("dummy"); + if (worldSave == null) { + return; + } + File file = worldSave.getParentFile(); + if (!file.exists() || !file.isDirectory()) { + return; + } - MailAddress address = new MailAddress(str.replace(TradeStation.SAVE_NAME, "").replace(".dat", "")); - ITradeStation trade = PostManager.postRegistry.getTradeStation(world, address); - if (trade == null) { - continue; - } + for (String str : file.list()) { + if (!str.startsWith(TradeStation.SAVE_NAME)) { + continue; + } + if (!str.endsWith(".dat")) { + continue; + } - registerTradeStation(trade); - } - } + MailAddress address = + new MailAddress(str.replace(TradeStation.SAVE_NAME, "").replace(".dat", "")); + ITradeStation trade = PostManager.postRegistry.getTradeStation(world, address); + if (trade == null) { + continue; + } - @Override - public void registerTradeStation(ITradeStation trade) { - if (!activeTradeStations.containsKey(trade.getAddress())) { - activeTradeStations.put(trade.getAddress(), trade); - } - } + registerTradeStation(trade); + } + } - @Override - public void deregisterTradeStation(ITradeStation trade) { - activeTradeStations.remove(trade.getAddress()); - } + @Override + public void registerTradeStation(ITradeStation trade) { + if (!activeTradeStations.containsKey(trade.getAddress())) { + activeTradeStations.put(trade.getAddress(), trade); + } + } - // / STAMP MANAGMENT - @Override - public ItemStack getAnyStamp(int max) { - return getAnyStamp(EnumPostage.values(), max); - } + @Override + public void deregisterTradeStation(ITradeStation trade) { + activeTradeStations.remove(trade.getAddress()); + } - @Override - public ItemStack getAnyStamp(EnumPostage postage, int max) { - return getAnyStamp(new EnumPostage[]{postage}, max); - } + // / STAMP MANAGMENT + @Override + public ItemStack getAnyStamp(int max) { + return getAnyStamp(EnumPostage.values(), max); + } - @Override - public ItemStack getAnyStamp(EnumPostage[] postages, int max) { - for (EnumPostage postage : postages) { - int collected = Math.min(max, collectedPostage[postage.ordinal()]); - collectedPostage[postage.ordinal()] -= collected; + @Override + public ItemStack getAnyStamp(EnumPostage postage, int max) { + return getAnyStamp(new EnumPostage[] {postage}, max); + } - if (collected > 0) { - EnumStampDefinition stampDefinition = EnumStampDefinition.getFromPostage(postage); - return PluginMail.items.stamps.get(stampDefinition, collected); - } - } + @Override + public ItemStack getAnyStamp(EnumPostage[] postages, int max) { + for (EnumPostage postage : postages) { + int collected = Math.min(max, collectedPostage[postage.ordinal()]); + collectedPostage[postage.ordinal()] -= collected; - return null; - } + if (collected > 0) { + EnumStampDefinition stampDefinition = EnumStampDefinition.getFromPostage(postage); + return PluginMail.items.stamps.get(stampDefinition, collected); + } + } - // / DELIVERY - @Override - public IPostalState lodgeLetter(World world, ItemStack itemstack, boolean doLodge) { - ILetter letter = PostManager.postRegistry.getLetter(itemstack); + return null; + } - if (letter.isProcessed()) { - return EnumDeliveryState.ALREADY_MAILED; - } + // / DELIVERY + @Override + public IPostalState lodgeLetter(World world, ItemStack itemstack, boolean doLodge) { + ILetter letter = PostManager.postRegistry.getLetter(itemstack); - if (!letter.isPostPaid()) { - return EnumDeliveryState.NOT_POSTPAID; - } + if (letter.isProcessed()) { + return EnumDeliveryState.ALREADY_MAILED; + } - if (!letter.isMailable()) { - return EnumDeliveryState.NOT_MAILABLE; - } + if (!letter.isPostPaid()) { + return EnumDeliveryState.NOT_POSTPAID; + } - IPostalState state = EnumDeliveryState.NOT_MAILABLE; - for (IMailAddress address : letter.getRecipients()) { - IPostalCarrier carrier = PostManager.postRegistry.getCarrier(address.getType()); - if (carrier == null) { - continue; - } - state = carrier.deliverLetter(world, this, address, itemstack, doLodge); - if (!state.isOk()) { - break; - } - } + if (!letter.isMailable()) { + return EnumDeliveryState.NOT_MAILABLE; + } - if (!state.isOk()) { - return state; - } + IPostalState state = EnumDeliveryState.NOT_MAILABLE; + for (IMailAddress address : letter.getRecipients()) { + IPostalCarrier carrier = PostManager.postRegistry.getCarrier(address.getType()); + if (carrier == null) { + continue; + } + state = carrier.deliverLetter(world, this, address, itemstack, doLodge); + if (!state.isOk()) { + break; + } + } - collectPostage(letter.getPostage()); + if (!state.isOk()) { + return state; + } - markDirty(); - return EnumDeliveryState.OK; + collectPostage(letter.getPostage()); - } + markDirty(); + return EnumDeliveryState.OK; + } - @Override - public void collectPostage(ItemStack[] stamps) { - for (ItemStack stamp : stamps) { - if (stamp == null) { - continue; - } + @Override + public void collectPostage(ItemStack[] stamps) { + for (ItemStack stamp : stamps) { + if (stamp == null) { + continue; + } - if (stamp.getItem() instanceof IStamps) { - EnumPostage postage = ((IStamps) stamp.getItem()).getPostage(stamp); - collectedPostage[postage.ordinal()] += stamp.stackSize; - } - } - } + if (stamp.getItem() instanceof IStamps) { + EnumPostage postage = ((IStamps) stamp.getItem()).getPostage(stamp); + collectedPostage[postage.ordinal()] += stamp.stackSize; + } + } + } } diff --git a/src/main/java/forestry/mail/PostRegistry.java b/src/main/java/forestry/mail/PostRegistry.java index 9dcee233d..e2eb9b9f3 100755 --- a/src/main/java/forestry/mail/PostRegistry.java +++ b/src/main/java/forestry/mail/PostRegistry.java @@ -10,18 +10,7 @@ ******************************************************************************/ package forestry.mail; -import java.io.File; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import forestry.api.mail.EnumAddressee; import forestry.api.mail.ILetter; import forestry.api.mail.IMailAddress; @@ -34,210 +23,218 @@ import forestry.core.proxy.Proxies; import forestry.core.utils.PlayerUtil; import forestry.mail.network.packets.PacketPOBoxInfoUpdate; import forestry.plugins.PluginMail; +import java.io.File; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; public class PostRegistry implements IPostRegistry { - public static PostOffice cachedPostOffice; - public static final Map cachedPOBoxes = new HashMap<>(); - public static final Map cachedTradeStations = new HashMap<>(); + public static PostOffice cachedPostOffice; + public static final Map cachedPOBoxes = new HashMap<>(); + public static final Map cachedTradeStations = new HashMap<>(); - /** - * @param world the Minecraft world the PO box will be in - * @param address the potential address of the PO box - * @return true if the passed address is valid for PO Boxes. - */ - @Override - public boolean isValidPOBox(World world, IMailAddress address) { - return address.isPlayer() && address.getName().matches("^[a-zA-Z0-9]+$"); - } + /** + * @param world the Minecraft world the PO box will be in + * @param address the potential address of the PO box + * @return true if the passed address is valid for PO Boxes. + */ + @Override + public boolean isValidPOBox(World world, IMailAddress address) { + return address.isPlayer() && address.getName().matches("^[a-zA-Z0-9]+$"); + } - public static POBox getPOBox(World world, IMailAddress address) { + public static POBox getPOBox(World world, IMailAddress address) { - if (cachedPOBoxes.containsKey(address)) { - return cachedPOBoxes.get(address); - } + if (cachedPOBoxes.containsKey(address)) { + return cachedPOBoxes.get(address); + } - POBox pobox = (POBox) world.loadItemData(POBox.class, POBox.SAVE_NAME + address); - if (pobox != null) { - cachedPOBoxes.put(address, pobox); - } - return pobox; - } + POBox pobox = (POBox) world.loadItemData(POBox.class, POBox.SAVE_NAME + address); + if (pobox != null) { + cachedPOBoxes.put(address, pobox); + } + return pobox; + } - public static POBox getOrCreatePOBox(World world, IMailAddress address) { - POBox pobox = getPOBox(world, address); + public static POBox getOrCreatePOBox(World world, IMailAddress address) { + POBox pobox = getPOBox(world, address); - if (pobox == null) { - pobox = new POBox(address); - world.setItemData(POBox.SAVE_NAME + address, pobox); - pobox.markDirty(); - cachedPOBoxes.put(address, pobox); + if (pobox == null) { + pobox = new POBox(address); + world.setItemData(POBox.SAVE_NAME + address, pobox); + pobox.markDirty(); + cachedPOBoxes.put(address, pobox); - EntityPlayer player = PlayerUtil.getPlayer(world, address.getPlayerProfile()); - if (player != null) { - Proxies.net.sendToPlayer(new PacketPOBoxInfoUpdate(pobox.getPOBoxInfo()), player); - } - } + EntityPlayer player = PlayerUtil.getPlayer(world, address.getPlayerProfile()); + if (player != null) { + Proxies.net.sendToPlayer(new PacketPOBoxInfoUpdate(pobox.getPOBoxInfo()), player); + } + } - return pobox; - } + return pobox; + } - /** - * @param world the Minecraft world the Trader will be in - * @param address the potential address of the Trader - * @return true if the passed address can be an address for a trade station - */ - @Override - public boolean isValidTradeAddress(World world, IMailAddress address) { - return address != null && address.isTrader() && address.getName().matches("^[a-zA-Z0-9]+$"); - } + /** + * @param world the Minecraft world the Trader will be in + * @param address the potential address of the Trader + * @return true if the passed address can be an address for a trade station + */ + @Override + public boolean isValidTradeAddress(World world, IMailAddress address) { + return address != null && address.isTrader() && address.getName().matches("^[a-zA-Z0-9]+$"); + } - /** - * @param world the Minecraft world the Trader will be in - * @param address the potential address of the Trader - * @return true if the trade address has not yet been used before. - */ - @Override - public boolean isAvailableTradeAddress(World world, IMailAddress address) { - return address != null && getTradeStation(world, address) == null; - } + /** + * @param world the Minecraft world the Trader will be in + * @param address the potential address of the Trader + * @return true if the trade address has not yet been used before. + */ + @Override + public boolean isAvailableTradeAddress(World world, IMailAddress address) { + return address != null && getTradeStation(world, address) == null; + } - @Override - public TradeStation getTradeStation(World world, IMailAddress address) { - if (address == null || address.getName() == null) { - return null; - } + @Override + public TradeStation getTradeStation(World world, IMailAddress address) { + if (address == null || address.getName() == null) { + return null; + } - if (cachedTradeStations.containsKey(address)) { - return (TradeStation) cachedTradeStations.get(address); - } + if (cachedTradeStations.containsKey(address)) { + return (TradeStation) cachedTradeStations.get(address); + } - TradeStation trade = (TradeStation) world.loadItemData(TradeStation.class, TradeStation.SAVE_NAME + address); + TradeStation trade = (TradeStation) world.loadItemData(TradeStation.class, TradeStation.SAVE_NAME + address); - // Only existing and valid mail orders are returned - if (trade != null && trade.isValid()) { - cachedTradeStations.put(address, trade); - getPostOffice(world).registerTradeStation(trade); - return trade; - } + // Only existing and valid mail orders are returned + if (trade != null && trade.isValid()) { + cachedTradeStations.put(address, trade); + getPostOffice(world).registerTradeStation(trade); + return trade; + } - return null; - } + return null; + } - @Override - public TradeStation getOrCreateTradeStation(World world, GameProfile owner, IMailAddress address) { - TradeStation trade = getTradeStation(world, address); + @Override + public TradeStation getOrCreateTradeStation(World world, GameProfile owner, IMailAddress address) { + TradeStation trade = getTradeStation(world, address); - if (trade == null) { - trade = new TradeStation(owner, address); - world.setItemData(TradeStation.SAVE_NAME + address, trade); - trade.markDirty(); - cachedTradeStations.put(address, trade); - getPostOffice(world).registerTradeStation(trade); - } + if (trade == null) { + trade = new TradeStation(owner, address); + world.setItemData(TradeStation.SAVE_NAME + address, trade); + trade.markDirty(); + cachedTradeStations.put(address, trade); + getPostOffice(world).registerTradeStation(trade); + } - return trade; - } + return trade; + } - @Override - public void deleteTradeStation(World world, IMailAddress address) { - TradeStation trade = getTradeStation(world, address); - if (trade == null) { - return; - } + @Override + public void deleteTradeStation(World world, IMailAddress address) { + TradeStation trade = getTradeStation(world, address); + if (trade == null) { + return; + } - // Need to be marked as invalid since WorldSavedData seems to do some caching of its own. - trade.invalidate(); - cachedTradeStations.remove(address); - getPostOffice(world).deregisterTradeStation(trade); - File file = world.getSaveHandler().getMapFileFromName(trade.mapName); - file.delete(); - } + // Need to be marked as invalid since WorldSavedData seems to do some caching of its own. + trade.invalidate(); + cachedTradeStations.remove(address); + getPostOffice(world).deregisterTradeStation(trade); + File file = world.getSaveHandler().getMapFileFromName(trade.mapName); + file.delete(); + } - @Override - public IPostOffice getPostOffice(World world) { - if (cachedPostOffice != null) { - return cachedPostOffice; - } + @Override + public IPostOffice getPostOffice(World world) { + if (cachedPostOffice != null) { + return cachedPostOffice; + } - PostOffice office = (PostOffice) world.loadItemData(PostOffice.class, PostOffice.SAVE_NAME); + PostOffice office = (PostOffice) world.loadItemData(PostOffice.class, PostOffice.SAVE_NAME); - // Create office if there is none yet - if (office == null) { - office = new PostOffice(); - world.setItemData(PostOffice.SAVE_NAME, office); - } + // Create office if there is none yet + if (office == null) { + office = new PostOffice(); + world.setItemData(PostOffice.SAVE_NAME, office); + } - office.setWorld(world); + office.setWorld(world); - cachedPostOffice = office; - return office; - } + cachedPostOffice = office; + return office; + } - @Override - public IMailAddress getMailAddress(GameProfile gameProfile) { - return new MailAddress(gameProfile); - } + @Override + public IMailAddress getMailAddress(GameProfile gameProfile) { + return new MailAddress(gameProfile); + } - @Override - public IMailAddress getMailAddress(String traderName) { - return new MailAddress(traderName); - } + @Override + public IMailAddress getMailAddress(String traderName) { + return new MailAddress(traderName); + } - /* CARRIER */ - private final Map carriers = new EnumMap<>(EnumAddressee.class); + /* CARRIER */ + private final Map carriers = new EnumMap<>(EnumAddressee.class); - @Override - public Map getRegisteredCarriers() { - return carriers; - } + @Override + public Map getRegisteredCarriers() { + return carriers; + } - @Override - public void registerCarrier(IPostalCarrier carrier) { - carriers.put(carrier.getType(), carrier); - } + @Override + public void registerCarrier(IPostalCarrier carrier) { + carriers.put(carrier.getType(), carrier); + } - @Override - public IPostalCarrier getCarrier(EnumAddressee type) { - return carriers.get(type); - } + @Override + public IPostalCarrier getCarrier(EnumAddressee type) { + return carriers.get(type); + } - /* LETTERS */ - @Override - public ILetter createLetter(IMailAddress sender, IMailAddress recipient) { - return new Letter(sender, recipient); - } + /* LETTERS */ + @Override + public ILetter createLetter(IMailAddress sender, IMailAddress recipient) { + return new Letter(sender, recipient); + } - @Override - public ItemStack createLetterStack(ILetter letter) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - letter.writeToNBT(nbttagcompound); + @Override + public ItemStack createLetterStack(ILetter letter) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + letter.writeToNBT(nbttagcompound); - ItemStack letterStack = LetterProperties.createStampedLetterStack(letter); - letterStack.setTagCompound(nbttagcompound); + ItemStack letterStack = LetterProperties.createStampedLetterStack(letter); + letterStack.setTagCompound(nbttagcompound); - return letterStack; - } + return letterStack; + } - @Override - public ILetter getLetter(ItemStack itemstack) { - if (itemstack == null) { - return null; - } + @Override + public ILetter getLetter(ItemStack itemstack) { + if (itemstack == null) { + return null; + } - if (!PostManager.postRegistry.isLetter(itemstack)) { - return null; - } + if (!PostManager.postRegistry.isLetter(itemstack)) { + return null; + } - if (itemstack.getTagCompound() == null) { - return null; - } + if (itemstack.getTagCompound() == null) { + return null; + } - return new Letter(itemstack.getTagCompound()); - } + return new Letter(itemstack.getTagCompound()); + } - @Override - public boolean isLetter(ItemStack itemstack) { - return itemstack != null && itemstack.getItem() == PluginMail.items.letters; - } + @Override + public boolean isLetter(ItemStack itemstack) { + return itemstack != null && itemstack.getItem() == PluginMail.items.letters; + } } diff --git a/src/main/java/forestry/mail/PostalCarrier.java b/src/main/java/forestry/mail/PostalCarrier.java index d66955314..90be14e22 100755 --- a/src/main/java/forestry/mail/PostalCarrier.java +++ b/src/main/java/forestry/mail/PostalCarrier.java @@ -10,15 +10,8 @@ ******************************************************************************/ package forestry.mail; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.mail.EnumAddressee; import forestry.api.mail.IMailAddress; import forestry.api.mail.IPostOffice; @@ -31,68 +24,74 @@ import forestry.core.render.TextureManager; import forestry.core.utils.PlayerUtil; import forestry.core.utils.StringUtil; import forestry.mail.network.packets.PacketPOBoxInfoUpdate; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; public class PostalCarrier implements IPostalCarrier { - private final String iconID; - private final EnumAddressee type; + private final String iconID; + private final EnumAddressee type; - public PostalCarrier(EnumAddressee type) { - iconID = "mail/carrier." + type; - this.type = type; - } + public PostalCarrier(EnumAddressee type) { + iconID = "mail/carrier." + type; + this.type = type; + } - @Override - public EnumAddressee getType() { - return type; - } + @Override + public EnumAddressee getType() { + return type; + } - @Override - public String getName() { - return StringUtil.localize("gui.addressee." + type); - } + @Override + public String getName() { + return StringUtil.localize("gui.addressee." + type); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon() { - return TextureManager.getInstance().getDefault(iconID); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon() { + return TextureManager.getInstance().getDefault(iconID); + } - @Override - public IPostalState deliverLetter(World world, IPostOffice office, IMailAddress recipient, ItemStack letterStack, boolean doDeliver) { - if (type == EnumAddressee.TRADER) { - return handleTradeLetter(world, recipient, letterStack, doDeliver); - } else { - return storeInPOBox(world, recipient, letterStack); - } - } + @Override + public IPostalState deliverLetter( + World world, IPostOffice office, IMailAddress recipient, ItemStack letterStack, boolean doDeliver) { + if (type == EnumAddressee.TRADER) { + return handleTradeLetter(world, recipient, letterStack, doDeliver); + } else { + return storeInPOBox(world, recipient, letterStack); + } + } - private static IPostalState handleTradeLetter(World world, IMailAddress recipient, ItemStack letterStack, boolean doLodge) { - ITradeStation trade = PostManager.postRegistry.getTradeStation(world, recipient); - if (trade == null) { - return EnumDeliveryState.NO_MAILBOX; - } + private static IPostalState handleTradeLetter( + World world, IMailAddress recipient, ItemStack letterStack, boolean doLodge) { + ITradeStation trade = PostManager.postRegistry.getTradeStation(world, recipient); + if (trade == null) { + return EnumDeliveryState.NO_MAILBOX; + } - return trade.handleLetter(world, recipient, letterStack, doLodge); - } + return trade.handleLetter(world, recipient, letterStack, doLodge); + } - private static EnumDeliveryState storeInPOBox(World world, IMailAddress recipient, ItemStack letterStack) { + private static EnumDeliveryState storeInPOBox(World world, IMailAddress recipient, ItemStack letterStack) { - POBox pobox = PostRegistry.getPOBox(world, recipient); - if (pobox == null) { - return EnumDeliveryState.NO_MAILBOX; - } + POBox pobox = PostRegistry.getPOBox(world, recipient); + if (pobox == null) { + return EnumDeliveryState.NO_MAILBOX; + } - if (!pobox.storeLetter(letterStack.copy())) { - return EnumDeliveryState.MAILBOX_FULL; - } else { - EntityPlayer player = PlayerUtil.getPlayer(world, recipient.getPlayerProfile()); - if (player instanceof EntityPlayerMP) { - Proxies.net.sendToPlayer(new PacketPOBoxInfoUpdate(pobox.getPOBoxInfo()), (EntityPlayerMP) player); - } - } - - return EnumDeliveryState.OK; - } + if (!pobox.storeLetter(letterStack.copy())) { + return EnumDeliveryState.MAILBOX_FULL; + } else { + EntityPlayer player = PlayerUtil.getPlayer(world, recipient.getPlayerProfile()); + if (player instanceof EntityPlayerMP) { + Proxies.net.sendToPlayer(new PacketPOBoxInfoUpdate(pobox.getPOBoxInfo()), (EntityPlayerMP) player); + } + } + return EnumDeliveryState.OK; + } } diff --git a/src/main/java/forestry/mail/SaveEventHandlerMail.java b/src/main/java/forestry/mail/SaveEventHandlerMail.java index 0e993c214..e3b3719e4 100755 --- a/src/main/java/forestry/mail/SaveEventHandlerMail.java +++ b/src/main/java/forestry/mail/SaveEventHandlerMail.java @@ -10,25 +10,21 @@ ******************************************************************************/ package forestry.mail; -import net.minecraft.world.World; - import forestry.core.ISaveEventHandler; +import net.minecraft.world.World; public class SaveEventHandlerMail implements ISaveEventHandler { - @Override - public void onWorldLoad(World world) { - PostRegistry.cachedPostOffice = null; - PostRegistry.cachedPOBoxes.clear(); - PostRegistry.cachedTradeStations.clear(); - } + @Override + public void onWorldLoad(World world) { + PostRegistry.cachedPostOffice = null; + PostRegistry.cachedPOBoxes.clear(); + PostRegistry.cachedTradeStations.clear(); + } - @Override - public void onWorldSave(World world) { - } - - @Override - public void onWorldUnload(World world) { - } + @Override + public void onWorldSave(World world) {} + @Override + public void onWorldUnload(World world) {} } diff --git a/src/main/java/forestry/mail/TradeStation.java b/src/main/java/forestry/mail/TradeStation.java index 43e6c232e..ef75f4ef9 100755 --- a/src/main/java/forestry/mail/TradeStation.java +++ b/src/main/java/forestry/mail/TradeStation.java @@ -10,18 +10,7 @@ ******************************************************************************/ package forestry.mail; -import java.util.ArrayList; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTUtil; -import net.minecraft.world.World; -import net.minecraft.world.WorldSavedData; - import com.mojang.authlib.GameProfile; - import forestry.api.mail.EnumPostage; import forestry.api.mail.ILetter; import forestry.api.mail.IMailAddress; @@ -38,604 +27,623 @@ import forestry.core.utils.StringUtil; import forestry.mail.inventory.InventoryTradeStation; import forestry.mail.items.EnumStampDefinition; import forestry.plugins.PluginMail; +import java.util.ArrayList; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTUtil; +import net.minecraft.world.World; +import net.minecraft.world.WorldSavedData; public class TradeStation extends WorldSavedData implements ITradeStation, IInventoryAdapter { - public static final String SAVE_NAME = "TradePO_"; - public static final short SLOT_TRADEGOOD = 0; - public static final short SLOT_TRADEGOOD_COUNT = 1; - public static final short SLOT_EXCHANGE_1 = 1; - public static final short SLOT_EXCHANGE_COUNT = 4; - public static final short SLOT_LETTERS_1 = 5; - public static final short SLOT_LETTERS_COUNT = 6; - public static final short SLOT_STAMPS_1 = 11; - public static final short SLOT_STAMPS_COUNT = 4; - public static final short SLOT_RECEIVE_BUFFER = 15; - public static final short SLOT_RECEIVE_BUFFER_COUNT = 15; - public static final short SLOT_SEND_BUFFER = 30; - public static final short SLOT_SEND_BUFFER_COUNT = 10; - public static final int SLOT_SIZE = SLOT_TRADEGOOD_COUNT + SLOT_EXCHANGE_COUNT + SLOT_LETTERS_COUNT + SLOT_STAMPS_COUNT + SLOT_RECEIVE_BUFFER_COUNT + SLOT_SEND_BUFFER_COUNT; - - private GameProfile owner; - private IMailAddress address; - private boolean isVirtual = false; - private boolean isInvalid = false; - private final InventoryAdapter inventory = new InventoryTradeStation(); - - public TradeStation(GameProfile owner, IMailAddress address) { - super(SAVE_NAME + address); - if (!address.isTrader()) { - throw new IllegalArgumentException("TradeStation address must be a trader"); - } - this.owner = owner; - this.address = address; - } - - @SuppressWarnings("unused") // required for WorldSavedData - public TradeStation(String savename) { - super(savename); - } - - @Override - public IMailAddress getAddress() { - return this.address; - } - - // / SAVING & LOADING - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - if (nbttagcompound.hasKey("owner")) { - owner = NBTUtil.func_152459_a(nbttagcompound.getCompoundTag("owner")); - } - - if (nbttagcompound.hasKey("address")) { - address = MailAddress.loadFromNBT(nbttagcompound.getCompoundTag("address")); - } - - this.isVirtual = nbttagcompound.getBoolean("VRT"); - this.isInvalid = nbttagcompound.getBoolean("IVL"); - inventory.readFromNBT(nbttagcompound); - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - if (owner != null) { - NBTTagCompound nbt = new NBTTagCompound(); - NBTUtil.func_152460_a(nbt, owner); - nbttagcompound.setTag("owner", nbt); - } - - if (address != null) { - NBTTagCompound nbt = new NBTTagCompound(); - address.writeToNBT(nbt); - nbttagcompound.setTag("address", nbt); - } - - nbttagcompound.setBoolean("VRT", this.isVirtual); - nbttagcompound.setBoolean("IVL", this.isInvalid); - inventory.writeToNBT(nbttagcompound); - } - - /* INVALIDATING */ - @Override - public boolean isValid() { - return !this.isInvalid; - } - - @Override - public void invalidate() { - this.isInvalid = true; - } - - /* INFORMATION */ - @Override - public void setVirtual(boolean isVirtual) { - this.isVirtual = isVirtual; - markDirty(); - } - - @Override - public boolean isVirtual() { - return isVirtual; - } - - @Override - public TradeStationInfo getTradeInfo() { - ItemStack[] condensedRequired = ItemStackUtil.condenseStacks(InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT)); - - // Set current state - EnumStationState state = EnumStationState.OK; - - // Virtual trade stations are always ready for service. - if (!isVirtual()) { - // Will assume that the owner should get a notice. - if (!hasPaper(2)) { - state = EnumStationState.INSUFFICIENT_PAPER; - } - - if (!canPayPostage(3)) { - state = EnumStationState.INSUFFICIENT_STAMPS; - } - - if (countFillableOrders(1, inventory.getStackInSlot(SLOT_TRADEGOOD)) <= 0) { - state = EnumStationState.INSUFFICIENT_TRADE_GOOD; - } - } - - return new TradeStationInfo(address, owner, inventory.getStackInSlot(SLOT_TRADEGOOD), condensedRequired, state); - } - - /* ILETTERHANDLER */ - @Override - public IPostalState handleLetter(World world, IMailAddress recipient, ItemStack letterstack, boolean doLodge) { - - boolean sendOwnerNotice = doLodge && owner != null; - - ILetter letter = PostManager.postRegistry.getLetter(letterstack); - - if (!isVirtual() && !hasPaper(sendOwnerNotice ? 2 : 1)) { - return EnumStationState.INSUFFICIENT_PAPER; - } - - int ordersToFillCount = ItemStackUtil.containsSets(InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT), letter.getAttachments(), false, false, true); - - // Not a single match. - if (ordersToFillCount <= 0) { - return EnumStationState.INSUFFICIENT_OFFER; - } - - if (!isVirtual()) { - int fillable = countFillableOrders(ordersToFillCount, inventory.getStackInSlot(SLOT_TRADEGOOD)); - - // Nothing can be filled. - if (fillable <= 0) { - return EnumStationState.INSUFFICIENT_TRADE_GOOD; - } - - if (fillable < ordersToFillCount) { - ordersToFillCount = fillable; - } - - // Check for sufficient output buffer - int storable = countStorablePayment(ordersToFillCount, InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT)); - - if (storable <= 0) { - return EnumStationState.INSUFFICIENT_BUFFER; - } - - if (storable < ordersToFillCount) { - ordersToFillCount = storable; - } - } - - // Prepare the letter - ILetter mail = new Letter(this.address, letter.getSender()); - mail.setText(StringUtil.localize("gui.mail.order.attached")); - for (int i = 0; i < ordersToFillCount; i++) { - mail.addAttachment(inventory.getStackInSlot(SLOT_TRADEGOOD).copy()); - } - mail.addAttachments(getSurplusAttachments(ordersToFillCount, letter.getAttachments())); - - // Check for necessary postage - int requiredPostage = mail.requiredPostage(); - if (!isVirtual()) { - if (!canPayPostage(requiredPostage + (sendOwnerNotice ? 1 : 0))) { - return EnumStationState.INSUFFICIENT_STAMPS; - } - } - - // Attach necessary postage - int[] stampCount = getPostage(requiredPostage, isVirtual()); - for (int i = 0; i < stampCount.length; i++) { - int count = stampCount[i]; - if (count > 0) { - EnumPostage postage = EnumPostage.values()[i]; - EnumStampDefinition stampDefinition = EnumStampDefinition.getFromPostage(postage); - mail.addStamps(PluginMail.items.stamps.get(stampDefinition, count)); - } - } - - // Send the letter - NBTTagCompound nbttagcompound = new NBTTagCompound(); - mail.writeToNBT(nbttagcompound); - - ItemStack mailstack = LetterProperties.createStampedLetterStack(mail); - mailstack.setTagCompound(nbttagcompound); - - IPostalState responseState = PostManager.postRegistry.getPostOffice(world).lodgeLetter(world, mailstack, doLodge); - - if (!responseState.isOk()) { - return EnumDeliveryState.RESPONSE_NOT_MAILABLE; - } - - // Store received items - for (int i = 0; i < ordersToFillCount; i++) { - for (ItemStack stack : InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT)) { - if (stack == null) { - continue; - } - - InventoryUtil.tryAddStack(inventory, stack.copy(), SLOT_RECEIVE_BUFFER, SLOT_RECEIVE_BUFFER_COUNT, false); - } - } - - // Remove resources - removePaper(); - removeStamps(stampCount); - removeTradegood(ordersToFillCount); - - // Send confirmation message to seller - if (sendOwnerNotice) { - nbttagcompound = new NBTTagCompound(); - - ILetter confirm = new Letter(this.address, new MailAddress(this.owner)); - - String orderFilledMessage; - if (ordersToFillCount == 1) { - orderFilledMessage = StringUtil.localize("gui.mail.order.filled.one"); - } else { - orderFilledMessage = StringUtil.localize("gui.mail.order.filled.multiple"); - orderFilledMessage = orderFilledMessage.replace("%COUNT", Integer.toString(ordersToFillCount)); - } - - orderFilledMessage = orderFilledMessage.replace("%SENDER", letter.getSender().getName()); - - confirm.setText(orderFilledMessage); - confirm.addStamps(PluginMail.items.stamps.get(EnumStampDefinition.P_1, 1)); - confirm.writeToNBT(nbttagcompound); - - ItemStack confirmstack = LetterProperties.createStampedLetterStack(confirm); - confirmstack.setTagCompound(nbttagcompound); - - PostManager.postRegistry.getPostOffice(world).lodgeLetter(world, confirmstack, doLodge); - - removePaper(); - removeStamps(new int[]{0, 1}); - } - - markDirty(); - - return EnumDeliveryState.OK; - } - - /* TRADE LOGIC */ - private int countFillableOrders(int max, ItemStack tradegood) { - - if (tradegood == null) { - return 0; - } - - // How many orders are fillable? - float orderCount = 0; - - for (ItemStack stack : InventoryUtil.getStacks(inventory, SLOT_SEND_BUFFER, SLOT_SEND_BUFFER_COUNT)) { - if (stack != null && stack.isItemEqual(tradegood) && ItemStack.areItemStackTagsEqual(stack, tradegood)) { - orderCount += (stack.stackSize / (float) tradegood.stackSize); - if (orderCount >= max) { - return max; - } - } - } - - return (int) Math.floor(orderCount); - } - - public boolean canReceivePayment() { - InventoryAdapter test = inventory.copy(); - ItemStack[] payment = InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT); - - return InventoryUtil.tryAddStacksCopy(test, payment, SLOT_RECEIVE_BUFFER, SLOT_RECEIVE_BUFFER_COUNT, true); - } - - private int countStorablePayment(int max, ItemStack[] exchange) { - - InventoryAdapter test = inventory.copy(); - int count = 0; - - for (int i = 0; i < max; i++) { - if (InventoryUtil.tryAddStacksCopy(test, exchange, SLOT_RECEIVE_BUFFER, SLOT_RECEIVE_BUFFER_COUNT, true)) { - count++; - } else { - break; - } - } - - return count; - } - - private void removeTradegood(int filled) { - - for (int j = 0; j < filled; j++) { - int toRemove = inventory.getStackInSlot(SLOT_TRADEGOOD).stackSize; - for (int i = SLOT_SEND_BUFFER; i < SLOT_SEND_BUFFER + SLOT_SEND_BUFFER_COUNT; i++) { - ItemStack buffer = inventory.getStackInSlot(i); - if (buffer == null) { - continue; - } - - if (!buffer.isItemEqual(inventory.getStackInSlot(SLOT_TRADEGOOD))) { - continue; - } - - if (!ItemStack.areItemStackTagsEqual(buffer, inventory.getStackInSlot(SLOT_TRADEGOOD))) { - continue; - } - - ItemStack decrease = inventory.decrStackSize(i, toRemove); - toRemove -= decrease.stackSize; - - if (toRemove <= 0) { - break; - } - } - } - } - - // Checks if this trade station has enough paper. - private boolean hasPaper(int amountRequired) { - - int amountFound = 0; - - for (ItemStack stack : InventoryUtil.getStacks(inventory, SLOT_LETTERS_1, SLOT_LETTERS_COUNT)) { - if (stack != null) { - amountFound += stack.stackSize; - } - - if (amountFound >= amountRequired) { - return true; - } - } - - return false; - } - - // Removes a single paper from the inventory - private void removePaper() { - for (int i = SLOT_LETTERS_1; i < SLOT_LETTERS_1 + SLOT_LETTERS_COUNT; i++) { - ItemStack stack = inventory.getStackInSlot(i); - if (stack != null && stack.getItem() == Items.paper && stack.stackSize > 0) { - inventory.decrStackSize(i, 1); - break; - } - } - } - - private boolean canPayPostage(int postage) { - int posted = 0; - - for (ItemStack stamp : InventoryUtil.getStacks(inventory, SLOT_STAMPS_1, SLOT_STAMPS_COUNT)) { - if (stamp == null) { - continue; - } - - if (!(stamp.getItem() instanceof IStamps)) { - continue; - } - - posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.stackSize; - - if (posted >= postage) { - return true; - } - } - - return false; - } - - private int[] getPostage(int postage, boolean virtual) { - int[] stamps = new int[EnumPostage.values().length]; - - for (int i = EnumPostage.values().length - 1; i > 0; i--) { - if (postage <= 0) { - break; - } - - EnumPostage postValue = EnumPostage.values()[i]; - - if (postValue.getValue() > postage) { - continue; - } - - int num = 99; - if (!virtual) { - num = getNumStamps(postValue); - } - int max = (int) Math.floor(postage / postValue.getValue()); - if (max < num) { - num = max; - } - - stamps[i] = num; - postage -= num * postValue.getValue(); - } - - return stamps; - } - - private int getNumStamps(EnumPostage postage) { - int count = 0; - for (ItemStack stamp : InventoryUtil.getStacks(inventory, SLOT_STAMPS_1, SLOT_STAMPS_COUNT)) { - if (stamp == null) { - continue; - } - if (!(stamp.getItem() instanceof IStamps)) { - continue; - } - - if (((IStamps) stamp.getItem()).getPostage(stamp) == postage) { - count += stamp.stackSize; - } - - } - - return count; - } - - private void removeStamps(int[] stampCount) { - for (int i = 1; i < stampCount.length; i++) { - - if (stampCount[i] <= 0) { - continue; - } - - for (int j = SLOT_STAMPS_1; j < SLOT_STAMPS_1 + SLOT_STAMPS_COUNT; j++) { - if (stampCount[i] <= 0) { - continue; - } - - ItemStack stamp = inventory.getStackInSlot(j); - if (stamp == null) { - continue; - } - - if (!(stamp.getItem() instanceof IStamps)) { - continue; - } - - if (((IStamps) stamp.getItem()).getPostage(stamp) == EnumPostage.values()[i]) { - ItemStack decrease = inventory.decrStackSize(j, stampCount[i]); - stampCount[i] -= decrease.stackSize; - } - } - } - } - - private ItemStack[] getSurplusAttachments(int filled, ItemStack[] attachments) { - ArrayList surplus = new ArrayList<>(); - - // Get a copy of the attachments to play with - ItemStack[] pool = new ItemStack[attachments.length]; - for (int i = 0; i < attachments.length; i++) { - if (attachments[i] != null) { - pool[i] = attachments[i].copy(); - } - } - - // Remove stuff until we are only left with the remnants - for (int i = 0; i < filled; i++) { - ItemStack[] required = InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT); - ItemStack[] condensedRequired = ItemStackUtil.condenseStacks(required); - for (ItemStack req : condensedRequired) { - for (int j = 0; j < pool.length; j++) { - ItemStack pol = pool[j]; - if (pol == null) { - continue; - } - if (!pol.isItemEqual(req)) { - continue; - } - if (!ItemStack.areItemStackTagsEqual(req, pol)) { - continue; - } - - if (req.stackSize >= pol.stackSize) { - req.stackSize -= pol.stackSize; - pool[j] = null; - } else { - pol.stackSize -= req.stackSize; - req.stackSize = 0; - } - } - } - } - - for (ItemStack stack : pool) { - if (stack != null) { - surplus.add(stack); - } - } - - return surplus.toArray(new ItemStack[surplus.size()]); - } - - /* IINVENTORY */ - @Override - public void markDirty() { - super.markDirty(); - inventory.markDirty(); - } - - @Override - public void setInventorySlotContents(int slot, ItemStack itemStack) { - this.markDirty(); - inventory.setInventorySlotContents(slot, itemStack); - } - - @Override - public int getSizeInventory() { - return inventory.getSizeInventory(); - } - - @Override - public ItemStack getStackInSlot(int var1) { - return inventory.getStackInSlot(var1); - } - - @Override - public ItemStack decrStackSize(int var1, int var2) { - return inventory.decrStackSize(var1, var2); - } - - @Override - public ItemStack getStackInSlotOnClosing(int var1) { - return inventory.getStackInSlotOnClosing(var1); - } - - @Override - public String getInventoryName() { - return inventory.getInventoryName(); - } - - @Override - public int getInventoryStackLimit() { - return inventory.getInventoryStackLimit(); - } - - @Override - public boolean isUseableByPlayer(EntityPlayer player) { - return true; - } - - @Override - public void openInventory() { - } - - @Override - public void closeInventory() { - } - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemStack) { - return inventory.isItemValidForSlot(i, itemStack); - } - - @Override - public boolean hasCustomInventoryName() { - return true; - } - - @Override - public int[] getAccessibleSlotsFromSide(int side) { - return inventory.getAccessibleSlotsFromSide(side); - } - - @Override - public boolean canInsertItem(int slot, ItemStack itemStack, int side) { - return inventory.canInsertItem(slot, itemStack, side); - } - - @Override - public boolean canExtractItem(int slot, ItemStack itemStack, int side) { - return inventory.canExtractItem(slot, itemStack, side); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return inventory.canSlotAccept(slotIndex, itemStack); - } - - @Override - public boolean isLocked(int slotIndex) { - return inventory.isLocked(slotIndex); - } + public static final String SAVE_NAME = "TradePO_"; + public static final short SLOT_TRADEGOOD = 0; + public static final short SLOT_TRADEGOOD_COUNT = 1; + public static final short SLOT_EXCHANGE_1 = 1; + public static final short SLOT_EXCHANGE_COUNT = 4; + public static final short SLOT_LETTERS_1 = 5; + public static final short SLOT_LETTERS_COUNT = 6; + public static final short SLOT_STAMPS_1 = 11; + public static final short SLOT_STAMPS_COUNT = 4; + public static final short SLOT_RECEIVE_BUFFER = 15; + public static final short SLOT_RECEIVE_BUFFER_COUNT = 15; + public static final short SLOT_SEND_BUFFER = 30; + public static final short SLOT_SEND_BUFFER_COUNT = 10; + public static final int SLOT_SIZE = SLOT_TRADEGOOD_COUNT + + SLOT_EXCHANGE_COUNT + + SLOT_LETTERS_COUNT + + SLOT_STAMPS_COUNT + + SLOT_RECEIVE_BUFFER_COUNT + + SLOT_SEND_BUFFER_COUNT; + + private GameProfile owner; + private IMailAddress address; + private boolean isVirtual = false; + private boolean isInvalid = false; + private final InventoryAdapter inventory = new InventoryTradeStation(); + + public TradeStation(GameProfile owner, IMailAddress address) { + super(SAVE_NAME + address); + if (!address.isTrader()) { + throw new IllegalArgumentException("TradeStation address must be a trader"); + } + this.owner = owner; + this.address = address; + } + + @SuppressWarnings("unused") // required for WorldSavedData + public TradeStation(String savename) { + super(savename); + } + + @Override + public IMailAddress getAddress() { + return this.address; + } + + // / SAVING & LOADING + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + if (nbttagcompound.hasKey("owner")) { + owner = NBTUtil.func_152459_a(nbttagcompound.getCompoundTag("owner")); + } + + if (nbttagcompound.hasKey("address")) { + address = MailAddress.loadFromNBT(nbttagcompound.getCompoundTag("address")); + } + + this.isVirtual = nbttagcompound.getBoolean("VRT"); + this.isInvalid = nbttagcompound.getBoolean("IVL"); + inventory.readFromNBT(nbttagcompound); + } + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + if (owner != null) { + NBTTagCompound nbt = new NBTTagCompound(); + NBTUtil.func_152460_a(nbt, owner); + nbttagcompound.setTag("owner", nbt); + } + + if (address != null) { + NBTTagCompound nbt = new NBTTagCompound(); + address.writeToNBT(nbt); + nbttagcompound.setTag("address", nbt); + } + + nbttagcompound.setBoolean("VRT", this.isVirtual); + nbttagcompound.setBoolean("IVL", this.isInvalid); + inventory.writeToNBT(nbttagcompound); + } + + /* INVALIDATING */ + @Override + public boolean isValid() { + return !this.isInvalid; + } + + @Override + public void invalidate() { + this.isInvalid = true; + } + + /* INFORMATION */ + @Override + public void setVirtual(boolean isVirtual) { + this.isVirtual = isVirtual; + markDirty(); + } + + @Override + public boolean isVirtual() { + return isVirtual; + } + + @Override + public TradeStationInfo getTradeInfo() { + ItemStack[] condensedRequired = + ItemStackUtil.condenseStacks(InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT)); + + // Set current state + EnumStationState state = EnumStationState.OK; + + // Virtual trade stations are always ready for service. + if (!isVirtual()) { + // Will assume that the owner should get a notice. + if (!hasPaper(2)) { + state = EnumStationState.INSUFFICIENT_PAPER; + } + + if (!canPayPostage(3)) { + state = EnumStationState.INSUFFICIENT_STAMPS; + } + + if (countFillableOrders(1, inventory.getStackInSlot(SLOT_TRADEGOOD)) <= 0) { + state = EnumStationState.INSUFFICIENT_TRADE_GOOD; + } + } + + return new TradeStationInfo(address, owner, inventory.getStackInSlot(SLOT_TRADEGOOD), condensedRequired, state); + } + + /* ILETTERHANDLER */ + @Override + public IPostalState handleLetter(World world, IMailAddress recipient, ItemStack letterstack, boolean doLodge) { + + boolean sendOwnerNotice = doLodge && owner != null; + + ILetter letter = PostManager.postRegistry.getLetter(letterstack); + + if (!isVirtual() && !hasPaper(sendOwnerNotice ? 2 : 1)) { + return EnumStationState.INSUFFICIENT_PAPER; + } + + int ordersToFillCount = ItemStackUtil.containsSets( + InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT), + letter.getAttachments(), + false, + false, + true); + + // Not a single match. + if (ordersToFillCount <= 0) { + return EnumStationState.INSUFFICIENT_OFFER; + } + + if (!isVirtual()) { + int fillable = countFillableOrders(ordersToFillCount, inventory.getStackInSlot(SLOT_TRADEGOOD)); + + // Nothing can be filled. + if (fillable <= 0) { + return EnumStationState.INSUFFICIENT_TRADE_GOOD; + } + + if (fillable < ordersToFillCount) { + ordersToFillCount = fillable; + } + + // Check for sufficient output buffer + int storable = countStorablePayment( + ordersToFillCount, InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT)); + + if (storable <= 0) { + return EnumStationState.INSUFFICIENT_BUFFER; + } + + if (storable < ordersToFillCount) { + ordersToFillCount = storable; + } + } + + // Prepare the letter + ILetter mail = new Letter(this.address, letter.getSender()); + mail.setText(StringUtil.localize("gui.mail.order.attached")); + for (int i = 0; i < ordersToFillCount; i++) { + mail.addAttachment(inventory.getStackInSlot(SLOT_TRADEGOOD).copy()); + } + mail.addAttachments(getSurplusAttachments(ordersToFillCount, letter.getAttachments())); + + // Check for necessary postage + int requiredPostage = mail.requiredPostage(); + if (!isVirtual()) { + if (!canPayPostage(requiredPostage + (sendOwnerNotice ? 1 : 0))) { + return EnumStationState.INSUFFICIENT_STAMPS; + } + } + + // Attach necessary postage + int[] stampCount = getPostage(requiredPostage, isVirtual()); + for (int i = 0; i < stampCount.length; i++) { + int count = stampCount[i]; + if (count > 0) { + EnumPostage postage = EnumPostage.values()[i]; + EnumStampDefinition stampDefinition = EnumStampDefinition.getFromPostage(postage); + mail.addStamps(PluginMail.items.stamps.get(stampDefinition, count)); + } + } + + // Send the letter + NBTTagCompound nbttagcompound = new NBTTagCompound(); + mail.writeToNBT(nbttagcompound); + + ItemStack mailstack = LetterProperties.createStampedLetterStack(mail); + mailstack.setTagCompound(nbttagcompound); + + IPostalState responseState = + PostManager.postRegistry.getPostOffice(world).lodgeLetter(world, mailstack, doLodge); + + if (!responseState.isOk()) { + return EnumDeliveryState.RESPONSE_NOT_MAILABLE; + } + + // Store received items + for (int i = 0; i < ordersToFillCount; i++) { + for (ItemStack stack : InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT)) { + if (stack == null) { + continue; + } + + InventoryUtil.tryAddStack( + inventory, stack.copy(), SLOT_RECEIVE_BUFFER, SLOT_RECEIVE_BUFFER_COUNT, false); + } + } + + // Remove resources + removePaper(); + removeStamps(stampCount); + removeTradegood(ordersToFillCount); + + // Send confirmation message to seller + if (sendOwnerNotice) { + nbttagcompound = new NBTTagCompound(); + + ILetter confirm = new Letter(this.address, new MailAddress(this.owner)); + + String orderFilledMessage; + if (ordersToFillCount == 1) { + orderFilledMessage = StringUtil.localize("gui.mail.order.filled.one"); + } else { + orderFilledMessage = StringUtil.localize("gui.mail.order.filled.multiple"); + orderFilledMessage = orderFilledMessage.replace("%COUNT", Integer.toString(ordersToFillCount)); + } + + orderFilledMessage = + orderFilledMessage.replace("%SENDER", letter.getSender().getName()); + + confirm.setText(orderFilledMessage); + confirm.addStamps(PluginMail.items.stamps.get(EnumStampDefinition.P_1, 1)); + confirm.writeToNBT(nbttagcompound); + + ItemStack confirmstack = LetterProperties.createStampedLetterStack(confirm); + confirmstack.setTagCompound(nbttagcompound); + + PostManager.postRegistry.getPostOffice(world).lodgeLetter(world, confirmstack, doLodge); + + removePaper(); + removeStamps(new int[] {0, 1}); + } + + markDirty(); + + return EnumDeliveryState.OK; + } + + /* TRADE LOGIC */ + private int countFillableOrders(int max, ItemStack tradegood) { + + if (tradegood == null) { + return 0; + } + + // How many orders are fillable? + float orderCount = 0; + + for (ItemStack stack : InventoryUtil.getStacks(inventory, SLOT_SEND_BUFFER, SLOT_SEND_BUFFER_COUNT)) { + if (stack != null && stack.isItemEqual(tradegood) && ItemStack.areItemStackTagsEqual(stack, tradegood)) { + orderCount += (stack.stackSize / (float) tradegood.stackSize); + if (orderCount >= max) { + return max; + } + } + } + + return (int) Math.floor(orderCount); + } + + public boolean canReceivePayment() { + InventoryAdapter test = inventory.copy(); + ItemStack[] payment = InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT); + + return InventoryUtil.tryAddStacksCopy(test, payment, SLOT_RECEIVE_BUFFER, SLOT_RECEIVE_BUFFER_COUNT, true); + } + + private int countStorablePayment(int max, ItemStack[] exchange) { + + InventoryAdapter test = inventory.copy(); + int count = 0; + for (int i = 0; i < max; i++) { + if (InventoryUtil.tryAddStacksCopy(test, exchange, SLOT_RECEIVE_BUFFER, SLOT_RECEIVE_BUFFER_COUNT, true)) { + count++; + } else { + break; + } + } + + return count; + } + + private void removeTradegood(int filled) { + + for (int j = 0; j < filled; j++) { + int toRemove = inventory.getStackInSlot(SLOT_TRADEGOOD).stackSize; + for (int i = SLOT_SEND_BUFFER; i < SLOT_SEND_BUFFER + SLOT_SEND_BUFFER_COUNT; i++) { + ItemStack buffer = inventory.getStackInSlot(i); + if (buffer == null) { + continue; + } + + if (!buffer.isItemEqual(inventory.getStackInSlot(SLOT_TRADEGOOD))) { + continue; + } + + if (!ItemStack.areItemStackTagsEqual(buffer, inventory.getStackInSlot(SLOT_TRADEGOOD))) { + continue; + } + + ItemStack decrease = inventory.decrStackSize(i, toRemove); + toRemove -= decrease.stackSize; + + if (toRemove <= 0) { + break; + } + } + } + } + + // Checks if this trade station has enough paper. + private boolean hasPaper(int amountRequired) { + + int amountFound = 0; + + for (ItemStack stack : InventoryUtil.getStacks(inventory, SLOT_LETTERS_1, SLOT_LETTERS_COUNT)) { + if (stack != null) { + amountFound += stack.stackSize; + } + + if (amountFound >= amountRequired) { + return true; + } + } + + return false; + } + + // Removes a single paper from the inventory + private void removePaper() { + for (int i = SLOT_LETTERS_1; i < SLOT_LETTERS_1 + SLOT_LETTERS_COUNT; i++) { + ItemStack stack = inventory.getStackInSlot(i); + if (stack != null && stack.getItem() == Items.paper && stack.stackSize > 0) { + inventory.decrStackSize(i, 1); + break; + } + } + } + + private boolean canPayPostage(int postage) { + int posted = 0; + + for (ItemStack stamp : InventoryUtil.getStacks(inventory, SLOT_STAMPS_1, SLOT_STAMPS_COUNT)) { + if (stamp == null) { + continue; + } + + if (!(stamp.getItem() instanceof IStamps)) { + continue; + } + + posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.stackSize; + + if (posted >= postage) { + return true; + } + } + + return false; + } + + private int[] getPostage(int postage, boolean virtual) { + int[] stamps = new int[EnumPostage.values().length]; + + for (int i = EnumPostage.values().length - 1; i > 0; i--) { + if (postage <= 0) { + break; + } + + EnumPostage postValue = EnumPostage.values()[i]; + + if (postValue.getValue() > postage) { + continue; + } + + int num = 99; + if (!virtual) { + num = getNumStamps(postValue); + } + int max = (int) Math.floor(postage / postValue.getValue()); + if (max < num) { + num = max; + } + + stamps[i] = num; + postage -= num * postValue.getValue(); + } + + return stamps; + } + + private int getNumStamps(EnumPostage postage) { + int count = 0; + for (ItemStack stamp : InventoryUtil.getStacks(inventory, SLOT_STAMPS_1, SLOT_STAMPS_COUNT)) { + if (stamp == null) { + continue; + } + if (!(stamp.getItem() instanceof IStamps)) { + continue; + } + + if (((IStamps) stamp.getItem()).getPostage(stamp) == postage) { + count += stamp.stackSize; + } + } + + return count; + } + + private void removeStamps(int[] stampCount) { + for (int i = 1; i < stampCount.length; i++) { + + if (stampCount[i] <= 0) { + continue; + } + + for (int j = SLOT_STAMPS_1; j < SLOT_STAMPS_1 + SLOT_STAMPS_COUNT; j++) { + if (stampCount[i] <= 0) { + continue; + } + + ItemStack stamp = inventory.getStackInSlot(j); + if (stamp == null) { + continue; + } + + if (!(stamp.getItem() instanceof IStamps)) { + continue; + } + + if (((IStamps) stamp.getItem()).getPostage(stamp) == EnumPostage.values()[i]) { + ItemStack decrease = inventory.decrStackSize(j, stampCount[i]); + stampCount[i] -= decrease.stackSize; + } + } + } + } + + private ItemStack[] getSurplusAttachments(int filled, ItemStack[] attachments) { + ArrayList surplus = new ArrayList<>(); + + // Get a copy of the attachments to play with + ItemStack[] pool = new ItemStack[attachments.length]; + for (int i = 0; i < attachments.length; i++) { + if (attachments[i] != null) { + pool[i] = attachments[i].copy(); + } + } + + // Remove stuff until we are only left with the remnants + for (int i = 0; i < filled; i++) { + ItemStack[] required = InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT); + ItemStack[] condensedRequired = ItemStackUtil.condenseStacks(required); + for (ItemStack req : condensedRequired) { + for (int j = 0; j < pool.length; j++) { + ItemStack pol = pool[j]; + if (pol == null) { + continue; + } + if (!pol.isItemEqual(req)) { + continue; + } + if (!ItemStack.areItemStackTagsEqual(req, pol)) { + continue; + } + + if (req.stackSize >= pol.stackSize) { + req.stackSize -= pol.stackSize; + pool[j] = null; + } else { + pol.stackSize -= req.stackSize; + req.stackSize = 0; + } + } + } + } + + for (ItemStack stack : pool) { + if (stack != null) { + surplus.add(stack); + } + } + + return surplus.toArray(new ItemStack[surplus.size()]); + } + + /* IINVENTORY */ + @Override + public void markDirty() { + super.markDirty(); + inventory.markDirty(); + } + + @Override + public void setInventorySlotContents(int slot, ItemStack itemStack) { + this.markDirty(); + inventory.setInventorySlotContents(slot, itemStack); + } + + @Override + public int getSizeInventory() { + return inventory.getSizeInventory(); + } + + @Override + public ItemStack getStackInSlot(int var1) { + return inventory.getStackInSlot(var1); + } + + @Override + public ItemStack decrStackSize(int var1, int var2) { + return inventory.decrStackSize(var1, var2); + } + + @Override + public ItemStack getStackInSlotOnClosing(int var1) { + return inventory.getStackInSlotOnClosing(var1); + } + + @Override + public String getInventoryName() { + return inventory.getInventoryName(); + } + + @Override + public int getInventoryStackLimit() { + return inventory.getInventoryStackLimit(); + } + + @Override + public boolean isUseableByPlayer(EntityPlayer player) { + return true; + } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemStack) { + return inventory.isItemValidForSlot(i, itemStack); + } + + @Override + public boolean hasCustomInventoryName() { + return true; + } + + @Override + public int[] getAccessibleSlotsFromSide(int side) { + return inventory.getAccessibleSlotsFromSide(side); + } + + @Override + public boolean canInsertItem(int slot, ItemStack itemStack, int side) { + return inventory.canInsertItem(slot, itemStack, side); + } + + @Override + public boolean canExtractItem(int slot, ItemStack itemStack, int side) { + return inventory.canExtractItem(slot, itemStack, side); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return inventory.canSlotAccept(slotIndex, itemStack); + } + + @Override + public boolean isLocked(int slotIndex) { + return inventory.isLocked(slotIndex); + } } diff --git a/src/main/java/forestry/mail/blocks/BlockMail.java b/src/main/java/forestry/mail/blocks/BlockMail.java index 412a048e7..4093ecd2a 100644 --- a/src/main/java/forestry/mail/blocks/BlockMail.java +++ b/src/main/java/forestry/mail/blocks/BlockMail.java @@ -1,19 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.blocks; - -import forestry.core.blocks.BlockBase; - -public class BlockMail extends BlockBase { - public BlockMail() { - super(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.blocks; + +import forestry.core.blocks.BlockBase; + +public class BlockMail extends BlockBase { + public BlockMail() { + super(); + } +} diff --git a/src/main/java/forestry/mail/blocks/BlockMailType.java b/src/main/java/forestry/mail/blocks/BlockMailType.java index d7c92d342..3bc3d3352 100644 --- a/src/main/java/forestry/mail/blocks/BlockMailType.java +++ b/src/main/java/forestry/mail/blocks/BlockMailType.java @@ -1,53 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.blocks; - -import java.util.Locale; - -import org.apache.commons.lang3.text.WordUtils; - -import forestry.core.blocks.IMachineProperties; -import forestry.core.tiles.TileForestry; -import forestry.mail.tiles.TileMailbox; -import forestry.mail.tiles.TileStampCollector; -import forestry.mail.tiles.TileTrader; - -public enum BlockMailType implements IMachineProperties { - MAILBOX(TileMailbox.class), - TRADESTATION(TileTrader.class), - PHILATELIST(TileStampCollector.class); - - public static final BlockMailType[] VALUES = values(); - - private final String teIdent; - private final Class teClass; - - BlockMailType(Class teClass) { - String name = toString().toLowerCase(Locale.ENGLISH); - this.teIdent = "forestry." + WordUtils.capitalize(name); - this.teClass = teClass; - } - - @Override - public int getMeta() { - return ordinal(); - } - - @Override - public String getTeIdent() { - return teIdent; - } - - @Override - public Class getTeClass() { - return teClass; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.blocks; + +import forestry.core.blocks.IMachineProperties; +import forestry.core.tiles.TileForestry; +import forestry.mail.tiles.TileMailbox; +import forestry.mail.tiles.TileStampCollector; +import forestry.mail.tiles.TileTrader; +import java.util.Locale; +import org.apache.commons.lang3.text.WordUtils; + +public enum BlockMailType implements IMachineProperties { + MAILBOX(TileMailbox.class), + TRADESTATION(TileTrader.class), + PHILATELIST(TileStampCollector.class); + + public static final BlockMailType[] VALUES = values(); + + private final String teIdent; + private final Class teClass; + + BlockMailType(Class teClass) { + String name = toString().toLowerCase(Locale.ENGLISH); + this.teIdent = "forestry." + WordUtils.capitalize(name); + this.teClass = teClass; + } + + @Override + public int getMeta() { + return ordinal(); + } + + @Override + public String getTeIdent() { + return teIdent; + } + + @Override + public Class getTeClass() { + return teClass; + } +} diff --git a/src/main/java/forestry/mail/blocks/BlockRegistryMail.java b/src/main/java/forestry/mail/blocks/BlockRegistryMail.java index afa83fc4c..a1c605e2a 100644 --- a/src/main/java/forestry/mail/blocks/BlockRegistryMail.java +++ b/src/main/java/forestry/mail/blocks/BlockRegistryMail.java @@ -1,22 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.blocks; - -import forestry.core.blocks.BlockRegistry; -import forestry.core.items.ItemBlockForestry; - -public class BlockRegistryMail extends BlockRegistry { - public final BlockMail mail; - - public BlockRegistryMail() { - mail = registerBlock(new BlockMail(), ItemBlockForestry.class, "mail"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.blocks; + +import forestry.core.blocks.BlockRegistry; +import forestry.core.items.ItemBlockForestry; + +public class BlockRegistryMail extends BlockRegistry { + public final BlockMail mail; + + public BlockRegistryMail() { + mail = registerBlock(new BlockMail(), ItemBlockForestry.class, "mail"); + } +} diff --git a/src/main/java/forestry/mail/commands/CommandMail.java b/src/main/java/forestry/mail/commands/CommandMail.java index 7cc1bd2f9..0521ba31b 100644 --- a/src/main/java/forestry/mail/commands/CommandMail.java +++ b/src/main/java/forestry/mail/commands/CommandMail.java @@ -12,13 +12,6 @@ */ package forestry.mail.commands; -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ChatStyle; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.world.World; - import forestry.api.mail.ITradeStation; import forestry.api.mail.PostManager; import forestry.api.mail.TradeStationInfo; @@ -26,83 +19,98 @@ import forestry.core.commands.CommandHelpers; import forestry.core.commands.SubCommand; import forestry.core.utils.StringUtil; import forestry.mail.MailAddress; +import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ChatStyle; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.world.World; /** * @author CovertJaguar */ public class CommandMail extends SubCommand { - public CommandMail() { - super("mail"); - addChildCommand(new CommandMailTrades()); - addChildCommand(new CommandMailVirtualize()); - addAlias("ml"); - } + public CommandMail() { + super("mail"); + addChildCommand(new CommandMailTrades()); + addChildCommand(new CommandMailVirtualize()); + addAlias("ml"); + } - public static class CommandMailTrades extends SubCommand { + public static class CommandMailTrades extends SubCommand { - public CommandMailTrades() { - super("trades"); - addAlias("tr"); - } + public CommandMailTrades() { + super("trades"); + addAlias("tr"); + } - @Override - public void processSubCommand(ICommandSender sender, String[] args) { - if (!(sender instanceof EntityPlayer)) { - return; - } - for (ITradeStation trade : PostManager.postRegistry.getPostOffice(((EntityPlayer) sender).worldObj).getActiveTradeStations(((EntityPlayer) sender).worldObj).values()) { - CommandHelpers.sendChatMessage(sender, makeTradeListEntry(trade.getTradeInfo())); - } - } + @Override + public void processSubCommand(ICommandSender sender, String[] args) { + if (!(sender instanceof EntityPlayer)) { + return; + } + for (ITradeStation trade : PostManager.postRegistry + .getPostOffice(((EntityPlayer) sender).worldObj) + .getActiveTradeStations(((EntityPlayer) sender).worldObj) + .values()) { + CommandHelpers.sendChatMessage(sender, makeTradeListEntry(trade.getTradeInfo())); + } + } - private static String makeTradeListEntry(TradeStationInfo info) { - EnumChatFormatting formatting = info.state.isOk() ? EnumChatFormatting.GREEN : EnumChatFormatting.RED; + private static String makeTradeListEntry(TradeStationInfo info) { + EnumChatFormatting formatting = info.state.isOk() ? EnumChatFormatting.GREEN : EnumChatFormatting.RED; - String tradegood = "[ ? ]"; - if (info.tradegood != null) { - tradegood = info.tradegood.stackSize + "x" + info.tradegood.getDisplayName(); - } - String demand = "[ ? ]"; - if (info.required.length > 0) { - demand = ""; - for (ItemStack dmd : info.required) { - demand = StringUtil.append(", ", demand, dmd.stackSize + "x" + dmd.getDisplayName()); - } - } + String tradegood = "[ ? ]"; + if (info.tradegood != null) { + tradegood = info.tradegood.stackSize + "x" + info.tradegood.getDisplayName(); + } + String demand = "[ ? ]"; + if (info.required.length > 0) { + demand = ""; + for (ItemStack dmd : info.required) { + demand = StringUtil.append(", ", demand, dmd.stackSize + "x" + dmd.getDisplayName()); + } + } - return String.format("%s%-12s | %-20s | %s", formatting, info.address.getName(), tradegood, demand); - } - } + return String.format("%s%-12s | %-20s | %s", formatting, info.address.getName(), tradegood, demand); + } + } - public static class CommandMailVirtualize extends SubCommand { + public static class CommandMailVirtualize extends SubCommand { - public CommandMailVirtualize() { - super("virtualize"); - addAlias("virt"); - setPermLevel(PermLevel.ADMIN); - } + public CommandMailVirtualize() { + super("virtualize"); + addAlias("virt"); + setPermLevel(PermLevel.ADMIN); + } - @Override - public void processSubCommand(ICommandSender sender, String[] args) { - if (args.length != 1) { - CommandHelpers.throwWrongUsage(sender, this); - } + @Override + public void processSubCommand(ICommandSender sender, String[] args) { + if (args.length != 1) { + CommandHelpers.throwWrongUsage(sender, this); + } - World world = CommandHelpers.getWorld(sender, this); - MailAddress address = new MailAddress(args[0]); - ITradeStation trade = PostManager.postRegistry.getTradeStation(world, address); - if (trade == null) { - ChatStyle red = new ChatStyle(); - red.setColor(EnumChatFormatting.RED); - CommandHelpers.sendLocalizedChatMessage(sender, red, "for.chat.command.forestry.mail.virtualize.no_tradestation", args[0]); - return; - } + World world = CommandHelpers.getWorld(sender, this); + MailAddress address = new MailAddress(args[0]); + ITradeStation trade = PostManager.postRegistry.getTradeStation(world, address); + if (trade == null) { + ChatStyle red = new ChatStyle(); + red.setColor(EnumChatFormatting.RED); + CommandHelpers.sendLocalizedChatMessage( + sender, red, "for.chat.command.forestry.mail.virtualize.no_tradestation", args[0]); + return; + } - trade.setVirtual(!trade.isVirtual()); - ChatStyle green = new ChatStyle(); - green.setColor(EnumChatFormatting.GREEN); - CommandHelpers.sendLocalizedChatMessage(sender, green, "for.chat.command.forestry.mail.virtualize.set", trade.getAddress().getName(), trade.isVirtual()); - } - } + trade.setVirtual(!trade.isVirtual()); + ChatStyle green = new ChatStyle(); + green.setColor(EnumChatFormatting.GREEN); + CommandHelpers.sendLocalizedChatMessage( + sender, + green, + "for.chat.command.forestry.mail.virtualize.set", + trade.getAddress().getName(), + trade.isVirtual()); + } + } } diff --git a/src/main/java/forestry/mail/gui/ContainerCatalogue.java b/src/main/java/forestry/mail/gui/ContainerCatalogue.java index 4b49c5b96..bbe20f670 100755 --- a/src/main/java/forestry/mail/gui/ContainerCatalogue.java +++ b/src/main/java/forestry/mail/gui/ContainerCatalogue.java @@ -10,18 +10,6 @@ ******************************************************************************/ package forestry.mail.gui; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.ICrafting; - import forestry.api.mail.EnumAddressee; import forestry.api.mail.IMailAddress; import forestry.api.mail.IPostOffice; @@ -34,198 +22,208 @@ import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.proxy.Proxies; import forestry.mail.EnumStationState; import forestry.mail.network.packets.PacketLetterInfoResponse; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; public class ContainerCatalogue extends Container implements IGuiSelectable, ILetterInfoReceiver { - private final EntityPlayer player; - private final List stations = new ArrayList<>(); + private final EntityPlayer player; + private final List stations = new ArrayList<>(); - private TradeStationInfo currentTrade = null; + private TradeStationInfo currentTrade = null; - private int stationIndex = 0; + private int stationIndex = 0; - // for display on client - private int stationCount; + // for display on client + private int stationCount; - private boolean needsSynch = true; - private int currentFilter = 1; + private boolean needsSynch = true; + private int currentFilter = 1; - private static final String[] FILTER_NAMES = new String[]{"all", "online", "offline"}; - private static final List> FILTERS = new ArrayList<>(); + private static final String[] FILTER_NAMES = new String[] {"all", "online", "offline"}; + private static final List> FILTERS = new ArrayList<>(); - static { - EnumSet all = EnumSet.allOf(EnumStationState.class); - EnumSet online = EnumSet.of(EnumStationState.OK); - EnumSet offline = EnumSet.copyOf(all); - offline.removeAll(online); + static { + EnumSet all = EnumSet.allOf(EnumStationState.class); + EnumSet online = EnumSet.of(EnumStationState.OK); + EnumSet offline = EnumSet.copyOf(all); + offline.removeAll(online); - FILTERS.add(Collections.unmodifiableSet(all)); - FILTERS.add(Collections.unmodifiableSet(online)); - FILTERS.add(Collections.unmodifiableSet(offline)); - } + FILTERS.add(Collections.unmodifiableSet(all)); + FILTERS.add(Collections.unmodifiableSet(online)); + FILTERS.add(Collections.unmodifiableSet(offline)); + } - public ContainerCatalogue(EntityPlayer player) { - this.player = player; + public ContainerCatalogue(EntityPlayer player) { + this.player = player; - if (!player.worldObj.isRemote) { - rebuildStationsList(); - } - } + if (!player.worldObj.isRemote) { + rebuildStationsList(); + } + } - public int getPageCount() { - return Math.max(stationCount, 1); - } + public int getPageCount() { + return Math.max(stationCount, 1); + } - public int getPageNumber() { - return stationIndex + 1; - } + public int getPageNumber() { + return stationIndex + 1; + } - public String getFilterIdent() { - return FILTER_NAMES[currentFilter]; - } + public String getFilterIdent() { + return FILTER_NAMES[currentFilter]; + } - private void rebuildStationsList() { - stations.clear(); + private void rebuildStationsList() { + stations.clear(); - IPostOffice postOffice = PostManager.postRegistry.getPostOffice(player.worldObj); - Map tradeStations = postOffice.getActiveTradeStations(player.worldObj); + IPostOffice postOffice = PostManager.postRegistry.getPostOffice(player.worldObj); + Map tradeStations = postOffice.getActiveTradeStations(player.worldObj); - for (ITradeStation station : tradeStations.values()) { - TradeStationInfo info = station.getTradeInfo(); + for (ITradeStation station : tradeStations.values()) { + TradeStationInfo info = station.getTradeInfo(); - // Filter out any trade stations which do not actually offer anything. - if (info.tradegood != null && FILTERS.get(currentFilter).contains(info.state)) { - stations.add(station); - } - } + // Filter out any trade stations which do not actually offer anything. + if (info.tradegood != null && FILTERS.get(currentFilter).contains(info.state)) { + stations.add(station); + } + } - stationIndex = 0; - updateTradeInfo(); - } + stationIndex = 0; + updateTradeInfo(); + } - public void nextPage() { - if (player.worldObj.isRemote) { - sendSelection(true); - return; - } + public void nextPage() { + if (player.worldObj.isRemote) { + sendSelection(true); + return; + } - if (stations.size() == 0) { - return; - } - stationIndex = (stationIndex + 1) % stations.size(); - updateTradeInfo(); - } + if (stations.size() == 0) { + return; + } + stationIndex = (stationIndex + 1) % stations.size(); + updateTradeInfo(); + } - public void previousPage() { - if (player.worldObj.isRemote) { - sendSelection(false); - return; - } + public void previousPage() { + if (player.worldObj.isRemote) { + sendSelection(false); + return; + } - if (stations.size() == 0) { - return; - } - stationIndex = (stationIndex - 1 + stations.size()) % stations.size(); - updateTradeInfo(); - } + if (stations.size() == 0) { + return; + } + stationIndex = (stationIndex - 1 + stations.size()) % stations.size(); + updateTradeInfo(); + } - public void cycleFilter() { - if (player.worldObj.isRemote) { - Proxies.net.sendToServer(new PacketGuiSelectRequest(2, 0)); - return; - } + public void cycleFilter() { + if (player.worldObj.isRemote) { + Proxies.net.sendToServer(new PacketGuiSelectRequest(2, 0)); + return; + } - currentFilter = (currentFilter + 1) % FILTERS.size(); + currentFilter = (currentFilter + 1) % FILTERS.size(); - rebuildStationsList(); - } + rebuildStationsList(); + } - private static void sendSelection(boolean advance) { - int value = advance ? 0 : 1; - Proxies.net.sendToServer(new PacketGuiSelectRequest(value, 0)); - } + private static void sendSelection(boolean advance) { + int value = advance ? 0 : 1; + Proxies.net.sendToServer(new PacketGuiSelectRequest(value, 0)); + } - /* Managing Trade info */ - private void updateTradeInfo() { - // Updating is done by the server. - if (player.worldObj.isRemote) { - return; - } + /* Managing Trade info */ + private void updateTradeInfo() { + // Updating is done by the server. + if (player.worldObj.isRemote) { + return; + } - if (!stations.isEmpty()) { - ITradeStation station = stations.get(stationIndex); - setTradeInfo(station.getTradeInfo()); - } else { - setTradeInfo(null); - } - needsSynch = true; - } + if (!stations.isEmpty()) { + ITradeStation station = stations.get(stationIndex); + setTradeInfo(station.getTradeInfo()); + } else { + setTradeInfo(null); + } + needsSynch = true; + } - @Override - public void handleLetterInfoUpdate(PacketLetterInfoResponse packet) { - setTradeInfo(packet.tradeInfo); - } + @Override + public void handleLetterInfoUpdate(PacketLetterInfoResponse packet) { + setTradeInfo(packet.tradeInfo); + } - public TradeStationInfo getTradeInfo() { - return currentTrade; - } + public TradeStationInfo getTradeInfo() { + return currentTrade; + } - private void setTradeInfo(TradeStationInfo info) { - currentTrade = info; - } + private void setTradeInfo(TradeStationInfo info) { + currentTrade = info; + } - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); - if (needsSynch) { - for (Object crafter1 : crafters) { - ICrafting crafter = (ICrafting) crafter1; - crafter.sendProgressBarUpdate(this, 0, stationIndex); - crafter.sendProgressBarUpdate(this, 1, stations.size()); - crafter.sendProgressBarUpdate(this, 2, currentFilter); - } + if (needsSynch) { + for (Object crafter1 : crafters) { + ICrafting crafter = (ICrafting) crafter1; + crafter.sendProgressBarUpdate(this, 0, stationIndex); + crafter.sendProgressBarUpdate(this, 1, stations.size()); + crafter.sendProgressBarUpdate(this, 2, currentFilter); + } - Proxies.net.sendToPlayer(new PacketLetterInfoResponse(EnumAddressee.TRADER, currentTrade, null), player); - needsSynch = false; - } - } + Proxies.net.sendToPlayer(new PacketLetterInfoResponse(EnumAddressee.TRADER, currentTrade, null), player); + needsSynch = false; + } + } - @Override - public void updateProgressBar(int i, int j) { - switch (i) { - case 0: - stationIndex = j; - break; - case 1: - stationCount = j; - break; - case 2: - currentFilter = j; - break; - } - } + @Override + public void updateProgressBar(int i, int j) { + switch (i) { + case 0: + stationIndex = j; + break; + case 1: + stationCount = j; + break; + case 2: + currentFilter = j; + break; + } + } - @Override - public boolean canInteractWith(EntityPlayer p_75145_1_) { - return true; - } + @Override + public boolean canInteractWith(EntityPlayer p_75145_1_) { + return true; + } - @Override - public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { + @Override + public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { - switch (packet.getPrimaryIndex()) { - case 0: - nextPage(); - break; - case 1: - previousPage(); - break; - case 2: - cycleFilter(); - break; - } + switch (packet.getPrimaryIndex()) { + case 0: + nextPage(); + break; + case 1: + previousPage(); + break; + case 2: + cycleFilter(); + break; + } - needsSynch = true; - } + needsSynch = true; + } } diff --git a/src/main/java/forestry/mail/gui/ContainerLetter.java b/src/main/java/forestry/mail/gui/ContainerLetter.java index 24a0c1380..c6e1048e9 100755 --- a/src/main/java/forestry/mail/gui/ContainerLetter.java +++ b/src/main/java/forestry/mail/gui/ContainerLetter.java @@ -10,15 +10,7 @@ ******************************************************************************/ package forestry.mail.gui; -import java.util.Iterator; -import java.util.UUID; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.server.MinecraftServer; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import forestry.api.mail.EnumAddressee; import forestry.api.mail.ILetter; import forestry.api.mail.IMailAddress; @@ -34,187 +26,200 @@ import forestry.mail.Letter; import forestry.mail.inventory.ItemInventoryLetter; import forestry.mail.network.packets.PacketLetterInfoResponse; import forestry.mail.network.packets.PacketLetterTextSet; +import java.util.Iterator; +import java.util.UUID; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.World; public class ContainerLetter extends ContainerItemInventory implements ILetterInfoReceiver { - private EnumAddressee carrierType = EnumAddressee.PLAYER; - private TradeStationInfo tradeInfo = null; + private EnumAddressee carrierType = EnumAddressee.PLAYER; + private TradeStationInfo tradeInfo = null; - public ContainerLetter(EntityPlayer player, ItemInventoryLetter inventory) { - super(inventory, player.inventory, 17, 145); + public ContainerLetter(EntityPlayer player, ItemInventoryLetter inventory) { + super(inventory, player.inventory, 17, 145); - // Init slots + // Init slots - // Stamps - for (int i = 0; i < 4; i++) { - addSlotToContainer(new SlotFiltered(inventory, Letter.SLOT_POSTAGE_1 + i, 150, 14 + i * 19).setStackLimit(1)); - } + // Stamps + for (int i = 0; i < 4; i++) { + addSlotToContainer( + new SlotFiltered(inventory, Letter.SLOT_POSTAGE_1 + i, 150, 14 + i * 19).setStackLimit(1)); + } - // Attachments - for (int i = 0; i < 2; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new SlotFiltered(inventory, Letter.SLOT_ATTACHMENT_1 + j + i * 9, 17 + j * 18, 98 + i * 18)); - } - } + // Attachments + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 9; j++) { + addSlotToContainer( + new SlotFiltered(inventory, Letter.SLOT_ATTACHMENT_1 + j + i * 9, 17 + j * 18, 98 + i * 18)); + } + } - // Rip open delivered mails - if (!player.worldObj.isRemote) { - if (inventory.getLetter().isProcessed()) { - inventory.onLetterOpened(); - } - } + // Rip open delivered mails + if (!player.worldObj.isRemote) { + if (inventory.getLetter().isProcessed()) { + inventory.onLetterOpened(); + } + } - // Set recipient type - ILetter letter = inventory.getLetter(); - if (letter != null) { - IMailAddress[] recipients = letter.getRecipients(); - if (recipients != null && recipients.length > 0) { - this.carrierType = recipients[0].getType(); - } - } - } + // Set recipient type + ILetter letter = inventory.getLetter(); + if (letter != null) { + IMailAddress[] recipients = letter.getRecipients(); + if (recipients != null && recipients.length > 0) { + this.carrierType = recipients[0].getType(); + } + } + } - @Override - public void onContainerClosed(EntityPlayer entityplayer) { + @Override + public void onContainerClosed(EntityPlayer entityplayer) { - if (!entityplayer.worldObj.isRemote) { - ILetter letter = inventory.getLetter(); - if (!letter.isProcessed()) { - IMailAddress sender = PostManager.postRegistry.getMailAddress(entityplayer.getGameProfile()); - letter.setSender(sender); - } - } + if (!entityplayer.worldObj.isRemote) { + ILetter letter = inventory.getLetter(); + if (!letter.isProcessed()) { + IMailAddress sender = PostManager.postRegistry.getMailAddress(entityplayer.getGameProfile()); + letter.setSender(sender); + } + } - inventory.onLetterClosed(); + inventory.onLetterClosed(); - super.onContainerClosed(entityplayer); - } + super.onContainerClosed(entityplayer); + } - public ILetter getLetter() { - return inventory.getLetter(); - } + public ILetter getLetter() { + return inventory.getLetter(); + } - public void setCarrierType(EnumAddressee type) { - this.carrierType = type; - } + public void setCarrierType(EnumAddressee type) { + this.carrierType = type; + } - public EnumAddressee getCarrierType() { - return this.carrierType; - } + public EnumAddressee getCarrierType() { + return this.carrierType; + } - public void advanceCarrierType() { - Iterator it = PostManager.postRegistry.getRegisteredCarriers().values().iterator(); - while (it.hasNext()) { - if (it.next().getType().equals(carrierType)) { - break; - } - } + public void advanceCarrierType() { + Iterator it = + PostManager.postRegistry.getRegisteredCarriers().values().iterator(); + while (it.hasNext()) { + if (it.next().getType().equals(carrierType)) { + break; + } + } - IPostalCarrier postal; - if (it.hasNext()) { - postal = it.next(); - } else { - postal = PostManager.postRegistry.getRegisteredCarriers().values().iterator().next(); - } + IPostalCarrier postal; + if (it.hasNext()) { + postal = it.next(); + } else { + postal = PostManager.postRegistry + .getRegisteredCarriers() + .values() + .iterator() + .next(); + } - setCarrierType(postal.getType()); - } + setCarrierType(postal.getType()); + } - public void handleRequestLetterInfo(EntityPlayer player, String recipientName, EnumAddressee type) { - IMailAddress recipient = getRecipient(recipientName, type); + public void handleRequestLetterInfo(EntityPlayer player, String recipientName, EnumAddressee type) { + IMailAddress recipient = getRecipient(recipientName, type); - getLetter().setRecipient(recipient); - - // Update the trading info - if (recipient == null || recipient.isTrader()) { - updateTradeInfo(player.worldObj, recipient); - } - - // Update info on client - Proxies.net.sendToPlayer(new PacketLetterInfoResponse(type, tradeInfo, recipient), player); - } + getLetter().setRecipient(recipient); - private static IMailAddress getRecipient(String recipientName, EnumAddressee type) { - switch (type) { - case PLAYER: { - GameProfile gameProfile = MinecraftServer.getServer().func_152358_ax().func_152655_a(recipientName); - if (gameProfile == null) { - gameProfile = new GameProfile(new UUID(0, 0), recipientName); - } - return PostManager.postRegistry.getMailAddress(gameProfile); - } - case TRADER: { - return PostManager.postRegistry.getMailAddress(recipientName); - } - default: - return null; - } - } + // Update the trading info + if (recipient == null || recipient.isTrader()) { + updateTradeInfo(player.worldObj, recipient); + } - public IMailAddress getRecipient() { - if (getLetter().getRecipients().length > 0) { - return getLetter().getRecipients()[0]; - } else { - return null; - } - } + // Update info on client + Proxies.net.sendToPlayer(new PacketLetterInfoResponse(type, tradeInfo, recipient), player); + } - public String getText() { - return getLetter().getText(); - } + private static IMailAddress getRecipient(String recipientName, EnumAddressee type) { + switch (type) { + case PLAYER: { + GameProfile gameProfile = + MinecraftServer.getServer().func_152358_ax().func_152655_a(recipientName); + if (gameProfile == null) { + gameProfile = new GameProfile(new UUID(0, 0), recipientName); + } + return PostManager.postRegistry.getMailAddress(gameProfile); + } + case TRADER: { + return PostManager.postRegistry.getMailAddress(recipientName); + } + default: + return null; + } + } - public void setText(String text) { - getLetter().setText(text); + public IMailAddress getRecipient() { + if (getLetter().getRecipients().length > 0) { + return getLetter().getRecipients()[0]; + } else { + return null; + } + } - Proxies.net.sendToServer(new PacketLetterTextSet(text)); - } + public String getText() { + return getLetter().getText(); + } - public void handleSetText(PacketString packet) { - String text = packet.getString(); - getLetter().setText(text); - } + public void setText(String text) { + getLetter().setText(text); - /* Managing Trade info */ - private void updateTradeInfo(World world, IMailAddress address) { - // Updating is done by the server. - if (world.isRemote) { - return; - } + Proxies.net.sendToServer(new PacketLetterTextSet(text)); + } - if (address == null) { - setTradeInfo(null); - return; - } + public void handleSetText(PacketString packet) { + String text = packet.getString(); + getLetter().setText(text); + } - ITradeStation station = PostManager.postRegistry.getTradeStation(world, address); - if (station == null) { - setTradeInfo(null); - return; - } + /* Managing Trade info */ + private void updateTradeInfo(World world, IMailAddress address) { + // Updating is done by the server. + if (world.isRemote) { + return; + } - setTradeInfo(station.getTradeInfo()); - } + if (address == null) { + setTradeInfo(null); + return; + } - @Override - public void handleLetterInfoUpdate(PacketLetterInfoResponse packet) { - carrierType = packet.type; - if (packet.type == EnumAddressee.PLAYER) { - getLetter().setRecipient(packet.address); - } else if (packet.type == EnumAddressee.TRADER) { - this.setTradeInfo(packet.tradeInfo); - } - } + ITradeStation station = PostManager.postRegistry.getTradeStation(world, address); + if (station == null) { + setTradeInfo(null); + return; + } - public TradeStationInfo getTradeInfo() { - return this.tradeInfo; - } + setTradeInfo(station.getTradeInfo()); + } - private void setTradeInfo(TradeStationInfo info) { - this.tradeInfo = info; - if (tradeInfo == null) { - getLetter().setRecipient(null); - } else { - getLetter().setRecipient(tradeInfo.address); - } - } + @Override + public void handleLetterInfoUpdate(PacketLetterInfoResponse packet) { + carrierType = packet.type; + if (packet.type == EnumAddressee.PLAYER) { + getLetter().setRecipient(packet.address); + } else if (packet.type == EnumAddressee.TRADER) { + this.setTradeInfo(packet.tradeInfo); + } + } + + public TradeStationInfo getTradeInfo() { + return this.tradeInfo; + } + + private void setTradeInfo(TradeStationInfo info) { + this.tradeInfo = info; + if (tradeInfo == null) { + getLetter().setRecipient(null); + } else { + getLetter().setRecipient(tradeInfo.address); + } + } } diff --git a/src/main/java/forestry/mail/gui/ContainerMailbox.java b/src/main/java/forestry/mail/gui/ContainerMailbox.java index 6bea0fc56..2d1200fc6 100755 --- a/src/main/java/forestry/mail/gui/ContainerMailbox.java +++ b/src/main/java/forestry/mail/gui/ContainerMailbox.java @@ -10,11 +10,6 @@ ******************************************************************************/ package forestry.mail.gui; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - import forestry.core.gui.ContainerTile; import forestry.core.gui.slots.SlotOutput; import forestry.core.proxy.Proxies; @@ -23,42 +18,47 @@ import forestry.mail.POBox; import forestry.mail.POBoxInfo; import forestry.mail.network.packets.PacketPOBoxInfoUpdate; import forestry.mail.tiles.TileMailbox; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; public class ContainerMailbox extends ContainerTile { - public static final short SLOT_LETTERS = 0; - public static final short SLOT_LETTERS_COUNT = 7 * 12; + public static final short SLOT_LETTERS = 0; + public static final short SLOT_LETTERS_COUNT = 7 * 12; - private final POBox mailInventory; + private final POBox mailInventory; - public ContainerMailbox(InventoryPlayer playerInventory, TileMailbox tile) { - super(tile, playerInventory, 35, 145); - IInventory inventory = tile.getOrCreateMailInventory(playerInventory.player.worldObj, playerInventory.player.getGameProfile()); + public ContainerMailbox(InventoryPlayer playerInventory, TileMailbox tile) { + super(tile, playerInventory, 35, 145); + IInventory inventory = + tile.getOrCreateMailInventory(playerInventory.player.worldObj, playerInventory.player.getGameProfile()); - if (inventory instanceof POBox) { - this.mailInventory = (POBox) inventory; - } else { - this.mailInventory = null; - } + if (inventory instanceof POBox) { + this.mailInventory = (POBox) inventory; + } else { + this.mailInventory = null; + } - for (int i = 0; i < 7; i++) { - for (int j = 0; j < 12; j++) { - addSlotToContainer(new SlotOutput(inventory, j + i * 9, 8 + j * 18, 8 + i * 18)); - } - } - } + for (int i = 0; i < 7; i++) { + for (int j = 0; j < 12; j++) { + addSlotToContainer(new SlotOutput(inventory, j + i * 9, 8 + j * 18, 8 + i * 18)); + } + } + } - @Override - public ItemStack slotClick(int slotIndex, int button, int par3, EntityPlayer player) { - ItemStack stack = super.slotClick(slotIndex, button, par3, player); + @Override + public ItemStack slotClick(int slotIndex, int button, int par3, EntityPlayer player) { + ItemStack stack = super.slotClick(slotIndex, button, par3, player); - if (SlotUtil.isSlotInRange(slotIndex, SLOT_LETTERS, SLOT_LETTERS_COUNT)) { - if (!player.worldObj.isRemote && mailInventory != null) { - POBoxInfo info = mailInventory.getPOBoxInfo(); - Proxies.net.sendToPlayer(new PacketPOBoxInfoUpdate(info), player); - } - } + if (SlotUtil.isSlotInRange(slotIndex, SLOT_LETTERS, SLOT_LETTERS_COUNT)) { + if (!player.worldObj.isRemote && mailInventory != null) { + POBoxInfo info = mailInventory.getPOBoxInfo(); + Proxies.net.sendToPlayer(new PacketPOBoxInfoUpdate(info), player); + } + } - return stack; - } + return stack; + } } diff --git a/src/main/java/forestry/mail/gui/ContainerStampCollector.java b/src/main/java/forestry/mail/gui/ContainerStampCollector.java index e3757b53a..0184a13ce 100644 --- a/src/main/java/forestry/mail/gui/ContainerStampCollector.java +++ b/src/main/java/forestry/mail/gui/ContainerStampCollector.java @@ -10,27 +10,27 @@ ******************************************************************************/ package forestry.mail.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.gui.ContainerTile; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.mail.inventory.InventoryStampCollector; import forestry.mail.tiles.TileStampCollector; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerStampCollector extends ContainerTile { - public ContainerStampCollector(InventoryPlayer player, TileStampCollector tile) { - super(tile, player, 8, 111); + public ContainerStampCollector(InventoryPlayer player, TileStampCollector tile) { + super(tile, player, 8, 111); - // Filter - addSlotToContainer(new SlotFiltered(tile, InventoryStampCollector.SLOT_FILTER, 80, 19)); + // Filter + addSlotToContainer(new SlotFiltered(tile, InventoryStampCollector.SLOT_FILTER, 80, 19)); - // Collected Stamps - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new SlotOutput(tile, j + i * 9 + InventoryStampCollector.SLOT_BUFFER_1, 8 + j * 18, 46 + i * 18)); - } - } - } + // Collected Stamps + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + addSlotToContainer(new SlotOutput( + tile, j + i * 9 + InventoryStampCollector.SLOT_BUFFER_1, 8 + j * 18, 46 + i * 18)); + } + } + } } diff --git a/src/main/java/forestry/mail/gui/ContainerTradeName.java b/src/main/java/forestry/mail/gui/ContainerTradeName.java index d73947462..7ee8bed43 100755 --- a/src/main/java/forestry/mail/gui/ContainerTradeName.java +++ b/src/main/java/forestry/mail/gui/ContainerTradeName.java @@ -10,33 +10,32 @@ ******************************************************************************/ package forestry.mail.gui; -import net.minecraft.entity.player.EntityPlayer; - import forestry.api.mail.IMailAddress; import forestry.core.gui.ContainerTile; import forestry.mail.tiles.TileTrader; +import net.minecraft.entity.player.EntityPlayer; public class ContainerTradeName extends ContainerTile { - public ContainerTradeName(TileTrader tile) { - super(tile); - } + public ContainerTradeName(TileTrader tile) { + super(tile); + } - public IMailAddress getAddress() { - return tile.getAddress(); - } + public IMailAddress getAddress() { + return tile.getAddress(); + } - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); - if (tile.isLinked()) { - for (Object crafter : crafters) { - if (crafter instanceof EntityPlayer) { - EntityPlayer player = (EntityPlayer) crafter; - tile.openGui(player); - } - } - } - } + if (tile.isLinked()) { + for (Object crafter : crafters) { + if (crafter instanceof EntityPlayer) { + EntityPlayer player = (EntityPlayer) crafter; + tile.openGui(player); + } + } + } + } } diff --git a/src/main/java/forestry/mail/gui/ContainerTrader.java b/src/main/java/forestry/mail/gui/ContainerTrader.java index 4ec08bc55..7c1aa33a0 100755 --- a/src/main/java/forestry/mail/gui/ContainerTrader.java +++ b/src/main/java/forestry/mail/gui/ContainerTrader.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.mail.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.api.mail.IMailAddress; import forestry.core.gui.ContainerTile; import forestry.core.gui.slots.SlotFiltered; @@ -19,53 +17,65 @@ import forestry.core.gui.slots.SlotForestry; import forestry.core.gui.slots.SlotOutput; import forestry.mail.TradeStation; import forestry.mail.tiles.TileTrader; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerTrader extends ContainerTile { - public ContainerTrader(InventoryPlayer player, TileTrader tile) { - super(tile, player, 33, 138); + public ContainerTrader(InventoryPlayer player, TileTrader tile) { + super(tile, player, 33, 138); - // Trade good - this.addSlotToContainer(new SlotForestry(this.tile, TradeStation.SLOT_TRADEGOOD, 78, 109).blockShift()); + // Trade good + this.addSlotToContainer(new SlotForestry(this.tile, TradeStation.SLOT_TRADEGOOD, 78, 109).blockShift()); - // Exchange - for (int row = 0; row < 2; row++) { - for (int col = 0; col < 2; col++) { - addSlotToContainer(new SlotForestry(this.tile, TradeStation.SLOT_EXCHANGE_1 + col + row * 2, 69 + col * 18, 55 + row * 18).blockShift()); - } - } + // Exchange + for (int row = 0; row < 2; row++) { + for (int col = 0; col < 2; col++) { + addSlotToContainer(new SlotForestry( + this.tile, TradeStation.SLOT_EXCHANGE_1 + col + row * 2, 69 + col * 18, 55 + row * 18) + .blockShift()); + } + } - // Stamps - for (int row = 0; row < 2; row++) { - for (int col = 0; col < 2; col++) { - addSlotToContainer(new SlotFiltered(this.tile, TradeStation.SLOT_STAMPS_1 + col + row * 2, 15 + col * 18, 37 + row * 18)); - } - } + // Stamps + for (int row = 0; row < 2; row++) { + for (int col = 0; col < 2; col++) { + addSlotToContainer(new SlotFiltered( + this.tile, TradeStation.SLOT_STAMPS_1 + col + row * 2, 15 + col * 18, 37 + row * 18)); + } + } - // Letters - for (int row = 0; row < 3; row++) { - for (int col = 0; col < 2; col++) { - addSlotToContainer(new SlotFiltered(this.tile, TradeStation.SLOT_LETTERS_1 + col + row * 2, 15 + col * 18, 73 + row * 18)); - } - } + // Letters + for (int row = 0; row < 3; row++) { + for (int col = 0; col < 2; col++) { + addSlotToContainer(new SlotFiltered( + this.tile, TradeStation.SLOT_LETTERS_1 + col + row * 2, 15 + col * 18, 73 + row * 18)); + } + } - // Buffers - final int bufCols = 5; - for (int row = 0; row < 3; row++) { - for (int col = 0; col < bufCols; col++) { - addSlotToContainer(new SlotOutput(this.tile, TradeStation.SLOT_RECEIVE_BUFFER + col + row * bufCols, 123 + col * 18, 19 + row * 18)); - } - } + // Buffers + final int bufCols = 5; + for (int row = 0; row < 3; row++) { + for (int col = 0; col < bufCols; col++) { + addSlotToContainer(new SlotOutput( + this.tile, + TradeStation.SLOT_RECEIVE_BUFFER + col + row * bufCols, + 123 + col * 18, + 19 + row * 18)); + } + } - for (int row = 0; row < 2; row++) { - for (int col = 0; col < bufCols; col++) { - addSlotToContainer(new SlotFiltered(this.tile, TradeStation.SLOT_SEND_BUFFER + col + row * bufCols, 123 + col * 18, (19 + (18 * 4)) + row * 18)); - } - } - } - - public IMailAddress getAddress() { - return tile.getAddress(); - } + for (int row = 0; row < 2; row++) { + for (int col = 0; col < bufCols; col++) { + addSlotToContainer(new SlotFiltered( + this.tile, + TradeStation.SLOT_SEND_BUFFER + col + row * bufCols, + 123 + col * 18, + (19 + (18 * 4)) + row * 18)); + } + } + } + public IMailAddress getAddress() { + return tile.getAddress(); + } } diff --git a/src/main/java/forestry/mail/gui/GuiCatalogue.java b/src/main/java/forestry/mail/gui/GuiCatalogue.java index fe7c68e7f..683768aa2 100755 --- a/src/main/java/forestry/mail/gui/GuiCatalogue.java +++ b/src/main/java/forestry/mail/gui/GuiCatalogue.java @@ -10,18 +10,6 @@ ******************************************************************************/ package forestry.mail.gui; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.input.Keyboard; - import forestry.api.mail.EnumAddressee; import forestry.api.mail.TradeStationInfo; import forestry.core.config.SessionVars; @@ -29,128 +17,157 @@ import forestry.core.gui.GuiForestry; import forestry.core.gui.widgets.ItemStackWidget; import forestry.core.gui.widgets.Widget; import forestry.core.utils.StringUtil; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.ResourceLocation; +import org.lwjgl.input.Keyboard; public class GuiCatalogue extends GuiForestry { - private static final String boldUnderline = EnumChatFormatting.BOLD.toString() + EnumChatFormatting.UNDERLINE; + private static final String boldUnderline = EnumChatFormatting.BOLD.toString() + EnumChatFormatting.UNDERLINE; - private GuiButton buttonFilter; - private GuiButton buttonUse; + private GuiButton buttonFilter; + private GuiButton buttonUse; - private final List tradeInfoWidgets = new ArrayList<>(); + private final List tradeInfoWidgets = new ArrayList<>(); - public GuiCatalogue(EntityPlayer player) { - super(new ResourceLocation("textures/gui/book.png"), new ContainerCatalogue(player), null); - this.xSize = 192; - this.ySize = 192; - } + public GuiCatalogue(EntityPlayer player) { + super(new ResourceLocation("textures/gui/book.png"), new ContainerCatalogue(player), null); + this.xSize = 192; + this.ySize = 192; + } - @SuppressWarnings("unchecked") - @Override - public void initGui() { - super.initGui(); + @SuppressWarnings("unchecked") + @Override + public void initGui() { + super.initGui(); - buttonList.clear(); - Keyboard.enableRepeatEvents(true); + buttonList.clear(); + Keyboard.enableRepeatEvents(true); - buttonList.add(new GuiButton(2, width / 2 + 44, guiTop + 150, 12, 20, ">")); - buttonList.add(new GuiButton(3, width / 2 - 58, guiTop + 150, 12, 20, "<")); + buttonList.add(new GuiButton(2, width / 2 + 44, guiTop + 150, 12, 20, ">")); + buttonList.add(new GuiButton(3, width / 2 - 58, guiTop + 150, 12, 20, "<")); - buttonFilter = new GuiButton(4, (width / 2) - 44, guiTop + 150, 42, 20, StringUtil.localize("gui.mail.filter.all")); - buttonList.add(buttonFilter); + buttonFilter = + new GuiButton(4, (width / 2) - 44, guiTop + 150, 42, 20, StringUtil.localize("gui.mail.filter.all")); + buttonList.add(buttonFilter); - buttonUse = new GuiButton(5, width / 2, guiTop + 150, 42, 20, StringUtil.localize("gui.mail.address.copy")); - buttonList.add(buttonUse); - } + buttonUse = new GuiButton(5, width / 2, guiTop + 150, 42, 20, StringUtil.localize("gui.mail.address.copy")); + buttonList.add(buttonUse); + } - @Override - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - super.onGuiClosed(); - } + @Override + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + super.onGuiClosed(); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - fontRendererObj.drawString(String.format("%s / %s", container.getPageNumber(), container.getPageCount()), guiLeft + xSize - 72, guiTop + 12, fontColor.get("gui.book")); + fontRendererObj.drawString( + String.format("%s / %s", container.getPageNumber(), container.getPageCount()), + guiLeft + xSize - 72, + guiTop + 12, + fontColor.get("gui.book")); - clearTradeInfoWidgets(); + clearTradeInfoWidgets(); - TradeStationInfo tradeInfo = container.getTradeInfo(); + TradeStationInfo tradeInfo = container.getTradeInfo(); - if (tradeInfo != null) { - drawTradePreview(tradeInfo, guiLeft + 38, guiTop + 30); - buttonUse.enabled = tradeInfo.state.isOk(); - } else { - drawNoTrade(guiLeft + 38, guiTop + 30); - buttonUse.enabled = false; - } + if (tradeInfo != null) { + drawTradePreview(tradeInfo, guiLeft + 38, guiTop + 30); + buttonUse.enabled = tradeInfo.state.isOk(); + } else { + drawNoTrade(guiLeft + 38, guiTop + 30); + buttonUse.enabled = false; + } - buttonFilter.displayString = StringUtil.localize("gui.mail.filter." + container.getFilterIdent()); - } + buttonFilter.displayString = StringUtil.localize("gui.mail.filter." + container.getFilterIdent()); + } - private void drawNoTrade(int x, int y) { - fontRendererObj.drawSplitString(StringUtil.localize("gui.mail.notrades"), x, y + 18, 119, fontColor.get("gui.book")); - } + private void drawNoTrade(int x, int y) { + fontRendererObj.drawSplitString( + StringUtil.localize("gui.mail.notrades"), x, y + 18, 119, fontColor.get("gui.book")); + } - private void drawTradePreview(TradeStationInfo tradeInfo, int x, int y) { + private void drawTradePreview(TradeStationInfo tradeInfo, int x, int y) { - fontRendererObj.drawString(boldUnderline + tradeInfo.address.getName(), x, y, fontColor.get("gui.book")); + fontRendererObj.drawString(boldUnderline + tradeInfo.address.getName(), x, y, fontColor.get("gui.book")); - fontRendererObj.drawString(String.format(StringUtil.localize("gui.mail.willtrade"), tradeInfo.owner.getName()), x, y + 18, fontColor.get("gui.book")); + fontRendererObj.drawString( + String.format(StringUtil.localize("gui.mail.willtrade"), tradeInfo.owner.getName()), + x, + y + 18, + fontColor.get("gui.book")); - addTradeInfoWidget(new ItemStackWidget(widgetManager, x - guiLeft, y - guiTop + 28, tradeInfo.tradegood)); + addTradeInfoWidget(new ItemStackWidget(widgetManager, x - guiLeft, y - guiTop + 28, tradeInfo.tradegood)); - fontRendererObj.drawString(StringUtil.localize("gui.mail.tradefor"), x, y + 46, fontColor.get("gui.book")); + fontRendererObj.drawString(StringUtil.localize("gui.mail.tradefor"), x, y + 46, fontColor.get("gui.book")); - for (int i = 0; i < tradeInfo.required.length; i++) { - ItemStack itemStack = tradeInfo.required[i]; - addTradeInfoWidget(new ItemStackWidget(widgetManager, x - guiLeft + i * 18, y - guiTop + 56, itemStack)); - } + for (int i = 0; i < tradeInfo.required.length; i++) { + ItemStack itemStack = tradeInfo.required[i]; + addTradeInfoWidget(new ItemStackWidget(widgetManager, x - guiLeft + i * 18, y - guiTop + 56, itemStack)); + } - if (tradeInfo.state.isOk()) { - fontRendererObj.drawSplitString(EnumChatFormatting.DARK_GREEN + StringUtil.localize("chat.mail." + tradeInfo.state.getIdentifier()), x, y + 82, 119, fontColor.get("gui.book")); - } else { - fontRendererObj.drawSplitString(EnumChatFormatting.DARK_RED + StringUtil.localize("chat.mail." + tradeInfo.state.getIdentifier()), x, y + 82, 119, fontColor.get("gui.book")); - } - } + if (tradeInfo.state.isOk()) { + fontRendererObj.drawSplitString( + EnumChatFormatting.DARK_GREEN + StringUtil.localize("chat.mail." + tradeInfo.state.getIdentifier()), + x, + y + 82, + 119, + fontColor.get("gui.book")); + } else { + fontRendererObj.drawSplitString( + EnumChatFormatting.DARK_RED + StringUtil.localize("chat.mail." + tradeInfo.state.getIdentifier()), + x, + y + 82, + 119, + fontColor.get("gui.book")); + } + } - private void addTradeInfoWidget(ItemStackWidget widget) { - tradeInfoWidgets.add(widget); - widgetManager.add(widget); - } + private void addTradeInfoWidget(ItemStackWidget widget) { + tradeInfoWidgets.add(widget); + widgetManager.add(widget); + } - private void clearTradeInfoWidgets() { - for (Widget widget : tradeInfoWidgets) { - widgetManager.remove(widget); - } - tradeInfoWidgets.clear(); - } + private void clearTradeInfoWidgets() { + for (Widget widget : tradeInfoWidgets) { + widgetManager.remove(widget); + } + tradeInfoWidgets.clear(); + } - @Override - protected void actionPerformed(GuiButton button) { - switch (button.id) { - case 0: - mc.thePlayer.closeScreen(); - break; - case 2: - container.nextPage(); - break; - case 3: - container.previousPage(); - break; - case 4: - container.cycleFilter(); - break; - case 5: - TradeStationInfo info = container.getTradeInfo(); - if (info != null) { - SessionVars.setStringVar("mail.letter.recipient", info.address.getName()); - SessionVars.setStringVar("mail.letter.addressee", EnumAddressee.TRADER.toString()); - } - mc.thePlayer.closeScreen(); - break; - } - } + @Override + protected void actionPerformed(GuiButton button) { + switch (button.id) { + case 0: + mc.thePlayer.closeScreen(); + break; + case 2: + container.nextPage(); + break; + case 3: + container.previousPage(); + break; + case 4: + container.cycleFilter(); + break; + case 5: + TradeStationInfo info = container.getTradeInfo(); + if (info != null) { + SessionVars.setStringVar("mail.letter.recipient", info.address.getName()); + SessionVars.setStringVar("mail.letter.addressee", EnumAddressee.TRADER.toString()); + } + mc.thePlayer.closeScreen(); + break; + } + } } diff --git a/src/main/java/forestry/mail/gui/GuiLetter.java b/src/main/java/forestry/mail/gui/GuiLetter.java index 48628e44c..920168477 100755 --- a/src/main/java/forestry/mail/gui/GuiLetter.java +++ b/src/main/java/forestry/mail/gui/GuiLetter.java @@ -10,15 +10,6 @@ ******************************************************************************/ package forestry.mail.gui; -import java.util.ArrayList; - -import org.apache.commons.lang3.StringUtils; - -import net.minecraft.client.gui.GuiTextField; -import net.minecraft.entity.player.EntityPlayer; - -import org.lwjgl.input.Keyboard; - import forestry.api.mail.EnumAddressee; import forestry.api.mail.IMailAddress; import forestry.core.config.Constants; @@ -32,215 +23,234 @@ import forestry.core.utils.StringUtil; import forestry.mail.gui.widgets.AddresseeSlot; import forestry.mail.inventory.ItemInventoryLetter; import forestry.mail.network.packets.PacketLetterInfoRequest; +import java.util.ArrayList; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.entity.player.EntityPlayer; +import org.apache.commons.lang3.StringUtils; +import org.lwjgl.input.Keyboard; public class GuiLetter extends GuiForestry { - private final boolean isProcessedLetter; - private boolean checkedSessionVars; + private final boolean isProcessedLetter; + private boolean checkedSessionVars; - private GuiTextField address; - private GuiTextBox text; + private GuiTextField address; + private GuiTextBox text; - private boolean addressFocus; - private boolean textFocus; + private boolean addressFocus; + private boolean textFocus; - private final ArrayList tradeInfoWidgets; + private final ArrayList tradeInfoWidgets; - public GuiLetter(EntityPlayer player, ItemInventoryLetter inventory) { - super(Constants.TEXTURE_PATH_GUI + "/letter.png", new ContainerLetter(player, inventory), inventory); - this.xSize = 194; - this.ySize = 227; + public GuiLetter(EntityPlayer player, ItemInventoryLetter inventory) { + super(Constants.TEXTURE_PATH_GUI + "/letter.png", new ContainerLetter(player, inventory), inventory); + this.xSize = 194; + this.ySize = 227; - this.isProcessedLetter = container.getLetter().isProcessed(); - this.widgetManager.add(new AddresseeSlot(widgetManager, 16, 12, container)); - this.tradeInfoWidgets = new ArrayList<>(); - } + this.isProcessedLetter = container.getLetter().isProcessed(); + this.widgetManager.add(new AddresseeSlot(widgetManager, 16, 12, container)); + this.tradeInfoWidgets = new ArrayList<>(); + } - @Override - public void initGui() { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - Keyboard.enableRepeatEvents(true); + Keyboard.enableRepeatEvents(true); - address = new GuiTextField(this.fontRendererObj, guiLeft + 46, guiTop + 13, 93, 13); - IMailAddress recipient = container.getRecipient(); - if (recipient != null) { - address.setText(recipient.getName()); - } + address = new GuiTextField(this.fontRendererObj, guiLeft + 46, guiTop + 13, 93, 13); + IMailAddress recipient = container.getRecipient(); + if (recipient != null) { + address.setText(recipient.getName()); + } - text = new GuiTextBox(this.fontRendererObj, guiLeft + 17, guiTop + 31, 122, 57); - text.setMaxStringLength(128); - if (!container.getText().isEmpty()) { - text.setText(container.getText()); - } - } + text = new GuiTextBox(this.fontRendererObj, guiLeft + 17, guiTop + 31, 122, 57); + text.setMaxStringLength(128); + if (!container.getText().isEmpty()) { + text.setText(container.getText()); + } + } - @Override - protected void keyTyped(char eventCharacter, int eventKey) { + @Override + protected void keyTyped(char eventCharacter, int eventKey) { - // Set focus or enter text into address - if (this.address.isFocused()) { - if (eventKey == Keyboard.KEY_RETURN) { - this.address.setFocused(false); - } else { - this.address.textboxKeyTyped(eventCharacter, eventKey); - } - return; - } + // Set focus or enter text into address + if (this.address.isFocused()) { + if (eventKey == Keyboard.KEY_RETURN) { + this.address.setFocused(false); + } else { + this.address.textboxKeyTyped(eventCharacter, eventKey); + } + return; + } - if (this.text.isFocused()) { - if (eventKey == Keyboard.KEY_RETURN) { - if (Proxies.common.isShiftDown()) { - text.setText(text.getText() + "\n"); - } else { - this.text.setFocused(false); - } - } else if (eventKey == Keyboard.KEY_DOWN) { - text.advanceLine(); - } else if (eventKey == Keyboard.KEY_UP) { - text.regressLine(); - } else if (text.moreLinesAllowed() || eventKey == Keyboard.KEY_DELETE || eventKey == Keyboard.KEY_BACK) { - this.text.textboxKeyTyped(eventCharacter, eventKey); - } - return; - } + if (this.text.isFocused()) { + if (eventKey == Keyboard.KEY_RETURN) { + if (Proxies.common.isShiftDown()) { + text.setText(text.getText() + "\n"); + } else { + this.text.setFocused(false); + } + } else if (eventKey == Keyboard.KEY_DOWN) { + text.advanceLine(); + } else if (eventKey == Keyboard.KEY_UP) { + text.regressLine(); + } else if (text.moreLinesAllowed() || eventKey == Keyboard.KEY_DELETE || eventKey == Keyboard.KEY_BACK) { + this.text.textboxKeyTyped(eventCharacter, eventKey); + } + return; + } - super.keyTyped(eventCharacter, eventKey); - } + super.keyTyped(eventCharacter, eventKey); + } - @Override - protected void mouseClicked(int par1, int par2, int mouseButton) { - super.mouseClicked(par1, par2, mouseButton); + @Override + protected void mouseClicked(int par1, int par2, int mouseButton) { + super.mouseClicked(par1, par2, mouseButton); - this.address.mouseClicked(par1, par2, mouseButton); - this.text.mouseClicked(par1, par2, mouseButton); + this.address.mouseClicked(par1, par2, mouseButton); + this.text.mouseClicked(par1, par2, mouseButton); + } - } + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + if (!isProcessedLetter && !checkedSessionVars) { + checkedSessionVars = true; + setFromSessionVars(); + String recipient = this.address.getText(); + EnumAddressee recipientType = container.getCarrierType(); + setRecipient(recipient, recipientType); + } - if (!isProcessedLetter && !checkedSessionVars) { - checkedSessionVars = true; - setFromSessionVars(); - String recipient = this.address.getText(); - EnumAddressee recipientType = container.getCarrierType(); - setRecipient(recipient, recipientType); - } + // Check for focus changes + if (addressFocus != address.isFocused()) { + String recipient = this.address.getText(); + if (StringUtils.isNotBlank(recipient)) { + EnumAddressee recipientType = container.getCarrierType(); + setRecipient(recipient, recipientType); + } + } + addressFocus = address.isFocused(); + if (textFocus != text.isFocused()) { + setText(); + } + textFocus = text.isFocused(); - // Check for focus changes - if (addressFocus != address.isFocused()) { - String recipient = this.address.getText(); - if (StringUtils.isNotBlank(recipient)) { - EnumAddressee recipientType = container.getCarrierType(); - setRecipient(recipient, recipientType); - } - } - addressFocus = address.isFocused(); - if (textFocus != text.isFocused()) { - setText(); - } - textFocus = text.isFocused(); + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + if (this.isProcessedLetter) { + fontRendererObj.drawString( + address.getText(), guiLeft + 49, guiTop + 16, fontColor.get("gui.mail.lettertext")); + fontRendererObj.drawSplitString( + text.getText(), guiLeft + 20, guiTop + 34, 119, fontColor.get("gui.mail.lettertext")); + } else { + clearTradeInfoWidgets(); + address.drawTextBox(); + if (container.getCarrierType() == EnumAddressee.TRADER) { + drawTradePreview(18, 32); + } else { + text.drawTextBox(); + } + } + } - if (this.isProcessedLetter) { - fontRendererObj.drawString(address.getText(), guiLeft + 49, guiTop + 16, fontColor.get("gui.mail.lettertext")); - fontRendererObj.drawSplitString(text.getText(), guiLeft + 20, guiTop + 34, 119, fontColor.get("gui.mail.lettertext")); - } else { - clearTradeInfoWidgets(); - address.drawTextBox(); - if (container.getCarrierType() == EnumAddressee.TRADER) { - drawTradePreview(18, 32); - } else { - text.drawTextBox(); - } - } - } + private void drawTradePreview(int x, int y) { - private void drawTradePreview(int x, int y) { + String infoString = null; + if (container.getTradeInfo() == null) { + infoString = "gui.mail.notrader"; + } else if (container.getTradeInfo().tradegood == null) { + infoString = "gui.mail.nothingtotrade"; + } else if (!container.getTradeInfo().state.isOk()) { + infoString = "chat.mail." + container.getTradeInfo().state.getIdentifier(); + } - String infoString = null; - if (container.getTradeInfo() == null) { - infoString = "gui.mail.notrader"; - } else if (container.getTradeInfo().tradegood == null) { - infoString = "gui.mail.nothingtotrade"; - } else if (!container.getTradeInfo().state.isOk()) { - infoString = "chat.mail." + container.getTradeInfo().state.getIdentifier(); - } + if (infoString != null) { + fontRendererObj.drawSplitString( + StringUtil.localize(infoString), + guiLeft + x, + guiTop + y, + 119, + fontColor.get("gui.mail.lettertext")); + return; + } - if (infoString != null) { - fontRendererObj.drawSplitString(StringUtil.localize(infoString), guiLeft + x, guiTop + y, 119, fontColor.get("gui.mail.lettertext")); - return; - } + fontRendererObj.drawString( + StringUtil.localize("gui.mail.pleasesend"), + guiLeft + x, + guiTop + y, + fontColor.get("gui.mail.lettertext")); - fontRendererObj.drawString(StringUtil.localize("gui.mail.pleasesend"), guiLeft + x, guiTop + y, fontColor.get("gui.mail.lettertext")); + addTradeInfoWidget(new ItemStackWidget(widgetManager, x, y + 10, container.getTradeInfo().tradegood)); - addTradeInfoWidget(new ItemStackWidget(widgetManager, x, y + 10, container.getTradeInfo().tradegood)); + fontRendererObj.drawString( + StringUtil.localize("gui.mail.foreveryattached"), + guiLeft + x, + guiTop + y + 28, + fontColor.get("gui.mail.lettertext")); - fontRendererObj.drawString(StringUtil.localize("gui.mail.foreveryattached"), guiLeft + x, guiTop + y + 28, fontColor.get("gui.mail.lettertext")); + for (int i = 0; i < container.getTradeInfo().required.length; i++) { + addTradeInfoWidget( + new ItemStackWidget(widgetManager, x + i * 18, y + 38, container.getTradeInfo().required[i])); + } + } - for (int i = 0; i < container.getTradeInfo().required.length; i++) { - addTradeInfoWidget(new ItemStackWidget(widgetManager, x + i * 18, y + 38, container.getTradeInfo().required[i])); - } - } + private void addTradeInfoWidget(Widget widget) { + tradeInfoWidgets.add(widget); + widgetManager.add(widget); + } - private void addTradeInfoWidget(Widget widget) { - tradeInfoWidgets.add(widget); - widgetManager.add(widget); - } + private void clearTradeInfoWidgets() { + for (Widget widget : tradeInfoWidgets) { + widgetManager.remove(widget); + } + tradeInfoWidgets.clear(); + } - private void clearTradeInfoWidgets() { - for (Widget widget : tradeInfoWidgets) { - widgetManager.remove(widget); - } - tradeInfoWidgets.clear(); - } + @Override + public void onGuiClosed() { + String recipientName = this.address.getText(); + EnumAddressee recipientType = container.getCarrierType(); + setRecipient(recipientName, recipientType); + setText(); + Keyboard.enableRepeatEvents(false); + super.onGuiClosed(); + } - @Override - public void onGuiClosed() { - String recipientName = this.address.getText(); - EnumAddressee recipientType = container.getCarrierType(); - setRecipient(recipientName, recipientType); - setText(); - Keyboard.enableRepeatEvents(false); - super.onGuiClosed(); - } + private void setFromSessionVars() { + if (SessionVars.getStringVar("mail.letter.recipient") == null) { + return; + } - private void setFromSessionVars() { - if (SessionVars.getStringVar("mail.letter.recipient") == null) { - return; - } + String recipient = SessionVars.getStringVar("mail.letter.recipient"); + String typeName = SessionVars.getStringVar("mail.letter.addressee"); - String recipient = SessionVars.getStringVar("mail.letter.recipient"); - String typeName = SessionVars.getStringVar("mail.letter.addressee"); - - if (StringUtils.isNotBlank(recipient) && StringUtils.isNotBlank(typeName)) { - address.setText(recipient); + if (StringUtils.isNotBlank(recipient) && StringUtils.isNotBlank(typeName)) { + address.setText(recipient); - EnumAddressee type = EnumAddressee.fromString(typeName); - container.setCarrierType(type); - } + EnumAddressee type = EnumAddressee.fromString(typeName); + container.setCarrierType(type); + } - SessionVars.clearStringVar("mail.letter.recipient"); - SessionVars.clearStringVar("mail.letter.addressee"); - } + SessionVars.clearStringVar("mail.letter.recipient"); + SessionVars.clearStringVar("mail.letter.addressee"); + } - private void setRecipient(String recipientName, EnumAddressee type) { - if (this.isProcessedLetter || StringUtils.isBlank(recipientName) || type == null) { - return; - } + private void setRecipient(String recipientName, EnumAddressee type) { + if (this.isProcessedLetter || StringUtils.isBlank(recipientName) || type == null) { + return; + } - PacketLetterInfoRequest packet = new PacketLetterInfoRequest(recipientName, type); - Proxies.net.sendToServer(packet); - } + PacketLetterInfoRequest packet = new PacketLetterInfoRequest(recipientName, type); + Proxies.net.sendToServer(packet); + } - private void setText() { - if (this.isProcessedLetter) { - return; - } - - container.setText(this.text.getText()); - } + private void setText() { + if (this.isProcessedLetter) { + return; + } + container.setText(this.text.getText()); + } } diff --git a/src/main/java/forestry/mail/gui/GuiMailbox.java b/src/main/java/forestry/mail/gui/GuiMailbox.java index ba035cf1e..85aa0e3bf 100755 --- a/src/main/java/forestry/mail/gui/GuiMailbox.java +++ b/src/main/java/forestry/mail/gui/GuiMailbox.java @@ -10,17 +10,16 @@ ******************************************************************************/ package forestry.mail.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestry; import forestry.mail.tiles.TileMailbox; +import net.minecraft.entity.player.InventoryPlayer; public class GuiMailbox extends GuiForestry { - public GuiMailbox(InventoryPlayer player, TileMailbox tile) { - super(Constants.TEXTURE_PATH_GUI + "/mailbox.png", new ContainerMailbox(player, tile), tile); - this.xSize = 230; - this.ySize = 227; - } + public GuiMailbox(InventoryPlayer player, TileMailbox tile) { + super(Constants.TEXTURE_PATH_GUI + "/mailbox.png", new ContainerMailbox(player, tile), tile); + this.xSize = 230; + this.ySize = 227; + } } diff --git a/src/main/java/forestry/mail/gui/GuiMailboxInfo.java b/src/main/java/forestry/mail/gui/GuiMailboxInfo.java index 9959032a7..8b1d22322 100755 --- a/src/main/java/forestry/mail/gui/GuiMailboxInfo.java +++ b/src/main/java/forestry/mail/gui/GuiMailboxInfo.java @@ -10,91 +10,103 @@ ******************************************************************************/ package forestry.mail.gui; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.gui.Gui; -import net.minecraft.client.gui.ScaledResolution; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.opengl.GL11; - import forestry.core.config.Config; import forestry.core.config.Constants; import forestry.core.proxy.Proxies; import forestry.core.render.ForestryResource; import forestry.mail.POBoxInfo; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.util.ResourceLocation; +import org.lwjgl.opengl.GL11; public class GuiMailboxInfo extends Gui { - public enum XPosition { - LEFT, RIGHT; - } + public enum XPosition { + LEFT, + RIGHT; + } - public enum YPosition { - TOP, BOTTOM; - } + public enum YPosition { + TOP, + BOTTOM; + } - public static final GuiMailboxInfo instance = new GuiMailboxInfo(); - private static final int WIDTH = 98; - private static final int HEIGHT = 17; + public static final GuiMailboxInfo instance = new GuiMailboxInfo(); + private static final int WIDTH = 98; + private static final int HEIGHT = 17; - private final FontRenderer fontRendererObj; - private POBoxInfo poInfo; - private final ResourceLocation textureAlert = new ForestryResource(Constants.TEXTURE_PATH_GUI + "/mailalert.png"); + private final FontRenderer fontRendererObj; + private POBoxInfo poInfo; + private final ResourceLocation textureAlert = new ForestryResource(Constants.TEXTURE_PATH_GUI + "/mailalert.png"); - private GuiMailboxInfo() { - fontRendererObj = Proxies.common.getClientInstance().fontRenderer; - } + private GuiMailboxInfo() { + fontRendererObj = Proxies.common.getClientInstance().fontRenderer; + } - public void render() { - if (poInfo == null || !Config.mailAlertEnabled || !poInfo.hasMail()) { - return; - } + public void render() { + if (poInfo == null || !Config.mailAlertEnabled || !poInfo.hasMail()) { + return; + } - int x = 0; - int y = 0; + int x = 0; + int y = 0; - Minecraft minecraft = Minecraft.getMinecraft(); - ScaledResolution scaledresolution = new ScaledResolution(minecraft, minecraft.displayWidth, minecraft.displayHeight); - if (Config.mailAlertXPosition == XPosition.RIGHT) { - x = scaledresolution.getScaledWidth() - WIDTH; - } - if (Config.mailAlertYPosition == YPosition.BOTTOM) { - y = scaledresolution.getScaledHeight() - HEIGHT; - } + Minecraft minecraft = Minecraft.getMinecraft(); + ScaledResolution scaledresolution = + new ScaledResolution(minecraft, minecraft.displayWidth, minecraft.displayHeight); + if (Config.mailAlertXPosition == XPosition.RIGHT) { + x = scaledresolution.getScaledWidth() - WIDTH; + } + if (Config.mailAlertYPosition == YPosition.BOTTOM) { + y = scaledresolution.getScaledHeight() - HEIGHT; + } - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Proxies.render.bindTexture(textureAlert); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Proxies.render.bindTexture(textureAlert); - this.drawTexturedModalRect(x, y, 0, 0, WIDTH, HEIGHT); + this.drawTexturedModalRect(x, y, 0, 0, WIDTH, HEIGHT); - fontRendererObj.drawString(Integer.toString(poInfo.playerLetters), x + 27 + getCenteredOffset(Integer.toString(poInfo.playerLetters), 22), y + 5, 0xffffff); - fontRendererObj.drawString(Integer.toString(poInfo.tradeLetters), x + 75 + getCenteredOffset(Integer.toString(poInfo.tradeLetters), 22), y + 5, 0xffffff); - } + fontRendererObj.drawString( + Integer.toString(poInfo.playerLetters), + x + 27 + getCenteredOffset(Integer.toString(poInfo.playerLetters), 22), + y + 5, + 0xffffff); + fontRendererObj.drawString( + Integer.toString(poInfo.tradeLetters), + x + 75 + getCenteredOffset(Integer.toString(poInfo.tradeLetters), 22), + y + 5, + 0xffffff); + } - protected int getCenteredOffset(String string, int xWidth) { - return (xWidth - fontRendererObj.getStringWidth(string)) / 2; - } + protected int getCenteredOffset(String string, int xWidth) { + return (xWidth - fontRendererObj.getStringWidth(string)) / 2; + } - public boolean hasPOBoxInfo() { - return poInfo != null; - } + public boolean hasPOBoxInfo() { + return poInfo != null; + } - public void setPOBoxInfo(POBoxInfo info) { - boolean playJingle = false; + public void setPOBoxInfo(POBoxInfo info) { + boolean playJingle = false; - if (info.hasMail()) { - if (this.poInfo == null) { - playJingle = true; - } else if (this.poInfo.playerLetters != info.playerLetters || this.poInfo.tradeLetters != info.tradeLetters) { - playJingle = true; - } - } + if (info.hasMail()) { + if (this.poInfo == null) { + playJingle = true; + } else if (this.poInfo.playerLetters != info.playerLetters + || this.poInfo.tradeLetters != info.tradeLetters) { + playJingle = true; + } + } - if (playJingle) { - Proxies.common.getRenderWorld().playSoundAtEntity(Proxies.common.getClientInstance().thePlayer, "random.levelup", 1.0f, 1.0f); - } + if (playJingle) { + Proxies.common + .getRenderWorld() + .playSoundAtEntity(Proxies.common.getClientInstance().thePlayer, "random.levelup", 1.0f, 1.0f); + } - this.poInfo = info; - } + this.poInfo = info; + } } diff --git a/src/main/java/forestry/mail/gui/GuiStampCollector.java b/src/main/java/forestry/mail/gui/GuiStampCollector.java index 4c8723cff..1ccb62a6f 100644 --- a/src/main/java/forestry/mail/gui/GuiStampCollector.java +++ b/src/main/java/forestry/mail/gui/GuiStampCollector.java @@ -10,16 +10,15 @@ ******************************************************************************/ package forestry.mail.gui; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestry; import forestry.mail.tiles.TileStampCollector; +import net.minecraft.entity.player.InventoryPlayer; public class GuiStampCollector extends GuiForestry { - public GuiStampCollector(InventoryPlayer player, TileStampCollector tile) { - super(Constants.TEXTURE_PATH_GUI + "/philatelist.png", new ContainerStampCollector(player, tile), tile); - this.xSize = 176; - this.ySize = 193; - } + public GuiStampCollector(InventoryPlayer player, TileStampCollector tile) { + super(Constants.TEXTURE_PATH_GUI + "/philatelist.png", new ContainerStampCollector(player, tile), tile); + this.xSize = 176; + this.ySize = 193; + } } diff --git a/src/main/java/forestry/mail/gui/GuiTradeName.java b/src/main/java/forestry/mail/gui/GuiTradeName.java index 1cd501bc5..6f324c1cc 100755 --- a/src/main/java/forestry/mail/gui/GuiTradeName.java +++ b/src/main/java/forestry/mail/gui/GuiTradeName.java @@ -10,86 +10,82 @@ ******************************************************************************/ package forestry.mail.gui; -import org.apache.commons.lang3.StringUtils; - -import net.minecraft.client.gui.GuiTextField; - -import org.lwjgl.input.Keyboard; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestry; import forestry.core.proxy.Proxies; import forestry.core.utils.StringUtil; import forestry.mail.network.packets.PacketTraderAddressRequest; import forestry.mail.tiles.TileTrader; +import net.minecraft.client.gui.GuiTextField; +import org.apache.commons.lang3.StringUtils; +import org.lwjgl.input.Keyboard; public class GuiTradeName extends GuiForestry { - private GuiTextField addressNameField; + private GuiTextField addressNameField; - public GuiTradeName(TileTrader tile) { - super(Constants.TEXTURE_PATH_GUI + "/tradername.png", new ContainerTradeName(tile), tile); - this.xSize = 176; - this.ySize = 90; - } + public GuiTradeName(TileTrader tile) { + super(Constants.TEXTURE_PATH_GUI + "/tradername.png", new ContainerTradeName(tile), tile); + this.xSize = 176; + this.ySize = 90; + } - @Override - public void initGui() { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - addressNameField = new GuiTextField(this.fontRendererObj, guiLeft + 44, guiTop + 39, 90, 14); - if (container.getAddress() != null) { - addressNameField.setText(container.getAddress().getName()); - } - addressNameField.setFocused(true); - } + addressNameField = new GuiTextField(this.fontRendererObj, guiLeft + 44, guiTop + 39, 90, 14); + if (container.getAddress() != null) { + addressNameField.setText(container.getAddress().getName()); + } + addressNameField.setFocused(true); + } - @Override - protected void keyTyped(char eventCharacter, int eventKey) { + @Override + protected void keyTyped(char eventCharacter, int eventKey) { - // Set focus or enter text into address - if (addressNameField.isFocused()) { - if (eventKey == Keyboard.KEY_RETURN) { - setAddress(); - } else { - addressNameField.textboxKeyTyped(eventCharacter, eventKey); - } - return; - } + // Set focus or enter text into address + if (addressNameField.isFocused()) { + if (eventKey == Keyboard.KEY_RETURN) { + setAddress(); + } else { + addressNameField.textboxKeyTyped(eventCharacter, eventKey); + } + return; + } - super.keyTyped(eventCharacter, eventKey); - } + super.keyTyped(eventCharacter, eventKey); + } - @Override - protected void mouseClicked(int par1, int par2, int mouseButton) { - super.mouseClicked(par1, par2, mouseButton); - addressNameField.mouseClicked(par1, par2, mouseButton); - } + @Override + protected void mouseClicked(int par1, int par2, int mouseButton) { + super.mouseClicked(par1, par2, mouseButton); + addressNameField.mouseClicked(par1, par2, mouseButton); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { - super.drawGuiContainerBackgroundLayer(var1, var2, var3); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { + super.drawGuiContainerBackgroundLayer(var1, var2, var3); - String prompt = StringUtil.localize("gui.mail.nametrader"); - textLayout.startPage(); - textLayout.newLine(); - textLayout.drawCenteredLine(prompt, 0, fontColor.get("gui.mail.text")); - textLayout.endPage(); - addressNameField.drawTextBox(); - } + String prompt = StringUtil.localize("gui.mail.nametrader"); + textLayout.startPage(); + textLayout.newLine(); + textLayout.drawCenteredLine(prompt, 0, fontColor.get("gui.mail.text")); + textLayout.endPage(); + addressNameField.drawTextBox(); + } - @Override - public void onGuiClosed() { - super.onGuiClosed(); - setAddress(); - } - - private void setAddress() { - String address = addressNameField.getText(); - if (StringUtils.isNotBlank(address)) { - PacketTraderAddressRequest packet = new PacketTraderAddressRequest(inventory, address); - Proxies.net.sendToServer(packet); - } - } + @Override + public void onGuiClosed() { + super.onGuiClosed(); + setAddress(); + } + private void setAddress() { + String address = addressNameField.getText(); + if (StringUtils.isNotBlank(address)) { + PacketTraderAddressRequest packet = new PacketTraderAddressRequest(inventory, address); + Proxies.net.sendToServer(packet); + } + } } diff --git a/src/main/java/forestry/mail/gui/GuiTrader.java b/src/main/java/forestry/mail/gui/GuiTrader.java index 6b06598a0..3af5e751e 100755 --- a/src/main/java/forestry/mail/gui/GuiTrader.java +++ b/src/main/java/forestry/mail/gui/GuiTrader.java @@ -10,40 +10,42 @@ ******************************************************************************/ package forestry.mail.gui; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.util.StatCollector; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestry; import forestry.core.utils.StringUtil; import forestry.mail.tiles.TileTrader; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.util.StatCollector; public class GuiTrader extends GuiForestry { - public GuiTrader(InventoryPlayer inventoryplayer, TileTrader tile) { - super(Constants.TEXTURE_PATH_GUI + "/mailtrader2.png", new ContainerTrader(inventoryplayer, tile), tile); - this.xSize = 226; - this.ySize = 220; - } + public GuiTrader(InventoryPlayer inventoryplayer, TileTrader tile) { + super(Constants.TEXTURE_PATH_GUI + "/mailtrader2.png", new ContainerTrader(inventoryplayer, tile), tile); + this.xSize = 226; + this.ySize = 220; + } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - String name = StatCollector.translateToLocal(inventory.getUnlocalizedTitle()); - this.fontRendererObj.drawString(name, textLayout.getCenteredOffset(name), 6, fontColor.get("gui.mail.text")); + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + String name = StatCollector.translateToLocal(inventory.getUnlocalizedTitle()); + this.fontRendererObj.drawString(name, textLayout.getCenteredOffset(name), 6, fontColor.get("gui.mail.text")); - String receive = StringUtil.localize("gui.mail.receive"); - this.fontRendererObj.drawString(receive, textLayout.getCenteredOffset(receive, 70) + 51, 45, fontColor.get("gui.mail.text")); + String receive = StringUtil.localize("gui.mail.receive"); + this.fontRendererObj.drawString( + receive, textLayout.getCenteredOffset(receive, 70) + 51, 45, fontColor.get("gui.mail.text")); - String send = StringUtil.localize("gui.mail.send"); - this.fontRendererObj.drawString(send, textLayout.getCenteredOffset(send, 70) + 51, 99, fontColor.get("gui.mail.text")); + String send = StringUtil.localize("gui.mail.send"); + this.fontRendererObj.drawString( + send, textLayout.getCenteredOffset(send, 70) + 51, 99, fontColor.get("gui.mail.text")); - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - } + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + } - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); + @Override + protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - fontRendererObj.drawString(container.getAddress().getName(), guiLeft + 19, guiTop + 22, fontColor.get("gui.mail.text")); - } + fontRendererObj.drawString( + container.getAddress().getName(), guiLeft + 19, guiTop + 22, fontColor.get("gui.mail.text")); + } } diff --git a/src/main/java/forestry/mail/gui/ILetterInfoReceiver.java b/src/main/java/forestry/mail/gui/ILetterInfoReceiver.java index b9eb41ef2..401c42c85 100644 --- a/src/main/java/forestry/mail/gui/ILetterInfoReceiver.java +++ b/src/main/java/forestry/mail/gui/ILetterInfoReceiver.java @@ -1,17 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.gui; - -import forestry.mail.network.packets.PacketLetterInfoResponse; - -public interface ILetterInfoReceiver { - void handleLetterInfoUpdate(PacketLetterInfoResponse packet); -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.gui; + +import forestry.mail.network.packets.PacketLetterInfoResponse; + +public interface ILetterInfoReceiver { + void handleLetterInfoUpdate(PacketLetterInfoResponse packet); +} diff --git a/src/main/java/forestry/mail/gui/widgets/AddresseeSlot.java b/src/main/java/forestry/mail/gui/widgets/AddresseeSlot.java index 2f9448664..ff56bd893 100644 --- a/src/main/java/forestry/mail/gui/widgets/AddresseeSlot.java +++ b/src/main/java/forestry/mail/gui/widgets/AddresseeSlot.java @@ -1,58 +1,57 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.gui.widgets; - -import net.minecraft.entity.player.EntityPlayer; - -import org.lwjgl.opengl.GL11; - -import forestry.api.mail.IPostalCarrier; -import forestry.api.mail.PostManager; -import forestry.core.gui.widgets.Widget; -import forestry.core.gui.widgets.WidgetManager; -import forestry.core.proxy.Proxies; -import forestry.core.render.SpriteSheet; -import forestry.core.utils.StringUtil; -import forestry.mail.gui.ContainerLetter; - -public class AddresseeSlot extends Widget { - - private final ContainerLetter containerLetter; - - public AddresseeSlot(WidgetManager widgetManager, int xPos, int yPos, ContainerLetter containerLetter) { - super(widgetManager, xPos, yPos); - this.containerLetter = containerLetter; - this.width = 26; - this.height = 15; - } - - @Override - public void draw(int startX, int startY) { - IPostalCarrier carrier = PostManager.postRegistry.getCarrier(containerLetter.getCarrierType()); - if (carrier != null) { - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); - Proxies.render.bindTexture(SpriteSheet.ITEMS); - manager.gui.drawTexturedModelRectFromIcon(startX + xPos, startY + yPos - 5, carrier.getIcon(), 26, 26); - } - } - - @Override - protected String getLegacyTooltip(EntityPlayer player) { - return StringUtil.localize("gui.addressee." + containerLetter.getCarrierType().toString()); - } - - @Override - public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - if (!containerLetter.getLetter().isProcessed()) { - containerLetter.advanceCarrierType(); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.gui.widgets; + +import forestry.api.mail.IPostalCarrier; +import forestry.api.mail.PostManager; +import forestry.core.gui.widgets.Widget; +import forestry.core.gui.widgets.WidgetManager; +import forestry.core.proxy.Proxies; +import forestry.core.render.SpriteSheet; +import forestry.core.utils.StringUtil; +import forestry.mail.gui.ContainerLetter; +import net.minecraft.entity.player.EntityPlayer; +import org.lwjgl.opengl.GL11; + +public class AddresseeSlot extends Widget { + + private final ContainerLetter containerLetter; + + public AddresseeSlot(WidgetManager widgetManager, int xPos, int yPos, ContainerLetter containerLetter) { + super(widgetManager, xPos, yPos); + this.containerLetter = containerLetter; + this.width = 26; + this.height = 15; + } + + @Override + public void draw(int startX, int startY) { + IPostalCarrier carrier = PostManager.postRegistry.getCarrier(containerLetter.getCarrierType()); + if (carrier != null) { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); + Proxies.render.bindTexture(SpriteSheet.ITEMS); + manager.gui.drawTexturedModelRectFromIcon(startX + xPos, startY + yPos - 5, carrier.getIcon(), 26, 26); + } + } + + @Override + protected String getLegacyTooltip(EntityPlayer player) { + return StringUtil.localize( + "gui.addressee." + containerLetter.getCarrierType().toString()); + } + + @Override + public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { + if (!containerLetter.getLetter().isProcessed()) { + containerLetter.advanceCarrierType(); + } + } +} diff --git a/src/main/java/forestry/mail/inventory/InventoryStampCollector.java b/src/main/java/forestry/mail/inventory/InventoryStampCollector.java index bc587b4ec..4353dec53 100644 --- a/src/main/java/forestry/mail/inventory/InventoryStampCollector.java +++ b/src/main/java/forestry/mail/inventory/InventoryStampCollector.java @@ -1,32 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.inventory; - -import net.minecraft.item.ItemStack; - -import forestry.api.mail.IStamps; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.mail.tiles.TileStampCollector; - -public class InventoryStampCollector extends InventoryAdapterTile { - public static final short SLOT_FILTER = 0; - public static final short SLOT_BUFFER_1 = 1; - public static final short SLOT_BUFFER_COUNT = 27; - - public InventoryStampCollector(TileStampCollector tile) { - super(tile, 28, "INV"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return itemStack.getItem() instanceof IStamps; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.inventory; + +import forestry.api.mail.IStamps; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.mail.tiles.TileStampCollector; +import net.minecraft.item.ItemStack; + +public class InventoryStampCollector extends InventoryAdapterTile { + public static final short SLOT_FILTER = 0; + public static final short SLOT_BUFFER_1 = 1; + public static final short SLOT_BUFFER_COUNT = 27; + + public InventoryStampCollector(TileStampCollector tile) { + super(tile, 28, "INV"); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return itemStack.getItem() instanceof IStamps; + } +} diff --git a/src/main/java/forestry/mail/inventory/InventoryTradeStation.java b/src/main/java/forestry/mail/inventory/InventoryTradeStation.java index efc6fb33a..93fdb8fb4 100644 --- a/src/main/java/forestry/mail/inventory/InventoryTradeStation.java +++ b/src/main/java/forestry/mail/inventory/InventoryTradeStation.java @@ -1,87 +1,91 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.inventory; - -import java.util.ArrayList; - -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import forestry.api.mail.IStamps; -import forestry.core.inventory.InventoryAdapter; -import forestry.core.utils.ItemStackUtil; -import forestry.core.utils.SlotUtil; -import forestry.mail.TradeStation; - -public class InventoryTradeStation extends InventoryAdapter { - - public InventoryTradeStation() { - super(TradeStation.SLOT_SIZE, "INV"); - } - - @Override - public int[] getAccessibleSlotsFromSide(int side) { - - ArrayList slots = new ArrayList<>(); - - for (int i = TradeStation.SLOT_LETTERS_1; i < TradeStation.SLOT_LETTERS_1 + TradeStation.SLOT_LETTERS_COUNT; i++) { - slots.add(i); - } - for (int i = TradeStation.SLOT_STAMPS_1; i < TradeStation.SLOT_STAMPS_1 + TradeStation.SLOT_STAMPS_COUNT; i++) { - slots.add(i); - } - for (int i = TradeStation.SLOT_RECEIVE_BUFFER; i < TradeStation.SLOT_RECEIVE_BUFFER + TradeStation.SLOT_RECEIVE_BUFFER_COUNT; i++) { - slots.add(i); - } - for (int i = TradeStation.SLOT_SEND_BUFFER; i < TradeStation.SLOT_SEND_BUFFER + TradeStation.SLOT_SEND_BUFFER_COUNT; i++) { - slots.add(i); - } - - int[] slotsInt = new int[slots.size()]; - for (int i = 0; i < slots.size(); i++) { - slotsInt[i] = slots.get(i); - } - - return slotsInt; - } - - @Override - public boolean canExtractItem(int slot, ItemStack itemStack, int side) { - return SlotUtil.isSlotInRange(slot, TradeStation.SLOT_RECEIVE_BUFFER, TradeStation.SLOT_RECEIVE_BUFFER_COUNT); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (SlotUtil.isSlotInRange(slotIndex, TradeStation.SLOT_SEND_BUFFER, TradeStation.SLOT_SEND_BUFFER_COUNT)) { - for (int i = 0; i < TradeStation.SLOT_TRADEGOOD_COUNT; i++) { - ItemStack tradeGood = getStackInSlot(TradeStation.SLOT_TRADEGOOD + i); - if (ItemStackUtil.isIdenticalItem(tradeGood, itemStack)) { - return true; - } - } - return false; - } else if (SlotUtil.isSlotInRange(slotIndex, TradeStation.SLOT_LETTERS_1, TradeStation.SLOT_LETTERS_COUNT)) { - Item item = itemStack.getItem(); - return item == Items.paper; - } else if (SlotUtil.isSlotInRange(slotIndex, TradeStation.SLOT_STAMPS_1, TradeStation.SLOT_STAMPS_COUNT)) { - Item item = itemStack.getItem(); - return item instanceof IStamps; - } - - return false; - } - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) { - return canSlotAccept(i, itemstack); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.inventory; + +import forestry.api.mail.IStamps; +import forestry.core.inventory.InventoryAdapter; +import forestry.core.utils.ItemStackUtil; +import forestry.core.utils.SlotUtil; +import forestry.mail.TradeStation; +import java.util.ArrayList; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +public class InventoryTradeStation extends InventoryAdapter { + + public InventoryTradeStation() { + super(TradeStation.SLOT_SIZE, "INV"); + } + + @Override + public int[] getAccessibleSlotsFromSide(int side) { + + ArrayList slots = new ArrayList<>(); + + for (int i = TradeStation.SLOT_LETTERS_1; + i < TradeStation.SLOT_LETTERS_1 + TradeStation.SLOT_LETTERS_COUNT; + i++) { + slots.add(i); + } + for (int i = TradeStation.SLOT_STAMPS_1; i < TradeStation.SLOT_STAMPS_1 + TradeStation.SLOT_STAMPS_COUNT; i++) { + slots.add(i); + } + for (int i = TradeStation.SLOT_RECEIVE_BUFFER; + i < TradeStation.SLOT_RECEIVE_BUFFER + TradeStation.SLOT_RECEIVE_BUFFER_COUNT; + i++) { + slots.add(i); + } + for (int i = TradeStation.SLOT_SEND_BUFFER; + i < TradeStation.SLOT_SEND_BUFFER + TradeStation.SLOT_SEND_BUFFER_COUNT; + i++) { + slots.add(i); + } + + int[] slotsInt = new int[slots.size()]; + for (int i = 0; i < slots.size(); i++) { + slotsInt[i] = slots.get(i); + } + + return slotsInt; + } + + @Override + public boolean canExtractItem(int slot, ItemStack itemStack, int side) { + return SlotUtil.isSlotInRange(slot, TradeStation.SLOT_RECEIVE_BUFFER, TradeStation.SLOT_RECEIVE_BUFFER_COUNT); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (SlotUtil.isSlotInRange(slotIndex, TradeStation.SLOT_SEND_BUFFER, TradeStation.SLOT_SEND_BUFFER_COUNT)) { + for (int i = 0; i < TradeStation.SLOT_TRADEGOOD_COUNT; i++) { + ItemStack tradeGood = getStackInSlot(TradeStation.SLOT_TRADEGOOD + i); + if (ItemStackUtil.isIdenticalItem(tradeGood, itemStack)) { + return true; + } + } + return false; + } else if (SlotUtil.isSlotInRange(slotIndex, TradeStation.SLOT_LETTERS_1, TradeStation.SLOT_LETTERS_COUNT)) { + Item item = itemStack.getItem(); + return item == Items.paper; + } else if (SlotUtil.isSlotInRange(slotIndex, TradeStation.SLOT_STAMPS_1, TradeStation.SLOT_STAMPS_COUNT)) { + Item item = itemStack.getItem(); + return item instanceof IStamps; + } + + return false; + } + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemstack) { + return canSlotAccept(i, itemstack); + } +} diff --git a/src/main/java/forestry/mail/inventory/ItemInventoryLetter.java b/src/main/java/forestry/mail/inventory/ItemInventoryLetter.java index aea500d04..a297428ff 100644 --- a/src/main/java/forestry/mail/inventory/ItemInventoryLetter.java +++ b/src/main/java/forestry/mail/inventory/ItemInventoryLetter.java @@ -1,152 +1,148 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.inventory; - -import com.google.common.collect.ImmutableSet; - -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import forestry.api.core.IErrorSource; -import forestry.api.core.IErrorState; -import forestry.api.mail.ILetter; -import forestry.core.config.Config; -import forestry.core.errors.EnumErrorCode; -import forestry.core.gui.IHintSource; -import forestry.core.inventory.ItemInventory; -import forestry.core.items.ItemWithGui; -import forestry.core.utils.SlotUtil; -import forestry.mail.Letter; -import forestry.mail.LetterProperties; -import forestry.mail.items.ItemStamps; - -public class ItemInventoryLetter extends ItemInventory implements IErrorSource, IHintSource { - private ILetter letter; - - public ItemInventoryLetter(EntityPlayer player, ItemStack itemstack) { - super(player, 0, itemstack); - } - - public ILetter getLetter() { - return letter; - } - - public void onLetterClosed() { - ItemStack parent = getParent(); - if (parent == null) { - return; - } - - LetterProperties.closeLetter(parent, letter); - } - - public void onLetterOpened() { - ItemStack parent = getParent(); - if (parent == null) { - return; - } - - LetterProperties.openLetter(parent); - } - - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - if (nbttagcompound == null) { - return; - } - - letter = new Letter(nbttagcompound); - } - - @Override - public ItemStack decrStackSize(int i, int j) { - ItemStack result = letter.decrStackSize(i, j); - letter.writeToNBT(getParent().getTagCompound()); - return result; - } - - @Override - public void setInventorySlotContents(int i, ItemStack itemstack) { - letter.setInventorySlotContents(i, itemstack); - letter.writeToNBT(getParent().getTagCompound()); - } - - @Override - public ItemStack getStackInSlot(int i) { - return letter.getStackInSlot(i); - } - - @Override - public int getSizeInventory() { - return letter.getSizeInventory(); - } - - @Override - public String getInventoryName() { - return letter.getInventoryName(); - } - - @Override - public int getInventoryStackLimit() { - return letter.getInventoryStackLimit(); - } - - @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return letter.isUseableByPlayer(entityplayer); - } - - @Override - public ItemStack getStackInSlotOnClosing(int slot) { - return letter.getStackInSlotOnClosing(slot); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (letter.isProcessed()) { - return false; - } else if (SlotUtil.isSlotInRange(slotIndex, Letter.SLOT_POSTAGE_1, Letter.SLOT_POSTAGE_COUNT)) { - Item item = itemStack.getItem(); - return item instanceof ItemStamps; - } else if (SlotUtil.isSlotInRange(slotIndex, Letter.SLOT_ATTACHMENT_1, Letter.SLOT_ATTACHMENT_COUNT)) { - return !(itemStack.getItem() instanceof ItemWithGui); - } - return false; - } - - /* IErrorSource */ - @Override - public ImmutableSet getErrorStates() { - - ImmutableSet.Builder errorStates = ImmutableSet.builder(); - - if (!letter.hasRecipient()) { - errorStates.add(EnumErrorCode.NO_RECIPIENT); - } - - if (!letter.isProcessed() && !letter.isPostPaid()) { - errorStates.add(EnumErrorCode.NOT_POST_PAID); - } - - return errorStates.build(); - } - - /* IHintSource */ - @Override - public List getHints() { - return Config.hints.get("letter"); - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.inventory; + +import com.google.common.collect.ImmutableSet; +import forestry.api.core.IErrorSource; +import forestry.api.core.IErrorState; +import forestry.api.mail.ILetter; +import forestry.core.config.Config; +import forestry.core.errors.EnumErrorCode; +import forestry.core.gui.IHintSource; +import forestry.core.inventory.ItemInventory; +import forestry.core.items.ItemWithGui; +import forestry.core.utils.SlotUtil; +import forestry.mail.Letter; +import forestry.mail.LetterProperties; +import forestry.mail.items.ItemStamps; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +public class ItemInventoryLetter extends ItemInventory implements IErrorSource, IHintSource { + private ILetter letter; + + public ItemInventoryLetter(EntityPlayer player, ItemStack itemstack) { + super(player, 0, itemstack); + } + + public ILetter getLetter() { + return letter; + } + + public void onLetterClosed() { + ItemStack parent = getParent(); + if (parent == null) { + return; + } + + LetterProperties.closeLetter(parent, letter); + } + + public void onLetterOpened() { + ItemStack parent = getParent(); + if (parent == null) { + return; + } + + LetterProperties.openLetter(parent); + } + + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + if (nbttagcompound == null) { + return; + } + + letter = new Letter(nbttagcompound); + } + + @Override + public ItemStack decrStackSize(int i, int j) { + ItemStack result = letter.decrStackSize(i, j); + letter.writeToNBT(getParent().getTagCompound()); + return result; + } + + @Override + public void setInventorySlotContents(int i, ItemStack itemstack) { + letter.setInventorySlotContents(i, itemstack); + letter.writeToNBT(getParent().getTagCompound()); + } + + @Override + public ItemStack getStackInSlot(int i) { + return letter.getStackInSlot(i); + } + + @Override + public int getSizeInventory() { + return letter.getSizeInventory(); + } + + @Override + public String getInventoryName() { + return letter.getInventoryName(); + } + + @Override + public int getInventoryStackLimit() { + return letter.getInventoryStackLimit(); + } + + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return letter.isUseableByPlayer(entityplayer); + } + + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + return letter.getStackInSlotOnClosing(slot); + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + if (letter.isProcessed()) { + return false; + } else if (SlotUtil.isSlotInRange(slotIndex, Letter.SLOT_POSTAGE_1, Letter.SLOT_POSTAGE_COUNT)) { + Item item = itemStack.getItem(); + return item instanceof ItemStamps; + } else if (SlotUtil.isSlotInRange(slotIndex, Letter.SLOT_ATTACHMENT_1, Letter.SLOT_ATTACHMENT_COUNT)) { + return !(itemStack.getItem() instanceof ItemWithGui); + } + return false; + } + + /* IErrorSource */ + @Override + public ImmutableSet getErrorStates() { + + ImmutableSet.Builder errorStates = ImmutableSet.builder(); + + if (!letter.hasRecipient()) { + errorStates.add(EnumErrorCode.NO_RECIPIENT); + } + + if (!letter.isProcessed() && !letter.isPostPaid()) { + errorStates.add(EnumErrorCode.NOT_POST_PAID); + } + + return errorStates.build(); + } + + /* IHintSource */ + @Override + public List getHints() { + return Config.hints.get("letter"); + } +} diff --git a/src/main/java/forestry/mail/items/EnumStampDefinition.java b/src/main/java/forestry/mail/items/EnumStampDefinition.java index 04784711f..cfd47b411 100644 --- a/src/main/java/forestry/mail/items/EnumStampDefinition.java +++ b/src/main/java/forestry/mail/items/EnumStampDefinition.java @@ -1,88 +1,85 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.items; - -import java.awt.Color; -import java.util.EnumMap; -import java.util.Map; - -import net.minecraft.init.Items; - -import forestry.api.mail.EnumPostage; -import forestry.core.items.ItemOverlay; -import forestry.plugins.PluginCore; - -public enum EnumStampDefinition implements ItemOverlay.IOverlayInfo { - P_1("1n", EnumPostage.P_1, "gemApatite", new Color(0x4a8ca7), new Color(0xffffff)), - P_2("2n", EnumPostage.P_2, "ingotCopper", new Color(0xe8c814), new Color(0xffffff)), - P_5("5n", EnumPostage.P_5, "ingotTin", new Color(0x9c0707), new Color(0xffffff)), - P_10("10n", EnumPostage.P_10, "ingotGold", new Color(0x7bd1b8), new Color(0xffffff)), - P_20("20n", EnumPostage.P_20, "gemDiamond", new Color(0xff9031), new Color(0xfff7dd)), - P_50("50n", EnumPostage.P_50, "gemEmerald", new Color(0x6431d7), new Color(0xfff7dd)), - P_100("100n", EnumPostage.P_100, Items.nether_star, new Color(0xd731ba), new Color(0xfff7dd)), - // P_200("200n", EnumPostage.P_200, Items.nether_star, new Color(0xcd9831), new Color(0xfff7dd)), - ; - - public static final EnumStampDefinition[] VALUES = values(); - private static final Map postageMap = new EnumMap<>(EnumPostage.class); - - static { - for (EnumStampDefinition stampDefinition : VALUES) { - postageMap.put(stampDefinition.getPostage(), stampDefinition); - } - } - - private final String name; - private final int primaryColor; - private final int secondaryColor; - private final Object craftingIngredient; - private final EnumPostage postage; - - EnumStampDefinition(String name, EnumPostage postage, Object crafting, Color primaryColor, Color secondaryColor) { - this.name = name; - this.primaryColor = primaryColor.getRGB(); - this.secondaryColor = secondaryColor.getRGB(); - this.craftingIngredient = crafting; - this.postage = postage; - } - - public EnumPostage getPostage() { - return this.postage; - } - - public Object getCraftingIngredient() { - return this.craftingIngredient; - } - - @Override - public String getName() { - return name; - } - - @Override - public int getPrimaryColor() { - return primaryColor; - } - - @Override - public int getSecondaryColor() { - return secondaryColor; - } - - @Override - public boolean isSecret() { - return false; - } - - public static EnumStampDefinition getFromPostage(EnumPostage postage) { - return postageMap.get(postage); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.items; + +import forestry.api.mail.EnumPostage; +import forestry.core.items.ItemOverlay; +import java.awt.Color; +import java.util.EnumMap; +import java.util.Map; +import net.minecraft.init.Items; + +public enum EnumStampDefinition implements ItemOverlay.IOverlayInfo { + P_1("1n", EnumPostage.P_1, "gemApatite", new Color(0x4a8ca7), new Color(0xffffff)), + P_2("2n", EnumPostage.P_2, "ingotCopper", new Color(0xe8c814), new Color(0xffffff)), + P_5("5n", EnumPostage.P_5, "ingotTin", new Color(0x9c0707), new Color(0xffffff)), + P_10("10n", EnumPostage.P_10, "ingotGold", new Color(0x7bd1b8), new Color(0xffffff)), + P_20("20n", EnumPostage.P_20, "gemDiamond", new Color(0xff9031), new Color(0xfff7dd)), + P_50("50n", EnumPostage.P_50, "gemEmerald", new Color(0x6431d7), new Color(0xfff7dd)), + P_100("100n", EnumPostage.P_100, Items.nether_star, new Color(0xd731ba), new Color(0xfff7dd)), +// P_200("200n", EnumPostage.P_200, Items.nether_star, new Color(0xcd9831), new Color(0xfff7dd)), +; + + public static final EnumStampDefinition[] VALUES = values(); + private static final Map postageMap = new EnumMap<>(EnumPostage.class); + + static { + for (EnumStampDefinition stampDefinition : VALUES) { + postageMap.put(stampDefinition.getPostage(), stampDefinition); + } + } + + private final String name; + private final int primaryColor; + private final int secondaryColor; + private final Object craftingIngredient; + private final EnumPostage postage; + + EnumStampDefinition(String name, EnumPostage postage, Object crafting, Color primaryColor, Color secondaryColor) { + this.name = name; + this.primaryColor = primaryColor.getRGB(); + this.secondaryColor = secondaryColor.getRGB(); + this.craftingIngredient = crafting; + this.postage = postage; + } + + public EnumPostage getPostage() { + return this.postage; + } + + public Object getCraftingIngredient() { + return this.craftingIngredient; + } + + @Override + public String getName() { + return name; + } + + @Override + public int getPrimaryColor() { + return primaryColor; + } + + @Override + public int getSecondaryColor() { + return secondaryColor; + } + + @Override + public boolean isSecret() { + return false; + } + + public static EnumStampDefinition getFromPostage(EnumPostage postage) { + return postageMap.get(postage); + } +} diff --git a/src/main/java/forestry/mail/items/ItemCatalogue.java b/src/main/java/forestry/mail/items/ItemCatalogue.java index 8479dbeb3..022887814 100644 --- a/src/main/java/forestry/mail/items/ItemCatalogue.java +++ b/src/main/java/forestry/mail/items/ItemCatalogue.java @@ -1,30 +1,29 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.items; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.core.items.ItemWithGui; -import forestry.mail.gui.ContainerCatalogue; -import forestry.mail.gui.GuiCatalogue; - -public class ItemCatalogue extends ItemWithGui { - @Override - public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { - return new GuiCatalogue(player); - } - - @Override - public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { - return new ContainerCatalogue(player); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.items; + +import forestry.core.items.ItemWithGui; +import forestry.mail.gui.ContainerCatalogue; +import forestry.mail.gui.GuiCatalogue; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class ItemCatalogue extends ItemWithGui { + @Override + public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { + return new GuiCatalogue(player); + } + + @Override + public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { + return new ContainerCatalogue(player); + } +} diff --git a/src/main/java/forestry/mail/items/ItemLetter.java b/src/main/java/forestry/mail/items/ItemLetter.java index c2f564da6..538def7ec 100755 --- a/src/main/java/forestry/mail/items/ItemLetter.java +++ b/src/main/java/forestry/mail/items/ItemLetter.java @@ -10,8 +10,17 @@ ******************************************************************************/ package forestry.mail.items; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.mail.ILetter; +import forestry.core.items.ItemWithGui; +import forestry.core.utils.StringUtil; +import forestry.mail.Letter; +import forestry.mail.LetterProperties; +import forestry.mail.gui.ContainerLetter; +import forestry.mail.gui.GuiLetter; +import forestry.mail.inventory.ItemInventoryLetter; import java.util.List; - import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; @@ -22,79 +31,67 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IIcon; import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.mail.ILetter; -import forestry.core.items.ItemWithGui; -import forestry.core.utils.StringUtil; -import forestry.mail.Letter; -import forestry.mail.LetterProperties; -import forestry.mail.gui.ContainerLetter; -import forestry.mail.gui.GuiLetter; -import forestry.mail.inventory.ItemInventoryLetter; - public class ItemLetter extends ItemWithGui { - public ItemLetter() { - setMaxStackSize(64); - } + public ItemLetter() { + setMaxStackSize(64); + } - @Override - public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { - if (!world.isRemote) { - if (itemstack.stackSize == 1) { - openGui(entityplayer); - } else { - entityplayer.addChatMessage(new ChatComponentTranslation("for.chat.mail.wrongstacksize")); - } - } + @Override + public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { + if (!world.isRemote) { + if (itemstack.stackSize == 1) { + openGui(entityplayer); + } else { + entityplayer.addChatMessage(new ChatComponentTranslation("for.chat.mail.wrongstacksize")); + } + } - return itemstack; - } + return itemstack; + } - @Override - public boolean getShareTag() { - return true; - } + @Override + public boolean getShareTag() { + return true; + } - /* ICONS */ - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - LetterProperties.registerIcons(register); - } + /* ICONS */ + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + LetterProperties.registerIcons(register); + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamage(int damage) { - return LetterProperties.getIconFromDamage(damage); - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamage(int damage) { + return LetterProperties.getIconFromDamage(damage); + } - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { - NBTTagCompound nbttagcompound = itemstack.getTagCompound(); - if (nbttagcompound == null) { - list.add('<' + StringUtil.localize("gui.blank") + '>'); - return; - } + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { + NBTTagCompound nbttagcompound = itemstack.getTagCompound(); + if (nbttagcompound == null) { + list.add('<' + StringUtil.localize("gui.blank") + '>'); + return; + } - ILetter letter = new Letter(nbttagcompound); - letter.addTooltip(list); - } - - @Override - public void getSubItems(Item item, CreativeTabs tab, List list) { - LetterProperties.getSubItems(item, tab, list); - } + ILetter letter = new Letter(nbttagcompound); + letter.addTooltip(list); + } - @Override - public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { - return new GuiLetter(player, new ItemInventoryLetter(player, heldItem)); - } + @Override + public void getSubItems(Item item, CreativeTabs tab, List list) { + LetterProperties.getSubItems(item, tab, list); + } - @Override - public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { - return new ContainerLetter(player, new ItemInventoryLetter(player, heldItem)); - } + @Override + public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { + return new GuiLetter(player, new ItemInventoryLetter(player, heldItem)); + } + + @Override + public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { + return new ContainerLetter(player, new ItemInventoryLetter(player, heldItem)); + } } diff --git a/src/main/java/forestry/mail/items/ItemRegistryMail.java b/src/main/java/forestry/mail/items/ItemRegistryMail.java index e6258c1ef..c8aadf1bd 100644 --- a/src/main/java/forestry/mail/items/ItemRegistryMail.java +++ b/src/main/java/forestry/mail/items/ItemRegistryMail.java @@ -1,25 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.items; - -import forestry.core.items.ItemRegistry; - -public class ItemRegistryMail extends ItemRegistry { - public final ItemStamps stamps; - public final ItemLetter letters; - public final ItemCatalogue catalogue; - - public ItemRegistryMail() { - stamps = registerItem(new ItemStamps(), "stamps"); - letters = registerItem(new ItemLetter(), "letters"); - catalogue = registerItem(new ItemCatalogue(), "catalogue"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.items; + +import forestry.core.items.ItemRegistry; + +public class ItemRegistryMail extends ItemRegistry { + public final ItemStamps stamps; + public final ItemLetter letters; + public final ItemCatalogue catalogue; + + public ItemRegistryMail() { + stamps = registerItem(new ItemStamps(), "stamps"); + letters = registerItem(new ItemLetter(), "letters"); + catalogue = registerItem(new ItemCatalogue(), "catalogue"); + } +} diff --git a/src/main/java/forestry/mail/items/ItemStamps.java b/src/main/java/forestry/mail/items/ItemStamps.java index 5ad941919..e5065d685 100755 --- a/src/main/java/forestry/mail/items/ItemStamps.java +++ b/src/main/java/forestry/mail/items/ItemStamps.java @@ -10,32 +10,31 @@ ******************************************************************************/ package forestry.mail.items; -import net.minecraft.item.ItemStack; - import forestry.api.mail.EnumPostage; import forestry.api.mail.IStamps; import forestry.core.CreativeTabForestry; import forestry.core.items.ItemOverlay; +import net.minecraft.item.ItemStack; public class ItemStamps extends ItemOverlay implements IStamps { - public ItemStamps() { - super(CreativeTabForestry.tabForestry, EnumStampDefinition.VALUES); - } + public ItemStamps() { + super(CreativeTabForestry.tabForestry, EnumStampDefinition.VALUES); + } - @Override - public EnumPostage getPostage(ItemStack itemstack) { - if (itemstack.getItem() != this) { - return EnumPostage.P_0; - } + @Override + public EnumPostage getPostage(ItemStack itemstack) { + if (itemstack.getItem() != this) { + return EnumPostage.P_0; + } - if (itemstack.getItemDamage() < 0 || itemstack.getItemDamage() >= EnumStampDefinition.VALUES.length) { - return EnumPostage.P_0; - } + if (itemstack.getItemDamage() < 0 || itemstack.getItemDamage() >= EnumStampDefinition.VALUES.length) { + return EnumPostage.P_0; + } - return EnumStampDefinition.VALUES[itemstack.getItemDamage()].getPostage(); - } + return EnumStampDefinition.VALUES[itemstack.getItemDamage()].getPostage(); + } - public ItemStack get(EnumStampDefinition stampInfo, int amount) { - return new ItemStack(this, amount, stampInfo.ordinal()); - } + public ItemStack get(EnumStampDefinition stampInfo, int amount) { + return new ItemStack(this, amount, stampInfo.ordinal()); + } } diff --git a/src/main/java/forestry/mail/network/PacketRegistryMail.java b/src/main/java/forestry/mail/network/PacketRegistryMail.java index 4dd7138e2..6e22c7a83 100644 --- a/src/main/java/forestry/mail/network/PacketRegistryMail.java +++ b/src/main/java/forestry/mail/network/PacketRegistryMail.java @@ -1,32 +1,32 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.network; - -import forestry.core.network.PacketRegistry; -import forestry.mail.network.packets.PacketLetterInfoRequest; -import forestry.mail.network.packets.PacketLetterInfoResponse; -import forestry.mail.network.packets.PacketLetterTextSet; -import forestry.mail.network.packets.PacketPOBoxInfoUpdate; -import forestry.mail.network.packets.PacketTraderAddressRequest; -import forestry.mail.network.packets.PacketTraderAddressResponse; - -public class PacketRegistryMail extends PacketRegistry { - @Override - public void registerPackets() { - registerServerPacket(new PacketLetterInfoRequest()); - registerServerPacket(new PacketTraderAddressRequest()); - registerServerPacket(new PacketLetterTextSet()); - - registerClientPacket(new PacketLetterInfoResponse()); - registerClientPacket(new PacketTraderAddressResponse()); - registerClientPacket(new PacketPOBoxInfoUpdate()); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.network; + +import forestry.core.network.PacketRegistry; +import forestry.mail.network.packets.PacketLetterInfoRequest; +import forestry.mail.network.packets.PacketLetterInfoResponse; +import forestry.mail.network.packets.PacketLetterTextSet; +import forestry.mail.network.packets.PacketPOBoxInfoUpdate; +import forestry.mail.network.packets.PacketTraderAddressRequest; +import forestry.mail.network.packets.PacketTraderAddressResponse; + +public class PacketRegistryMail extends PacketRegistry { + @Override + public void registerPackets() { + registerServerPacket(new PacketLetterInfoRequest()); + registerServerPacket(new PacketTraderAddressRequest()); + registerServerPacket(new PacketLetterTextSet()); + + registerClientPacket(new PacketLetterInfoResponse()); + registerClientPacket(new PacketTraderAddressResponse()); + registerClientPacket(new PacketPOBoxInfoUpdate()); + } +} diff --git a/src/main/java/forestry/mail/network/packets/PacketLetterInfoRequest.java b/src/main/java/forestry/mail/network/packets/PacketLetterInfoRequest.java index 59c616b04..f7a42ef12 100644 --- a/src/main/java/forestry/mail/network/packets/PacketLetterInfoRequest.java +++ b/src/main/java/forestry/mail/network/packets/PacketLetterInfoRequest.java @@ -1,65 +1,62 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayerMP; - -import forestry.api.mail.EnumAddressee; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.ForestryPacket; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; -import forestry.mail.gui.ContainerLetter; - -public class PacketLetterInfoRequest extends ForestryPacket implements IForestryPacketServer { - - private String recipientName; - private EnumAddressee addressType; - - public PacketLetterInfoRequest() { - } - - public PacketLetterInfoRequest(String recipientName, EnumAddressee addressType) { - this.recipientName = recipientName; - this.addressType = addressType; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeUTF(recipientName); - data.writeByte(addressType.ordinal()); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - recipientName = data.readUTF(); - addressType = EnumAddressee.values()[data.readByte()]; - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - if (!(player.openContainer instanceof ContainerLetter)) { - return; - } - - ((ContainerLetter) player.openContainer).handleRequestLetterInfo(player, recipientName, addressType); - } - - @Override - public PacketIdServer getPacketId() { - return PacketIdServer.LETTER_INFO_REQUEST; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.network.packets; + +import forestry.api.mail.EnumAddressee; +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketIdServer; +import forestry.mail.gui.ContainerLetter; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayerMP; + +public class PacketLetterInfoRequest extends ForestryPacket implements IForestryPacketServer { + + private String recipientName; + private EnumAddressee addressType; + + public PacketLetterInfoRequest() {} + + public PacketLetterInfoRequest(String recipientName, EnumAddressee addressType) { + this.recipientName = recipientName; + this.addressType = addressType; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeUTF(recipientName); + data.writeByte(addressType.ordinal()); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + recipientName = data.readUTF(); + addressType = EnumAddressee.values()[data.readByte()]; + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { + if (!(player.openContainer instanceof ContainerLetter)) { + return; + } + + ((ContainerLetter) player.openContainer).handleRequestLetterInfo(player, recipientName, addressType); + } + + @Override + public PacketIdServer getPacketId() { + return PacketIdServer.LETTER_INFO_REQUEST; + } +} diff --git a/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponse.java b/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponse.java index 455380d2f..5e3d5c554 100644 --- a/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponse.java +++ b/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponse.java @@ -10,15 +10,7 @@ ******************************************************************************/ package forestry.mail.network.packets; -import java.io.IOException; -import java.util.UUID; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.item.ItemStack; - import com.mojang.authlib.GameProfile; - import forestry.api.mail.EnumAddressee; import forestry.api.mail.IMailAddress; import forestry.api.mail.PostManager; @@ -30,114 +22,119 @@ import forestry.core.network.IForestryPacketClient; import forestry.core.network.PacketIdClient; import forestry.mail.EnumStationState; import forestry.mail.gui.ILetterInfoReceiver; +import java.io.IOException; +import java.util.UUID; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.item.ItemStack; public class PacketLetterInfoResponse extends ForestryPacket implements IForestryPacketClient { - public EnumAddressee type; - public TradeStationInfo tradeInfo; - public IMailAddress address; + public EnumAddressee type; + public TradeStationInfo tradeInfo; + public IMailAddress address; - public PacketLetterInfoResponse() { - } + public PacketLetterInfoResponse() {} - public PacketLetterInfoResponse(EnumAddressee type, TradeStationInfo info, IMailAddress address) { - this.type = type; - if (type == EnumAddressee.TRADER) { - this.tradeInfo = info; - } else if (type == EnumAddressee.PLAYER) { - this.address = address; - } - } + public PacketLetterInfoResponse(EnumAddressee type, TradeStationInfo info, IMailAddress address) { + this.type = type; + if (type == EnumAddressee.TRADER) { + this.tradeInfo = info; + } else if (type == EnumAddressee.PLAYER) { + this.address = address; + } + } - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.LETTER_INFO_RESPONSE; - } + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.LETTER_INFO_RESPONSE; + } - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { - if (type == null) { - data.writeShort(-1); - return; - } - data.writeShort(0); + if (type == null) { + data.writeShort(-1); + return; + } + data.writeShort(0); - data.writeUTF(type.toString()); + data.writeUTF(type.toString()); - if (type == EnumAddressee.PLAYER) { + if (type == EnumAddressee.PLAYER) { - if (address == null) { - data.writeShort(-1); - return; - } - data.writeShort(0); + if (address == null) { + data.writeShort(-1); + return; + } + data.writeShort(0); - GameProfile profile = address.getPlayerProfile(); + GameProfile profile = address.getPlayerProfile(); - data.writeLong(profile.getId().getMostSignificantBits()); - data.writeLong(profile.getId().getLeastSignificantBits()); - data.writeUTF(profile.getName()); + data.writeLong(profile.getId().getMostSignificantBits()); + data.writeLong(profile.getId().getLeastSignificantBits()); + data.writeUTF(profile.getName()); - } else if (type == EnumAddressee.TRADER) { + } else if (type == EnumAddressee.TRADER) { - if (tradeInfo == null) { - data.writeShort(-1); - return; - } + if (tradeInfo == null) { + data.writeShort(-1); + return; + } - data.writeShort(0); + data.writeShort(0); - data.writeUTF(tradeInfo.address.getName()); + data.writeUTF(tradeInfo.address.getName()); - data.writeLong(tradeInfo.owner.getId().getMostSignificantBits()); - data.writeLong(tradeInfo.owner.getId().getLeastSignificantBits()); - data.writeUTF(tradeInfo.owner.getName()); + data.writeLong(tradeInfo.owner.getId().getMostSignificantBits()); + data.writeLong(tradeInfo.owner.getId().getLeastSignificantBits()); + data.writeUTF(tradeInfo.owner.getName()); - data.writeItemStack(tradeInfo.tradegood); - data.writeItemStacks(tradeInfo.required); + data.writeItemStack(tradeInfo.tradegood); + data.writeItemStacks(tradeInfo.required); - data.writeShort(tradeInfo.state.ordinal()); - } - } + data.writeShort(tradeInfo.state.ordinal()); + } + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { + @Override + public void readData(DataInputStreamForestry data) throws IOException { - if (data.readShort() < 0) { - return; - } + if (data.readShort() < 0) { + return; + } - type = EnumAddressee.fromString(data.readUTF()); + type = EnumAddressee.fromString(data.readUTF()); - if (type == EnumAddressee.PLAYER) { - if (data.readShort() < 0) { - return; - } - GameProfile player = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); - this.address = PostManager.postRegistry.getMailAddress(player); + if (type == EnumAddressee.PLAYER) { + if (data.readShort() < 0) { + return; + } + GameProfile player = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); + this.address = PostManager.postRegistry.getMailAddress(player); - } else if (type == EnumAddressee.TRADER) { - if (data.readShort() < 0) { - return; - } - IMailAddress address = PostManager.postRegistry.getMailAddress(data.readUTF()); - GameProfile owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); - ItemStack tradegood; - ItemStack[] required; + } else if (type == EnumAddressee.TRADER) { + if (data.readShort() < 0) { + return; + } + IMailAddress address = PostManager.postRegistry.getMailAddress(data.readUTF()); + GameProfile owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); + ItemStack tradegood; + ItemStack[] required; - tradegood = data.readItemStack(); - required = data.readItemStacks(); + tradegood = data.readItemStack(); + required = data.readItemStacks(); - this.tradeInfo = new TradeStationInfo(address, owner, tradegood, required, EnumStationState.values()[data.readShort()]); - } - } + this.tradeInfo = new TradeStationInfo( + address, owner, tradegood, required, EnumStationState.values()[data.readShort()]); + } + } - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Container container = player.openContainer; - if (container instanceof ILetterInfoReceiver) { - ((ILetterInfoReceiver) container).handleLetterInfoUpdate(this); - } - } + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + Container container = player.openContainer; + if (container instanceof ILetterInfoReceiver) { + ((ILetterInfoReceiver) container).handleLetterInfoUpdate(this); + } + } } diff --git a/src/main/java/forestry/mail/network/packets/PacketLetterTextSet.java b/src/main/java/forestry/mail/network/packets/PacketLetterTextSet.java index ee6804259..d070feb1b 100644 --- a/src/main/java/forestry/mail/network/packets/PacketLetterTextSet.java +++ b/src/main/java/forestry/mail/network/packets/PacketLetterTextSet.java @@ -1,45 +1,42 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayerMP; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; -import forestry.core.network.packets.PacketString; -import forestry.mail.gui.ContainerLetter; - -public class PacketLetterTextSet extends PacketString implements IForestryPacketServer { - - public PacketLetterTextSet() { - } - - public PacketLetterTextSet(String string) { - super(string); - } - - @Override - public PacketIdServer getPacketId() { - return PacketIdServer.LETTER_TEXT_SET; - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - if (!(player.openContainer instanceof ContainerLetter)) { - return; - } - - ((ContainerLetter) player.openContainer).handleSetText(this); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketIdServer; +import forestry.core.network.packets.PacketString; +import forestry.mail.gui.ContainerLetter; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayerMP; + +public class PacketLetterTextSet extends PacketString implements IForestryPacketServer { + + public PacketLetterTextSet() {} + + public PacketLetterTextSet(String string) { + super(string); + } + + @Override + public PacketIdServer getPacketId() { + return PacketIdServer.LETTER_TEXT_SET; + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { + if (!(player.openContainer instanceof ContainerLetter)) { + return; + } + + ((ContainerLetter) player.openContainer).handleSetText(this); + } +} diff --git a/src/main/java/forestry/mail/network/packets/PacketPOBoxInfoUpdate.java b/src/main/java/forestry/mail/network/packets/PacketPOBoxInfoUpdate.java index fd6224c5d..626607d69 100644 --- a/src/main/java/forestry/mail/network/packets/PacketPOBoxInfoUpdate.java +++ b/src/main/java/forestry/mail/network/packets/PacketPOBoxInfoUpdate.java @@ -10,10 +10,6 @@ ******************************************************************************/ package forestry.mail.network.packets; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; - import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.ForestryPacket; @@ -21,48 +17,48 @@ import forestry.core.network.IForestryPacketClient; import forestry.core.network.PacketIdClient; import forestry.mail.POBoxInfo; import forestry.mail.gui.GuiMailboxInfo; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; public class PacketPOBoxInfoUpdate extends ForestryPacket implements IForestryPacketClient { - public POBoxInfo poboxInfo; + public POBoxInfo poboxInfo; - public PacketPOBoxInfoUpdate() { - } + public PacketPOBoxInfoUpdate() {} - public PacketPOBoxInfoUpdate(POBoxInfo info) { - this.poboxInfo = info; - } + public PacketPOBoxInfoUpdate(POBoxInfo info) { + this.poboxInfo = info; + } - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.POBOX_INFO_RESPONSE; - } + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.POBOX_INFO_RESPONSE; + } - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - if (poboxInfo == null) { - data.writeShort(-1); - return; - } + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + if (poboxInfo == null) { + data.writeShort(-1); + return; + } - data.writeShort(0); - data.writeInt(poboxInfo.playerLetters); - data.writeInt(poboxInfo.tradeLetters); - } + data.writeShort(0); + data.writeInt(poboxInfo.playerLetters); + data.writeInt(poboxInfo.tradeLetters); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - short isNotNull = data.readShort(); - if (isNotNull < 0) { - return; - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + short isNotNull = data.readShort(); + if (isNotNull < 0) { + return; + } - this.poboxInfo = new POBoxInfo(data.readInt(), data.readInt()); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - GuiMailboxInfo.instance.setPOBoxInfo(poboxInfo); - } + this.poboxInfo = new POBoxInfo(data.readInt(), data.readInt()); + } + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + GuiMailboxInfo.instance.setPOBoxInfo(poboxInfo); + } } diff --git a/src/main/java/forestry/mail/network/packets/PacketTraderAddressRequest.java b/src/main/java/forestry/mail/network/packets/PacketTraderAddressRequest.java index bc3dfe752..184557d53 100644 --- a/src/main/java/forestry/mail/network/packets/PacketTraderAddressRequest.java +++ b/src/main/java/forestry/mail/network/packets/PacketTraderAddressRequest.java @@ -1,61 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; -import forestry.core.network.packets.PacketCoordinates; -import forestry.mail.tiles.TileTrader; - -public class PacketTraderAddressRequest extends PacketCoordinates implements IForestryPacketServer { - - private String addressName; - - public PacketTraderAddressRequest() { - } - - public PacketTraderAddressRequest(TileTrader tile, String addressName) { - super(tile); - this.addressName = addressName; - } - - @Override - public PacketIdServer getPacketId() { - return PacketIdServer.TRADING_ADDRESS_REQUEST; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeUTF(addressName); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - addressName = data.readUTF(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - TileEntity tile = getTarget(player.worldObj); - if ((tile instanceof TileTrader)) { - ((TileTrader) tile).handleSetAddressRequest(addressName); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketIdServer; +import forestry.core.network.packets.PacketCoordinates; +import forestry.mail.tiles.TileTrader; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.tileentity.TileEntity; + +public class PacketTraderAddressRequest extends PacketCoordinates implements IForestryPacketServer { + + private String addressName; + + public PacketTraderAddressRequest() {} + + public PacketTraderAddressRequest(TileTrader tile, String addressName) { + super(tile); + this.addressName = addressName; + } + + @Override + public PacketIdServer getPacketId() { + return PacketIdServer.TRADING_ADDRESS_REQUEST; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeUTF(addressName); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + addressName = data.readUTF(); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { + TileEntity tile = getTarget(player.worldObj); + if ((tile instanceof TileTrader)) { + ((TileTrader) tile).handleSetAddressRequest(addressName); + } + } +} diff --git a/src/main/java/forestry/mail/network/packets/PacketTraderAddressResponse.java b/src/main/java/forestry/mail/network/packets/PacketTraderAddressResponse.java index 28e4d4316..f4cee718f 100644 --- a/src/main/java/forestry/mail/network/packets/PacketTraderAddressResponse.java +++ b/src/main/java/forestry/mail/network/packets/PacketTraderAddressResponse.java @@ -1,62 +1,58 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.mail.tiles.TileTrader; - -public class PacketTraderAddressResponse extends PacketCoordinates implements IForestryPacketClient { - - private String addressName; - - public PacketTraderAddressResponse() { - } - - public PacketTraderAddressResponse(TileTrader tile, String addressName) { - super(tile); - this.addressName = addressName; - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.TRADING_ADDRESS_RESPONSE; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeUTF(addressName); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - addressName = data.readUTF(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(player.worldObj); - if ((tile instanceof TileTrader)) { - ((TileTrader) tile).handleSetAddressResponse(addressName); - } - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.network.packets; + +import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.PacketIdClient; +import forestry.core.network.packets.PacketCoordinates; +import forestry.mail.tiles.TileTrader; +import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; + +public class PacketTraderAddressResponse extends PacketCoordinates implements IForestryPacketClient { + + private String addressName; + + public PacketTraderAddressResponse() {} + + public PacketTraderAddressResponse(TileTrader tile, String addressName) { + super(tile); + this.addressName = addressName; + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.TRADING_ADDRESS_RESPONSE; + } + + @Override + protected void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + data.writeUTF(addressName); + } + + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + addressName = data.readUTF(); + } + + @Override + public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { + TileEntity tile = getTarget(player.worldObj); + if ((tile instanceof TileTrader)) { + ((TileTrader) tile).handleSetAddressResponse(addressName); + } + } +} diff --git a/src/main/java/forestry/mail/tiles/IMailContainer.java b/src/main/java/forestry/mail/tiles/IMailContainer.java index a99fa9159..0d98a3d65 100644 --- a/src/main/java/forestry/mail/tiles/IMailContainer.java +++ b/src/main/java/forestry/mail/tiles/IMailContainer.java @@ -11,5 +11,5 @@ package forestry.mail.tiles; public interface IMailContainer { - boolean hasMail(); + boolean hasMail(); } diff --git a/src/main/java/forestry/mail/tiles/TileMailbox.java b/src/main/java/forestry/mail/tiles/TileMailbox.java index 30ed38f3f..f4bf4033f 100644 --- a/src/main/java/forestry/mail/tiles/TileMailbox.java +++ b/src/main/java/forestry/mail/tiles/TileMailbox.java @@ -10,22 +10,9 @@ ******************************************************************************/ package forestry.mail.tiles; -import java.util.Collection; -import java.util.LinkedList; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChatComponentTranslation; -import net.minecraft.world.World; - +import buildcraft.api.statements.ITriggerExternal; import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.util.ForgeDirection; - import cpw.mods.fml.common.Optional; - import forestry.api.mail.ILetter; import forestry.api.mail.IMailAddress; import forestry.api.mail.IPostalState; @@ -38,102 +25,110 @@ import forestry.mail.PostRegistry; import forestry.mail.gui.ContainerMailbox; import forestry.mail.gui.GuiMailbox; import forestry.mail.triggers.MailTriggers; - -import buildcraft.api.statements.ITriggerExternal; +import java.util.Collection; +import java.util.LinkedList; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChatComponentTranslation; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; public class TileMailbox extends TileBase implements IMailContainer { - private boolean isLinked = false; + private boolean isLinked = false; - public TileMailbox() { - super("mailbox"); - setInternalInventory(new InventoryAdapter(POBox.SLOT_SIZE, "Letters").disableAutomation()); - } + public TileMailbox() { + super("mailbox"); + setInternalInventory(new InventoryAdapter(POBox.SLOT_SIZE, "Letters").disableAutomation()); + } - /* GUI */ - @Override - public void openGui(EntityPlayer player) { - if (worldObj.isRemote) { - return; - } + /* GUI */ + @Override + public void openGui(EntityPlayer player) { + if (worldObj.isRemote) { + return; + } - ItemStack held = player.getCurrentEquippedItem(); + ItemStack held = player.getCurrentEquippedItem(); - // Handle letter sending - if (PostManager.postRegistry.isLetter(held)) { - IPostalState result = this.tryDispatchLetter(held); - if (!result.isOk()) { - player.addChatMessage(new ChatComponentTranslation("for.chat.mail." + result.getIdentifier())); - } else { - held.stackSize--; - } - } else { - super.openGui(player); - } - } + // Handle letter sending + if (PostManager.postRegistry.isLetter(held)) { + IPostalState result = this.tryDispatchLetter(held); + if (!result.isOk()) { + player.addChatMessage(new ChatComponentTranslation("for.chat.mail." + result.getIdentifier())); + } else { + held.stackSize--; + } + } else { + super.openGui(player); + } + } - /* UPDATING */ - @Override - public void updateServerSide() { - if (!isLinked) { - getOrCreateMailInventory(worldObj, getAccessHandler().getOwner()); - isLinked = true; - } - } + /* UPDATING */ + @Override + public void updateServerSide() { + if (!isLinked) { + getOrCreateMailInventory(worldObj, getAccessHandler().getOwner()); + isLinked = true; + } + } - /* MAIL HANDLING */ - public IInventory getOrCreateMailInventory(World world, GameProfile playerProfile) { - if (world.isRemote) { - return getInternalInventory(); - } + /* MAIL HANDLING */ + public IInventory getOrCreateMailInventory(World world, GameProfile playerProfile) { + if (world.isRemote) { + return getInternalInventory(); + } - IMailAddress address = PostManager.postRegistry.getMailAddress(playerProfile); - return PostRegistry.getOrCreatePOBox(worldObj, address); - } + IMailAddress address = PostManager.postRegistry.getMailAddress(playerProfile); + return PostRegistry.getOrCreatePOBox(worldObj, address); + } - private IPostalState tryDispatchLetter(ItemStack letterstack) { - ILetter letter = PostManager.postRegistry.getLetter(letterstack); - IPostalState result; + private IPostalState tryDispatchLetter(ItemStack letterstack) { + ILetter letter = PostManager.postRegistry.getLetter(letterstack); + IPostalState result; - if (letter != null) { - result = PostManager.postRegistry.getPostOffice(worldObj).lodgeLetter(worldObj, letterstack, true); - } else { - result = EnumDeliveryState.NOT_MAILABLE; - } + if (letter != null) { + result = PostManager.postRegistry.getPostOffice(worldObj).lodgeLetter(worldObj, letterstack, true); + } else { + result = EnumDeliveryState.NOT_MAILABLE; + } - return result; - } + return result; + } - /* IMAILCONTAINER */ - @Override - public boolean hasMail() { + /* IMAILCONTAINER */ + @Override + public boolean hasMail() { - IInventory mailInventory = getOrCreateMailInventory(worldObj, getAccessHandler().getOwner()); - for (int i = 0; i < mailInventory.getSizeInventory(); i++) { - if (mailInventory.getStackInSlot(i) != null) { - return true; - } - } + IInventory mailInventory = + getOrCreateMailInventory(worldObj, getAccessHandler().getOwner()); + for (int i = 0; i < mailInventory.getSizeInventory(); i++) { + if (mailInventory.getStackInSlot(i) != null) { + return true; + } + } - return false; - } + return false; + } - /* ITRIGGERPROVIDER */ - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { - LinkedList res = new LinkedList<>(); - res.add(MailTriggers.triggerHasMail); - return res; - } + /* ITRIGGERPROVIDER */ + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { + LinkedList res = new LinkedList<>(); + res.add(MailTriggers.triggerHasMail); + return res; + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiMailbox(player.inventory, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiMailbox(player.inventory, this); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerMailbox(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerMailbox(player.inventory, this); + } } diff --git a/src/main/java/forestry/mail/tiles/TileStampCollector.java b/src/main/java/forestry/mail/tiles/TileStampCollector.java index ae73864ef..72e372c3e 100644 --- a/src/main/java/forestry/mail/tiles/TileStampCollector.java +++ b/src/main/java/forestry/mail/tiles/TileStampCollector.java @@ -10,10 +10,6 @@ ******************************************************************************/ package forestry.mail.tiles; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - import forestry.api.mail.IStamps; import forestry.api.mail.PostManager; import forestry.core.inventory.IInventoryAdapter; @@ -22,46 +18,56 @@ import forestry.core.utils.InventoryUtil; import forestry.mail.gui.ContainerStampCollector; import forestry.mail.gui.GuiStampCollector; import forestry.mail.inventory.InventoryStampCollector; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; public class TileStampCollector extends TileBase implements IInventory { - public TileStampCollector() { - super("philatelist"); - setInternalInventory(new InventoryStampCollector(this)); - } + public TileStampCollector() { + super("philatelist"); + setInternalInventory(new InventoryStampCollector(this)); + } - @Override - public void updateServerSide() { - if (!updateOnInterval(20)) { - return; - } + @Override + public void updateServerSide() { + if (!updateOnInterval(20)) { + return; + } - ItemStack stamp = null; + ItemStack stamp = null; - IInventoryAdapter inventory = getInternalInventory(); - if (inventory.getStackInSlot(InventoryStampCollector.SLOT_FILTER) == null) { - stamp = PostManager.postRegistry.getPostOffice(worldObj).getAnyStamp(1); - } else { - ItemStack filter = inventory.getStackInSlot(InventoryStampCollector.SLOT_FILTER); - if (filter.getItem() instanceof IStamps) { - stamp = PostManager.postRegistry.getPostOffice(worldObj).getAnyStamp(((IStamps) filter.getItem()).getPostage(filter), 1); - } - } + IInventoryAdapter inventory = getInternalInventory(); + if (inventory.getStackInSlot(InventoryStampCollector.SLOT_FILTER) == null) { + stamp = PostManager.postRegistry.getPostOffice(worldObj).getAnyStamp(1); + } else { + ItemStack filter = inventory.getStackInSlot(InventoryStampCollector.SLOT_FILTER); + if (filter.getItem() instanceof IStamps) { + stamp = PostManager.postRegistry + .getPostOffice(worldObj) + .getAnyStamp(((IStamps) filter.getItem()).getPostage(filter), 1); + } + } - if (stamp == null) { - return; - } + if (stamp == null) { + return; + } - // Store it. - InventoryUtil.stowInInventory(stamp, inventory, true, InventoryStampCollector.SLOT_BUFFER_1, InventoryStampCollector.SLOT_BUFFER_COUNT); - } + // Store it. + InventoryUtil.stowInInventory( + stamp, + inventory, + true, + InventoryStampCollector.SLOT_BUFFER_1, + InventoryStampCollector.SLOT_BUFFER_COUNT); + } - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiStampCollector(player.inventory, this); - } + @Override + public Object getGui(EntityPlayer player, int data) { + return new GuiStampCollector(player.inventory, this); + } - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerStampCollector(player.inventory, this); - } + @Override + public Object getContainer(EntityPlayer player, int data) { + return new ContainerStampCollector(player.inventory, this); + } } diff --git a/src/main/java/forestry/mail/tiles/TileTrader.java b/src/main/java/forestry/mail/tiles/TileTrader.java index 1dc852f74..13fc7c6ae 100644 --- a/src/main/java/forestry/mail/tiles/TileTrader.java +++ b/src/main/java/forestry/mail/tiles/TileTrader.java @@ -10,21 +10,8 @@ ******************************************************************************/ package forestry.mail.tiles; -import java.io.IOException; -import java.util.Collection; -import java.util.LinkedList; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Items; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - +import buildcraft.api.statements.ITriggerExternal; import cpw.mods.fml.common.Optional; - import forestry.api.core.IErrorLogic; import forestry.api.mail.IMailAddress; import forestry.api.mail.IStamps; @@ -46,304 +33,318 @@ import forestry.mail.gui.GuiTrader; import forestry.mail.inventory.InventoryTradeStation; import forestry.mail.network.packets.PacketTraderAddressResponse; import forestry.mail.triggers.MailTriggers; - -import buildcraft.api.statements.ITriggerExternal; +import java.io.IOException; +import java.util.Collection; +import java.util.LinkedList; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Items; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TileTrader extends TileBase { - private IMailAddress address; + private IMailAddress address; - public TileTrader() { - super("trade.station"); - address = new MailAddress(); - setInternalInventory(new InventoryTradeStation()); - } + public TileTrader() { + super("trade.station"); + address = new MailAddress(); + setInternalInventory(new InventoryTradeStation()); + } - @Override - public void openGui(EntityPlayer player) { - short data = (short) (isLinked() ? 0 : 1); - GuiHandler.openGui(player, this, data); - } + @Override + public void openGui(EntityPlayer player) { + short data = (short) (isLinked() ? 0 : 1); + GuiHandler.openGui(player, this, data); + } - @Override - public void onRemoval() { - if (isLinked()) { - PostManager.postRegistry.deleteTradeStation(worldObj, address); - } - } + @Override + public void onRemoval() { + if (isLinked()) { + PostManager.postRegistry.deleteTradeStation(worldObj, address); + } + } - /* SAVING & LOADING */ - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + /* SAVING & LOADING */ + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - if (address != null) { - NBTTagCompound nbt = new NBTTagCompound(); - address.writeToNBT(nbt); - nbttagcompound.setTag("address", nbt); - } - } + if (address != null) { + NBTTagCompound nbt = new NBTTagCompound(); + address.writeToNBT(nbt); + nbttagcompound.setTag("address", nbt); + } + } - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); - if (nbttagcompound.hasKey("address")) { - address = MailAddress.loadFromNBT(nbttagcompound.getCompoundTag("address")); - } - } + if (nbttagcompound.hasKey("address")) { + address = MailAddress.loadFromNBT(nbttagcompound.getCompoundTag("address")); + } + } - /* NETWORK */ + /* NETWORK */ - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - String name = null; - if (address != null) { - name = address.getName(); - } - if (name == null) { - name = ""; - } - data.writeUTF(name); - } + @Override + public void writeData(DataOutputStreamForestry data) throws IOException { + super.writeData(data); + String name = null; + if (address != null) { + name = address.getName(); + } + if (name == null) { + name = ""; + } + data.writeUTF(name); + } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - String address = data.readUTF(); - if (address.length() > 0) { - this.address = PostManager.postRegistry.getMailAddress(address); - } - } + @Override + public void readData(DataInputStreamForestry data) throws IOException { + super.readData(data); + String address = data.readUTF(); + if (address.length() > 0) { + this.address = PostManager.postRegistry.getMailAddress(address); + } + } - /* UPDATING */ + /* UPDATING */ - /** - * The trade station should show errors for missing stamps and paper first. - * Once it is able to send letters, it should display other error states. - */ - @Override - public void updateServerSide() { + /** + * The trade station should show errors for missing stamps and paper first. + * Once it is able to send letters, it should display other error states. + */ + @Override + public void updateServerSide() { - if (!isLinked() || !updateOnInterval(10)) { - return; - } + if (!isLinked() || !updateOnInterval(10)) { + return; + } - IErrorLogic errorLogic = getErrorLogic(); + IErrorLogic errorLogic = getErrorLogic(); - errorLogic.setCondition(!hasPostageMin(3), EnumErrorCode.NO_STAMPS); - errorLogic.setCondition(!hasPaperMin(2), EnumErrorCode.NO_PAPER); + errorLogic.setCondition(!hasPostageMin(3), EnumErrorCode.NO_STAMPS); + errorLogic.setCondition(!hasPaperMin(2), EnumErrorCode.NO_PAPER); - IInventory inventory = getInternalInventory(); - ItemStack tradeGood = inventory.getStackInSlot(TradeStation.SLOT_TRADEGOOD); - errorLogic.setCondition(tradeGood == null, EnumErrorCode.NO_TRADE); + IInventory inventory = getInternalInventory(); + ItemStack tradeGood = inventory.getStackInSlot(TradeStation.SLOT_TRADEGOOD); + errorLogic.setCondition(tradeGood == null, EnumErrorCode.NO_TRADE); - boolean hasRequest = hasItemCount(TradeStation.SLOT_EXCHANGE_1, TradeStation.SLOT_EXCHANGE_COUNT, null, 1); - errorLogic.setCondition(!hasRequest, EnumErrorCode.NO_TRADE); + boolean hasRequest = hasItemCount(TradeStation.SLOT_EXCHANGE_1, TradeStation.SLOT_EXCHANGE_COUNT, null, 1); + errorLogic.setCondition(!hasRequest, EnumErrorCode.NO_TRADE); - if (tradeGood != null) { - boolean hasSupplies = hasItemCount(TradeStation.SLOT_SEND_BUFFER, TradeStation.SLOT_SEND_BUFFER_COUNT, tradeGood, tradeGood.stackSize); - errorLogic.setCondition(!hasSupplies, EnumErrorCode.NO_SUPPLIES); - } + if (tradeGood != null) { + boolean hasSupplies = hasItemCount( + TradeStation.SLOT_SEND_BUFFER, TradeStation.SLOT_SEND_BUFFER_COUNT, tradeGood, tradeGood.stackSize); + errorLogic.setCondition(!hasSupplies, EnumErrorCode.NO_SUPPLIES); + } - if (inventory instanceof TradeStation && updateOnInterval(200)) { - boolean canReceivePayment = ((TradeStation) inventory).canReceivePayment(); - errorLogic.setCondition(!canReceivePayment, EnumErrorCode.NO_SPACE_INVENTORY); - } - } + if (inventory instanceof TradeStation && updateOnInterval(200)) { + boolean canReceivePayment = ((TradeStation) inventory).canReceivePayment(); + errorLogic.setCondition(!canReceivePayment, EnumErrorCode.NO_SPACE_INVENTORY); + } + } - /* STATE INFORMATION */ - public boolean isLinked() { - if (address == null || !address.isValid()) { - return false; - } + /* STATE INFORMATION */ + public boolean isLinked() { + if (address == null || !address.isValid()) { + return false; + } - IErrorLogic errorLogic = getErrorLogic(); + IErrorLogic errorLogic = getErrorLogic(); - return !errorLogic.contains(EnumErrorCode.NOT_ALPHANUMERIC) && !errorLogic.contains(EnumErrorCode.NOT_UNIQUE); - } + return !errorLogic.contains(EnumErrorCode.NOT_ALPHANUMERIC) && !errorLogic.contains(EnumErrorCode.NOT_UNIQUE); + } - /** - * Returns true if there are 'itemCount' of 'item' in the inventory - * wildcard when item == null, counts all types of items - */ - private boolean hasItemCount(int startSlot, int countSlots, ItemStack item, int itemCount) { - int count = 0; + /** + * Returns true if there are 'itemCount' of 'item' in the inventory + * wildcard when item == null, counts all types of items + */ + private boolean hasItemCount(int startSlot, int countSlots, ItemStack item, int itemCount) { + int count = 0; - IInventory tradeInventory = this.getInternalInventory(); - for (int i = startSlot; i < startSlot + countSlots; i++) { - ItemStack itemInSlot = tradeInventory.getStackInSlot(i); - if (itemInSlot == null) { - continue; - } - if (item == null || ItemStackUtil.isIdenticalItem(itemInSlot, item)) { - count += itemInSlot.stackSize; - } - if (count >= itemCount) { - return true; - } - } + IInventory tradeInventory = this.getInternalInventory(); + for (int i = startSlot; i < startSlot + countSlots; i++) { + ItemStack itemInSlot = tradeInventory.getStackInSlot(i); + if (itemInSlot == null) { + continue; + } + if (item == null || ItemStackUtil.isIdenticalItem(itemInSlot, item)) { + count += itemInSlot.stackSize; + } + if (count >= itemCount) { + return true; + } + } - return false; - } + return false; + } - /** - * Returns the percentage of the inventory that is occupied by 'item' - * if item == null, returns the percentage occupied by all kinds of items - */ - private float percentOccupied(int startSlot, int countSlots, ItemStack item) { - int count = 0; - int total = 0; + /** + * Returns the percentage of the inventory that is occupied by 'item' + * if item == null, returns the percentage occupied by all kinds of items + */ + private float percentOccupied(int startSlot, int countSlots, ItemStack item) { + int count = 0; + int total = 0; - IInventory tradeInventory = this.getInternalInventory(); - for (int i = startSlot; i < startSlot + countSlots; i++) { - ItemStack itemInSlot = tradeInventory.getStackInSlot(i); - if (itemInSlot == null) { - total += 64; - } else { - total += itemInSlot.getMaxStackSize(); - if (item == null || ItemStackUtil.isIdenticalItem(itemInSlot, item)) { - count += itemInSlot.stackSize; - } - } - } + IInventory tradeInventory = this.getInternalInventory(); + for (int i = startSlot; i < startSlot + countSlots; i++) { + ItemStack itemInSlot = tradeInventory.getStackInSlot(i); + if (itemInSlot == null) { + total += 64; + } else { + total += itemInSlot.getMaxStackSize(); + if (item == null || ItemStackUtil.isIdenticalItem(itemInSlot, item)) { + count += itemInSlot.stackSize; + } + } + } - return ((float) count / (float) total); - } + return ((float) count / (float) total); + } - public boolean hasPaperMin(int count) { - return hasItemCount(TradeStation.SLOT_LETTERS_1, TradeStation.SLOT_LETTERS_COUNT, new ItemStack(Items.paper), count); - } + public boolean hasPaperMin(int count) { + return hasItemCount( + TradeStation.SLOT_LETTERS_1, TradeStation.SLOT_LETTERS_COUNT, new ItemStack(Items.paper), count); + } - public boolean hasInputBufMin(float percentage) { - IInventory inventory = getInternalInventory(); - ItemStack tradeGood = inventory.getStackInSlot(TradeStation.SLOT_TRADEGOOD); - if (tradeGood == null) { - return true; - } - return percentOccupied(TradeStation.SLOT_SEND_BUFFER, TradeStation.SLOT_SEND_BUFFER_COUNT, tradeGood) > percentage; - } + public boolean hasInputBufMin(float percentage) { + IInventory inventory = getInternalInventory(); + ItemStack tradeGood = inventory.getStackInSlot(TradeStation.SLOT_TRADEGOOD); + if (tradeGood == null) { + return true; + } + return percentOccupied(TradeStation.SLOT_SEND_BUFFER, TradeStation.SLOT_SEND_BUFFER_COUNT, tradeGood) + > percentage; + } - public boolean hasOutputBufMin(float percentage) { - return percentOccupied(TradeStation.SLOT_RECEIVE_BUFFER, TradeStation.SLOT_RECEIVE_BUFFER_COUNT, null) > percentage; - } + public boolean hasOutputBufMin(float percentage) { + return percentOccupied(TradeStation.SLOT_RECEIVE_BUFFER, TradeStation.SLOT_RECEIVE_BUFFER_COUNT, null) + > percentage; + } - public boolean hasPostageMin(int postage) { + public boolean hasPostageMin(int postage) { - int posted = 0; + int posted = 0; - IInventory tradeInventory = this.getInternalInventory(); - for (int i = TradeStation.SLOT_STAMPS_1; i < TradeStation.SLOT_STAMPS_1 + TradeStation.SLOT_STAMPS_COUNT; i++) { - ItemStack stamp = tradeInventory.getStackInSlot(i); - if (stamp == null) { - continue; - } - if (!(stamp.getItem() instanceof IStamps)) { - continue; - } + IInventory tradeInventory = this.getInternalInventory(); + for (int i = TradeStation.SLOT_STAMPS_1; i < TradeStation.SLOT_STAMPS_1 + TradeStation.SLOT_STAMPS_COUNT; i++) { + ItemStack stamp = tradeInventory.getStackInSlot(i); + if (stamp == null) { + continue; + } + if (!(stamp.getItem() instanceof IStamps)) { + continue; + } - posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.stackSize; - if (posted >= postage) { - return true; - } - } + posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.stackSize; + if (posted >= postage) { + return true; + } + } - return false; - } + return false; + } - /* ADDRESS */ - public IMailAddress getAddress() { - return address; - } + /* ADDRESS */ + public IMailAddress getAddress() { + return address; + } - public void handleSetAddressRequest(String addressName) { - IMailAddress address = PostManager.postRegistry.getMailAddress(addressName); - setAddress(address); + public void handleSetAddressRequest(String addressName) { + IMailAddress address = PostManager.postRegistry.getMailAddress(addressName); + setAddress(address); - IMailAddress newAddress = getAddress(); - if (newAddress != null) { - String newAddressName = newAddress.getName(); - if (newAddressName != null && newAddressName.equals(addressName)) { - PacketTraderAddressResponse packetResponse = new PacketTraderAddressResponse(this, addressName); - Proxies.net.sendNetworkPacket(packetResponse, worldObj); - } - } - } + IMailAddress newAddress = getAddress(); + if (newAddress != null) { + String newAddressName = newAddress.getName(); + if (newAddressName != null && newAddressName.equals(addressName)) { + PacketTraderAddressResponse packetResponse = new PacketTraderAddressResponse(this, addressName); + Proxies.net.sendNetworkPacket(packetResponse, worldObj); + } + } + } - public void handleSetAddressResponse(String addressName) { - IMailAddress address = PostManager.postRegistry.getMailAddress(addressName); - setAddress(address); - } + public void handleSetAddressResponse(String addressName) { + IMailAddress address = PostManager.postRegistry.getMailAddress(addressName); + setAddress(address); + } - private void setAddress(IMailAddress address) { - if (address == null) { - throw new NullPointerException("address must not be null"); - } + private void setAddress(IMailAddress address) { + if (address == null) { + throw new NullPointerException("address must not be null"); + } - if (this.address != null && this.address.isValid() && this.address.equals(address)) { - return; - } + if (this.address != null && this.address.isValid() && this.address.equals(address)) { + return; + } - if (!worldObj.isRemote) { - IErrorLogic errorLogic = getErrorLogic(); + if (!worldObj.isRemote) { + IErrorLogic errorLogic = getErrorLogic(); - boolean hasValidTradeAddress = PostManager.postRegistry.isValidTradeAddress(worldObj, address); - errorLogic.setCondition(!hasValidTradeAddress, EnumErrorCode.NOT_ALPHANUMERIC); + boolean hasValidTradeAddress = PostManager.postRegistry.isValidTradeAddress(worldObj, address); + errorLogic.setCondition(!hasValidTradeAddress, EnumErrorCode.NOT_ALPHANUMERIC); - boolean hasUniqueTradeAddress = PostManager.postRegistry.isAvailableTradeAddress(worldObj, address); - errorLogic.setCondition(!hasUniqueTradeAddress, EnumErrorCode.NOT_UNIQUE); + boolean hasUniqueTradeAddress = PostManager.postRegistry.isAvailableTradeAddress(worldObj, address); + errorLogic.setCondition(!hasUniqueTradeAddress, EnumErrorCode.NOT_UNIQUE); - if (hasValidTradeAddress & hasUniqueTradeAddress) { - this.address = address; - PostManager.postRegistry.getOrCreateTradeStation(worldObj, getAccessHandler().getOwner(), address); - } - } else { - this.address = address; - } - } + if (hasValidTradeAddress & hasUniqueTradeAddress) { + this.address = address; + PostManager.postRegistry.getOrCreateTradeStation( + worldObj, getAccessHandler().getOwner(), address); + } + } else { + this.address = address; + } + } - @Override - public IInventoryAdapter getInternalInventory() { - // Handle client side - if (worldObj.isRemote || !address.isValid()) { - return super.getInternalInventory(); - } + @Override + public IInventoryAdapter getInternalInventory() { + // Handle client side + if (worldObj.isRemote || !address.isValid()) { + return super.getInternalInventory(); + } - return (TradeStation) PostManager.postRegistry.getOrCreateTradeStation(worldObj, getAccessHandler().getOwner(), address); - } + return (TradeStation) PostManager.postRegistry.getOrCreateTradeStation( + worldObj, getAccessHandler().getOwner(), address); + } - /* ITRIGGERPROVIDER */ - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { - LinkedList res = new LinkedList<>(); - res.add(MailTriggers.lowPaper64); - res.add(MailTriggers.lowPaper32); - res.add(MailTriggers.lowInput25); - res.add(MailTriggers.lowInput10); - res.add(MailTriggers.lowPostage40); - res.add(MailTriggers.lowPostage20); - res.add(MailTriggers.highBuffer90); - res.add(MailTriggers.highBuffer75); - return res; - } + /* ITRIGGERPROVIDER */ + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { + LinkedList res = new LinkedList<>(); + res.add(MailTriggers.lowPaper64); + res.add(MailTriggers.lowPaper32); + res.add(MailTriggers.lowInput25); + res.add(MailTriggers.lowInput10); + res.add(MailTriggers.lowPostage40); + res.add(MailTriggers.lowPostage20); + res.add(MailTriggers.highBuffer90); + res.add(MailTriggers.highBuffer75); + return res; + } - @Override - public Object getGui(EntityPlayer player, int data) { - if (data == 0) { - return new GuiTrader(player.inventory, this); - } else { - return new GuiTradeName(this); - } - } + @Override + public Object getGui(EntityPlayer player, int data) { + if (data == 0) { + return new GuiTrader(player.inventory, this); + } else { + return new GuiTradeName(this); + } + } - @Override - public Object getContainer(EntityPlayer player, int data) { - if (data == 0) { - return new ContainerTrader(player.inventory, this); - } else { - return new ContainerTradeName(this); - } - } + @Override + public Object getContainer(EntityPlayer player, int data) { + if (data == 0) { + return new ContainerTrader(player.inventory, this); + } else { + return new ContainerTradeName(this); + } + } } diff --git a/src/main/java/forestry/mail/triggers/MailTriggers.java b/src/main/java/forestry/mail/triggers/MailTriggers.java index aa57d1d73..ec7226de0 100644 --- a/src/main/java/forestry/mail/triggers/MailTriggers.java +++ b/src/main/java/forestry/mail/triggers/MailTriggers.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.triggers; - -import forestry.core.triggers.Trigger; - -public class MailTriggers { - public static Trigger triggerHasMail; - public static Trigger lowPaper64; - public static Trigger lowPaper32; - public static Trigger lowPostage40; - public static Trigger lowPostage20; - public static Trigger lowInput25; - public static Trigger lowInput10; - public static Trigger highBuffer75; - public static Trigger highBuffer90; - - public static void initialize() { - triggerHasMail = new TriggerHasMail(); - lowPaper64 = new TriggerLowPaper("mail.lowPaper.64", 64); - lowPaper32 = new TriggerLowPaper("mail.lowPaper.32", 32); - lowPostage40 = new TriggerLowStamps("mail.lowStamps.40", 40); - lowPostage20 = new TriggerLowStamps("mail.lowStamps.20", 20); - lowInput25 = new TriggerLowInput("mail.lowInput.25", 0.25f); - lowInput10 = new TriggerLowInput("mail.lowInput.10", 0.1f); - highBuffer75 = new TriggerBuffer("mail.lowBuffer.75", 0.75f); - highBuffer90 = new TriggerBuffer("mail.lowBuffer.90", 0.90f); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.triggers; + +import forestry.core.triggers.Trigger; + +public class MailTriggers { + public static Trigger triggerHasMail; + public static Trigger lowPaper64; + public static Trigger lowPaper32; + public static Trigger lowPostage40; + public static Trigger lowPostage20; + public static Trigger lowInput25; + public static Trigger lowInput10; + public static Trigger highBuffer75; + public static Trigger highBuffer90; + + public static void initialize() { + triggerHasMail = new TriggerHasMail(); + lowPaper64 = new TriggerLowPaper("mail.lowPaper.64", 64); + lowPaper32 = new TriggerLowPaper("mail.lowPaper.32", 32); + lowPostage40 = new TriggerLowStamps("mail.lowStamps.40", 40); + lowPostage20 = new TriggerLowStamps("mail.lowStamps.20", 20); + lowInput25 = new TriggerLowInput("mail.lowInput.25", 0.25f); + lowInput10 = new TriggerLowInput("mail.lowInput.10", 0.1f); + highBuffer75 = new TriggerBuffer("mail.lowBuffer.75", 0.75f); + highBuffer90 = new TriggerBuffer("mail.lowBuffer.90", 0.90f); + } +} diff --git a/src/main/java/forestry/mail/triggers/TriggerBuffer.java b/src/main/java/forestry/mail/triggers/TriggerBuffer.java index 3f29dba7e..b37c559e6 100755 --- a/src/main/java/forestry/mail/triggers/TriggerBuffer.java +++ b/src/main/java/forestry/mail/triggers/TriggerBuffer.java @@ -10,37 +10,35 @@ ******************************************************************************/ package forestry.mail.triggers; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.core.triggers.Trigger; -import forestry.mail.tiles.TileTrader; - import buildcraft.api.statements.IStatementContainer; import buildcraft.api.statements.IStatementParameter; +import forestry.core.triggers.Trigger; +import forestry.mail.tiles.TileTrader; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TriggerBuffer extends Trigger { - private final float threshold; + private final float threshold; - public TriggerBuffer(String tag, float threshold) { - super(tag, "mailBuffer"); - this.threshold = threshold; - } + public TriggerBuffer(String tag, float threshold) { + super(tag, "mailBuffer"); + this.threshold = threshold; + } - @Override - public String getDescription() { - return super.getDescription() + " > " + threshold * 100 + "%"; - } + @Override + public String getDescription() { + return super.getDescription() + " > " + threshold * 100 + "%"; + } - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - if (!(tile instanceof TileTrader)) { - return false; - } + if (!(tile instanceof TileTrader)) { + return false; + } - return ((TileTrader) tile).hasOutputBufMin(threshold); - } + return ((TileTrader) tile).hasOutputBufMin(threshold); + } } diff --git a/src/main/java/forestry/mail/triggers/TriggerHasMail.java b/src/main/java/forestry/mail/triggers/TriggerHasMail.java index 6125749fd..c454318d5 100755 --- a/src/main/java/forestry/mail/triggers/TriggerHasMail.java +++ b/src/main/java/forestry/mail/triggers/TriggerHasMail.java @@ -10,30 +10,27 @@ ******************************************************************************/ package forestry.mail.triggers; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.core.triggers.Trigger; -import forestry.mail.tiles.IMailContainer; - import buildcraft.api.statements.IStatementContainer; import buildcraft.api.statements.IStatementParameter; +import forestry.core.triggers.Trigger; +import forestry.mail.tiles.IMailContainer; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TriggerHasMail extends Trigger { - public TriggerHasMail() { - super("mail.hasMail", "hasMail"); - } + public TriggerHasMail() { + super("mail.hasMail", "hasMail"); + } - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - if (!(tile instanceof IMailContainer)) { - return false; - } - - return ((IMailContainer) tile).hasMail(); - } + if (!(tile instanceof IMailContainer)) { + return false; + } + return ((IMailContainer) tile).hasMail(); + } } diff --git a/src/main/java/forestry/mail/triggers/TriggerLowInput.java b/src/main/java/forestry/mail/triggers/TriggerLowInput.java index 889ea245f..0083f19a7 100755 --- a/src/main/java/forestry/mail/triggers/TriggerLowInput.java +++ b/src/main/java/forestry/mail/triggers/TriggerLowInput.java @@ -10,37 +10,35 @@ ******************************************************************************/ package forestry.mail.triggers; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.core.triggers.Trigger; -import forestry.mail.tiles.TileTrader; - import buildcraft.api.statements.IStatementContainer; import buildcraft.api.statements.IStatementParameter; +import forestry.core.triggers.Trigger; +import forestry.mail.tiles.TileTrader; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TriggerLowInput extends Trigger { - private final float threshold; + private final float threshold; - public TriggerLowInput(String tag, float threshold) { - super(tag, "lowInput"); - this.threshold = threshold; - } + public TriggerLowInput(String tag, float threshold) { + super(tag, "lowInput"); + this.threshold = threshold; + } - @Override - public String getDescription() { - return super.getDescription() + " < " + threshold * 100 + "%"; - } + @Override + public String getDescription() { + return super.getDescription() + " < " + threshold * 100 + "%"; + } - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - if (!(tile instanceof TileTrader)) { - return false; - } + if (!(tile instanceof TileTrader)) { + return false; + } - return !((TileTrader) tile).hasInputBufMin(threshold); - } + return !((TileTrader) tile).hasInputBufMin(threshold); + } } diff --git a/src/main/java/forestry/mail/triggers/TriggerLowPaper.java b/src/main/java/forestry/mail/triggers/TriggerLowPaper.java index 88c885cd8..abd7b37ec 100755 --- a/src/main/java/forestry/mail/triggers/TriggerLowPaper.java +++ b/src/main/java/forestry/mail/triggers/TriggerLowPaper.java @@ -10,38 +10,35 @@ ******************************************************************************/ package forestry.mail.triggers; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.core.triggers.Trigger; -import forestry.mail.tiles.TileTrader; - import buildcraft.api.statements.IStatementContainer; import buildcraft.api.statements.IStatementParameter; +import forestry.core.triggers.Trigger; +import forestry.mail.tiles.TileTrader; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TriggerLowPaper extends Trigger { - private final int threshold; + private final int threshold; - public TriggerLowPaper(String tag, int threshold) { - super(tag, "lowPaper"); - this.threshold = threshold; - } + public TriggerLowPaper(String tag, int threshold) { + super(tag, "lowPaper"); + this.threshold = threshold; + } - @Override - public String getDescription() { - return super.getDescription() + " < " + threshold; - } + @Override + public String getDescription() { + return super.getDescription() + " < " + threshold; + } - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - if (!(tile instanceof TileTrader)) { - return false; - } - - return !((TileTrader) tile).hasPaperMin(threshold); - } + if (!(tile instanceof TileTrader)) { + return false; + } + return !((TileTrader) tile).hasPaperMin(threshold); + } } diff --git a/src/main/java/forestry/mail/triggers/TriggerLowStamps.java b/src/main/java/forestry/mail/triggers/TriggerLowStamps.java index fccf07cf1..94bc3d3e3 100755 --- a/src/main/java/forestry/mail/triggers/TriggerLowStamps.java +++ b/src/main/java/forestry/mail/triggers/TriggerLowStamps.java @@ -10,38 +10,35 @@ ******************************************************************************/ package forestry.mail.triggers; -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.core.triggers.Trigger; -import forestry.mail.tiles.TileTrader; - import buildcraft.api.statements.IStatementContainer; import buildcraft.api.statements.IStatementParameter; +import forestry.core.triggers.Trigger; +import forestry.mail.tiles.TileTrader; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; public class TriggerLowStamps extends Trigger { - private final int threshold; + private final int threshold; - public TriggerLowStamps(String tag, int threshold) { - super(tag, "lowStamps"); - this.threshold = threshold; - } + public TriggerLowStamps(String tag, int threshold) { + super(tag, "lowStamps"); + this.threshold = threshold; + } - @Override - public String getDescription() { - return super.getDescription() + " < " + threshold + "p"; - } + @Override + public String getDescription() { + return super.getDescription() + " < " + threshold + "p"; + } - @Override - public boolean isTriggerActive(TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { + @Override + public boolean isTriggerActive( + TileEntity tile, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { - if (!(tile instanceof TileTrader)) { - return false; - } - - return !((TileTrader) tile).hasPostageMin(threshold); - } + if (!(tile instanceof TileTrader)) { + return false; + } + return !((TileTrader) tile).hasPostageMin(threshold); + } } diff --git a/src/main/java/forestry/plugins/ForestryPlugin.java b/src/main/java/forestry/plugins/ForestryPlugin.java index b4e90523f..6784bf7f2 100755 --- a/src/main/java/forestry/plugins/ForestryPlugin.java +++ b/src/main/java/forestry/plugins/ForestryPlugin.java @@ -10,128 +10,120 @@ ******************************************************************************/ package forestry.plugins; -import java.util.EnumSet; -import java.util.Random; - -import net.minecraft.command.ICommand; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; - import cpw.mods.fml.common.IFuelHandler; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; - import forestry.core.IPickupHandler; import forestry.core.IResupplyHandler; import forestry.core.ISaveEventHandler; import forestry.core.network.IPacketRegistry; import forestry.core.network.PacketRegistryDummy; import forestry.core.utils.Log; +import java.util.EnumSet; +import java.util.Random; +import net.minecraft.command.ICommand; +import net.minecraft.world.World; +import net.minecraft.world.chunk.IChunkProvider; public abstract class ForestryPlugin { - public boolean isAvailable() { - return true; - } + public boolean isAvailable() { + return true; + } - public String getFailMessage() { - return ""; - } + public String getFailMessage() { + return ""; + } - public EnumSet getDependancies() { - return EnumSet.of(PluginManager.Module.CORE); - } + public EnumSet getDependancies() { + return EnumSet.of(PluginManager.Module.CORE); + } - protected void setupAPI() { - } + protected void setupAPI() {} - protected void disabledSetupAPI() { - } + protected void disabledSetupAPI() {} - protected void registerItemsAndBlocks() { - } + protected void registerItemsAndBlocks() {} - protected void preInit() { - } + protected void preInit() {} - protected void registerTriggers() { - } + protected void registerTriggers() {} - protected void registerBackpackItems() { - } + protected void registerBackpackItems() {} - protected void registerCrates() { - } + protected void registerCrates() {} - protected void doInit() { - } + protected void doInit() {} - protected void registerRecipes() { - } + protected void registerRecipes() {} - protected void postInit() { - } + protected void postInit() {} - public boolean processIMCMessage(IMCMessage message) { - return false; - } + public boolean processIMCMessage(IMCMessage message) { + return false; + } - protected static String getInvalidIMCMessageText(IMCMessage message) { - final Object messageValue; - if (message.isItemStackMessage()) { - messageValue = message.getItemStackValue().toString(); - } else if (message.isNBTMessage()) { - messageValue = message.getNBTValue(); - } else if (message.isStringMessage()) { - messageValue = message.getStringValue(); - } else { - messageValue = ""; - } + protected static String getInvalidIMCMessageText(IMCMessage message) { + final Object messageValue; + if (message.isItemStackMessage()) { + messageValue = message.getItemStackValue().toString(); + } else if (message.isNBTMessage()) { + messageValue = message.getNBTValue(); + } else if (message.isStringMessage()) { + messageValue = message.getStringValue(); + } else { + messageValue = ""; + } - return String.format("Received an invalid '%s' request '%s' from mod '%s'. Please contact the author and report this issue.", message.key, messageValue, message.getSender()); - } + return String.format( + "Received an invalid '%s' request '%s' from mod '%s'. Please contact the author and report this issue.", + message.key, messageValue, message.getSender()); + } - protected static void logInvalidIMCMessage(IMCMessage message) { - String invalidIMCMessageText = getInvalidIMCMessageText(message); - Log.warning(invalidIMCMessageText); - } + protected static void logInvalidIMCMessage(IMCMessage message) { + String invalidIMCMessageText = getInvalidIMCMessageText(message); + Log.warning(invalidIMCMessageText); + } - public ISaveEventHandler getSaveEventHandler() { - return null; - } + public ISaveEventHandler getSaveEventHandler() { + return null; + } - public void populateChunk(IChunkProvider chunkProvider, World world, Random rand, int chunkX, int chunkZ, boolean hasVillageGeneratedZ) { - } + public void populateChunk( + IChunkProvider chunkProvider, + World world, + Random rand, + int chunkX, + int chunkZ, + boolean hasVillageGeneratedZ) {} - public void populateChunkRetroGen(World world, Random rand, int chunkX, int chunkZ) { - } + public void populateChunkRetroGen(World world, Random rand, int chunkX, int chunkZ) {} - public IPacketRegistry getPacketRegistry() { - return PacketRegistryDummy.instance; - } + public IPacketRegistry getPacketRegistry() { + return PacketRegistryDummy.instance; + } - public IPickupHandler getPickupHandler() { - return null; - } + public IPickupHandler getPickupHandler() { + return null; + } - public IResupplyHandler getResupplyHandler() { - return null; - } + public IResupplyHandler getResupplyHandler() { + return null; + } - public ICommand[] getConsoleCommands() { - return null; - } - - public IFuelHandler getFuelHandler() { - return null; - } + public ICommand[] getConsoleCommands() { + return null; + } - @Override - public String toString() { - Plugin info = getClass().getAnnotation(Plugin.class); - if (info == null) { - return getClass().getSimpleName(); - } - return info.name() + " Plugin"; - } + public IFuelHandler getFuelHandler() { + return null; + } + @Override + public String toString() { + Plugin info = getClass().getAnnotation(Plugin.class); + if (info == null) { + return getClass().getSimpleName(); + } + return info.name() + " Plugin"; + } } diff --git a/src/main/java/forestry/plugins/Plugin.java b/src/main/java/forestry/plugins/Plugin.java index 2406bc33f..93b49f81c 100644 --- a/src/main/java/forestry/plugins/Plugin.java +++ b/src/main/java/forestry/plugins/Plugin.java @@ -16,39 +16,38 @@ import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Plugin { - /** - * @return Unique identifier for the plugin, no spaces! - */ - String pluginID(); + /** + * @return Unique identifier for the plugin, no spaces! + */ + String pluginID(); - /** - * @return Nice and readable plugin name. - */ - String name(); + /** + * @return Nice and readable plugin name. + */ + String name(); - /** - * @return Plugin author's name. - */ - String author() default ""; + /** + * @return Plugin author's name. + */ + String author() default ""; - /** - * @return URL of plugin homepage. - */ - String url() default ""; + /** + * @return URL of plugin homepage. + */ + String url() default ""; - /** - * @return Version of the plugin, if any. - */ - String version() default ""; + /** + * @return Version of the plugin, if any. + */ + String version() default ""; - /** - * @return Localization key for a short description what the plugin does. - */ - String unlocalizedDescription() default ""; - - /** - * @return Not used (yet?). - */ - String help() default ""; + /** + * @return Localization key for a short description what the plugin does. + */ + String unlocalizedDescription() default ""; + /** + * @return Not used (yet?). + */ + String help() default ""; } diff --git a/src/main/java/forestry/plugins/PluginApiculture.java b/src/main/java/forestry/plugins/PluginApiculture.java index 727d59fc0..f4da492d4 100644 --- a/src/main/java/forestry/plugins/PluginApiculture.java +++ b/src/main/java/forestry/plugins/PluginApiculture.java @@ -11,33 +11,6 @@ package forestry.plugins; import com.google.common.collect.ImmutableMap; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Random; -import java.util.Set; - -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.IIcon; -import net.minecraft.util.WeightedRandomChestContent; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; - -import net.minecraftforge.client.event.TextureStitchEvent; -import net.minecraftforge.common.ChestGenHooks; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.config.Property; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.oredict.OreDictionary; - import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; @@ -47,7 +20,6 @@ import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.VillagerRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.Forestry; import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; @@ -121,819 +93,1043 @@ import forestry.core.utils.Log; import forestry.core.utils.Stack; import forestry.core.utils.StringUtil; import forestry.food.items.ItemRegistryFood; +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Random; +import java.util.Set; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.IIcon; +import net.minecraft.util.WeightedRandomChestContent; +import net.minecraft.world.World; +import net.minecraft.world.chunk.IChunkProvider; +import net.minecraftforge.client.event.TextureStitchEvent; +import net.minecraftforge.common.ChestGenHooks; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.config.Property; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.oredict.OreDictionary; -@Plugin(pluginID = "Apiculture", name = "Apiculture", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.apiculture.description") +@Plugin( + pluginID = "Apiculture", + name = "Apiculture", + author = "SirSengir", + url = Constants.URL, + unlocalizedDescription = "for.plugin.apiculture.description") public class PluginApiculture extends ForestryPlugin { - @SidedProxy(clientSide = "forestry.apiculture.proxy.ProxyApicultureClient", serverSide = "forestry.apiculture.proxy.ProxyApiculture") - public static ProxyApiculture proxy; - private static final String CONFIG_CATEGORY = "apiculture"; - public static String beekeepingMode = "NORMAL"; - private static float secondPrincessChance = 0; - public static final int ticksPerBeeWorkCycle = 550; - public static boolean fancyRenderedBees = false; - - public static ItemRegistryApiculture items; - public static BlockRegistryApiculture blocks; - - public static HiveRegistry hiveRegistry; - - private final Map defaultAcceptedFlowers = new HashMap<>(); - private final Map defaultPlantableFlowers = new HashMap<>(); - - @Override - @SuppressWarnings({"unchecked"}) - protected void setupAPI() { - super.setupAPI(); - - HiveManager.hiveRegistry = hiveRegistry = new HiveRegistry(); - HiveManager.genHelper = new HiveGenHelper(); - - FlowerManager.flowerRegistry = new FlowerRegistry(); - - BeeManager.villageBees = new ArrayList[]{new ArrayList<>(), new ArrayList<>()}; - - BeeManager.beeFactory = new BeeFactory(); - BeeManager.beeMutationFactory = new BeeMutationFactory(); - BeeManager.jubilanceFactory = new JubilanceFactory(); - BeeManager.armorApiaristHelper = new ArmorApiaristHelper(); - - // Init bee interface - BeeManager.beeRoot = new BeeHelper(); - AlleleManager.alleleRegistry.registerSpeciesRoot(BeeManager.beeRoot); - - // Modes - BeeManager.beeRoot.registerBeekeepingMode(BeekeepingMode.easy); - BeeManager.beeRoot.registerBeekeepingMode(BeekeepingMode.normal); - BeeManager.beeRoot.registerBeekeepingMode(BeekeepingMode.hard); - BeeManager.beeRoot.registerBeekeepingMode(BeekeepingMode.hardcore); - BeeManager.beeRoot.registerBeekeepingMode(BeekeepingMode.insane); - } - - @Override - protected void registerItemsAndBlocks() { - items = new ItemRegistryApiculture(); - blocks = new BlockRegistryApiculture(); - } - - @Override - public void preInit() { - super.preInit(); - - MinecraftForge.EVENT_BUS.register(this); - - blocks.apiculture.addDefinitions( - new MachineDefinition(BlockApicultureType.APIARY).setFaces(0, 1, 2, 2, 4, 4, 0, 7), - new MachineDefinition(BlockApicultureType.APIARIST_CHEST_LEGACY).setLegacy(), - new MachineDefinition(BlockApicultureType.BEEHOUSE).setFaces(0, 1, 2, 2, 4, 4, 0, 7) - ); - - MachineDefinition definitionChest = new MachineDefinition(0, "forestry.ApiaristChestNew", TileApiaristChest.class, Proxies.render.getRenderChest("apiaristchest")) - .setBoundingBox(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); - blocks.apicultureChest.addDefinition(definitionChest); - - // Add triggers - if (PluginManager.Module.BUILDCRAFT_STATEMENTS.isEnabled()) { - ApicultureTriggers.initialize(); - } - - if (Config.enableVillagers) { - // Register village components with the Structure registry. - VillageHandlerApiculture.registerVillageComponents(); - } - - // Commands - PluginCore.rootCommand.addChildCommand(new CommandBee()); - } - - @Override - public void doInit() { - File configFile = new File(Forestry.instance.getConfigFolder(), CONFIG_CATEGORY + ".cfg"); - if (!configFile.exists()) { - setDefaultsForConfig(); - } - - LocalizedConfiguration config = new LocalizedConfiguration(configFile, "2.0.0"); - if (!Objects.equals(config.getLoadedConfigVersion(), config.getDefinedConfigVersion())) { - boolean deleted = configFile.delete(); - if (deleted) { - config = new LocalizedConfiguration(configFile, "2.0.0"); - setDefaultsForConfig(); - } - } - - List beekeepingModes = BeeManager.beeRoot.getBeekeepingModes(); - String[] validBeekeepingModeNames = new String[beekeepingModes.size()]; - for (int i = 0; i < beekeepingModes.size(); i++) { - validBeekeepingModeNames[i] = beekeepingModes.get(i).getName(); - } - - beekeepingMode = config.getStringLocalized("beekeeping", "mode", "NORMAL", validBeekeepingModeNames); - Log.finer("Beekeeping mode read from config: " + beekeepingMode); - - secondPrincessChance = config.getFloatLocalized("beekeeping", "second.princess", secondPrincessChance, 0.0f, 100.0f); - - String acceptedFlowerMessage = StringUtil.localize("config.beekeeping.flowers.accepted.comment"); - String plantableFlowerMessage = StringUtil.localize("config.beekeeping.flowers.plantable.comment"); - - for (String flowerType : FlowerManager.flowerRegistry.getFlowerTypes()) { - String[] defaultAccepted = defaultAcceptedFlowers.get(flowerType); - if (defaultAccepted == null) { - defaultAccepted = Constants.EMPTY_STRINGS; - } - Property property = config.get("beekeeping.flowers." + flowerType, "accepted", defaultAccepted); - property.comment = acceptedFlowerMessage; - parseAcceptedFlowers(property.getStringList(), flowerType); - - String[] defaultPlantable = defaultPlantableFlowers.get(flowerType); - if (defaultPlantable == null) { - defaultPlantable = Constants.EMPTY_STRINGS; - } - property = config.get("beekeeping.flowers." + flowerType, "plantable", defaultPlantable); - property.comment = plantableFlowerMessage; - parsePlantableFlowers(property, flowerType); - - Set acceptableFlowers = FlowerManager.flowerRegistry.getAcceptableFlowers(flowerType); - if (acceptableFlowers == null || acceptableFlowers.size() == 0) { - Log.severe("Flower type '" + flowerType + "' has no valid flowers set in apiculture.cfg. Add valid flowers or delete the config to set it to default."); - } - } - - String[] blacklist = config.getStringListLocalized("species", "blacklist", Constants.EMPTY_STRINGS); - parseBeeBlacklist(blacklist); - - config.save(); - - // Genetics - createAlleles(); - BeeDefinition.initBees(); - - AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement("forestry.speciesArgrarian", BeeDefinition.AGRARIAN.getGenome().getPrimary()); - - // Hives - createHives(); - registerBeehiveDrops(); - - // Inducers for swarmer - BeeManager.inducers.put(items.royalJelly.getItemStack(), 10); - - GameRegistry.registerTileEntity(TileAlvearyPlain.class, "forestry.Alveary"); - GameRegistry.registerTileEntity(TileSwarm.class, "forestry.Swarm"); - GameRegistry.registerTileEntity(TileAlvearySwarmer.class, "forestry.AlvearySwarmer"); - GameRegistry.registerTileEntity(TileAlvearyHeater.class, "forestry.AlvearyHeater"); - GameRegistry.registerTileEntity(TileAlvearyFan.class, "forestry.AlvearyFan"); - GameRegistry.registerTileEntity(TileAlvearyHygroregulator.class, "forestry.AlvearyHygro"); - GameRegistry.registerTileEntity(TileAlvearyStabiliser.class, "forestry.AlvearyStabiliser"); - GameRegistry.registerTileEntity(TileAlvearySieve.class, "forestry.AlvearySieve"); - GameRegistry.registerTileEntity(TileCandle.class, "forestry.Candle"); - - EntityUtil.registerEntity(EntityMinecartBeehouse.class, "cart.beehouse", 1, 0x000000, 0xffffff, 256, 3, true); - EntityUtil.registerEntity(EntityMinecartApiary.class, "cart.apiary", 2, 0x000000, 0xffffff, 256, 3, true); - - BeeManager.villageBees[0].add(BeeDefinition.FOREST.getGenome()); - BeeManager.villageBees[0].add(BeeDefinition.MEADOWS.getGenome()); - BeeManager.villageBees[0].add(BeeDefinition.MODEST.getGenome()); - BeeManager.villageBees[0].add(BeeDefinition.MARSHY.getGenome()); - BeeManager.villageBees[0].add(BeeDefinition.WINTRY.getGenome()); - BeeManager.villageBees[0].add(BeeDefinition.TROPICAL.getGenome()); - - BeeManager.villageBees[1].add(BeeDefinition.FOREST.getRainResist().getGenome()); - BeeManager.villageBees[1].add(BeeDefinition.COMMON.getGenome()); - BeeManager.villageBees[1].add(BeeDefinition.VALIANT.getGenome()); - - if (Config.enableVillagers) { - // Register villager stuff - VillageHandlerApiculture villageHandler = new VillageHandlerApiculture(); - VillagerRegistry.instance().registerVillageCreationHandler(villageHandler); - VillagerRegistry.instance().registerVillagerId(Constants.ID_VILLAGER_BEEKEEPER); - Proxies.render.registerVillagerSkin(Constants.ID_VILLAGER_BEEKEEPER, Constants.TEXTURE_SKIN_BEEKPEEPER); - VillagerRegistry.instance().registerVillageTradeHandler(Constants.ID_VILLAGER_BEEKEEPER, villageHandler); - } - - proxy.initializeRendering(); - - blocks.apiculture.init(); - blocks.apicultureChest.init(); - } - - @Override - public void postInit() { - super.postInit(); - registerDungeonLoot(); - } - - private void setDefaultsForConfig() { - - IFlowerRegistry flowerRegistry = FlowerManager.flowerRegistry; - - // Register acceptable plants - flowerRegistry.registerAcceptableFlower(Blocks.dragon_egg, FlowerManager.FlowerTypeEnd); - flowerRegistry.registerAcceptableFlower(Blocks.vine, FlowerManager.FlowerTypeJungle); - flowerRegistry.registerAcceptableFlower(Blocks.tallgrass, FlowerManager.FlowerTypeJungle); - flowerRegistry.registerAcceptableFlower(Blocks.wheat, FlowerManager.FlowerTypeWheat); - flowerRegistry.registerAcceptableFlower(Blocks.pumpkin_stem, FlowerManager.FlowerTypeGourd); - flowerRegistry.registerAcceptableFlower(Blocks.melon_stem, FlowerManager.FlowerTypeGourd); - flowerRegistry.registerAcceptableFlower(Blocks.nether_wart, FlowerManager.FlowerTypeNether); - flowerRegistry.registerAcceptableFlower(Blocks.cactus, FlowerManager.FlowerTypeCacti); - - flowerRegistry.registerAcceptableFlower(Blocks.double_plant, 0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); - flowerRegistry.registerAcceptableFlower(Blocks.double_plant, 1, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); - flowerRegistry.registerAcceptableFlower(Blocks.double_plant, 4, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); - flowerRegistry.registerAcceptableFlower(Blocks.double_plant, 5, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); - - // Register plantable plants - for (int meta = 0; meta <= 8; meta++) { - flowerRegistry.registerPlantableFlower(Blocks.red_flower, meta, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); - } - - flowerRegistry.registerPlantableFlower(Blocks.yellow_flower, 0, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); - flowerRegistry.registerPlantableFlower(Blocks.brown_mushroom, 0, 1.0, FlowerManager.FlowerTypeMushrooms); - flowerRegistry.registerPlantableFlower(Blocks.red_mushroom, 0, 1.0, FlowerManager.FlowerTypeMushrooms); - flowerRegistry.registerPlantableFlower(Blocks.cactus, 0, 1.0, FlowerManager.FlowerTypeCacti); - - for (String flowerType : FlowerManager.flowerRegistry.getFlowerTypes()) { - Set flowers = FlowerManager.flowerRegistry.getAcceptableFlowers(flowerType); - List acceptedFlowerNames = new ArrayList<>(); - List plantableFlowerNames = new ArrayList<>(); - if (flowers != null) { - for (IFlower flower : flowers) { - String name = GameData.getBlockRegistry().getNameForObject(flower.getBlock()); - if (name == null) { - Log.severe("Could not find name for flower: " + flower + " with type: " + flowerType); - continue; - } - - int meta = flower.getMeta(); - if (flower.getMeta() != OreDictionary.WILDCARD_VALUE) { - name = name + ':' + meta; - } - - if (flower.isPlantable()) { - plantableFlowerNames.add(name); - } else { - acceptedFlowerNames.add(name); - } - } - } - - String[] acceptedFlowerNamesArray = acceptedFlowerNames.toArray(new String[acceptedFlowerNames.size()]); - defaultAcceptedFlowers.put(flowerType, acceptedFlowerNamesArray); - - String[] plantableFlowerNamesArray = plantableFlowerNames.toArray(new String[plantableFlowerNames.size()]); - defaultPlantableFlowers.put(flowerType, plantableFlowerNamesArray); - } - } - - @Override - public IPacketRegistry getPacketRegistry() { - return new PacketRegistryApiculture(); - } - - @Override - protected void registerCrates() { - ICrateRegistry crateRegistry = StorageManager.crateRegistry; - crateRegistry.registerCrate(PluginCore.items.beeswax.getItemStack(), "cratedBeeswax"); - crateRegistry.registerCrate(items.pollenCluster.get(EnumPollenCluster.NORMAL, 1), "cratedPollen"); - crateRegistry.registerCrate(items.pollenCluster.get(EnumPollenCluster.CRYSTALLINE, 1), "cratedCrystallinePollen"); - crateRegistry.registerCrate(items.propolis.getItemStack(), "cratedPropolis"); - crateRegistry.registerCrate(items.honeydew.getItemStack(), "cratedHoneydew"); - crateRegistry.registerCrate(items.royalJelly.getItemStack(), "cratedRoyalJelly"); - - crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.HONEY, 1), "cratedHoneycombs"); - crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.COCOA, 1), "cratedCocoaComb"); - crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.SIMMERING, 1), "cratedSimmeringCombs"); - crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.STRINGY, 1), "cratedStringyCombs"); - crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.FROZEN, 1), "cratedFrozenCombs"); - crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.DRIPPING, 1), "cratedDrippingCombs"); - crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.SILKY, 1), "cratedSilkyCombs"); - crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.PARCHED, 1), "cratedParchedCombs"); - crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.MYSTERIOUS, 1), "cratedMysteriousCombs"); - crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.POWDERY, 1), "cratedPowderyCombs"); - crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.WHEATEN, 1), "cratedWheatenCombs"); - crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.MOSSY, 1), "cratedMossyCombs"); - crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.MELLOW, 1), "cratedMellowCombs"); - - crateRegistry.registerCrate(PluginCore.items.refractoryWax.getItemStack(), "cratedRefractoryWax"); - } - - @Override - protected void registerRecipes() { - - // / APIARIST'S ARMOR - ItemStack wovenSilk = PluginCore.items.craftingMaterial.getWovenSilk(); - RecipeUtil.addRecipe(items.apiaristHat, - "###", "# #", - '#', wovenSilk); - RecipeUtil.addRecipe(items.apiaristChest, - "# #", "###", "###", - '#', wovenSilk); - RecipeUtil.addRecipe(items.apiaristLegs, - "###", "# #", "# #", - '#', wovenSilk); - RecipeUtil.addRecipe(items.apiaristBoots, - "# #", "# #", - '#', wovenSilk); - - // / HABITAT LOCATOR - RecipeUtil.addRecipe(items.habitatLocator, - " X ", - "X#X", - " X ", - '#', "dustRedstone", 'X', "ingotBronze"); - - // Bees - RecipeUtil.addRecipe(items.scoop, - "#X#", "###", " # ", - '#', "stickWood", - 'X', Blocks.wool); - RecipeUtil.addRecipe(new ItemStack(Items.slime_ball), - "#X#", "#X#", "#X#", - '#', items.propolis, - 'X', items.pollenCluster.get(EnumPollenCluster.NORMAL, 1)); - RecipeUtil.addRecipe(new ItemStack(Items.speckled_melon), - "#X#", "#Y#", "#X#", - '#', items.honeyDrop, - 'X', items.honeydew, - 'Y', Items.melon); - RecipeUtil.addRecipe(items.frameUntreated, - "###", "#S#", "###", - '#', "stickWood", - 'S', Items.string); - RecipeUtil.addRecipe(items.frameImpregnated, - "###", "#S#", "###", - '#', PluginCore.items.stickImpregnated, - 'S', Items.string); - RecipeUtil.addRecipe(items.minecartBeehouse.getBeeHouseMinecart(), - "B", - "C", - 'B', blocks.apiculture.get(BlockApicultureType.BEEHOUSE), - 'C', Items.minecart); - RecipeUtil.addRecipe(items.minecartBeehouse.getApiaryMinecart(), - "B", - "C", - 'B', blocks.apiculture.get(BlockApicultureType.APIARY), - 'C', Items.minecart); - - // FOOD STUFF - ItemRegistryFood foodItems = PluginFood.items; - if (foodItems != null) { - RecipeUtil.addRecipe(new ItemStack(foodItems.honeyedSlice, 4), - "###", "#X#", "###", - '#', items.honeyDrop, - 'X', Items.bread); - - RecipeUtil.addRecipe(foodItems.honeyPot, - "# #", " X ", "# #", - '#', items.honeyDrop, - 'X', PluginFluids.items.waxCapsuleEmpty); - - RecipeUtil.addRecipe(foodItems.ambrosia, - "#Y#", "XXX", "###", - '#', items.honeydew, - 'X', items.royalJelly, - 'Y', PluginFluids.items.waxCapsuleEmpty); - } - - // / CAPSULES - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.capsule"), "###", '#', PluginCore.items.beeswax); - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.refractory"), "###", '#', PluginCore.items.refractoryWax); - - // / BITUMINOUS PEAT - RecipeUtil.addRecipe(PluginCore.items.bituminousPeat.getItemStack(), - " # ", "XYX", " # ", - '#', "dustAsh", - 'X', PluginCore.items.peat, - 'Y', items.propolis); - - // / TORCHES - RecipeUtil.addRecipe(new ItemStack(Blocks.torch, 3), - " # ", " # ", " Y ", - '#', PluginCore.items.beeswax, - 'Y', "stickWood"); - RecipeUtil.addRecipe(PluginCore.items.craftingMaterial.getPulsatingMesh(), - "# #", " # ", "# #", - '#', items.propolis.get(EnumPropolis.PULSATING, 1)); - - // / WAX CAST - RecipeUtil.addRecipe(items.waxCast, - "###", - "# #", - "###", - '#', PluginCore.items.beeswax); - - // / ALVEARY - RecipeUtil.addRecipe(blocks.alveary.get(BlockAlveary.Type.PLAIN), - "###", - "#X#", - "###", - 'X', PluginCore.items.impregnatedCasing, - '#', PluginCore.items.craftingMaterial.getScentedPaneling()); - // SWARMER - RecipeUtil.addRecipe(blocks.alveary.get(BlockAlveary.Type.SWARMER), - "#G#", - " X ", - "#G#", - '#', PluginCore.items.tubes.get(EnumElectronTube.DIAMOND, 1), - 'X', blocks.alveary, - 'G', "ingotGold"); - // FAN - RecipeUtil.addRecipe(blocks.alveary.get(BlockAlveary.Type.FAN), - "I I", - " X ", - "I#I", - '#', PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), - 'X', blocks.alveary, - 'I', "ingotIron"); - // HEATER - RecipeUtil.addRecipe(blocks.alveary.get(BlockAlveary.Type.HEATER), - "#I#", - " X ", - "YYY", - '#', PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), - 'X', blocks.alveary, - 'I', "ingotIron", 'Y', "stone"); - // HYGROREGULATOR - RecipeUtil.addRecipe(blocks.alveary.get(BlockAlveary.Type.HYGRO), - "GIG", - "GXG", - "GIG", - 'X', blocks.alveary, - 'I', "ingotIron", - 'G', "blockGlass"); - // STABILISER - RecipeUtil.addRecipe(blocks.alveary.get(BlockAlveary.Type.STABILIZER), - "G G", - "GXG", - "G G", - 'X', blocks.alveary, - 'G', "gemQuartz"); - // SIEVE - RecipeUtil.addRecipe(blocks.alveary.get(BlockAlveary.Type.SIEVE), - "III", - " X ", - "WWW", - 'X', blocks.alveary, - 'I', "ingotIron", - 'W', PluginCore.items.craftingMaterial.getWovenSilk()); - - if (PluginManager.Module.FACTORY.isEnabled()) { - // / SQUEEZER - FluidStack honeyDropFluid = Fluids.HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{items.honeyDrop.getItemStack()}, honeyDropFluid, items.propolis.getItemStack(), 5); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{items.honeydew.getItemStack()}, honeyDropFluid); - - ItemStack phosphor = PluginCore.items.phosphor.getItemStack(2); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{phosphor, new ItemStack(Blocks.sand)}, Fluids.LAVA.getFluid(2000)); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{phosphor, new ItemStack(Blocks.sand, 1, 1)}, Fluids.LAVA.getFluid(2000)); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{phosphor, new ItemStack(Blocks.dirt)}, Fluids.LAVA.getFluid(1600)); - - // / CARPENTER - RecipeManagers.carpenterManager.addRecipe(100, Fluids.WATER.getFluid(2000), null, items.beealyzer.getItemStack(), - "X#X", "X#X", "RDR", - '#', "paneGlass", - 'X', "ingotTin", - 'R', "dustRedstone", - 'D', "gemDiamond"); - RecipeManagers.carpenterManager.addRecipe(50, Fluids.HONEY.getFluid(500), null, PluginCore.items.craftingMaterial.getScentedPaneling(), - " J ", "###", "WPW", - '#', "plankWood", - 'J', items.royalJelly, - 'W', PluginCore.items.beeswax, - 'P', items.pollenCluster.get(EnumPollenCluster.NORMAL, 1)); - - RecipeManagers.carpenterManager.addRecipe(30, Fluids.WATER.getFluid(600), null, blocks.candle.getUnlitCandle(24), - " X ", - "###", - "###", - '#', PluginCore.items.beeswax, - 'X', Items.string); - RecipeManagers.carpenterManager.addRecipe(10, Fluids.WATER.getFluid(200), null, blocks.candle.getUnlitCandle(6), - "#X#", - '#', PluginCore.items.beeswax, - 'X', PluginCore.items.craftingMaterial.getSilkWisp()); - RecipeUtil.addShapelessRecipe(blocks.candle.getUnlitCandle(1), blocks.candle.getUnlitCandle(1)); - RecipeUtil.addShapelessRecipe(blocks.candle.getLitCandle(1), blocks.candle.getLitCandle(1)); - - // / CENTRIFUGE - // Honey combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.HONEY, 1), ImmutableMap.of( - PluginCore.items.beeswax.getItemStack(), 1.0f, - items.honeyDrop.getItemStack(), 0.9f - )); - - // Cocoa combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.COCOA, 1), ImmutableMap.of( - PluginCore.items.beeswax.getItemStack(), 1.0f, - new ItemStack(Items.dye, 1, 3), 0.5f - )); - - // Simmering combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.SIMMERING, 1), ImmutableMap.of( - PluginCore.items.refractoryWax.getItemStack(), 1.0f, - PluginCore.items.phosphor.getItemStack(2), 0.7f - )); - - // Stringy combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.STRINGY, 1), ImmutableMap.of( - items.propolis.getItemStack(), 1.0f, - items.honeyDrop.getItemStack(), 0.4f - )); - - // Dripping combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.DRIPPING, 1), ImmutableMap.of( - items.honeydew.getItemStack(), 1.0f, - items.honeyDrop.getItemStack(), 0.4f - )); - - // Frozen combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.FROZEN, 1), ImmutableMap.of( - PluginCore.items.beeswax.getItemStack(), 0.8f, - items.honeyDrop.getItemStack(), 0.7f, - new ItemStack(Items.snowball), 0.4f, - items.pollenCluster.get(EnumPollenCluster.CRYSTALLINE, 1), 0.2f - )); - - // Silky combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.SILKY, 1), ImmutableMap.of( - items.honeyDrop.getItemStack(), 1.0f, - items.propolis.get(EnumPropolis.SILKY, 1), 0.8f - )); - - // Parched combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.PARCHED, 1), ImmutableMap.of( - PluginCore.items.beeswax.getItemStack(), 1.0f, - items.honeyDrop.getItemStack(), 0.9f - )); - - // Mysterious combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.MYSTERIOUS, 1), ImmutableMap.of( - items.propolis.get(EnumPropolis.PULSATING, 1), 1.0f, - items.honeyDrop.getItemStack(), 0.4f - )); - - // Irradiated combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.IRRADIATED, 1), ImmutableMap.of( - )); - - // Powdery combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.POWDERY, 1), ImmutableMap.of( - items.honeyDrop.getItemStack(), 0.2f, - PluginCore.items.beeswax.getItemStack(), 0.2f, - new ItemStack(Items.gunpowder), 0.9f - )); - - // Wheaten Combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.WHEATEN, 1), ImmutableMap.of( - items.honeyDrop.getItemStack(), 0.2f, - PluginCore.items.beeswax.getItemStack(), 0.2f, - new ItemStack(Items.wheat), 0.8f - )); - - // Mossy Combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.MOSSY, 1), ImmutableMap.of( - PluginCore.items.beeswax.getItemStack(), 1.0f, - items.honeyDrop.getItemStack(), 0.9f - )); - - // Mellow Combs - RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.MELLOW, 1), ImmutableMap.of( - items.honeydew.getItemStack(), 0.6f, - PluginCore.items.beeswax.getItemStack(), 0.2f, - new ItemStack(Items.quartz), 0.3f - )); - - // Silky Propolis - RecipeManagers.centrifugeManager.addRecipe(5, items.propolis.get(EnumPropolis.SILKY, 1), ImmutableMap.of( - PluginCore.items.craftingMaterial.getSilkWisp(), 0.6f, - items.propolis.getItemStack(), 0.1f - )); - - // / FERMENTER - RecipeManagers.fermenterManager.addRecipe(items.honeydew.getItemStack(), 500, 1.0f, Fluids.SHORT_MEAD.getFluid(1), Fluids.HONEY.getFluid(1)); - // / STILL - RecipeManagers.stillManager.addRecipe(Constants.STILL_DESTILLATION_DURATION, Fluids.SHORT_MEAD.getFluid(10), Fluids.MEAD.getFluid(5)); - } - - // ANALYZER - RecipeUtil.addRecipe(PluginCore.blocks.core.get(BlockCoreType.ANALYZER), - "XTX", - " Y ", - "X X", - 'Y', PluginCore.items.sturdyCasing, - 'T', items.beealyzer, - 'X', "ingotBronze"); - - RecipeUtil.addRecipe(blocks.apiculture.get(BlockApicultureType.APIARY), - "XXX", - "#C#", - "###", - 'X', "slabWood", - '#', "plankWood", - 'C', PluginCore.items.impregnatedCasing); - - RecipeUtil.addRecipe(new ItemStack(blocks.apicultureChest), - " # ", - "XYX", - "XXX", - '#', "blockGlass", - 'X', "beeComb", - 'Y', "chestWood"); - - RecipeUtil.addRecipe(blocks.apiculture.get(BlockApicultureType.BEEHOUSE), - "XXX", - "#C#", - "###", - 'X', "slabWood", - '#', "plankWood", - 'C', "beeComb"); - } - - private static void registerBeehiveDrops() { - ItemStack honeyComb = items.beeComb.get(EnumHoneyComb.HONEY, 1); - hiveRegistry.addDrops(HiveRegistry.forest, - new HiveDrop(80, BeeDefinition.FOREST, honeyComb).setIgnobleShare(0.7f), - new HiveDrop(8, BeeDefinition.FOREST.getRainResist(), honeyComb), - new HiveDrop(3, BeeDefinition.VALIANT, honeyComb) - ); - - hiveRegistry.addDrops(HiveRegistry.meadows, - new HiveDrop(80, BeeDefinition.MEADOWS, honeyComb).setIgnobleShare(0.7f), - new HiveDrop(3, BeeDefinition.VALIANT, honeyComb) - ); - - ItemStack parchedComb = items.beeComb.get(EnumHoneyComb.PARCHED, 1); - hiveRegistry.addDrops(HiveRegistry.desert, - new HiveDrop(80, BeeDefinition.MODEST, parchedComb).setIgnobleShare(0.7f), - new HiveDrop(3, BeeDefinition.VALIANT, parchedComb) - ); - - ItemStack silkyComb = items.beeComb.get(EnumHoneyComb.SILKY, 1); - hiveRegistry.addDrops(HiveRegistry.jungle, - new HiveDrop(80, BeeDefinition.TROPICAL, silkyComb).setIgnobleShare(0.7f), - new HiveDrop(3, BeeDefinition.VALIANT, silkyComb) - ); - - ItemStack mysteriousComb = items.beeComb.get(EnumHoneyComb.MYSTERIOUS, 1); - hiveRegistry.addDrops(HiveRegistry.end, - new HiveDrop(90, BeeDefinition.ENDED, mysteriousComb) - ); - - ItemStack frozenComb = items.beeComb.get(EnumHoneyComb.FROZEN, 1); - hiveRegistry.addDrops(HiveRegistry.snow, - new HiveDrop(80, BeeDefinition.WINTRY, frozenComb).setIgnobleShare(0.5f), - new HiveDrop(3, BeeDefinition.VALIANT, frozenComb) - ); - - ItemStack mossyComb = items.beeComb.get(EnumHoneyComb.MOSSY, 1); - hiveRegistry.addDrops(HiveRegistry.swamp, - new HiveDrop(80, BeeDefinition.MARSHY, mossyComb).setIgnobleShare(0.4f), - new HiveDrop(3, BeeDefinition.VALIANT, mossyComb) - ); - } - - private static void registerDungeonLoot() { - int rarity; - if (Config.dungeonLootRare) { - rarity = 5; - } else { - rarity = 10; - } - - ChestGenHooks.addItem(ChestGenHooks.DUNGEON_CHEST, new WeightedRandomChestContent(BeeDefinition.STEADFAST.getMemberStack(EnumBeeType.DRONE), 1, 1, rarity)); - - ItemStack stack = blocks.candle.getUnlitCandle(1); - NBTTagCompound tag = new NBTTagCompound(); - tag.setInteger(BlockCandle.colourTagName, 0xffffff); - stack.setTagCompound(tag); - - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(stack, 7, 12, 12)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(items.scoop.getItemStack(), 1, 1, 8)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(items.propolis.get(EnumPropolis.NORMAL, 1), 2, 4, 6)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(items.beeComb.get(EnumHoneyComb.HONEY, 1), 4, 12, 7)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(items.beeComb.get(EnumHoneyComb.FROZEN, 1), 2, 10, 7)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(items.beeComb.get(EnumHoneyComb.SILKY, 1), 1, 6, 7)); - - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(BeeDefinition.FOREST.getRainResist().getMemberStack(EnumBeeType.PRINCESS), 1, 1, 5)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(BeeDefinition.COMMON.getMemberStack(EnumBeeType.DRONE), 1, 2, 8)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(BeeDefinition.MEADOWS.getMemberStack(EnumBeeType.PRINCESS), 1, 1, 5)); - } - - private static void createHives() { - hiveRegistry.registerHive(HiveRegistry.forest, HiveDescription.FOREST); - hiveRegistry.registerHive(HiveRegistry.meadows, HiveDescription.MEADOWS); - hiveRegistry.registerHive(HiveRegistry.desert, HiveDescription.DESERT); - hiveRegistry.registerHive(HiveRegistry.jungle, HiveDescription.JUNGLE); - hiveRegistry.registerHive(HiveRegistry.end, HiveDescription.END); - hiveRegistry.registerHive(HiveRegistry.snow, HiveDescription.SNOW); - hiveRegistry.registerHive(HiveRegistry.swamp, HiveDescription.SWAMP); - } - - private static void createAlleles() { - - IClassification hymnoptera = AlleleManager.alleleRegistry.createAndRegisterClassification(EnumClassLevel.ORDER, "hymnoptera", "Hymnoptera"); - AlleleManager.alleleRegistry.getClassification("class.insecta").addMemberGroup(hymnoptera); - - IClassification apidae = AlleleManager.alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "apidae", "Apidae"); - hymnoptera.addMemberGroup(apidae); - - for (BeeBranchDefinition beeBranch : BeeBranchDefinition.values()) { - apidae.addMemberGroup(beeBranch.getBranch()); - } - - AlleleEffect.createAlleles(); - } - - public static double getSecondPrincessChance() { - return secondPrincessChance; - } - - private static void parseBeeBlacklist(String[] items) { - for (String item : items) { - if (item.isEmpty()) { - continue; - } - - FMLCommonHandler.instance().getFMLLogger().debug("Blacklisting bee species identified by " + item); - AlleleManager.alleleRegistry.blacklistAllele(item); - } - } - - private static void parseAcceptedFlowers(String[] acceptedFlowers, String flowerType) { - List acceptedFlowerItemStacks = Stack.parseStackStrings(acceptedFlowers, OreDictionary.WILDCARD_VALUE); - for (Stack acceptedFlower : acceptedFlowerItemStacks) { - Block acceptedFlowerBlock = acceptedFlower.getBlock(); - int meta = acceptedFlower.getMeta(); - if (acceptedFlowerBlock != null) { - FlowerManager.flowerRegistry.registerAcceptableFlower(acceptedFlowerBlock, meta, flowerType); - } else { - Log.warning("No block found for '" + acceptedFlower + "' in apiculture config for '" + flowerType + "'."); - } - } - } - - private static void parsePlantableFlowers(Property property, String flowerType) { - for (String string : property.getStringList()) { - Stack plantableFlower = Stack.parseStackString(string, OreDictionary.WILDCARD_VALUE); - if (plantableFlower == null) { - continue; - } - - Block plantableFlowerBlock = plantableFlower.getBlock(); - int meta = plantableFlower.getMeta(); - if (plantableFlowerBlock != null) { - FlowerManager.flowerRegistry.registerPlantableFlower(plantableFlowerBlock, meta, 1.0, flowerType); - } else { - Log.warning("No block found for '" + string + "' in config '" + property.getName() + "'."); - } - } - } - - @Override - public ISaveEventHandler getSaveEventHandler() { - return new SaveEventHandlerApiculture(); - } - - @Override - public void populateChunk(IChunkProvider chunkProvider, World world, Random rand, int chunkX, int chunkZ, boolean hasVillageGenerated) { - if (Config.getBeehivesAmount() > 0.0) { - HiveDecorator.decorateHives(chunkProvider, world, rand, chunkX, chunkZ, hasVillageGenerated); - } - } - - @Override - public void populateChunkRetroGen(World world, Random rand, int chunkX, int chunkZ) { - if (Config.getBeehivesAmount() > 0.0) { - HiveDecorator.decorateHives(world, rand, chunkX, chunkZ); - } - } - - @Override - public boolean processIMCMessage(IMCMessage message) { - if (message.key.equals("add-candle-lighting-id")) { - ItemStack value = message.getItemStackValue(); - if (value != null) { - BlockCandle.addItemToLightingList(value.getItem()); - } else { - logInvalidIMCMessage(message); - } - return true; - } else if (message.key.equals("add-alveary-slab") && message.isStringMessage()) { - String messageString = String.format("Received a '%s' request from mod '%s'. This IMC message has been replaced with the oreDictionary for 'slabWood'. Please contact the author and report this issue.", message.key, message.getSender()); - Log.warning(messageString); - return true; - } - - return super.processIMCMessage(message); - } - - @SubscribeEvent - @SideOnly(Side.CLIENT) - public void textureHook(TextureStitchEvent.Pre event) { - if (event.map.getTextureType() == 1) { - EntityFXSnow.icons = new IIcon[3]; - for (int i = 0; i < EntityFXSnow.icons.length; i++) { - EntityFXSnow.icons[i] = event.map.registerIcon("forestry:particles/snow." + (i + 1)); - } - } - } + @SidedProxy( + clientSide = "forestry.apiculture.proxy.ProxyApicultureClient", + serverSide = "forestry.apiculture.proxy.ProxyApiculture") + public static ProxyApiculture proxy; + + private static final String CONFIG_CATEGORY = "apiculture"; + public static String beekeepingMode = "NORMAL"; + private static float secondPrincessChance = 0; + public static final int ticksPerBeeWorkCycle = 550; + public static boolean fancyRenderedBees = false; + + public static ItemRegistryApiculture items; + public static BlockRegistryApiculture blocks; + + public static HiveRegistry hiveRegistry; + + private final Map defaultAcceptedFlowers = new HashMap<>(); + private final Map defaultPlantableFlowers = new HashMap<>(); + + @Override + @SuppressWarnings({"unchecked"}) + protected void setupAPI() { + super.setupAPI(); + + HiveManager.hiveRegistry = hiveRegistry = new HiveRegistry(); + HiveManager.genHelper = new HiveGenHelper(); + + FlowerManager.flowerRegistry = new FlowerRegistry(); + + BeeManager.villageBees = new ArrayList[] {new ArrayList<>(), new ArrayList<>()}; + + BeeManager.beeFactory = new BeeFactory(); + BeeManager.beeMutationFactory = new BeeMutationFactory(); + BeeManager.jubilanceFactory = new JubilanceFactory(); + BeeManager.armorApiaristHelper = new ArmorApiaristHelper(); + + // Init bee interface + BeeManager.beeRoot = new BeeHelper(); + AlleleManager.alleleRegistry.registerSpeciesRoot(BeeManager.beeRoot); + + // Modes + BeeManager.beeRoot.registerBeekeepingMode(BeekeepingMode.easy); + BeeManager.beeRoot.registerBeekeepingMode(BeekeepingMode.normal); + BeeManager.beeRoot.registerBeekeepingMode(BeekeepingMode.hard); + BeeManager.beeRoot.registerBeekeepingMode(BeekeepingMode.hardcore); + BeeManager.beeRoot.registerBeekeepingMode(BeekeepingMode.insane); + } + + @Override + protected void registerItemsAndBlocks() { + items = new ItemRegistryApiculture(); + blocks = new BlockRegistryApiculture(); + } + + @Override + public void preInit() { + super.preInit(); + + MinecraftForge.EVENT_BUS.register(this); + + blocks.apiculture.addDefinitions( + new MachineDefinition(BlockApicultureType.APIARY).setFaces(0, 1, 2, 2, 4, 4, 0, 7), + new MachineDefinition(BlockApicultureType.APIARIST_CHEST_LEGACY).setLegacy(), + new MachineDefinition(BlockApicultureType.BEEHOUSE).setFaces(0, 1, 2, 2, 4, 4, 0, 7)); + + MachineDefinition definitionChest = new MachineDefinition( + 0, + "forestry.ApiaristChestNew", + TileApiaristChest.class, + Proxies.render.getRenderChest("apiaristchest")) + .setBoundingBox(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); + blocks.apicultureChest.addDefinition(definitionChest); + + // Add triggers + if (PluginManager.Module.BUILDCRAFT_STATEMENTS.isEnabled()) { + ApicultureTriggers.initialize(); + } + + if (Config.enableVillagers) { + // Register village components with the Structure registry. + VillageHandlerApiculture.registerVillageComponents(); + } + + // Commands + PluginCore.rootCommand.addChildCommand(new CommandBee()); + } + + @Override + public void doInit() { + File configFile = new File(Forestry.instance.getConfigFolder(), CONFIG_CATEGORY + ".cfg"); + if (!configFile.exists()) { + setDefaultsForConfig(); + } + + LocalizedConfiguration config = new LocalizedConfiguration(configFile, "2.0.0"); + if (!Objects.equals(config.getLoadedConfigVersion(), config.getDefinedConfigVersion())) { + boolean deleted = configFile.delete(); + if (deleted) { + config = new LocalizedConfiguration(configFile, "2.0.0"); + setDefaultsForConfig(); + } + } + + List beekeepingModes = BeeManager.beeRoot.getBeekeepingModes(); + String[] validBeekeepingModeNames = new String[beekeepingModes.size()]; + for (int i = 0; i < beekeepingModes.size(); i++) { + validBeekeepingModeNames[i] = beekeepingModes.get(i).getName(); + } + + beekeepingMode = config.getStringLocalized("beekeeping", "mode", "NORMAL", validBeekeepingModeNames); + Log.finer("Beekeeping mode read from config: " + beekeepingMode); + + secondPrincessChance = + config.getFloatLocalized("beekeeping", "second.princess", secondPrincessChance, 0.0f, 100.0f); + + String acceptedFlowerMessage = StringUtil.localize("config.beekeeping.flowers.accepted.comment"); + String plantableFlowerMessage = StringUtil.localize("config.beekeeping.flowers.plantable.comment"); + + for (String flowerType : FlowerManager.flowerRegistry.getFlowerTypes()) { + String[] defaultAccepted = defaultAcceptedFlowers.get(flowerType); + if (defaultAccepted == null) { + defaultAccepted = Constants.EMPTY_STRINGS; + } + Property property = config.get("beekeeping.flowers." + flowerType, "accepted", defaultAccepted); + property.comment = acceptedFlowerMessage; + parseAcceptedFlowers(property.getStringList(), flowerType); + + String[] defaultPlantable = defaultPlantableFlowers.get(flowerType); + if (defaultPlantable == null) { + defaultPlantable = Constants.EMPTY_STRINGS; + } + property = config.get("beekeeping.flowers." + flowerType, "plantable", defaultPlantable); + property.comment = plantableFlowerMessage; + parsePlantableFlowers(property, flowerType); + + Set acceptableFlowers = FlowerManager.flowerRegistry.getAcceptableFlowers(flowerType); + if (acceptableFlowers == null || acceptableFlowers.size() == 0) { + Log.severe( + "Flower type '" + flowerType + + "' has no valid flowers set in apiculture.cfg. Add valid flowers or delete the config to set it to default."); + } + } + + String[] blacklist = config.getStringListLocalized("species", "blacklist", Constants.EMPTY_STRINGS); + parseBeeBlacklist(blacklist); + + config.save(); + + // Genetics + createAlleles(); + BeeDefinition.initBees(); + + AlleleManager.alleleRegistry.registerDeprecatedAlleleReplacement( + "forestry.speciesArgrarian", BeeDefinition.AGRARIAN.getGenome().getPrimary()); + + // Hives + createHives(); + registerBeehiveDrops(); + + // Inducers for swarmer + BeeManager.inducers.put(items.royalJelly.getItemStack(), 10); + + GameRegistry.registerTileEntity(TileAlvearyPlain.class, "forestry.Alveary"); + GameRegistry.registerTileEntity(TileSwarm.class, "forestry.Swarm"); + GameRegistry.registerTileEntity(TileAlvearySwarmer.class, "forestry.AlvearySwarmer"); + GameRegistry.registerTileEntity(TileAlvearyHeater.class, "forestry.AlvearyHeater"); + GameRegistry.registerTileEntity(TileAlvearyFan.class, "forestry.AlvearyFan"); + GameRegistry.registerTileEntity(TileAlvearyHygroregulator.class, "forestry.AlvearyHygro"); + GameRegistry.registerTileEntity(TileAlvearyStabiliser.class, "forestry.AlvearyStabiliser"); + GameRegistry.registerTileEntity(TileAlvearySieve.class, "forestry.AlvearySieve"); + GameRegistry.registerTileEntity(TileCandle.class, "forestry.Candle"); + + EntityUtil.registerEntity(EntityMinecartBeehouse.class, "cart.beehouse", 1, 0x000000, 0xffffff, 256, 3, true); + EntityUtil.registerEntity(EntityMinecartApiary.class, "cart.apiary", 2, 0x000000, 0xffffff, 256, 3, true); + + BeeManager.villageBees[0].add(BeeDefinition.FOREST.getGenome()); + BeeManager.villageBees[0].add(BeeDefinition.MEADOWS.getGenome()); + BeeManager.villageBees[0].add(BeeDefinition.MODEST.getGenome()); + BeeManager.villageBees[0].add(BeeDefinition.MARSHY.getGenome()); + BeeManager.villageBees[0].add(BeeDefinition.WINTRY.getGenome()); + BeeManager.villageBees[0].add(BeeDefinition.TROPICAL.getGenome()); + + BeeManager.villageBees[1].add(BeeDefinition.FOREST.getRainResist().getGenome()); + BeeManager.villageBees[1].add(BeeDefinition.COMMON.getGenome()); + BeeManager.villageBees[1].add(BeeDefinition.VALIANT.getGenome()); + + if (Config.enableVillagers) { + // Register villager stuff + VillageHandlerApiculture villageHandler = new VillageHandlerApiculture(); + VillagerRegistry.instance().registerVillageCreationHandler(villageHandler); + VillagerRegistry.instance().registerVillagerId(Constants.ID_VILLAGER_BEEKEEPER); + Proxies.render.registerVillagerSkin(Constants.ID_VILLAGER_BEEKEEPER, Constants.TEXTURE_SKIN_BEEKPEEPER); + VillagerRegistry.instance().registerVillageTradeHandler(Constants.ID_VILLAGER_BEEKEEPER, villageHandler); + } + + proxy.initializeRendering(); + + blocks.apiculture.init(); + blocks.apicultureChest.init(); + } + + @Override + public void postInit() { + super.postInit(); + registerDungeonLoot(); + } + + private void setDefaultsForConfig() { + + IFlowerRegistry flowerRegistry = FlowerManager.flowerRegistry; + + // Register acceptable plants + flowerRegistry.registerAcceptableFlower(Blocks.dragon_egg, FlowerManager.FlowerTypeEnd); + flowerRegistry.registerAcceptableFlower(Blocks.vine, FlowerManager.FlowerTypeJungle); + flowerRegistry.registerAcceptableFlower(Blocks.tallgrass, FlowerManager.FlowerTypeJungle); + flowerRegistry.registerAcceptableFlower(Blocks.wheat, FlowerManager.FlowerTypeWheat); + flowerRegistry.registerAcceptableFlower(Blocks.pumpkin_stem, FlowerManager.FlowerTypeGourd); + flowerRegistry.registerAcceptableFlower(Blocks.melon_stem, FlowerManager.FlowerTypeGourd); + flowerRegistry.registerAcceptableFlower(Blocks.nether_wart, FlowerManager.FlowerTypeNether); + flowerRegistry.registerAcceptableFlower(Blocks.cactus, FlowerManager.FlowerTypeCacti); + + flowerRegistry.registerAcceptableFlower( + Blocks.double_plant, 0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); + flowerRegistry.registerAcceptableFlower( + Blocks.double_plant, 1, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); + flowerRegistry.registerAcceptableFlower( + Blocks.double_plant, 4, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); + flowerRegistry.registerAcceptableFlower( + Blocks.double_plant, 5, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); + + // Register plantable plants + for (int meta = 0; meta <= 8; meta++) { + flowerRegistry.registerPlantableFlower( + Blocks.red_flower, meta, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); + } + + flowerRegistry.registerPlantableFlower( + Blocks.yellow_flower, 0, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); + flowerRegistry.registerPlantableFlower(Blocks.brown_mushroom, 0, 1.0, FlowerManager.FlowerTypeMushrooms); + flowerRegistry.registerPlantableFlower(Blocks.red_mushroom, 0, 1.0, FlowerManager.FlowerTypeMushrooms); + flowerRegistry.registerPlantableFlower(Blocks.cactus, 0, 1.0, FlowerManager.FlowerTypeCacti); + + for (String flowerType : FlowerManager.flowerRegistry.getFlowerTypes()) { + Set flowers = FlowerManager.flowerRegistry.getAcceptableFlowers(flowerType); + List acceptedFlowerNames = new ArrayList<>(); + List plantableFlowerNames = new ArrayList<>(); + if (flowers != null) { + for (IFlower flower : flowers) { + String name = GameData.getBlockRegistry().getNameForObject(flower.getBlock()); + if (name == null) { + Log.severe("Could not find name for flower: " + flower + " with type: " + flowerType); + continue; + } + + int meta = flower.getMeta(); + if (flower.getMeta() != OreDictionary.WILDCARD_VALUE) { + name = name + ':' + meta; + } + + if (flower.isPlantable()) { + plantableFlowerNames.add(name); + } else { + acceptedFlowerNames.add(name); + } + } + } + + String[] acceptedFlowerNamesArray = acceptedFlowerNames.toArray(new String[acceptedFlowerNames.size()]); + defaultAcceptedFlowers.put(flowerType, acceptedFlowerNamesArray); + + String[] plantableFlowerNamesArray = plantableFlowerNames.toArray(new String[plantableFlowerNames.size()]); + defaultPlantableFlowers.put(flowerType, plantableFlowerNamesArray); + } + } + + @Override + public IPacketRegistry getPacketRegistry() { + return new PacketRegistryApiculture(); + } + + @Override + protected void registerCrates() { + ICrateRegistry crateRegistry = StorageManager.crateRegistry; + crateRegistry.registerCrate(PluginCore.items.beeswax.getItemStack(), "cratedBeeswax"); + crateRegistry.registerCrate(items.pollenCluster.get(EnumPollenCluster.NORMAL, 1), "cratedPollen"); + crateRegistry.registerCrate( + items.pollenCluster.get(EnumPollenCluster.CRYSTALLINE, 1), "cratedCrystallinePollen"); + crateRegistry.registerCrate(items.propolis.getItemStack(), "cratedPropolis"); + crateRegistry.registerCrate(items.honeydew.getItemStack(), "cratedHoneydew"); + crateRegistry.registerCrate(items.royalJelly.getItemStack(), "cratedRoyalJelly"); + + crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.HONEY, 1), "cratedHoneycombs"); + crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.COCOA, 1), "cratedCocoaComb"); + crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.SIMMERING, 1), "cratedSimmeringCombs"); + crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.STRINGY, 1), "cratedStringyCombs"); + crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.FROZEN, 1), "cratedFrozenCombs"); + crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.DRIPPING, 1), "cratedDrippingCombs"); + crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.SILKY, 1), "cratedSilkyCombs"); + crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.PARCHED, 1), "cratedParchedCombs"); + crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.MYSTERIOUS, 1), "cratedMysteriousCombs"); + crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.POWDERY, 1), "cratedPowderyCombs"); + crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.WHEATEN, 1), "cratedWheatenCombs"); + crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.MOSSY, 1), "cratedMossyCombs"); + crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.MELLOW, 1), "cratedMellowCombs"); + + crateRegistry.registerCrate(PluginCore.items.refractoryWax.getItemStack(), "cratedRefractoryWax"); + } + + @Override + protected void registerRecipes() { + + // / APIARIST'S ARMOR + ItemStack wovenSilk = PluginCore.items.craftingMaterial.getWovenSilk(); + RecipeUtil.addRecipe(items.apiaristHat, "###", "# #", '#', wovenSilk); + RecipeUtil.addRecipe(items.apiaristChest, "# #", "###", "###", '#', wovenSilk); + RecipeUtil.addRecipe(items.apiaristLegs, "###", "# #", "# #", '#', wovenSilk); + RecipeUtil.addRecipe(items.apiaristBoots, "# #", "# #", '#', wovenSilk); + + // / HABITAT LOCATOR + RecipeUtil.addRecipe(items.habitatLocator, " X ", "X#X", " X ", '#', "dustRedstone", 'X', "ingotBronze"); + + // Bees + RecipeUtil.addRecipe(items.scoop, "#X#", "###", " # ", '#', "stickWood", 'X', Blocks.wool); + RecipeUtil.addRecipe( + new ItemStack(Items.slime_ball), + "#X#", + "#X#", + "#X#", + '#', + items.propolis, + 'X', + items.pollenCluster.get(EnumPollenCluster.NORMAL, 1)); + RecipeUtil.addRecipe( + new ItemStack(Items.speckled_melon), + "#X#", + "#Y#", + "#X#", + '#', + items.honeyDrop, + 'X', + items.honeydew, + 'Y', + Items.melon); + RecipeUtil.addRecipe(items.frameUntreated, "###", "#S#", "###", '#', "stickWood", 'S', Items.string); + RecipeUtil.addRecipe( + items.frameImpregnated, "###", "#S#", "###", '#', PluginCore.items.stickImpregnated, 'S', Items.string); + RecipeUtil.addRecipe( + items.minecartBeehouse.getBeeHouseMinecart(), + "B", + "C", + 'B', + blocks.apiculture.get(BlockApicultureType.BEEHOUSE), + 'C', + Items.minecart); + RecipeUtil.addRecipe( + items.minecartBeehouse.getApiaryMinecart(), + "B", + "C", + 'B', + blocks.apiculture.get(BlockApicultureType.APIARY), + 'C', + Items.minecart); + + // FOOD STUFF + ItemRegistryFood foodItems = PluginFood.items; + if (foodItems != null) { + RecipeUtil.addRecipe( + new ItemStack(foodItems.honeyedSlice, 4), + "###", + "#X#", + "###", + '#', + items.honeyDrop, + 'X', + Items.bread); + + RecipeUtil.addRecipe( + foodItems.honeyPot, + "# #", + " X ", + "# #", + '#', + items.honeyDrop, + 'X', + PluginFluids.items.waxCapsuleEmpty); + + RecipeUtil.addRecipe( + foodItems.ambrosia, + "#Y#", + "XXX", + "###", + '#', + items.honeydew, + 'X', + items.royalJelly, + 'Y', + PluginFluids.items.waxCapsuleEmpty); + } + + // / CAPSULES + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.capsule"), "###", '#', PluginCore.items.beeswax); + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.refractory"), + "###", + '#', + PluginCore.items.refractoryWax); + + // / BITUMINOUS PEAT + RecipeUtil.addRecipe( + PluginCore.items.bituminousPeat.getItemStack(), + " # ", + "XYX", + " # ", + '#', + "dustAsh", + 'X', + PluginCore.items.peat, + 'Y', + items.propolis); + + // / TORCHES + RecipeUtil.addRecipe( + new ItemStack(Blocks.torch, 3), " # ", " # ", " Y ", '#', PluginCore.items.beeswax, 'Y', "stickWood"); + RecipeUtil.addRecipe( + PluginCore.items.craftingMaterial.getPulsatingMesh(), + "# #", + " # ", + "# #", + '#', + items.propolis.get(EnumPropolis.PULSATING, 1)); + + // / WAX CAST + RecipeUtil.addRecipe(items.waxCast, "###", "# #", "###", '#', PluginCore.items.beeswax); + + // / ALVEARY + RecipeUtil.addRecipe( + blocks.alveary.get(BlockAlveary.Type.PLAIN), + "###", + "#X#", + "###", + 'X', + PluginCore.items.impregnatedCasing, + '#', + PluginCore.items.craftingMaterial.getScentedPaneling()); + // SWARMER + RecipeUtil.addRecipe( + blocks.alveary.get(BlockAlveary.Type.SWARMER), + "#G#", + " X ", + "#G#", + '#', + PluginCore.items.tubes.get(EnumElectronTube.DIAMOND, 1), + 'X', + blocks.alveary, + 'G', + "ingotGold"); + // FAN + RecipeUtil.addRecipe( + blocks.alveary.get(BlockAlveary.Type.FAN), + "I I", + " X ", + "I#I", + '#', + PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), + 'X', + blocks.alveary, + 'I', + "ingotIron"); + // HEATER + RecipeUtil.addRecipe( + blocks.alveary.get(BlockAlveary.Type.HEATER), + "#I#", + " X ", + "YYY", + '#', + PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), + 'X', + blocks.alveary, + 'I', + "ingotIron", + 'Y', + "stone"); + // HYGROREGULATOR + RecipeUtil.addRecipe( + blocks.alveary.get(BlockAlveary.Type.HYGRO), + "GIG", + "GXG", + "GIG", + 'X', + blocks.alveary, + 'I', + "ingotIron", + 'G', + "blockGlass"); + // STABILISER + RecipeUtil.addRecipe( + blocks.alveary.get(BlockAlveary.Type.STABILIZER), + "G G", + "GXG", + "G G", + 'X', + blocks.alveary, + 'G', + "gemQuartz"); + // SIEVE + RecipeUtil.addRecipe( + blocks.alveary.get(BlockAlveary.Type.SIEVE), + "III", + " X ", + "WWW", + 'X', + blocks.alveary, + 'I', + "ingotIron", + 'W', + PluginCore.items.craftingMaterial.getWovenSilk()); + + if (PluginManager.Module.FACTORY.isEnabled()) { + // / SQUEEZER + FluidStack honeyDropFluid = Fluids.HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP); + RecipeManagers.squeezerManager.addRecipe( + 10, + new ItemStack[] {items.honeyDrop.getItemStack()}, + honeyDropFluid, + items.propolis.getItemStack(), + 5); + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {items.honeydew.getItemStack()}, honeyDropFluid); + + ItemStack phosphor = PluginCore.items.phosphor.getItemStack(2); + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {phosphor, new ItemStack(Blocks.sand)}, Fluids.LAVA.getFluid(2000)); + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {phosphor, new ItemStack(Blocks.sand, 1, 1)}, Fluids.LAVA.getFluid(2000)); + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {phosphor, new ItemStack(Blocks.dirt)}, Fluids.LAVA.getFluid(1600)); + + // / CARPENTER + RecipeManagers.carpenterManager.addRecipe( + 100, + Fluids.WATER.getFluid(2000), + null, + items.beealyzer.getItemStack(), + "X#X", + "X#X", + "RDR", + '#', + "paneGlass", + 'X', + "ingotTin", + 'R', + "dustRedstone", + 'D', + "gemDiamond"); + RecipeManagers.carpenterManager.addRecipe( + 50, + Fluids.HONEY.getFluid(500), + null, + PluginCore.items.craftingMaterial.getScentedPaneling(), + " J ", + "###", + "WPW", + '#', + "plankWood", + 'J', + items.royalJelly, + 'W', + PluginCore.items.beeswax, + 'P', + items.pollenCluster.get(EnumPollenCluster.NORMAL, 1)); + + RecipeManagers.carpenterManager.addRecipe( + 30, + Fluids.WATER.getFluid(600), + null, + blocks.candle.getUnlitCandle(24), + " X ", + "###", + "###", + '#', + PluginCore.items.beeswax, + 'X', + Items.string); + RecipeManagers.carpenterManager.addRecipe( + 10, + Fluids.WATER.getFluid(200), + null, + blocks.candle.getUnlitCandle(6), + "#X#", + '#', + PluginCore.items.beeswax, + 'X', + PluginCore.items.craftingMaterial.getSilkWisp()); + RecipeUtil.addShapelessRecipe(blocks.candle.getUnlitCandle(1), blocks.candle.getUnlitCandle(1)); + RecipeUtil.addShapelessRecipe(blocks.candle.getLitCandle(1), blocks.candle.getLitCandle(1)); + + // / CENTRIFUGE + // Honey combs + RecipeManagers.centrifugeManager.addRecipe( + 20, + items.beeComb.get(EnumHoneyComb.HONEY, 1), + ImmutableMap.of( + PluginCore.items.beeswax.getItemStack(), 1.0f, + items.honeyDrop.getItemStack(), 0.9f)); + + // Cocoa combs + RecipeManagers.centrifugeManager.addRecipe( + 20, + items.beeComb.get(EnumHoneyComb.COCOA, 1), + ImmutableMap.of( + PluginCore.items.beeswax.getItemStack(), 1.0f, new ItemStack(Items.dye, 1, 3), 0.5f)); + + // Simmering combs + RecipeManagers.centrifugeManager.addRecipe( + 20, + items.beeComb.get(EnumHoneyComb.SIMMERING, 1), + ImmutableMap.of( + PluginCore.items.refractoryWax.getItemStack(), 1.0f, + PluginCore.items.phosphor.getItemStack(2), 0.7f)); + + // Stringy combs + RecipeManagers.centrifugeManager.addRecipe( + 20, + items.beeComb.get(EnumHoneyComb.STRINGY, 1), + ImmutableMap.of( + items.propolis.getItemStack(), 1.0f, + items.honeyDrop.getItemStack(), 0.4f)); + + // Dripping combs + RecipeManagers.centrifugeManager.addRecipe( + 20, + items.beeComb.get(EnumHoneyComb.DRIPPING, 1), + ImmutableMap.of( + items.honeydew.getItemStack(), 1.0f, + items.honeyDrop.getItemStack(), 0.4f)); + + // Frozen combs + RecipeManagers.centrifugeManager.addRecipe( + 20, + items.beeComb.get(EnumHoneyComb.FROZEN, 1), + ImmutableMap.of( + PluginCore.items.beeswax.getItemStack(), + 0.8f, + items.honeyDrop.getItemStack(), + 0.7f, + new ItemStack(Items.snowball), + 0.4f, + items.pollenCluster.get(EnumPollenCluster.CRYSTALLINE, 1), + 0.2f)); + + // Silky combs + RecipeManagers.centrifugeManager.addRecipe( + 20, + items.beeComb.get(EnumHoneyComb.SILKY, 1), + ImmutableMap.of( + items.honeyDrop.getItemStack(), 1.0f, + items.propolis.get(EnumPropolis.SILKY, 1), 0.8f)); + + // Parched combs + RecipeManagers.centrifugeManager.addRecipe( + 20, + items.beeComb.get(EnumHoneyComb.PARCHED, 1), + ImmutableMap.of( + PluginCore.items.beeswax.getItemStack(), 1.0f, + items.honeyDrop.getItemStack(), 0.9f)); + + // Mysterious combs + RecipeManagers.centrifugeManager.addRecipe( + 20, + items.beeComb.get(EnumHoneyComb.MYSTERIOUS, 1), + ImmutableMap.of( + items.propolis.get(EnumPropolis.PULSATING, 1), 1.0f, + items.honeyDrop.getItemStack(), 0.4f)); + + // Irradiated combs + RecipeManagers.centrifugeManager.addRecipe( + 20, items.beeComb.get(EnumHoneyComb.IRRADIATED, 1), ImmutableMap.of()); + + // Powdery combs + RecipeManagers.centrifugeManager.addRecipe( + 20, + items.beeComb.get(EnumHoneyComb.POWDERY, 1), + ImmutableMap.of( + items.honeyDrop.getItemStack(), + 0.2f, + PluginCore.items.beeswax.getItemStack(), + 0.2f, + new ItemStack(Items.gunpowder), + 0.9f)); + + // Wheaten Combs + RecipeManagers.centrifugeManager.addRecipe( + 20, + items.beeComb.get(EnumHoneyComb.WHEATEN, 1), + ImmutableMap.of( + items.honeyDrop.getItemStack(), + 0.2f, + PluginCore.items.beeswax.getItemStack(), + 0.2f, + new ItemStack(Items.wheat), + 0.8f)); + + // Mossy Combs + RecipeManagers.centrifugeManager.addRecipe( + 20, + items.beeComb.get(EnumHoneyComb.MOSSY, 1), + ImmutableMap.of( + PluginCore.items.beeswax.getItemStack(), 1.0f, + items.honeyDrop.getItemStack(), 0.9f)); + + // Mellow Combs + RecipeManagers.centrifugeManager.addRecipe( + 20, + items.beeComb.get(EnumHoneyComb.MELLOW, 1), + ImmutableMap.of( + items.honeydew.getItemStack(), + 0.6f, + PluginCore.items.beeswax.getItemStack(), + 0.2f, + new ItemStack(Items.quartz), + 0.3f)); + + // Silky Propolis + RecipeManagers.centrifugeManager.addRecipe( + 5, + items.propolis.get(EnumPropolis.SILKY, 1), + ImmutableMap.of( + PluginCore.items.craftingMaterial.getSilkWisp(), 0.6f, + items.propolis.getItemStack(), 0.1f)); + + // / FERMENTER + RecipeManagers.fermenterManager.addRecipe( + items.honeydew.getItemStack(), 500, 1.0f, Fluids.SHORT_MEAD.getFluid(1), Fluids.HONEY.getFluid(1)); + // / STILL + RecipeManagers.stillManager.addRecipe( + Constants.STILL_DESTILLATION_DURATION, Fluids.SHORT_MEAD.getFluid(10), Fluids.MEAD.getFluid(5)); + } + + // ANALYZER + RecipeUtil.addRecipe( + PluginCore.blocks.core.get(BlockCoreType.ANALYZER), + "XTX", + " Y ", + "X X", + 'Y', + PluginCore.items.sturdyCasing, + 'T', + items.beealyzer, + 'X', + "ingotBronze"); + + RecipeUtil.addRecipe( + blocks.apiculture.get(BlockApicultureType.APIARY), + "XXX", + "#C#", + "###", + 'X', + "slabWood", + '#', + "plankWood", + 'C', + PluginCore.items.impregnatedCasing); + + RecipeUtil.addRecipe( + new ItemStack(blocks.apicultureChest), + " # ", + "XYX", + "XXX", + '#', + "blockGlass", + 'X', + "beeComb", + 'Y', + "chestWood"); + + RecipeUtil.addRecipe( + blocks.apiculture.get(BlockApicultureType.BEEHOUSE), + "XXX", + "#C#", + "###", + 'X', + "slabWood", + '#', + "plankWood", + 'C', + "beeComb"); + } + + private static void registerBeehiveDrops() { + ItemStack honeyComb = items.beeComb.get(EnumHoneyComb.HONEY, 1); + hiveRegistry.addDrops( + HiveRegistry.forest, + new HiveDrop(80, BeeDefinition.FOREST, honeyComb).setIgnobleShare(0.7f), + new HiveDrop(8, BeeDefinition.FOREST.getRainResist(), honeyComb), + new HiveDrop(3, BeeDefinition.VALIANT, honeyComb)); + + hiveRegistry.addDrops( + HiveRegistry.meadows, + new HiveDrop(80, BeeDefinition.MEADOWS, honeyComb).setIgnobleShare(0.7f), + new HiveDrop(3, BeeDefinition.VALIANT, honeyComb)); + + ItemStack parchedComb = items.beeComb.get(EnumHoneyComb.PARCHED, 1); + hiveRegistry.addDrops( + HiveRegistry.desert, + new HiveDrop(80, BeeDefinition.MODEST, parchedComb).setIgnobleShare(0.7f), + new HiveDrop(3, BeeDefinition.VALIANT, parchedComb)); + + ItemStack silkyComb = items.beeComb.get(EnumHoneyComb.SILKY, 1); + hiveRegistry.addDrops( + HiveRegistry.jungle, + new HiveDrop(80, BeeDefinition.TROPICAL, silkyComb).setIgnobleShare(0.7f), + new HiveDrop(3, BeeDefinition.VALIANT, silkyComb)); + + ItemStack mysteriousComb = items.beeComb.get(EnumHoneyComb.MYSTERIOUS, 1); + hiveRegistry.addDrops(HiveRegistry.end, new HiveDrop(90, BeeDefinition.ENDED, mysteriousComb)); + + ItemStack frozenComb = items.beeComb.get(EnumHoneyComb.FROZEN, 1); + hiveRegistry.addDrops( + HiveRegistry.snow, + new HiveDrop(80, BeeDefinition.WINTRY, frozenComb).setIgnobleShare(0.5f), + new HiveDrop(3, BeeDefinition.VALIANT, frozenComb)); + + ItemStack mossyComb = items.beeComb.get(EnumHoneyComb.MOSSY, 1); + hiveRegistry.addDrops( + HiveRegistry.swamp, + new HiveDrop(80, BeeDefinition.MARSHY, mossyComb).setIgnobleShare(0.4f), + new HiveDrop(3, BeeDefinition.VALIANT, mossyComb)); + } + + private static void registerDungeonLoot() { + int rarity; + if (Config.dungeonLootRare) { + rarity = 5; + } else { + rarity = 10; + } + + ChestGenHooks.addItem( + ChestGenHooks.DUNGEON_CHEST, + new WeightedRandomChestContent( + BeeDefinition.STEADFAST.getMemberStack(EnumBeeType.DRONE), 1, 1, rarity)); + + ItemStack stack = blocks.candle.getUnlitCandle(1); + NBTTagCompound tag = new NBTTagCompound(); + tag.setInteger(BlockCandle.colourTagName, 0xffffff); + stack.setTagCompound(tag); + + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(stack, 7, 12, 12)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent(items.scoop.getItemStack(), 1, 1, 8)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent(items.propolis.get(EnumPropolis.NORMAL, 1), 2, 4, 6)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent(items.beeComb.get(EnumHoneyComb.HONEY, 1), 4, 12, 7)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent(items.beeComb.get(EnumHoneyComb.FROZEN, 1), 2, 10, 7)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent(items.beeComb.get(EnumHoneyComb.SILKY, 1), 1, 6, 7)); + + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent( + BeeDefinition.FOREST.getRainResist().getMemberStack(EnumBeeType.PRINCESS), 1, 1, 5)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent(BeeDefinition.COMMON.getMemberStack(EnumBeeType.DRONE), 1, 2, 8)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent(BeeDefinition.MEADOWS.getMemberStack(EnumBeeType.PRINCESS), 1, 1, 5)); + } + + private static void createHives() { + hiveRegistry.registerHive(HiveRegistry.forest, HiveDescription.FOREST); + hiveRegistry.registerHive(HiveRegistry.meadows, HiveDescription.MEADOWS); + hiveRegistry.registerHive(HiveRegistry.desert, HiveDescription.DESERT); + hiveRegistry.registerHive(HiveRegistry.jungle, HiveDescription.JUNGLE); + hiveRegistry.registerHive(HiveRegistry.end, HiveDescription.END); + hiveRegistry.registerHive(HiveRegistry.snow, HiveDescription.SNOW); + hiveRegistry.registerHive(HiveRegistry.swamp, HiveDescription.SWAMP); + } + + private static void createAlleles() { + + IClassification hymnoptera = AlleleManager.alleleRegistry.createAndRegisterClassification( + EnumClassLevel.ORDER, "hymnoptera", "Hymnoptera"); + AlleleManager.alleleRegistry.getClassification("class.insecta").addMemberGroup(hymnoptera); + + IClassification apidae = + AlleleManager.alleleRegistry.createAndRegisterClassification(EnumClassLevel.FAMILY, "apidae", "Apidae"); + hymnoptera.addMemberGroup(apidae); + + for (BeeBranchDefinition beeBranch : BeeBranchDefinition.values()) { + apidae.addMemberGroup(beeBranch.getBranch()); + } + + AlleleEffect.createAlleles(); + } + + public static double getSecondPrincessChance() { + return secondPrincessChance; + } + + private static void parseBeeBlacklist(String[] items) { + for (String item : items) { + if (item.isEmpty()) { + continue; + } + + FMLCommonHandler.instance().getFMLLogger().debug("Blacklisting bee species identified by " + item); + AlleleManager.alleleRegistry.blacklistAllele(item); + } + } + + private static void parseAcceptedFlowers(String[] acceptedFlowers, String flowerType) { + List acceptedFlowerItemStacks = Stack.parseStackStrings(acceptedFlowers, OreDictionary.WILDCARD_VALUE); + for (Stack acceptedFlower : acceptedFlowerItemStacks) { + Block acceptedFlowerBlock = acceptedFlower.getBlock(); + int meta = acceptedFlower.getMeta(); + if (acceptedFlowerBlock != null) { + FlowerManager.flowerRegistry.registerAcceptableFlower(acceptedFlowerBlock, meta, flowerType); + } else { + Log.warning( + "No block found for '" + acceptedFlower + "' in apiculture config for '" + flowerType + "'."); + } + } + } + + private static void parsePlantableFlowers(Property property, String flowerType) { + for (String string : property.getStringList()) { + Stack plantableFlower = Stack.parseStackString(string, OreDictionary.WILDCARD_VALUE); + if (plantableFlower == null) { + continue; + } + + Block plantableFlowerBlock = plantableFlower.getBlock(); + int meta = plantableFlower.getMeta(); + if (plantableFlowerBlock != null) { + FlowerManager.flowerRegistry.registerPlantableFlower(plantableFlowerBlock, meta, 1.0, flowerType); + } else { + Log.warning("No block found for '" + string + "' in config '" + property.getName() + "'."); + } + } + } + + @Override + public ISaveEventHandler getSaveEventHandler() { + return new SaveEventHandlerApiculture(); + } + + @Override + public void populateChunk( + IChunkProvider chunkProvider, + World world, + Random rand, + int chunkX, + int chunkZ, + boolean hasVillageGenerated) { + if (Config.getBeehivesAmount() > 0.0) { + HiveDecorator.decorateHives(chunkProvider, world, rand, chunkX, chunkZ, hasVillageGenerated); + } + } + + @Override + public void populateChunkRetroGen(World world, Random rand, int chunkX, int chunkZ) { + if (Config.getBeehivesAmount() > 0.0) { + HiveDecorator.decorateHives(world, rand, chunkX, chunkZ); + } + } + + @Override + public boolean processIMCMessage(IMCMessage message) { + if (message.key.equals("add-candle-lighting-id")) { + ItemStack value = message.getItemStackValue(); + if (value != null) { + BlockCandle.addItemToLightingList(value.getItem()); + } else { + logInvalidIMCMessage(message); + } + return true; + } else if (message.key.equals("add-alveary-slab") && message.isStringMessage()) { + String messageString = String.format( + "Received a '%s' request from mod '%s'. This IMC message has been replaced with the oreDictionary for 'slabWood'. Please contact the author and report this issue.", + message.key, message.getSender()); + Log.warning(messageString); + return true; + } + + return super.processIMCMessage(message); + } + + @SubscribeEvent + @SideOnly(Side.CLIENT) + public void textureHook(TextureStitchEvent.Pre event) { + if (event.map.getTextureType() == 1) { + EntityFXSnow.icons = new IIcon[3]; + for (int i = 0; i < EntityFXSnow.icons.length; i++) { + EntityFXSnow.icons[i] = event.map.registerIcon("forestry:particles/snow." + (i + 1)); + } + } + } } diff --git a/src/main/java/forestry/plugins/PluginArboriculture.java b/src/main/java/forestry/plugins/PluginArboriculture.java index 3e1cff402..890bbb772 100644 --- a/src/main/java/forestry/plugins/PluginArboriculture.java +++ b/src/main/java/forestry/plugins/PluginArboriculture.java @@ -10,21 +10,6 @@ ******************************************************************************/ package forestry.plugins; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.WeightedRandomChestContent; - -import net.minecraftforge.common.ChestGenHooks; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.FuelBurnTimeEvent; -import net.minecraftforge.oredict.OreDictionary; - import cpw.mods.fml.common.IFuelHandler; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; @@ -33,7 +18,6 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.registry.GameData; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.VillagerRegistry; - import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.EnumWoodType; import forestry.api.arboriculture.TreeManager; @@ -76,367 +60,452 @@ import forestry.core.proxy.Proxies; import forestry.core.recipes.RecipeUtil; import forestry.core.tiles.MachineDefinition; import forestry.factory.recipes.FabricatorRecipe; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.WeightedRandomChestContent; +import net.minecraftforge.common.ChestGenHooks; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.FuelBurnTimeEvent; +import net.minecraftforge.oredict.OreDictionary; -@Plugin(pluginID = "Arboriculture", name = "Arboriculture", author = "Binnie & SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.arboriculture.description") +@Plugin( + pluginID = "Arboriculture", + name = "Arboriculture", + author = "Binnie & SirSengir", + url = Constants.URL, + unlocalizedDescription = "for.plugin.arboriculture.description") public class PluginArboriculture extends ForestryPlugin { - @SidedProxy(clientSide = "forestry.arboriculture.proxy.ProxyArboricultureClient", serverSide = "forestry.arboriculture.proxy.ProxyArboriculture") - public static ProxyArboriculture proxy; - public static String treekeepingMode = "NORMAL"; + @SidedProxy( + clientSide = "forestry.arboriculture.proxy.ProxyArboricultureClient", + serverSide = "forestry.arboriculture.proxy.ProxyArboriculture") + public static ProxyArboriculture proxy; - public static int modelIdSaplings; - public static int modelIdLeaves; - public static int modelIdPods; + public static String treekeepingMode = "NORMAL"; - public static final List validFences = new ArrayList<>(); + public static int modelIdSaplings; + public static int modelIdLeaves; + public static int modelIdPods; - public static ItemRegistryArboriculture items; - public static BlockRegistryArboriculture blocks; + public static final List validFences = new ArrayList<>(); - @Override - protected void setupAPI() { - super.setupAPI(); + public static ItemRegistryArboriculture items; + public static BlockRegistryArboriculture blocks; - TreeManager.treeFactory = new TreeFactory(); - TreeManager.treeMutationFactory = new TreeMutationFactory(); + @Override + protected void setupAPI() { + super.setupAPI(); - TreeManager.woodItemAccess = new WoodItemAccess(); + TreeManager.treeFactory = new TreeFactory(); + TreeManager.treeMutationFactory = new TreeMutationFactory(); - // Init tree interface - TreeManager.treeRoot = new TreeHelper(); - AlleleManager.alleleRegistry.registerSpeciesRoot(TreeManager.treeRoot); + TreeManager.woodItemAccess = new WoodItemAccess(); - // Modes - TreeManager.treeRoot.registerTreekeepingMode(TreekeepingMode.easy); - TreeManager.treeRoot.registerTreekeepingMode(TreekeepingMode.normal); - TreeManager.treeRoot.registerTreekeepingMode(TreekeepingMode.hard); - TreeManager.treeRoot.registerTreekeepingMode(TreekeepingMode.hardcore); - TreeManager.treeRoot.registerTreekeepingMode(TreekeepingMode.insane); - } + // Init tree interface + TreeManager.treeRoot = new TreeHelper(); + AlleleManager.alleleRegistry.registerSpeciesRoot(TreeManager.treeRoot); - @Override - protected void registerItemsAndBlocks() { - items = new ItemRegistryArboriculture(); - blocks = new BlockRegistryArboriculture(); - } + // Modes + TreeManager.treeRoot.registerTreekeepingMode(TreekeepingMode.easy); + TreeManager.treeRoot.registerTreekeepingMode(TreekeepingMode.normal); + TreeManager.treeRoot.registerTreekeepingMode(TreekeepingMode.hard); + TreeManager.treeRoot.registerTreekeepingMode(TreekeepingMode.hardcore); + TreeManager.treeRoot.registerTreekeepingMode(TreekeepingMode.insane); + } - @Override - public void preInit() { - super.preInit(); + @Override + protected void registerItemsAndBlocks() { + items = new ItemRegistryArboriculture(); + blocks = new BlockRegistryArboriculture(); + } - // register for FuelBurnTimeEvent - MinecraftForge.EVENT_BUS.register(this); + @Override + public void preInit() { + super.preInit(); - for (EnumWoodType woodType : EnumWoodType.VALUES) { - WoodItemAccess.registerLog(blocks.logs, woodType, false); - WoodItemAccess.registerPlanks(blocks.planks, woodType, false); - WoodItemAccess.registerSlab(blocks.slabs, woodType, false); - WoodItemAccess.registerFence(blocks.fences, woodType, false); - WoodItemAccess.registerStairs(blocks.stairs, woodType, false); + // register for FuelBurnTimeEvent + MinecraftForge.EVENT_BUS.register(this); - WoodItemAccess.registerLog(blocks.logsFireproof, woodType, true); - WoodItemAccess.registerPlanks(blocks.planksFireproof, woodType, true); - WoodItemAccess.registerSlab(blocks.slabsFireproof, woodType, true); - WoodItemAccess.registerFence(blocks.fencesFireproof, woodType, true); - WoodItemAccess.registerStairs(blocks.stairsFireproof, woodType, true); - } + for (EnumWoodType woodType : EnumWoodType.VALUES) { + WoodItemAccess.registerLog(blocks.logs, woodType, false); + WoodItemAccess.registerPlanks(blocks.planks, woodType, false); + WoodItemAccess.registerSlab(blocks.slabs, woodType, false); + WoodItemAccess.registerFence(blocks.fences, woodType, false); + WoodItemAccess.registerStairs(blocks.stairs, woodType, false); - MachineDefinition definitionChest = new MachineDefinition(BlockArboricultureType.ARBCHEST.ordinal(), - "forestry.ArbChest", TileArboristChest.class, Proxies.render.getRenderChest("arbchest")) - .setBoundingBox(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); - blocks.arboriculture.addDefinition(definitionChest); + WoodItemAccess.registerLog(blocks.logsFireproof, woodType, true); + WoodItemAccess.registerPlanks(blocks.planksFireproof, woodType, true); + WoodItemAccess.registerSlab(blocks.slabsFireproof, woodType, true); + WoodItemAccess.registerFence(blocks.fencesFireproof, woodType, true); + WoodItemAccess.registerStairs(blocks.stairsFireproof, woodType, true); + } - // Init rendering - proxy.initializeRendering(); + MachineDefinition definitionChest = new MachineDefinition( + BlockArboricultureType.ARBCHEST.ordinal(), + "forestry.ArbChest", + TileArboristChest.class, + Proxies.render.getRenderChest("arbchest")) + .setBoundingBox(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); + blocks.arboriculture.addDefinition(definitionChest); - // Register vanilla and forestry fence ids - validFences.add(blocks.fences); - validFences.add(blocks.fencesFireproof); - validFences.add(Blocks.fence); - validFences.add(Blocks.fence_gate); - validFences.add(Blocks.nether_brick_fence); + // Init rendering + proxy.initializeRendering(); - // Commands - PluginCore.rootCommand.addChildCommand(new CommandTree()); - } + // Register vanilla and forestry fence ids + validFences.add(blocks.fences); + validFences.add(blocks.fencesFireproof); + validFences.add(Blocks.fence); + validFences.add(Blocks.fence_gate); + validFences.add(Blocks.nether_brick_fence); - @Override - public void doInit() { - super.doInit(); + // Commands + PluginCore.rootCommand.addChildCommand(new CommandTree()); + } - // Create alleles - createAlleles(); - TreeDefinition.initTrees(); - registerErsatzGenomes(); + @Override + public void doInit() { + super.doInit(); - GameRegistry.registerTileEntity(TileSapling.class, "forestry.Sapling"); - GameRegistry.registerTileEntity(TileLeaves.class, "forestry.Leaves"); - GameRegistry.registerTileEntity(TileWood.class, "forestry.Wood"); - GameRegistry.registerTileEntity(TileFruitPod.class, "forestry.Pods"); + // Create alleles + createAlleles(); + TreeDefinition.initTrees(); + registerErsatzGenomes(); - blocks.arboriculture.init(); + GameRegistry.registerTileEntity(TileSapling.class, "forestry.Sapling"); + GameRegistry.registerTileEntity(TileLeaves.class, "forestry.Leaves"); + GameRegistry.registerTileEntity(TileWood.class, "forestry.Wood"); + GameRegistry.registerTileEntity(TileFruitPod.class, "forestry.Pods"); - if (Config.enableVillagers) { - VillagerRegistry.instance().registerVillagerId(Constants.ID_VILLAGER_LUMBERJACK); - Proxies.render.registerVillagerSkin(Constants.ID_VILLAGER_LUMBERJACK, Constants.TEXTURE_SKIN_LUMBERJACK); - VillagerRegistry.instance().registerVillageTradeHandler(Constants.ID_VILLAGER_LUMBERJACK, new VillageHandlerArboriculture()); - } - } + blocks.arboriculture.init(); - @Override - public void postInit() { - super.postInit(); - registerDungeonLoot(); - } + if (Config.enableVillagers) { + VillagerRegistry.instance().registerVillagerId(Constants.ID_VILLAGER_LUMBERJACK); + Proxies.render.registerVillagerSkin(Constants.ID_VILLAGER_LUMBERJACK, Constants.TEXTURE_SKIN_LUMBERJACK); + VillagerRegistry.instance() + .registerVillageTradeHandler(Constants.ID_VILLAGER_LUMBERJACK, new VillageHandlerArboriculture()); + } + } - @Override - protected void registerCrates() { - ICrateRegistry crateRegistry = StorageManager.crateRegistry; - crateRegistry.registerCrate(EnumFruit.CHERRY.getStack(), "cratedCherry"); - crateRegistry.registerCrate(EnumFruit.WALNUT.getStack(), "cratedWalnut"); - crateRegistry.registerCrate(EnumFruit.CHESTNUT.getStack(), "cratedChestnut"); - crateRegistry.registerCrate(EnumFruit.LEMON.getStack(), "cratedLemon"); - crateRegistry.registerCrate(EnumFruit.PLUM.getStack(), "cratedPlum"); - crateRegistry.registerCrate(EnumFruit.PAPAYA.getStack(), "cratedPapaya"); - crateRegistry.registerCrate(EnumFruit.DATES.getStack(), "cratedDates"); - } + @Override + public void postInit() { + super.postInit(); + registerDungeonLoot(); + } - @Override - protected void registerRecipes() { + @Override + protected void registerCrates() { + ICrateRegistry crateRegistry = StorageManager.crateRegistry; + crateRegistry.registerCrate(EnumFruit.CHERRY.getStack(), "cratedCherry"); + crateRegistry.registerCrate(EnumFruit.WALNUT.getStack(), "cratedWalnut"); + crateRegistry.registerCrate(EnumFruit.CHESTNUT.getStack(), "cratedChestnut"); + crateRegistry.registerCrate(EnumFruit.LEMON.getStack(), "cratedLemon"); + crateRegistry.registerCrate(EnumFruit.PLUM.getStack(), "cratedPlum"); + crateRegistry.registerCrate(EnumFruit.PAPAYA.getStack(), "cratedPapaya"); + crateRegistry.registerCrate(EnumFruit.DATES.getStack(), "cratedDates"); + } - RecipeUtil.addSmelting(new ItemStack(blocks.logs, 1, OreDictionary.WILDCARD_VALUE), new ItemStack(Items.coal, 1, 1), 0.15F); + @Override + protected void registerRecipes() { - for (EnumWoodType woodType : EnumWoodType.VALUES) { - ItemStack planks = TreeManager.woodItemAccess.getPlanks(woodType, false); - ItemStack logs = TreeManager.woodItemAccess.getLog(woodType, false); - ItemStack slabs = TreeManager.woodItemAccess.getSlab(woodType, false); - ItemStack fences = TreeManager.woodItemAccess.getFence(woodType, false); - ItemStack stairs = TreeManager.woodItemAccess.getStairs(woodType, false); + RecipeUtil.addSmelting( + new ItemStack(blocks.logs, 1, OreDictionary.WILDCARD_VALUE), new ItemStack(Items.coal, 1, 1), 0.15F); - ItemStack fireproofPlanks = TreeManager.woodItemAccess.getPlanks(woodType, true); - ItemStack fireproofLogs = TreeManager.woodItemAccess.getLog(woodType, true); - ItemStack fireproofSlabs = TreeManager.woodItemAccess.getSlab(woodType, true); - ItemStack fireproofFences = TreeManager.woodItemAccess.getFence(woodType, true); - ItemStack fireproofStairs = TreeManager.woodItemAccess.getStairs(woodType, true); + for (EnumWoodType woodType : EnumWoodType.VALUES) { + ItemStack planks = TreeManager.woodItemAccess.getPlanks(woodType, false); + ItemStack logs = TreeManager.woodItemAccess.getLog(woodType, false); + ItemStack slabs = TreeManager.woodItemAccess.getSlab(woodType, false); + ItemStack fences = TreeManager.woodItemAccess.getFence(woodType, false); + ItemStack stairs = TreeManager.woodItemAccess.getStairs(woodType, false); - planks.stackSize = 4; - logs.stackSize = 1; - RecipeUtil.addShapelessRecipe(planks.copy(), logs.copy()); + ItemStack fireproofPlanks = TreeManager.woodItemAccess.getPlanks(woodType, true); + ItemStack fireproofLogs = TreeManager.woodItemAccess.getLog(woodType, true); + ItemStack fireproofSlabs = TreeManager.woodItemAccess.getSlab(woodType, true); + ItemStack fireproofFences = TreeManager.woodItemAccess.getFence(woodType, true); + ItemStack fireproofStairs = TreeManager.woodItemAccess.getStairs(woodType, true); - fireproofPlanks.stackSize = 4; - fireproofLogs.stackSize = 1; - RecipeUtil.addShapelessRecipe(fireproofPlanks.copy(), fireproofLogs.copy()); + planks.stackSize = 4; + logs.stackSize = 1; + RecipeUtil.addShapelessRecipe(planks.copy(), logs.copy()); - slabs.stackSize = 6; - planks.stackSize = 1; - RecipeUtil.addPriorityRecipe(slabs.copy(), - "###", - '#', planks.copy()); + fireproofPlanks.stackSize = 4; + fireproofLogs.stackSize = 1; + RecipeUtil.addShapelessRecipe(fireproofPlanks.copy(), fireproofLogs.copy()); - fireproofSlabs.stackSize = 6; - fireproofPlanks.stackSize = 1; - RecipeUtil.addPriorityRecipe(fireproofSlabs.copy(), - "###", - '#', fireproofPlanks.copy()); + slabs.stackSize = 6; + planks.stackSize = 1; + RecipeUtil.addPriorityRecipe(slabs.copy(), "###", '#', planks.copy()); - fences.stackSize = 3; - planks.stackSize = 1; - RecipeUtil.addRecipe(fences.copy(), - "#X#", - "#X#", - '#', planks.copy(), 'X', "stickWood"); + fireproofSlabs.stackSize = 6; + fireproofPlanks.stackSize = 1; + RecipeUtil.addPriorityRecipe(fireproofSlabs.copy(), "###", '#', fireproofPlanks.copy()); - fireproofFences.stackSize = 3; - fireproofPlanks.stackSize = 1; - RecipeUtil.addRecipe(fireproofFences.copy(), - "#X#", - "#X#", - '#', fireproofPlanks.copy(), 'X', "stickWood"); + fences.stackSize = 3; + planks.stackSize = 1; + RecipeUtil.addRecipe(fences.copy(), "#X#", "#X#", '#', planks.copy(), 'X', "stickWood"); - stairs.stackSize = 4; - planks.stackSize = 1; - RecipeUtil.addPriorityRecipe(stairs.copy(), - "# ", - "## ", - "###", - '#', planks.copy()); + fireproofFences.stackSize = 3; + fireproofPlanks.stackSize = 1; + RecipeUtil.addRecipe(fireproofFences.copy(), "#X#", "#X#", '#', fireproofPlanks.copy(), 'X', "stickWood"); - fireproofStairs.stackSize = 4; - fireproofPlanks.stackSize = 1; - RecipeUtil.addPriorityRecipe(fireproofStairs.copy(), - "# ", - "## ", - "###", - '#', fireproofPlanks.copy()); + stairs.stackSize = 4; + planks.stackSize = 1; + RecipeUtil.addPriorityRecipe(stairs.copy(), "# ", "## ", "###", '#', planks.copy()); - // Fabricator recipes - if (PluginManager.Module.FACTORY.isEnabled() && PluginManager.Module.APICULTURE.isEnabled()) { - logs.stackSize = 1; - fireproofLogs.stackSize = 1; - RecipeManagers.fabricatorManager.addRecipe(new FabricatorRecipe(null, Fluids.GLASS.getFluid(500), fireproofLogs.copy(), new Object[]{ - " # ", - "#X#", - " # ", - '#', PluginCore.items.refractoryWax, - 'X', logs.copy()})); + fireproofStairs.stackSize = 4; + fireproofPlanks.stackSize = 1; + RecipeUtil.addPriorityRecipe(fireproofStairs.copy(), "# ", "## ", "###", '#', fireproofPlanks.copy()); - planks.stackSize = 1; - fireproofPlanks.stackSize = 5; - RecipeManagers.fabricatorManager.addRecipe(new FabricatorRecipe(null, Fluids.GLASS.getFluid(500), fireproofPlanks.copy(), new Object[]{ - "X#X", - "#X#", - "X#X", - '#', PluginCore.items.refractoryWax, - 'X', planks.copy()})); - } - } + // Fabricator recipes + if (PluginManager.Module.FACTORY.isEnabled() && PluginManager.Module.APICULTURE.isEnabled()) { + logs.stackSize = 1; + fireproofLogs.stackSize = 1; + RecipeManagers.fabricatorManager.addRecipe( + new FabricatorRecipe(null, Fluids.GLASS.getFluid(500), fireproofLogs.copy(), new Object[] { + " # ", "#X#", " # ", '#', PluginCore.items.refractoryWax, 'X', logs.copy() + })); - if (PluginManager.Module.FACTORY.isEnabled()) { - // Treealyzer - RecipeManagers.carpenterManager.addRecipe(100, Fluids.WATER.getFluid(2000), null, items.treealyzer.getItemStack(), "X#X", "X#X", "RDR", - '#', "paneGlass", - 'X', "ingotCopper", - 'R', "dustRedstone", - 'D', "gemDiamond"); + planks.stackSize = 1; + fireproofPlanks.stackSize = 5; + RecipeManagers.fabricatorManager.addRecipe( + new FabricatorRecipe(null, Fluids.GLASS.getFluid(500), fireproofPlanks.copy(), new Object[] { + "X#X", "#X#", "X#X", '#', PluginCore.items.refractoryWax, 'X', planks.copy() + })); + } + } - // SQUEEZER RECIPES - int seedOilMultiplier = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - int juiceMultiplier = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); - int mulchMultiplier = ForestryAPI.activeMode.getIntegerSetting("squeezer.mulch.apple"); - ItemStack mulch = new ItemStack(PluginCore.items.mulch); - RecipeManagers.squeezerManager.addRecipe(20, new ItemStack[]{EnumFruit.CHERRY.getStack()}, Fluids.SEEDOIL.getFluid(5 * seedOilMultiplier), mulch, 5); - RecipeManagers.squeezerManager.addRecipe(60, new ItemStack[]{EnumFruit.WALNUT.getStack()}, Fluids.SEEDOIL.getFluid(18 * seedOilMultiplier), mulch, 5); - RecipeManagers.squeezerManager.addRecipe(70, new ItemStack[]{EnumFruit.CHESTNUT.getStack()}, Fluids.SEEDOIL.getFluid(22 * seedOilMultiplier), mulch, 2); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{EnumFruit.LEMON.getStack()}, Fluids.JUICE.getFluid(juiceMultiplier * 2), mulch, (int) Math.floor(mulchMultiplier * 0.5f)); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{EnumFruit.PLUM.getStack()}, Fluids.JUICE.getFluid((int) Math.floor(juiceMultiplier * 0.5f)), mulch, mulchMultiplier * 3); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{EnumFruit.PAPAYA.getStack()}, Fluids.JUICE.getFluid(juiceMultiplier * 3), mulch, (int) Math.floor(mulchMultiplier * 0.5f)); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{EnumFruit.DATES.getStack()}, Fluids.JUICE.getFluid((int) Math.floor(juiceMultiplier * 0.25)), mulch, mulchMultiplier); + if (PluginManager.Module.FACTORY.isEnabled()) { + // Treealyzer + RecipeManagers.carpenterManager.addRecipe( + 100, + Fluids.WATER.getFluid(2000), + null, + items.treealyzer.getItemStack(), + "X#X", + "X#X", + "RDR", + '#', + "paneGlass", + 'X', + "ingotCopper", + 'R', + "dustRedstone", + 'D', + "gemDiamond"); - RecipeUtil.addFermenterRecipes(items.sapling.getItemStack(), ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); - } + // SQUEEZER RECIPES + int seedOilMultiplier = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); + int juiceMultiplier = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); + int mulchMultiplier = ForestryAPI.activeMode.getIntegerSetting("squeezer.mulch.apple"); + ItemStack mulch = new ItemStack(PluginCore.items.mulch); + RecipeManagers.squeezerManager.addRecipe( + 20, + new ItemStack[] {EnumFruit.CHERRY.getStack()}, + Fluids.SEEDOIL.getFluid(5 * seedOilMultiplier), + mulch, + 5); + RecipeManagers.squeezerManager.addRecipe( + 60, + new ItemStack[] {EnumFruit.WALNUT.getStack()}, + Fluids.SEEDOIL.getFluid(18 * seedOilMultiplier), + mulch, + 5); + RecipeManagers.squeezerManager.addRecipe( + 70, + new ItemStack[] {EnumFruit.CHESTNUT.getStack()}, + Fluids.SEEDOIL.getFluid(22 * seedOilMultiplier), + mulch, + 2); + RecipeManagers.squeezerManager.addRecipe( + 10, + new ItemStack[] {EnumFruit.LEMON.getStack()}, + Fluids.JUICE.getFluid(juiceMultiplier * 2), + mulch, + (int) Math.floor(mulchMultiplier * 0.5f)); + RecipeManagers.squeezerManager.addRecipe( + 10, + new ItemStack[] {EnumFruit.PLUM.getStack()}, + Fluids.JUICE.getFluid((int) Math.floor(juiceMultiplier * 0.5f)), + mulch, + mulchMultiplier * 3); + RecipeManagers.squeezerManager.addRecipe( + 10, + new ItemStack[] {EnumFruit.PAPAYA.getStack()}, + Fluids.JUICE.getFluid(juiceMultiplier * 3), + mulch, + (int) Math.floor(mulchMultiplier * 0.5f)); + RecipeManagers.squeezerManager.addRecipe( + 10, + new ItemStack[] {EnumFruit.DATES.getStack()}, + Fluids.JUICE.getFluid((int) Math.floor(juiceMultiplier * 0.25)), + mulch, + mulchMultiplier); - // Grafter - RecipeUtil.addRecipe(items.grafter.getItemStack(), - " B", - " # ", - "# ", - 'B', "ingotBronze", - '#', "stickWood"); + RecipeUtil.addFermenterRecipes( + items.sapling.getItemStack(), + ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), + Fluids.BIOMASS); + } - // ANALYZER - RecipeUtil.addRecipe(PluginCore.blocks.core.get(BlockCoreType.ANALYZER), - "XTX", - " Y ", - "X X", - 'Y', PluginCore.items.sturdyCasing, - 'T', items.treealyzer, - 'X', "ingotBronze"); + // Grafter + RecipeUtil.addRecipe(items.grafter.getItemStack(), " B", " # ", "# ", 'B', "ingotBronze", '#', "stickWood"); - RecipeUtil.addRecipe(blocks.arboriculture.get(BlockArboricultureType.ARBCHEST), - " # ", - "XYX", - "XXX", - '#', "blockGlass", - 'X', "treeSapling", - 'Y', "chestWood"); - } + // ANALYZER + RecipeUtil.addRecipe( + PluginCore.blocks.core.get(BlockCoreType.ANALYZER), + "XTX", + " Y ", + "X X", + 'Y', + PluginCore.items.sturdyCasing, + 'T', + items.treealyzer, + 'X', + "ingotBronze"); - private static void createAlleles() { + RecipeUtil.addRecipe( + blocks.arboriculture.get(BlockArboricultureType.ARBCHEST), + " # ", + "XYX", + "XXX", + '#', + "blockGlass", + 'X', + "treeSapling", + 'Y', + "chestWood"); + } - TreeBranchDefinition.createAlleles(); + private static void createAlleles() { - AlleleFruit.createAlleles(); - AlleleGrowth.createAlleles(); - AlleleLeafEffect.createAlleles(); - AllelePlantType.createAlleles(); - } + TreeBranchDefinition.createAlleles(); - private static void registerErsatzGenomes() { - AlleleManager.ersatzSpecimen.put(new ItemStack(Blocks.leaves, 1, 0), TreeDefinition.Oak.getIndividual()); - AlleleManager.ersatzSpecimen.put(new ItemStack(Blocks.leaves, 1, 1), TreeDefinition.Spruce.getIndividual()); - AlleleManager.ersatzSpecimen.put(new ItemStack(Blocks.leaves, 1, 2), TreeDefinition.Birch.getIndividual()); - AlleleManager.ersatzSpecimen.put(new ItemStack(Blocks.leaves, 1, 3), TreeDefinition.Jungle.getIndividual()); - AlleleManager.ersatzSpecimen.put(new ItemStack(Blocks.leaves2, 1, 0), TreeDefinition.AcaciaVanilla.getIndividual()); - AlleleManager.ersatzSpecimen.put(new ItemStack(Blocks.leaves2, 1, 1), TreeDefinition.DarkOak.getIndividual()); + AlleleFruit.createAlleles(); + AlleleGrowth.createAlleles(); + AlleleLeafEffect.createAlleles(); + AllelePlantType.createAlleles(); + } - AlleleManager.ersatzSaplings.put(new ItemStack(Blocks.sapling, 1, 0), TreeDefinition.Oak.getIndividual()); - AlleleManager.ersatzSaplings.put(new ItemStack(Blocks.sapling, 1, 1), TreeDefinition.Spruce.getIndividual()); - AlleleManager.ersatzSaplings.put(new ItemStack(Blocks.sapling, 1, 2), TreeDefinition.Birch.getIndividual()); - AlleleManager.ersatzSaplings.put(new ItemStack(Blocks.sapling, 1, 3), TreeDefinition.Jungle.getIndividual()); - AlleleManager.ersatzSaplings.put(new ItemStack(Blocks.sapling, 1, 4), TreeDefinition.AcaciaVanilla.getIndividual()); - AlleleManager.ersatzSaplings.put(new ItemStack(Blocks.sapling, 1, 5), TreeDefinition.DarkOak.getIndividual()); - } + private static void registerErsatzGenomes() { + AlleleManager.ersatzSpecimen.put(new ItemStack(Blocks.leaves, 1, 0), TreeDefinition.Oak.getIndividual()); + AlleleManager.ersatzSpecimen.put(new ItemStack(Blocks.leaves, 1, 1), TreeDefinition.Spruce.getIndividual()); + AlleleManager.ersatzSpecimen.put(new ItemStack(Blocks.leaves, 1, 2), TreeDefinition.Birch.getIndividual()); + AlleleManager.ersatzSpecimen.put(new ItemStack(Blocks.leaves, 1, 3), TreeDefinition.Jungle.getIndividual()); + AlleleManager.ersatzSpecimen.put( + new ItemStack(Blocks.leaves2, 1, 0), TreeDefinition.AcaciaVanilla.getIndividual()); + AlleleManager.ersatzSpecimen.put(new ItemStack(Blocks.leaves2, 1, 1), TreeDefinition.DarkOak.getIndividual()); - @Override - public IFuelHandler getFuelHandler() { - return new FuelHandler(); - } + AlleleManager.ersatzSaplings.put(new ItemStack(Blocks.sapling, 1, 0), TreeDefinition.Oak.getIndividual()); + AlleleManager.ersatzSaplings.put(new ItemStack(Blocks.sapling, 1, 1), TreeDefinition.Spruce.getIndividual()); + AlleleManager.ersatzSaplings.put(new ItemStack(Blocks.sapling, 1, 2), TreeDefinition.Birch.getIndividual()); + AlleleManager.ersatzSaplings.put(new ItemStack(Blocks.sapling, 1, 3), TreeDefinition.Jungle.getIndividual()); + AlleleManager.ersatzSaplings.put( + new ItemStack(Blocks.sapling, 1, 4), TreeDefinition.AcaciaVanilla.getIndividual()); + AlleleManager.ersatzSaplings.put(new ItemStack(Blocks.sapling, 1, 5), TreeDefinition.DarkOak.getIndividual()); + } - @Override - public IPacketRegistry getPacketRegistry() { - return new PacketRegistryArboriculture(); - } + @Override + public IFuelHandler getFuelHandler() { + return new FuelHandler(); + } - @Override - public boolean processIMCMessage(IMCMessage message) { - if (message.key.equals("add-fence-block") && message.isStringMessage()) { - Block block = GameData.getBlockRegistry().getRaw(message.getStringValue()); + @Override + public IPacketRegistry getPacketRegistry() { + return new PacketRegistryArboriculture(); + } - if (block != null && block != Blocks.air) { - validFences.add(block); - } else { - logInvalidIMCMessage(message); - } - return true; - } - return super.processIMCMessage(message); - } + @Override + public boolean processIMCMessage(IMCMessage message) { + if (message.key.equals("add-fence-block") && message.isStringMessage()) { + Block block = GameData.getBlockRegistry().getRaw(message.getStringValue()); - private static void registerDungeonLoot() { - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(items.grafter.getItemStack(), 1, 1, 8)); + if (block != null && block != Blocks.air) { + validFences.add(block); + } else { + logInvalidIMCMessage(message); + } + return true; + } + return super.processIMCMessage(message); + } - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(TreeDefinition.Oak.getMemberStack(EnumGermlingType.SAPLING), 2, 3, 6)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(TreeDefinition.Spruce.getMemberStack(EnumGermlingType.SAPLING), 2, 3, 6)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(TreeDefinition.Birch.getMemberStack(EnumGermlingType.SAPLING), 2, 3, 6)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(TreeDefinition.Larch.getMemberStack(EnumGermlingType.SAPLING), 1, 2, 4)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(TreeDefinition.Lime.getMemberStack(EnumGermlingType.SAPLING), 1, 2, 4)); + private static void registerDungeonLoot() { + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent(items.grafter.getItemStack(), 1, 1, 8)); - if (PluginManager.Module.APICULTURE.isEnabled()) { - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(TreeDefinition.Oak.getMemberStack(EnumGermlingType.POLLEN), 2, 3, 4)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(TreeDefinition.Spruce.getMemberStack(EnumGermlingType.POLLEN), 2, 3, 4)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(TreeDefinition.Birch.getMemberStack(EnumGermlingType.POLLEN), 2, 3, 4)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(TreeDefinition.Larch.getMemberStack(EnumGermlingType.POLLEN), 1, 2, 3)); - ChestGenHooks.addItem(Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, new WeightedRandomChestContent(TreeDefinition.Lime.getMemberStack(EnumGermlingType.POLLEN), 1, 2, 3)); - } - } + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent(TreeDefinition.Oak.getMemberStack(EnumGermlingType.SAPLING), 2, 3, 6)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent( + TreeDefinition.Spruce.getMemberStack(EnumGermlingType.SAPLING), 2, 3, 6)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent(TreeDefinition.Birch.getMemberStack(EnumGermlingType.SAPLING), 2, 3, 6)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent(TreeDefinition.Larch.getMemberStack(EnumGermlingType.SAPLING), 1, 2, 4)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent(TreeDefinition.Lime.getMemberStack(EnumGermlingType.SAPLING), 1, 2, 4)); - private static class FuelHandler implements IFuelHandler { - @Override - public int getBurnTime(ItemStack fuel) { - Item item = fuel.getItem(); + if (PluginManager.Module.APICULTURE.isEnabled()) { + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent( + TreeDefinition.Oak.getMemberStack(EnumGermlingType.POLLEN), 2, 3, 4)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent( + TreeDefinition.Spruce.getMemberStack(EnumGermlingType.POLLEN), 2, 3, 4)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent( + TreeDefinition.Birch.getMemberStack(EnumGermlingType.POLLEN), 2, 3, 4)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent( + TreeDefinition.Larch.getMemberStack(EnumGermlingType.POLLEN), 1, 2, 3)); + ChestGenHooks.addItem( + Constants.CHEST_GEN_HOOK_NATURALIST_CHEST, + new WeightedRandomChestContent( + TreeDefinition.Lime.getMemberStack(EnumGermlingType.POLLEN), 1, 2, 3)); + } + } - if (items.sapling == item) { - return 100; - } + private static class FuelHandler implements IFuelHandler { + @Override + public int getBurnTime(ItemStack fuel) { + Item item = fuel.getItem(); - return 0; - } - } + if (items.sapling == item) { + return 100; + } - @SubscribeEvent - public void fuelBurnTimeEvent(FuelBurnTimeEvent fuelBurnTimeEvent) { - Item item = fuelBurnTimeEvent.fuel.getItem(); - Block block = Block.getBlockFromItem(item); + return 0; + } + } - if (block instanceof IWoodTyped) { - IWoodTyped woodTypedBlock = (IWoodTyped) block; - if (woodTypedBlock.isFireproof()) { - fuelBurnTimeEvent.burnTime = 0; - fuelBurnTimeEvent.setResult(Event.Result.DENY); - } else if (blocks.slabs == block) { - fuelBurnTimeEvent.burnTime = 150; - fuelBurnTimeEvent.setResult(Event.Result.DENY); - } - } - } + @SubscribeEvent + public void fuelBurnTimeEvent(FuelBurnTimeEvent fuelBurnTimeEvent) { + Item item = fuelBurnTimeEvent.fuel.getItem(); + Block block = Block.getBlockFromItem(item); + + if (block instanceof IWoodTyped) { + IWoodTyped woodTypedBlock = (IWoodTyped) block; + if (woodTypedBlock.isFireproof()) { + fuelBurnTimeEvent.burnTime = 0; + fuelBurnTimeEvent.setResult(Event.Result.DENY); + } else if (blocks.slabs == block) { + fuelBurnTimeEvent.burnTime = 150; + fuelBurnTimeEvent.setResult(Event.Result.DENY); + } + } + } } diff --git a/src/main/java/forestry/plugins/PluginCore.java b/src/main/java/forestry/plugins/PluginCore.java index 79c17a9a4..4cb6d17f4 100644 --- a/src/main/java/forestry/plugins/PluginCore.java +++ b/src/main/java/forestry/plugins/PluginCore.java @@ -10,17 +10,7 @@ ******************************************************************************/ package forestry.plugins; -import java.util.ArrayList; - -import net.minecraft.command.ICommand; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.oredict.OreDictionary; - import cpw.mods.fml.common.IFuelHandler; - import forestry.api.circuits.ChipsetManager; import forestry.api.core.ForestryAPI; import forestry.api.genetics.AlleleManager; @@ -57,271 +47,408 @@ import forestry.core.recipes.RecipeUtil; import forestry.core.tiles.MachineDefinition; import forestry.core.utils.ClimateUtil; import forestry.core.utils.ForestryModEnvWarningCallable; +import java.util.ArrayList; +import net.minecraft.command.ICommand; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; -@Plugin(pluginID = "Core", name = "Core", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.core.description") +@Plugin( + pluginID = "Core", + name = "Core", + author = "SirSengir", + url = Constants.URL, + unlocalizedDescription = "for.plugin.core.description") public class PluginCore extends ForestryPlugin { - public static final RootCommand rootCommand = new RootCommand(); - public static ItemRegistryCore items; - public static BlockRegistryCore blocks; + public static final RootCommand rootCommand = new RootCommand(); + public static ItemRegistryCore items; + public static BlockRegistryCore blocks; - @Override - protected void setupAPI() { - super.setupAPI(); + @Override + protected void setupAPI() { + super.setupAPI(); - ChipsetManager.solderManager = new SolderManager(); + ChipsetManager.solderManager = new SolderManager(); - ChipsetManager.circuitRegistry = new CircuitRegistry(); + ChipsetManager.circuitRegistry = new CircuitRegistry(); - AlleleRegistry alleleRegistry = new AlleleRegistry(); - AlleleManager.alleleRegistry = alleleRegistry; - AlleleManager.climateHelper = new ClimateUtil(); - AlleleManager.alleleFactory = new AlleleFactory(); - alleleRegistry.initialize(); + AlleleRegistry alleleRegistry = new AlleleRegistry(); + AlleleManager.alleleRegistry = alleleRegistry; + AlleleManager.climateHelper = new ClimateUtil(); + AlleleManager.alleleFactory = new AlleleFactory(); + alleleRegistry.initialize(); - AlleleHelper.instance = new AlleleHelper(); + AlleleHelper.instance = new AlleleHelper(); - MultiblockManager.logicFactory = new MultiblockLogicFactory(); - } + MultiblockManager.logicFactory = new MultiblockLogicFactory(); + } - @Override - protected void registerItemsAndBlocks() { - items = new ItemRegistryCore(); - blocks = new BlockRegistryCore(); - } + @Override + protected void registerItemsAndBlocks() { + items = new ItemRegistryCore(); + blocks = new BlockRegistryCore(); + } - @Override - public void preInit() { - super.preInit(); + @Override + public void preInit() { + super.preInit(); - rootCommand.addChildCommand(new CommandVersion()); - rootCommand.addChildCommand(new CommandPlugins()); + rootCommand.addChildCommand(new CommandVersion()); + rootCommand.addChildCommand(new CommandPlugins()); - blocks.core.addDefinitions( - new MachineDefinition(BlockCoreType.ESCRITOIRE), - new MachineDefinition(BlockCoreType.ANALYZER) - ); - } + blocks.core.addDefinitions( + new MachineDefinition(BlockCoreType.ESCRITOIRE), new MachineDefinition(BlockCoreType.ANALYZER)); + } - @Override - public void doInit() { - super.doInit(); + @Override + public void doInit() { + super.doInit(); - Proxies.render.init(); + Proxies.render.init(); - blocks.core.init(); + blocks.core.init(); - ForestryModEnvWarningCallable.register(); + ForestryModEnvWarningCallable.register(); - AlleleHelper.instance.init(); - } + AlleleHelper.instance.init(); + } - @Override - public boolean isAvailable() { - return true; - } + @Override + public boolean isAvailable() { + return true; + } - @Override - public ISaveEventHandler getSaveEventHandler() { - return new SaveEventHandlerCore(); - } + @Override + public ISaveEventHandler getSaveEventHandler() { + return new SaveEventHandlerCore(); + } - @Override - protected void registerCrates() { - ICrateRegistry crateRegistry = StorageManager.crateRegistry; + @Override + protected void registerCrates() { + ICrateRegistry crateRegistry = StorageManager.crateRegistry; - // forestry items - crateRegistry.registerCrate(items.peat, "cratedPeat"); - crateRegistry.registerCrate(items.apatite, "cratedApatite"); - crateRegistry.registerCrate(items.fertilizerCompound, "cratedFertilizer"); - crateRegistry.registerCrate(items.mulch, "cratedMulch"); - crateRegistry.registerCrate(items.phosphor, "cratedPhosphor"); - crateRegistry.registerCrate(items.ash, "cratedAsh"); - crateRegistry.registerCrateUsingOreDict(items.ingotTin, "cratedTin"); - crateRegistry.registerCrateUsingOreDict(items.ingotCopper, "cratedCopper"); - crateRegistry.registerCrateUsingOreDict(items.ingotBronze, "cratedBronze"); + // forestry items + crateRegistry.registerCrate(items.peat, "cratedPeat"); + crateRegistry.registerCrate(items.apatite, "cratedApatite"); + crateRegistry.registerCrate(items.fertilizerCompound, "cratedFertilizer"); + crateRegistry.registerCrate(items.mulch, "cratedMulch"); + crateRegistry.registerCrate(items.phosphor, "cratedPhosphor"); + crateRegistry.registerCrate(items.ash, "cratedAsh"); + crateRegistry.registerCrateUsingOreDict(items.ingotTin, "cratedTin"); + crateRegistry.registerCrateUsingOreDict(items.ingotCopper, "cratedCopper"); + crateRegistry.registerCrateUsingOreDict(items.ingotBronze, "cratedBronze"); - // forestry blocks - crateRegistry.registerCrate(blocks.soil.get(BlockSoil.SoilType.HUMUS, 1), "cratedHumus"); - crateRegistry.registerCrate(blocks.soil.get(BlockSoil.SoilType.BOG_EARTH, 1), "cratedBogearth"); + // forestry blocks + crateRegistry.registerCrate(blocks.soil.get(BlockSoil.SoilType.HUMUS, 1), "cratedHumus"); + crateRegistry.registerCrate(blocks.soil.get(BlockSoil.SoilType.BOG_EARTH, 1), "cratedBogearth"); - // vanilla items - crateRegistry.registerCrate(Items.wheat, "cratedWheat"); - crateRegistry.registerCrate(Items.cookie, "cratedCookies"); - crateRegistry.registerCrate(Items.redstone, "cratedRedstone"); - crateRegistry.registerCrate(new ItemStack(Items.dye, 1, 4), "cratedLapis"); - crateRegistry.registerCrate(Items.reeds, "cratedReeds"); - crateRegistry.registerCrate(Items.clay_ball, "cratedClay"); - crateRegistry.registerCrate(Items.glowstone_dust, "cratedGlowstone"); - crateRegistry.registerCrate(Items.apple, "cratedApples"); - crateRegistry.registerCrate(new ItemStack(Items.nether_wart), "cratedNetherwart"); - crateRegistry.registerCrate(new ItemStack(Items.coal, 1, 1), "cratedCharcoal"); - crateRegistry.registerCrate(new ItemStack(Items.coal, 1, 0), "cratedCoal"); - crateRegistry.registerCrate(Items.wheat_seeds, "cratedSeeds"); - crateRegistry.registerCrate(Items.potato, "cratedPotatoes"); - crateRegistry.registerCrate(Items.carrot, "cratedCarrots"); + // vanilla items + crateRegistry.registerCrate(Items.wheat, "cratedWheat"); + crateRegistry.registerCrate(Items.cookie, "cratedCookies"); + crateRegistry.registerCrate(Items.redstone, "cratedRedstone"); + crateRegistry.registerCrate(new ItemStack(Items.dye, 1, 4), "cratedLapis"); + crateRegistry.registerCrate(Items.reeds, "cratedReeds"); + crateRegistry.registerCrate(Items.clay_ball, "cratedClay"); + crateRegistry.registerCrate(Items.glowstone_dust, "cratedGlowstone"); + crateRegistry.registerCrate(Items.apple, "cratedApples"); + crateRegistry.registerCrate(new ItemStack(Items.nether_wart), "cratedNetherwart"); + crateRegistry.registerCrate(new ItemStack(Items.coal, 1, 1), "cratedCharcoal"); + crateRegistry.registerCrate(new ItemStack(Items.coal, 1, 0), "cratedCoal"); + crateRegistry.registerCrate(Items.wheat_seeds, "cratedSeeds"); + crateRegistry.registerCrate(Items.potato, "cratedPotatoes"); + crateRegistry.registerCrate(Items.carrot, "cratedCarrots"); - // vanilla blocks - crateRegistry.registerCrate(new ItemStack(Blocks.log, 1, 0), "cratedWood"); - crateRegistry.registerCrate(new ItemStack(Blocks.log, 1, 1), "cratedSpruceWood"); - crateRegistry.registerCrate(new ItemStack(Blocks.log, 1, 2), "cratedBirchWood"); - crateRegistry.registerCrate(new ItemStack(Blocks.log, 1, 3), "cratedJungleWood"); - crateRegistry.registerCrate(new ItemStack(Blocks.log2, 1, 0), "cratedAcaciaWood"); - crateRegistry.registerCrate(new ItemStack(Blocks.log2, 1, 1), "cratedDarkOakWood"); - crateRegistry.registerCrate(Blocks.cobblestone, "cratedCobblestone"); - crateRegistry.registerCrate(new ItemStack(Blocks.dirt, 1, 0), "cratedDirt"); - crateRegistry.registerCrate(new ItemStack(Blocks.dirt, 1, 2), "cratedPodzol"); - crateRegistry.registerCrate(Blocks.stone, "cratedStone"); - crateRegistry.registerCrate(Blocks.brick_block, "cratedBrick"); - crateRegistry.registerCrate(Blocks.cactus, "cratedCacti"); - crateRegistry.registerCrate(new ItemStack(Blocks.sand, 1, 0), "cratedSand"); - crateRegistry.registerCrate(new ItemStack(Blocks.sand, 1, 1), "cratedRedSand"); - crateRegistry.registerCrate(Blocks.obsidian, "cratedObsidian"); - crateRegistry.registerCrate(Blocks.netherrack, "cratedNetherrack"); - crateRegistry.registerCrate(Blocks.soul_sand, "cratedSoulsand"); - crateRegistry.registerCrate(Blocks.sandstone, "cratedSandstone"); - crateRegistry.registerCrate(Blocks.nether_brick, "cratedNetherbrick"); - crateRegistry.registerCrate(Blocks.mycelium, "cratedMycelium"); - crateRegistry.registerCrate(Blocks.gravel, "cratedGravel"); - crateRegistry.registerCrate(new ItemStack(Blocks.sapling, 1, 0), "cratedSaplings"); - crateRegistry.registerCrate(new ItemStack(Blocks.sapling, 1, 1), "cratedSpruceSapling"); - crateRegistry.registerCrate(new ItemStack(Blocks.sapling, 1, 2), "cratedBirchSapling"); - crateRegistry.registerCrate(new ItemStack(Blocks.sapling, 1, 3), "cratedJungleSapling"); - crateRegistry.registerCrate(new ItemStack(Blocks.sapling, 1, 4), "cratedAcaciaSapling"); - crateRegistry.registerCrate(new ItemStack(Blocks.sapling, 1, 5), "cratedDarkOakSapling"); - } + // vanilla blocks + crateRegistry.registerCrate(new ItemStack(Blocks.log, 1, 0), "cratedWood"); + crateRegistry.registerCrate(new ItemStack(Blocks.log, 1, 1), "cratedSpruceWood"); + crateRegistry.registerCrate(new ItemStack(Blocks.log, 1, 2), "cratedBirchWood"); + crateRegistry.registerCrate(new ItemStack(Blocks.log, 1, 3), "cratedJungleWood"); + crateRegistry.registerCrate(new ItemStack(Blocks.log2, 1, 0), "cratedAcaciaWood"); + crateRegistry.registerCrate(new ItemStack(Blocks.log2, 1, 1), "cratedDarkOakWood"); + crateRegistry.registerCrate(Blocks.cobblestone, "cratedCobblestone"); + crateRegistry.registerCrate(new ItemStack(Blocks.dirt, 1, 0), "cratedDirt"); + crateRegistry.registerCrate(new ItemStack(Blocks.dirt, 1, 2), "cratedPodzol"); + crateRegistry.registerCrate(Blocks.stone, "cratedStone"); + crateRegistry.registerCrate(Blocks.brick_block, "cratedBrick"); + crateRegistry.registerCrate(Blocks.cactus, "cratedCacti"); + crateRegistry.registerCrate(new ItemStack(Blocks.sand, 1, 0), "cratedSand"); + crateRegistry.registerCrate(new ItemStack(Blocks.sand, 1, 1), "cratedRedSand"); + crateRegistry.registerCrate(Blocks.obsidian, "cratedObsidian"); + crateRegistry.registerCrate(Blocks.netherrack, "cratedNetherrack"); + crateRegistry.registerCrate(Blocks.soul_sand, "cratedSoulsand"); + crateRegistry.registerCrate(Blocks.sandstone, "cratedSandstone"); + crateRegistry.registerCrate(Blocks.nether_brick, "cratedNetherbrick"); + crateRegistry.registerCrate(Blocks.mycelium, "cratedMycelium"); + crateRegistry.registerCrate(Blocks.gravel, "cratedGravel"); + crateRegistry.registerCrate(new ItemStack(Blocks.sapling, 1, 0), "cratedSaplings"); + crateRegistry.registerCrate(new ItemStack(Blocks.sapling, 1, 1), "cratedSpruceSapling"); + crateRegistry.registerCrate(new ItemStack(Blocks.sapling, 1, 2), "cratedBirchSapling"); + crateRegistry.registerCrate(new ItemStack(Blocks.sapling, 1, 3), "cratedJungleSapling"); + crateRegistry.registerCrate(new ItemStack(Blocks.sapling, 1, 4), "cratedAcaciaSapling"); + crateRegistry.registerCrate(new ItemStack(Blocks.sapling, 1, 5), "cratedDarkOakSapling"); + } - @Override - protected void registerRecipes() { + @Override + protected void registerRecipes() { - /* SMELTING RECIPES */ - RecipeUtil.addSmelting(blocks.resources.get(BlockResourceOre.ResourceType.APATITE, 1), items.apatite, 0.5f); - RecipeUtil.addSmelting(blocks.resources.get(BlockResourceOre.ResourceType.COPPER, 1), items.ingotCopper, 0.5f); - RecipeUtil.addSmelting(blocks.resources.get(BlockResourceOre.ResourceType.TIN, 1), items.ingotTin, 0.5f); - RecipeUtil.addSmelting(new ItemStack(items.peat), items.ash, 0.0f); + /* SMELTING RECIPES */ + RecipeUtil.addSmelting(blocks.resources.get(BlockResourceOre.ResourceType.APATITE, 1), items.apatite, 0.5f); + RecipeUtil.addSmelting(blocks.resources.get(BlockResourceOre.ResourceType.COPPER, 1), items.ingotCopper, 0.5f); + RecipeUtil.addSmelting(blocks.resources.get(BlockResourceOre.ResourceType.TIN, 1), items.ingotTin, 0.5f); + RecipeUtil.addSmelting(new ItemStack(items.peat), items.ash, 0.0f); - /* BRONZE INGOTS */ - if (Config.isCraftingBronzeEnabled()) { - RecipeUtil.addShapelessRecipe(new ItemStack(items.ingotBronze, 4), "ingotTin", "ingotCopper", "ingotCopper", "ingotCopper"); - } + /* BRONZE INGOTS */ + if (Config.isCraftingBronzeEnabled()) { + RecipeUtil.addShapelessRecipe( + new ItemStack(items.ingotBronze, 4), "ingotTin", "ingotCopper", "ingotCopper", "ingotCopper"); + } - /* STURDY MACHINE */ - RecipeUtil.addRecipe(items.sturdyCasing, "###", "# #", "###", '#', "ingotBronze"); + /* STURDY MACHINE */ + RecipeUtil.addRecipe(items.sturdyCasing, "###", "# #", "###", '#', "ingotBronze"); - // / EMPTY CANS - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.can"), " # ", "# #", '#', "ingotTin"); + // / EMPTY CANS + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.can"), " # ", "# #", '#', "ingotTin"); - // / GEARS - ArrayList stoneGear = OreDictionary.getOres("gearStone"); - Object gearCenter; - if (!stoneGear.isEmpty()) { - gearCenter = "gearStone"; - } else { - gearCenter = "ingotCopper"; - } - RecipeUtil.addRecipe(items.gearBronze, " # ", "#X#", " # ", '#', "ingotBronze", 'X', gearCenter); - RecipeUtil.addRecipe(items.gearCopper, " # ", "#X#", " # ", '#', "ingotCopper", 'X', gearCenter); - RecipeUtil.addRecipe(items.gearTin, " # ", "#X#", " # ", '#', "ingotTin", 'X', gearCenter); + // / GEARS + ArrayList stoneGear = OreDictionary.getOres("gearStone"); + Object gearCenter; + if (!stoneGear.isEmpty()) { + gearCenter = "gearStone"; + } else { + gearCenter = "ingotCopper"; + } + RecipeUtil.addRecipe(items.gearBronze, " # ", "#X#", " # ", '#', "ingotBronze", 'X', gearCenter); + RecipeUtil.addRecipe(items.gearCopper, " # ", "#X#", " # ", '#', "ingotCopper", 'X', gearCenter); + RecipeUtil.addRecipe(items.gearTin, " # ", "#X#", " # ", '#', "ingotTin", 'X', gearCenter); - // / SURVIVALIST TOOLS - RecipeUtil.addRecipe(items.bronzePickaxe, " X ", " X ", "###", '#', "ingotBronze", 'X', "stickWood"); - RecipeUtil.addRecipe(items.bronzeShovel, " X ", " X ", " # ", '#', "ingotBronze", 'X', "stickWood"); - RecipeUtil.addShapelessRecipe(items.kitPickaxe, items.bronzePickaxe, items.carton); - RecipeUtil.addShapelessRecipe(items.kitShovel, items.bronzeShovel, items.carton); + // / SURVIVALIST TOOLS + RecipeUtil.addRecipe(items.bronzePickaxe, " X ", " X ", "###", '#', "ingotBronze", 'X', "stickWood"); + RecipeUtil.addRecipe(items.bronzeShovel, " X ", " X ", " # ", '#', "ingotBronze", 'X', "stickWood"); + RecipeUtil.addShapelessRecipe(items.kitPickaxe, items.bronzePickaxe, items.carton); + RecipeUtil.addShapelessRecipe(items.kitShovel, items.bronzeShovel, items.carton); - /* NATURALIST'S ARMOR */ - RecipeUtil.addRecipe(items.spectacles, " X ", "Y Y", 'X', "ingotBronze", 'Y', "paneGlass"); + /* NATURALIST'S ARMOR */ + RecipeUtil.addRecipe(items.spectacles, " X ", "Y Y", 'X', "ingotBronze", 'Y', "paneGlass"); - // / WRENCH - RecipeUtil.addRecipe(items.wrench, "# #", " # ", " # ", '#', "ingotBronze"); + // / WRENCH + RecipeUtil.addRecipe(items.wrench, "# #", " # ", " # ", '#', "ingotBronze"); - // Manure and Fertilizer - if (ForestryAPI.activeMode.getStackSetting("recipe.output.compost.wheat").stackSize > 0) { - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.compost.wheat"), " X ", "X#X", " X ", '#', Blocks.dirt, 'X', "cropWheat"); - } - if (ForestryAPI.activeMode.getStackSetting("recipe.output.compost.ash").stackSize > 0) { - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.compost.ash"), " X ", "X#X", " X ", '#', Blocks.dirt, 'X', "dustAsh"); - } - if (ForestryAPI.activeMode.getStackSetting("recipe.output.fertilizer.apatite").stackSize > 0) { - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.fertilizer.apatite"), " # ", " X ", " # ", '#', "sand", 'X', "gemApatite"); - } - if (ForestryAPI.activeMode.getStackSetting("recipe.output.fertilizer.ash").stackSize > 0) { - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.fertilizer.ash"), "###", "#X#", "###", '#', "dustAsh", 'X', "gemApatite"); - } + // Manure and Fertilizer + if (ForestryAPI.activeMode.getStackSetting("recipe.output.compost.wheat").stackSize > 0) { + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.compost.wheat"), + " X ", + "X#X", + " X ", + '#', + Blocks.dirt, + 'X', + "cropWheat"); + } + if (ForestryAPI.activeMode.getStackSetting("recipe.output.compost.ash").stackSize > 0) { + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.compost.ash"), + " X ", + "X#X", + " X ", + '#', + Blocks.dirt, + 'X', + "dustAsh"); + } + if (ForestryAPI.activeMode.getStackSetting("recipe.output.fertilizer.apatite").stackSize > 0) { + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.fertilizer.apatite"), + " # ", + " X ", + " # ", + '#', + "sand", + 'X', + "gemApatite"); + } + if (ForestryAPI.activeMode.getStackSetting("recipe.output.fertilizer.ash").stackSize > 0) { + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.fertilizer.ash"), + "###", + "#X#", + "###", + '#', + "dustAsh", + 'X', + "gemApatite"); + } - // Humus - if (ForestryAPI.activeMode.getStackSetting("recipe.output.humus.compost").stackSize > 0) { - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.humus.compost"), "###", "#X#", "###", '#', Blocks.dirt, 'X', items.fertilizerBio); - } - if (ForestryAPI.activeMode.getStackSetting("recipe.output.humus.fertilizer").stackSize > 0) { - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.humus.fertilizer"), "###", "#X#", "###", '#', Blocks.dirt, 'X', items.fertilizerCompound); - } + // Humus + if (ForestryAPI.activeMode.getStackSetting("recipe.output.humus.compost").stackSize > 0) { + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.humus.compost"), + "###", + "#X#", + "###", + '#', + Blocks.dirt, + 'X', + items.fertilizerBio); + } + if (ForestryAPI.activeMode.getStackSetting("recipe.output.humus.fertilizer").stackSize > 0) { + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.humus.fertilizer"), + "###", + "#X#", + "###", + '#', + Blocks.dirt, + 'X', + items.fertilizerCompound); + } - // Bog earth - if (ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.bucket").stackSize > 0) { - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.bucket"), "#Y#", "YXY", "#Y#", '#', Blocks.dirt, 'X', Items.water_bucket, 'Y', "sand"); - } + // Bog earth + if (ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.bucket").stackSize > 0) { + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.bucket"), + "#Y#", + "YXY", + "#Y#", + '#', + Blocks.dirt, + 'X', + Items.water_bucket, + 'Y', + "sand"); + } - if (ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.can").stackSize > 0) { - ItemStack canWater = PluginFluids.items.getContainer(EnumContainerType.CAN, Fluids.WATER).getItemStack(); - ItemStack waxCapsuleWater = PluginFluids.items.getContainer(EnumContainerType.CAPSULE, Fluids.WATER).getItemStack(); - ItemStack refractoryWater = PluginFluids.items.getContainer(EnumContainerType.REFRACTORY, Fluids.WATER).getItemStack(); - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.can"), "#Y#", "YXY", "#Y#", '#', Blocks.dirt, 'X', canWater, 'Y', "sand"); - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.can"), "#Y#", "YXY", "#Y#", '#', Blocks.dirt, 'X', waxCapsuleWater, 'Y', "sand"); - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.can"), "#Y#", "YXY", "#Y#", '#', Blocks.dirt, 'X', refractoryWater, 'Y', "sand"); - } + if (ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.can").stackSize > 0) { + ItemStack canWater = PluginFluids.items + .getContainer(EnumContainerType.CAN, Fluids.WATER) + .getItemStack(); + ItemStack waxCapsuleWater = PluginFluids.items + .getContainer(EnumContainerType.CAPSULE, Fluids.WATER) + .getItemStack(); + ItemStack refractoryWater = PluginFluids.items + .getContainer(EnumContainerType.REFRACTORY, Fluids.WATER) + .getItemStack(); + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.can"), + "#Y#", + "YXY", + "#Y#", + '#', + Blocks.dirt, + 'X', + canWater, + 'Y', + "sand"); + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.can"), + "#Y#", + "YXY", + "#Y#", + '#', + Blocks.dirt, + 'X', + waxCapsuleWater, + 'Y', + "sand"); + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.can"), + "#Y#", + "YXY", + "#Y#", + '#', + Blocks.dirt, + 'X', + refractoryWater, + 'Y', + "sand"); + } - // Crafting Material - RecipeUtil.addRecipe(new ItemStack(Items.string), "#", "#", "#", '#', items.craftingMaterial.getSilkWisp()); + // Crafting Material + RecipeUtil.addRecipe(new ItemStack(Items.string), "#", "#", "#", '#', items.craftingMaterial.getSilkWisp()); - // / Pipette - RecipeUtil.addRecipe(items.pipette, " #", " X ", "X ", 'X', "paneGlass", '#', new ItemStack(Blocks.wool, 1, OreDictionary.WILDCARD_VALUE)); + // / Pipette + RecipeUtil.addRecipe( + items.pipette, + " #", + " X ", + "X ", + 'X', + "paneGlass", + '#', + new ItemStack(Blocks.wool, 1, OreDictionary.WILDCARD_VALUE)); - // Storage Blocks - RecipeUtil.addRecipe(blocks.resourceStorage.get(BlockResourceStorage.ResourceType.APATITE), "###", "###", "###", '#', "gemApatite"); - RecipeUtil.addShapelessRecipe(new ItemStack(items.apatite, 9), "blockApatite"); + // Storage Blocks + RecipeUtil.addRecipe( + blocks.resourceStorage.get(BlockResourceStorage.ResourceType.APATITE), + "###", + "###", + "###", + '#', + "gemApatite"); + RecipeUtil.addShapelessRecipe(new ItemStack(items.apatite, 9), "blockApatite"); - RecipeUtil.addRecipe(blocks.resourceStorage.get(BlockResourceStorage.ResourceType.COPPER), "###", "###", "###", '#', "ingotCopper"); - RecipeUtil.addShapelessRecipe(new ItemStack(items.ingotCopper, 9), "blockCopper"); + RecipeUtil.addRecipe( + blocks.resourceStorage.get(BlockResourceStorage.ResourceType.COPPER), + "###", + "###", + "###", + '#', + "ingotCopper"); + RecipeUtil.addShapelessRecipe(new ItemStack(items.ingotCopper, 9), "blockCopper"); - RecipeUtil.addRecipe(blocks.resourceStorage.get(BlockResourceStorage.ResourceType.TIN), "###", "###", "###", '#', "ingotTin"); - RecipeUtil.addShapelessRecipe(new ItemStack(items.ingotTin, 9), "blockTin"); + RecipeUtil.addRecipe( + blocks.resourceStorage.get(BlockResourceStorage.ResourceType.TIN), + "###", + "###", + "###", + '#', + "ingotTin"); + RecipeUtil.addShapelessRecipe(new ItemStack(items.ingotTin, 9), "blockTin"); - RecipeUtil.addRecipe(blocks.resourceStorage.get(BlockResourceStorage.ResourceType.BRONZE), "###", "###", "###", '#', "ingotBronze"); - RecipeUtil.addShapelessRecipe(new ItemStack(items.ingotBronze, 9), "blockBronze"); - } + RecipeUtil.addRecipe( + blocks.resourceStorage.get(BlockResourceStorage.ResourceType.BRONZE), + "###", + "###", + "###", + '#', + "ingotBronze"); + RecipeUtil.addShapelessRecipe(new ItemStack(items.ingotBronze, 9), "blockBronze"); + } - @Override - public IPacketRegistry getPacketRegistry() { - return new PacketRegistryCore(); - } + @Override + public IPacketRegistry getPacketRegistry() { + return new PacketRegistryCore(); + } - @Override - public IPickupHandler getPickupHandler() { - return new PickupHandlerCore(); - } + @Override + public IPickupHandler getPickupHandler() { + return new PickupHandlerCore(); + } - @Override - public ICommand[] getConsoleCommands() { - return new ICommand[]{rootCommand}; - } + @Override + public ICommand[] getConsoleCommands() { + return new ICommand[] {rootCommand}; + } - @Override - public IFuelHandler getFuelHandler() { - return new FuelHandler(); - } + @Override + public IFuelHandler getFuelHandler() { + return new FuelHandler(); + } - private static class FuelHandler implements IFuelHandler { + private static class FuelHandler implements IFuelHandler { - @Override - public int getBurnTime(ItemStack fuel) { - if (fuel != null && fuel.getItem() == items.peat) { - return 2000; - } - if (fuel != null && fuel.getItem() == items.bituminousPeat) { - return 4200; - } + @Override + public int getBurnTime(ItemStack fuel) { + if (fuel != null && fuel.getItem() == items.peat) { + return 2000; + } + if (fuel != null && fuel.getItem() == items.bituminousPeat) { + return 4200; + } - return 0; - } - } + return 0; + } + } } diff --git a/src/main/java/forestry/plugins/PluginEnergy.java b/src/main/java/forestry/plugins/PluginEnergy.java index 60e88b9bb..9a1921de6 100755 --- a/src/main/java/forestry/plugins/PluginEnergy.java +++ b/src/main/java/forestry/plugins/PluginEnergy.java @@ -10,11 +10,7 @@ ******************************************************************************/ package forestry.plugins; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; - import cpw.mods.fml.common.SidedProxy; - import forestry.api.core.ForestryAPI; import forestry.core.config.Constants; import forestry.core.recipes.RecipeUtil; @@ -22,69 +18,92 @@ import forestry.energy.blocks.BlockEngineType; import forestry.energy.blocks.BlockRegistryEnergy; import forestry.energy.proxy.ProxyEnergy; import forestry.energy.tiles.EngineDefinition; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; -@Plugin(pluginID = "Energy", name = "Energy", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.energy.description") +@Plugin( + pluginID = "Energy", + name = "Energy", + author = "SirSengir", + url = Constants.URL, + unlocalizedDescription = "for.plugin.energy.description") public class PluginEnergy extends ForestryPlugin { - @SidedProxy(clientSide = "forestry.energy.proxy.ProxyEnergyClient", serverSide = "forestry.energy.proxy.ProxyEnergy") - public static ProxyEnergy proxy; + @SidedProxy( + clientSide = "forestry.energy.proxy.ProxyEnergyClient", + serverSide = "forestry.energy.proxy.ProxyEnergy") + public static ProxyEnergy proxy; - public static BlockRegistryEnergy blocks; + public static BlockRegistryEnergy blocks; - @Override - protected void registerItemsAndBlocks() { - blocks = new BlockRegistryEnergy(); - } + @Override + protected void registerItemsAndBlocks() { + blocks = new BlockRegistryEnergy(); + } - @Override - public void preInit() { - blocks.engine.addDefinitions( - new EngineDefinition(BlockEngineType.PEAT), - new EngineDefinition(BlockEngineType.BIOGAS) - ); + @Override + public void preInit() { + blocks.engine.addDefinitions( + new EngineDefinition(BlockEngineType.PEAT), new EngineDefinition(BlockEngineType.BIOGAS)); - if (ForestryAPI.activeMode.getBooleanSetting("energy.engine.clockwork")) { - blocks.engine.addDefinition(new EngineDefinition(BlockEngineType.CLOCKWORK)); - } - } + if (ForestryAPI.activeMode.getBooleanSetting("energy.engine.clockwork")) { + blocks.engine.addDefinition(new EngineDefinition(BlockEngineType.CLOCKWORK)); + } + } - @Override - public void doInit() { - blocks.engine.init(); - } + @Override + public void doInit() { + blocks.engine.init(); + } - @Override - protected void registerRecipes() { - super.registerRecipes(); + @Override + protected void registerRecipes() { + super.registerRecipes(); - RecipeUtil.addRecipe(blocks.engine.get(BlockEngineType.PEAT), - "###", - " X ", - "YVY", - '#', "ingotCopper", - 'X', "blockGlass", - 'Y', "gearCopper", - 'V', Blocks.piston); + RecipeUtil.addRecipe( + blocks.engine.get(BlockEngineType.PEAT), + "###", + " X ", + "YVY", + '#', + "ingotCopper", + 'X', + "blockGlass", + 'Y', + "gearCopper", + 'V', + Blocks.piston); - RecipeUtil.addRecipe(blocks.engine.get(BlockEngineType.BIOGAS), - "###", - " X ", - "YVY", - '#', "ingotBronze", - 'X', "blockGlass", - 'Y', "gearBronze", - 'V', Blocks.piston); + RecipeUtil.addRecipe( + blocks.engine.get(BlockEngineType.BIOGAS), + "###", + " X ", + "YVY", + '#', + "ingotBronze", + 'X', + "blockGlass", + 'Y', + "gearBronze", + 'V', + Blocks.piston); - if (ForestryAPI.activeMode.getBooleanSetting("energy.engine.clockwork")) { - RecipeUtil.addRecipe(blocks.engine.get(BlockEngineType.CLOCKWORK), - "###", - " X ", - "ZVY", - '#', "plankWood", - 'X', "blockGlass", - 'Y', Items.clock, - 'Z', "gearCopper", - 'V', Blocks.piston); - } - } + if (ForestryAPI.activeMode.getBooleanSetting("energy.engine.clockwork")) { + RecipeUtil.addRecipe( + blocks.engine.get(BlockEngineType.CLOCKWORK), + "###", + " X ", + "ZVY", + '#', + "plankWood", + 'X', + "blockGlass", + 'Y', + Items.clock, + 'Z', + "gearCopper", + 'V', + Blocks.piston); + } + } } diff --git a/src/main/java/forestry/plugins/PluginFactory.java b/src/main/java/forestry/plugins/PluginFactory.java index 540f7918a..64d4228db 100644 --- a/src/main/java/forestry/plugins/PluginFactory.java +++ b/src/main/java/forestry/plugins/PluginFactory.java @@ -11,14 +11,6 @@ package forestry.plugins; import com.google.common.collect.ImmutableList; - -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.CircuitSocketType; import forestry.api.circuits.ICircuitLayout; @@ -66,460 +58,746 @@ import forestry.factory.recipes.MoistenerRecipeManager; import forestry.factory.recipes.SqueezerRecipeManager; import forestry.factory.recipes.StillRecipeManager; import forestry.factory.triggers.FactoryTriggers; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; -@Plugin(pluginID = "Factory", name = "Factory", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.factory.description") +@Plugin( + pluginID = "Factory", + name = "Factory", + author = "SirSengir", + url = Constants.URL, + unlocalizedDescription = "for.plugin.factory.description") public class PluginFactory extends ForestryPlugin { - public static BlockRegistryFactory blocks; + public static BlockRegistryFactory blocks; - @Override - protected void setupAPI() { - super.setupAPI(); + @Override + protected void setupAPI() { + super.setupAPI(); - RecipeManagers.craftingProviders = ImmutableList.of( - RecipeManagers.carpenterManager = new CarpenterRecipeManager(), - RecipeManagers.centrifugeManager = new CentrifugeRecipeManager(), - RecipeManagers.fabricatorManager = new FabricatorRecipeManager(), - RecipeManagers.fabricatorSmeltingManager = new FabricatorSmeltingRecipeManager(), - RecipeManagers.fermenterManager = new FermenterRecipeManager(), - RecipeManagers.moistenerManager = new MoistenerRecipeManager(), - RecipeManagers.squeezerManager = new SqueezerRecipeManager(), - RecipeManagers.stillManager = new StillRecipeManager() - ); + RecipeManagers.craftingProviders = ImmutableList.of( + RecipeManagers.carpenterManager = new CarpenterRecipeManager(), + RecipeManagers.centrifugeManager = new CentrifugeRecipeManager(), + RecipeManagers.fabricatorManager = new FabricatorRecipeManager(), + RecipeManagers.fabricatorSmeltingManager = new FabricatorSmeltingRecipeManager(), + RecipeManagers.fermenterManager = new FermenterRecipeManager(), + RecipeManagers.moistenerManager = new MoistenerRecipeManager(), + RecipeManagers.squeezerManager = new SqueezerRecipeManager(), + RecipeManagers.stillManager = new StillRecipeManager()); - setupFuelManager(); - } + setupFuelManager(); + } - @Override - protected void disabledSetupAPI() { - super.disabledSetupAPI(); + @Override + protected void disabledSetupAPI() { + super.disabledSetupAPI(); - RecipeManagers.craftingProviders = ImmutableList.of( - RecipeManagers.carpenterManager = new DummyManagers.DummyCarpenterManager(), - RecipeManagers.centrifugeManager = new DummyManagers.DummyCentrifugeManager(), - RecipeManagers.fabricatorManager = new DummyManagers.DummyFabricatorManager(), - RecipeManagers.fabricatorSmeltingManager = new DummyManagers.DummyFabricatorSmeltingManager(), - RecipeManagers.fermenterManager = new DummyManagers.DummyFermenterManager(), - RecipeManagers.moistenerManager = new DummyManagers.DummyMoistenerManager(), - RecipeManagers.squeezerManager = new DummyManagers.DummySqueezerManager(), - RecipeManagers.stillManager = new DummyManagers.DummyStillManager() - ); + RecipeManagers.craftingProviders = ImmutableList.of( + RecipeManagers.carpenterManager = new DummyManagers.DummyCarpenterManager(), + RecipeManagers.centrifugeManager = new DummyManagers.DummyCentrifugeManager(), + RecipeManagers.fabricatorManager = new DummyManagers.DummyFabricatorManager(), + RecipeManagers.fabricatorSmeltingManager = new DummyManagers.DummyFabricatorSmeltingManager(), + RecipeManagers.fermenterManager = new DummyManagers.DummyFermenterManager(), + RecipeManagers.moistenerManager = new DummyManagers.DummyMoistenerManager(), + RecipeManagers.squeezerManager = new DummyManagers.DummySqueezerManager(), + RecipeManagers.stillManager = new DummyManagers.DummyStillManager()); - setupFuelManager(); - } + setupFuelManager(); + } - private static void setupFuelManager() { - FuelManager.fermenterFuel = new ItemStackMap<>(); - FuelManager.moistenerResource = new ItemStackMap<>(); - FuelManager.rainSubstrate = new ItemStackMap<>(); - FuelManager.bronzeEngineFuel = new FluidMap<>(); - FuelManager.copperEngineFuel = new ItemStackMap<>(); - FuelManager.generatorFuel = new FluidMap<>(); - } + private static void setupFuelManager() { + FuelManager.fermenterFuel = new ItemStackMap<>(); + FuelManager.moistenerResource = new ItemStackMap<>(); + FuelManager.rainSubstrate = new ItemStackMap<>(); + FuelManager.bronzeEngineFuel = new FluidMap<>(); + FuelManager.copperEngineFuel = new ItemStackMap<>(); + FuelManager.generatorFuel = new FluidMap<>(); + } - @Override - protected void registerItemsAndBlocks() { - blocks = new BlockRegistryFactory(); - } + @Override + protected void registerItemsAndBlocks() { + blocks = new BlockRegistryFactory(); + } - @Override - public IPacketRegistry getPacketRegistry() { - return new PacketRegistryFactory(); - } + @Override + public IPacketRegistry getPacketRegistry() { + return new PacketRegistryFactory(); + } - @Override - public void preInit() { - super.preInit(); + @Override + public void preInit() { + super.preInit(); - ItemRegistryCore coreItems = PluginCore.items; + ItemRegistryCore coreItems = PluginCore.items; - // Set fuels and resources for the fermenter - ItemStack fertilizerCompound = coreItems.fertilizerCompound.getItemStack(); - FuelManager.fermenterFuel.put(fertilizerCompound, new FermenterFuel(fertilizerCompound, - ForestryAPI.activeMode.getIntegerSetting("fermenter.value.fertilizer"), ForestryAPI.activeMode.getIntegerSetting("fermenter.cycles.fertilizer"))); + // Set fuels and resources for the fermenter + ItemStack fertilizerCompound = coreItems.fertilizerCompound.getItemStack(); + FuelManager.fermenterFuel.put( + fertilizerCompound, + new FermenterFuel( + fertilizerCompound, + ForestryAPI.activeMode.getIntegerSetting("fermenter.value.fertilizer"), + ForestryAPI.activeMode.getIntegerSetting("fermenter.cycles.fertilizer"))); - int cyclesCompost = ForestryAPI.activeMode.getIntegerSetting("fermenter.cycles.compost"); - int valueCompost = ForestryAPI.activeMode.getIntegerSetting("fermenter.value.compost"); - ItemStack fertilizerBio = coreItems.fertilizerBio.getItemStack(); - ItemStack mulch = coreItems.mulch.getItemStack(); - FuelManager.fermenterFuel.put(fertilizerBio, new FermenterFuel(fertilizerBio, valueCompost, cyclesCompost)); - FuelManager.fermenterFuel.put(mulch, new FermenterFuel(mulch, valueCompost, cyclesCompost)); + int cyclesCompost = ForestryAPI.activeMode.getIntegerSetting("fermenter.cycles.compost"); + int valueCompost = ForestryAPI.activeMode.getIntegerSetting("fermenter.value.compost"); + ItemStack fertilizerBio = coreItems.fertilizerBio.getItemStack(); + ItemStack mulch = coreItems.mulch.getItemStack(); + FuelManager.fermenterFuel.put(fertilizerBio, new FermenterFuel(fertilizerBio, valueCompost, cyclesCompost)); + FuelManager.fermenterFuel.put(mulch, new FermenterFuel(mulch, valueCompost, cyclesCompost)); - // Add moistener resources - ItemStack wheat = new ItemStack(Items.wheat); - ItemStack mouldyWheat = coreItems.mouldyWheat.getItemStack(); - ItemStack decayingWheat = coreItems.decayingWheat.getItemStack(); - FuelManager.moistenerResource.put(wheat, new MoistenerFuel(wheat, mouldyWheat, 0, 300)); - FuelManager.moistenerResource.put(mouldyWheat, new MoistenerFuel(mouldyWheat, decayingWheat, 1, 600)); - FuelManager.moistenerResource.put(decayingWheat, new MoistenerFuel(decayingWheat, mulch, 2, 900)); + // Add moistener resources + ItemStack wheat = new ItemStack(Items.wheat); + ItemStack mouldyWheat = coreItems.mouldyWheat.getItemStack(); + ItemStack decayingWheat = coreItems.decayingWheat.getItemStack(); + FuelManager.moistenerResource.put(wheat, new MoistenerFuel(wheat, mouldyWheat, 0, 300)); + FuelManager.moistenerResource.put(mouldyWheat, new MoistenerFuel(mouldyWheat, decayingWheat, 1, 600)); + FuelManager.moistenerResource.put(decayingWheat, new MoistenerFuel(decayingWheat, mulch, 2, 900)); - // Set fuels for our own engines - ItemStack peat = coreItems.peat.getItemStack(); - FuelManager.copperEngineFuel.put(peat, new EngineCopperFuel(peat, Constants.ENGINE_COPPER_FUEL_VALUE_PEAT, Constants.ENGINE_COPPER_CYCLE_DURATION_PEAT)); + // Set fuels for our own engines + ItemStack peat = coreItems.peat.getItemStack(); + FuelManager.copperEngineFuel.put( + peat, + new EngineCopperFuel( + peat, Constants.ENGINE_COPPER_FUEL_VALUE_PEAT, Constants.ENGINE_COPPER_CYCLE_DURATION_PEAT)); - ItemStack bituminousPeat = coreItems.bituminousPeat.getItemStack(); - FuelManager.copperEngineFuel.put(bituminousPeat, new EngineCopperFuel(bituminousPeat, Constants.ENGINE_COPPER_FUEL_VALUE_BITUMINOUS_PEAT, Constants.ENGINE_COPPER_CYCLE_DURATION_BITUMINOUS_PEAT)); + ItemStack bituminousPeat = coreItems.bituminousPeat.getItemStack(); + FuelManager.copperEngineFuel.put( + bituminousPeat, + new EngineCopperFuel( + bituminousPeat, + Constants.ENGINE_COPPER_FUEL_VALUE_BITUMINOUS_PEAT, + Constants.ENGINE_COPPER_CYCLE_DURATION_BITUMINOUS_PEAT)); - FuelManager.bronzeEngineFuel.put(Fluids.BIOMASS.getFluid(), new EngineBronzeFuel(Fluids.BIOMASS.getFluid(), - Constants.ENGINE_FUEL_VALUE_BIOMASS, (int) (Constants.ENGINE_CYCLE_DURATION_BIOMASS * ForestryAPI.activeMode.getFloatSetting("fuel.biomass.biogas")), 1)); - FuelManager.bronzeEngineFuel.put(Fluids.WATER.getFluid(), new EngineBronzeFuel(Fluids.WATER.getFluid(), - Constants.ENGINE_FUEL_VALUE_WATER, Constants.ENGINE_CYCLE_DURATION_WATER, 3)); - FuelManager.bronzeEngineFuel.put(Fluids.MILK.getFluid(), new EngineBronzeFuel(Fluids.MILK.getFluid(), - Constants.ENGINE_FUEL_VALUE_MILK, Constants.ENGINE_CYCLE_DURATION_MILK, 3)); - FuelManager.bronzeEngineFuel.put(Fluids.SEEDOIL.getFluid(), new EngineBronzeFuel(Fluids.SEEDOIL.getFluid(), - Constants.ENGINE_FUEL_VALUE_SEED_OIL, Constants.ENGINE_CYCLE_DURATION_SEED_OIL, 1)); - FuelManager.bronzeEngineFuel.put(Fluids.HONEY.getFluid(), new EngineBronzeFuel(Fluids.HONEY.getFluid(), - Constants.ENGINE_FUEL_VALUE_HONEY, Constants.ENGINE_CYCLE_DURATION_HONEY, 1)); - FuelManager.bronzeEngineFuel.put(Fluids.JUICE.getFluid(), new EngineBronzeFuel(Fluids.JUICE.getFluid(), - Constants.ENGINE_FUEL_VALUE_JUICE, Constants.ENGINE_CYCLE_DURATION_JUICE, 1)); + FuelManager.bronzeEngineFuel.put( + Fluids.BIOMASS.getFluid(), + new EngineBronzeFuel( + Fluids.BIOMASS.getFluid(), + Constants.ENGINE_FUEL_VALUE_BIOMASS, + (int) (Constants.ENGINE_CYCLE_DURATION_BIOMASS + * ForestryAPI.activeMode.getFloatSetting("fuel.biomass.biogas")), + 1)); + FuelManager.bronzeEngineFuel.put( + Fluids.WATER.getFluid(), + new EngineBronzeFuel( + Fluids.WATER.getFluid(), + Constants.ENGINE_FUEL_VALUE_WATER, + Constants.ENGINE_CYCLE_DURATION_WATER, + 3)); + FuelManager.bronzeEngineFuel.put( + Fluids.MILK.getFluid(), + new EngineBronzeFuel( + Fluids.MILK.getFluid(), + Constants.ENGINE_FUEL_VALUE_MILK, + Constants.ENGINE_CYCLE_DURATION_MILK, + 3)); + FuelManager.bronzeEngineFuel.put( + Fluids.SEEDOIL.getFluid(), + new EngineBronzeFuel( + Fluids.SEEDOIL.getFluid(), + Constants.ENGINE_FUEL_VALUE_SEED_OIL, + Constants.ENGINE_CYCLE_DURATION_SEED_OIL, + 1)); + FuelManager.bronzeEngineFuel.put( + Fluids.HONEY.getFluid(), + new EngineBronzeFuel( + Fluids.HONEY.getFluid(), + Constants.ENGINE_FUEL_VALUE_HONEY, + Constants.ENGINE_CYCLE_DURATION_HONEY, + 1)); + FuelManager.bronzeEngineFuel.put( + Fluids.JUICE.getFluid(), + new EngineBronzeFuel( + Fluids.JUICE.getFluid(), + Constants.ENGINE_FUEL_VALUE_JUICE, + Constants.ENGINE_CYCLE_DURATION_JUICE, + 1)); - // Set rain substrates - ItemStack iodineCharge = coreItems.iodineCharge.getItemStack(); - ItemStack dissipationCharge = coreItems.craftingMaterial.getDissipationCharge(); - FuelManager.rainSubstrate.put(iodineCharge, new RainSubstrate(iodineCharge, Constants.RAINMAKER_RAIN_DURATION_IODINE, 0.01f)); - FuelManager.rainSubstrate.put(dissipationCharge, new RainSubstrate(dissipationCharge, 0.075f)); + // Set rain substrates + ItemStack iodineCharge = coreItems.iodineCharge.getItemStack(); + ItemStack dissipationCharge = coreItems.craftingMaterial.getDissipationCharge(); + FuelManager.rainSubstrate.put( + iodineCharge, new RainSubstrate(iodineCharge, Constants.RAINMAKER_RAIN_DURATION_IODINE, 0.01f)); + FuelManager.rainSubstrate.put(dissipationCharge, new RainSubstrate(dissipationCharge, 0.075f)); - for (BlockFactoryTesrType type : BlockFactoryTesrType.VALUES) { - MachineDefinition machineDefinition = new MachineDefinition(type); - blocks.factoryTESR.addDefinition(machineDefinition); - } + for (BlockFactoryTesrType type : BlockFactoryTesrType.VALUES) { + MachineDefinition machineDefinition = new MachineDefinition(type); + blocks.factoryTESR.addDefinition(machineDefinition); + } - blocks.factoryPlain.addDefinitions( - new MachineDefinition(BlockFactoryPlainType.FABRICATOR).setFaces(0, 1, 2, 3, 4, 4), - new MachineDefinition(BlockFactoryPlainType.RAINTANK).setFaces(0, 1, 0, 0, 0, 0), - new MachineDefinition(BlockFactoryPlainType.WORKTABLE).setFaces(0, 1, 2, 3, 4, 4) - ); + blocks.factoryPlain.addDefinitions( + new MachineDefinition(BlockFactoryPlainType.FABRICATOR).setFaces(0, 1, 2, 3, 4, 4), + new MachineDefinition(BlockFactoryPlainType.RAINTANK).setFaces(0, 1, 0, 0, 0, 0), + new MachineDefinition(BlockFactoryPlainType.WORKTABLE).setFaces(0, 1, 2, 3, 4, 4)); - ICircuitLayout layoutMachineUpgrade = new CircuitLayout("machine.upgrade", CircuitSocketType.MACHINE); - ChipsetManager.circuitRegistry.registerLayout(layoutMachineUpgrade); + ICircuitLayout layoutMachineUpgrade = new CircuitLayout("machine.upgrade", CircuitSocketType.MACHINE); + ChipsetManager.circuitRegistry.registerLayout(layoutMachineUpgrade); + } - } + @Override + protected void registerTriggers() { + FactoryTriggers.initialize(); + } - @Override - protected void registerTriggers() { - FactoryTriggers.initialize(); - } + @Override + public void doInit() { + super.doInit(); - @Override - public void doInit() { - super.doInit(); + blocks.factoryTESR.init(); + blocks.factoryPlain.init(); - blocks.factoryTESR.init(); - blocks.factoryPlain.init(); + Circuit.machineSpeedUpgrade1 = new CircuitSpeedUpgrade("machine.speed.boost.1", 0.125f, 0.05f, 4); + Circuit.machineSpeedUpgrade2 = new CircuitSpeedUpgrade("machine.speed.boost.2", 0.250f, 0.10f, 4); + Circuit.machineEfficiencyUpgrade1 = new CircuitSpeedUpgrade("machine.efficiency.1", 0, -0.10f, 2); + } - Circuit.machineSpeedUpgrade1 = new CircuitSpeedUpgrade("machine.speed.boost.1", 0.125f, 0.05f, 4); - Circuit.machineSpeedUpgrade2 = new CircuitSpeedUpgrade("machine.speed.boost.2", 0.250f, 0.10f, 4); - Circuit.machineEfficiencyUpgrade1 = new CircuitSpeedUpgrade("machine.efficiency.1", 0, -0.10f, 2); - } + @Override + public void postInit() { + super.postInit(); - @Override - public void postInit() { - super.postInit(); + if (ModUtil.isModLoaded("craftguide")) { + CraftGuideIntegration.register(); + } else { + Log.info("Skipping CraftGuide integration."); + } + } - if (ModUtil.isModLoaded("craftguide")) { - CraftGuideIntegration.register(); - } else { - Log.info("Skipping CraftGuide integration."); - } - } + @Override + protected void registerRecipes() { - @Override - protected void registerRecipes() { + // / FABRICATOR + ItemElectronTube electronTube = PluginCore.items.tubes; - // / FABRICATOR - ItemElectronTube electronTube = PluginCore.items.tubes; + EnumElectronTube.COPPER.registerTubeRecipe("ingotCopper"); + EnumElectronTube.BRONZE.registerTubeRecipe("ingotBronze"); + EnumElectronTube.TIN.registerTubeRecipe("ingotTin"); + EnumElectronTube.IRON.registerTubeRecipe("ingotIron"); + EnumElectronTube.GOLD.registerTubeRecipe("ingotGold"); + EnumElectronTube.DIAMOND.registerTubeRecipe("gemDiamond"); + EnumElectronTube.OBSIDIAN.registerTubeRecipe(new ItemStack(Blocks.obsidian)); + EnumElectronTube.BLAZE.registerTubeRecipe(new ItemStack(Items.blaze_powder)); + EnumElectronTube.EMERALD.registerTubeRecipe("gemEmerald"); + EnumElectronTube.APATITE.registerTubeRecipe("gemApatite"); + EnumElectronTube.LAPIS.registerTubeRecipe("gemLapis"); + RecipeManagers.fabricatorManager.addRecipe( + null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.ENDER, 4), new Object[] { + " X ", + "#X#", + "XXX", + '#', + new ItemStack(Items.ender_eye, 1, 0), + 'X', + new ItemStack(Blocks.end_stone, 1, 0) + }); - EnumElectronTube.COPPER.registerTubeRecipe("ingotCopper"); - EnumElectronTube.BRONZE.registerTubeRecipe("ingotBronze"); - EnumElectronTube.TIN.registerTubeRecipe("ingotTin"); - EnumElectronTube.IRON.registerTubeRecipe("ingotIron"); - EnumElectronTube.GOLD.registerTubeRecipe("ingotGold"); - EnumElectronTube.DIAMOND.registerTubeRecipe("gemDiamond"); - EnumElectronTube.OBSIDIAN.registerTubeRecipe(new ItemStack(Blocks.obsidian)); - EnumElectronTube.BLAZE.registerTubeRecipe(new ItemStack(Items.blaze_powder)); - EnumElectronTube.EMERALD.registerTubeRecipe("gemEmerald"); - EnumElectronTube.APATITE.registerTubeRecipe("gemApatite"); - EnumElectronTube.LAPIS.registerTubeRecipe("gemLapis"); - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.ENDER, 4), - new Object[]{" X ", "#X#", "XXX", '#', new ItemStack(Items.ender_eye, 1, 0), 'X', new ItemStack(Blocks.end_stone, 1, 0)}); + String[] dyes = { + "dyeBlack", + "dyeRed", + "dyeGreen", + "dyeBrown", + "dyeBlue", + "dyePurple", + "dyeCyan", + "dyeLightGray", + "dyeGray", + "dyePink", + "dyeLime", + "dyeYellow", + "dyeLightBlue", + "dyeMagenta", + "dyeOrange", + "dyeWhite" + }; - String[] dyes = {"dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", "dyePink", "dyeLime", - "dyeYellow", "dyeLightBlue", "dyeMagenta", "dyeOrange", "dyeWhite"}; + if (PluginManager.Module.APICULTURE.isEnabled()) { + ItemRegistryApiculture beeItems = PluginApiculture.items; + FluidStack liquidGlassX4 = Fluids.GLASS.getFluid(Constants.BUCKET_VOLUME * 4); + for (int i = 0; i < 16; i++) { + RecipeManagers.fabricatorManager.addRecipe( + beeItems.waxCast.getWildcard(), + liquidGlassX4, + new ItemStack(Blocks.stained_glass, 4, 15 - i), + new Object[] {"#", "X", '#', dyes[i], 'X', beeItems.propolis.getWildcard()}); + } + RecipeManagers.fabricatorManager.addRecipe( + beeItems.waxCast.getWildcard(), liquidGlassX4, new ItemStack(Blocks.glass, 4, 0), new Object[] { + "#", "X", 'X', beeItems.propolis.getWildcard() + }); + } - if (PluginManager.Module.APICULTURE.isEnabled()) { - ItemRegistryApiculture beeItems = PluginApiculture.items; - FluidStack liquidGlassX4 = Fluids.GLASS.getFluid(Constants.BUCKET_VOLUME * 4); - for (int i = 0; i < 16; i++) { - RecipeManagers.fabricatorManager.addRecipe(beeItems.waxCast.getWildcard(), liquidGlassX4, new ItemStack(Blocks.stained_glass, 4, 15 - i), new Object[]{ - "#", "X", - '#', dyes[i], - 'X', beeItems.propolis.getWildcard()}); - } - RecipeManagers.fabricatorManager.addRecipe(beeItems.waxCast.getWildcard(), liquidGlassX4, new ItemStack(Blocks.glass, 4, 0), new Object[]{ - "#", "X", - 'X', beeItems.propolis.getWildcard()}); - } + // / SQUEEZER + int appleMulchAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.mulch.apple"); + int appleJuiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); + RecipeManagers.squeezerManager.addRecipe( + 10, + new ItemStack[] {new ItemStack(Items.apple)}, + Fluids.JUICE.getFluid(appleJuiceAmount), + PluginCore.items.mulch.getItemStack(), + appleMulchAmount); - // / SQUEEZER - int appleMulchAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.mulch.apple"); - int appleJuiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Items.apple)}, Fluids.JUICE.getFluid(appleJuiceAmount), - PluginCore.items.mulch.getItemStack(), appleMulchAmount); + int seedOilAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); + FluidStack seedOil = Fluids.SEEDOIL.getFluid(seedOilAmount); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[] {new ItemStack(Items.wheat_seeds)}, seedOil); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[] {new ItemStack(Items.pumpkin_seeds)}, seedOil); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[] {new ItemStack(Items.melon_seeds)}, seedOil); + RecipeManagers.squeezerManager.addRecipe( + 10, + new ItemStack[] {PluginCore.items.phosphor.getItemStack(2), new ItemStack(Blocks.cobblestone)}, + Fluids.LAVA.getFluid(1600)); + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {new ItemStack(Blocks.cactus)}, Fluids.WATER.getFluid(500)); + RecipeManagers.squeezerManager.addRecipe( + 10, + new ItemStack[] {new ItemStack(Items.snowball), PluginCore.items.craftingMaterial.getIceShard(4)}, + Fluids.ICE.getFluid(4000)); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Items.carrot)}, Fluids.JUICE.getFluid(appleJuiceAmount), - PluginCore.items.mulch.getItemStack(), appleMulchAmount); - int seedOilAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - FluidStack seedOil = Fluids.SEEDOIL.getFluid(seedOilAmount); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Items.wheat_seeds)}, seedOil); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Items.pumpkin_seeds)}, seedOil); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Items.melon_seeds)}, seedOil); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{PluginCore.items.phosphor.getItemStack(2), new ItemStack(Blocks.cobblestone)}, Fluids.LAVA.getFluid(1600)); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Blocks.cactus)}, Fluids.WATER.getFluid(500)); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Items.snowball), PluginCore.items.craftingMaterial.getIceShard(4)}, Fluids.ICE.getFluid(4000)); + // STILL + RecipeManagers.stillManager.addRecipe( + Constants.STILL_DESTILLATION_DURATION, + Fluids.BIOMASS.getFluid(Constants.STILL_DESTILLATION_INPUT), + Fluids.ETHANOL.getFluid(Constants.STILL_DESTILLATION_OUTPUT)); - // STILL - RecipeManagers.stillManager.addRecipe(Constants.STILL_DESTILLATION_DURATION, Fluids.BIOMASS.getFluid(Constants.STILL_DESTILLATION_INPUT), - Fluids.ETHANOL.getFluid(Constants.STILL_DESTILLATION_OUTPUT)); + // convert old honey to new honey + if (FluidRegistry.isFluidRegistered(Fluids.LEGACY_HONEY.name())) { + RecipeManagers.stillManager.addRecipe(1, Fluids.LEGACY_HONEY.getFluid(1000), Fluids.HONEY.getFluid(1000)); + } - // convert old honey to new honey - if (FluidRegistry.isFluidRegistered(Fluids.LEGACY_HONEY.name())) { - RecipeManagers.stillManager.addRecipe(1, Fluids.LEGACY_HONEY.getFluid(1000), Fluids.HONEY.getFluid(1000)); - } + // MOISTENER + RecipeManagers.moistenerManager.addRecipe( + new ItemStack(Items.wheat_seeds), new ItemStack(Blocks.mycelium), 5000); + RecipeManagers.moistenerManager.addRecipe( + new ItemStack(Blocks.cobblestone), new ItemStack(Blocks.mossy_cobblestone), 20000); + RecipeManagers.moistenerManager.addRecipe( + new ItemStack(Blocks.stonebrick), new ItemStack(Blocks.stonebrick, 1, 1), 20000); - // MOISTENER - RecipeManagers.moistenerManager.addRecipe(new ItemStack(Items.wheat_seeds), new ItemStack(Blocks.mycelium), 5000); - RecipeManagers.moistenerManager.addRecipe(new ItemStack(Blocks.cobblestone), new ItemStack(Blocks.mossy_cobblestone), 20000); - RecipeManagers.moistenerManager.addRecipe(new ItemStack(Blocks.stonebrick), new ItemStack(Blocks.stonebrick, 1, 1), 20000); + // FERMENTER + for (int i = 0; i < 6; i++) { + RecipeUtil.addFermenterRecipes( + new ItemStack(Blocks.sapling, 1, i), + ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), + Fluids.BIOMASS); + } - // FERMENTER - for (int i = 0; i < 6; i++) { - RecipeUtil.addFermenterRecipes(new ItemStack(Blocks.sapling, 1, i), ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); - } + RecipeUtil.addFermenterRecipes( + new ItemStack(Blocks.cactus), + ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.cactus"), + Fluids.BIOMASS); + RecipeUtil.addFermenterRecipes( + new ItemStack(Items.wheat), + ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), + Fluids.BIOMASS); + RecipeUtil.addFermenterRecipes( + new ItemStack(Items.potato), + (2 * ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat")), + Fluids.BIOMASS); + RecipeUtil.addFermenterRecipes( + new ItemStack(Items.reeds), + ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.cane"), + Fluids.BIOMASS); + RecipeUtil.addFermenterRecipes( + new ItemStack(Blocks.brown_mushroom), + ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.mushroom"), + Fluids.BIOMASS); + RecipeUtil.addFermenterRecipes( + new ItemStack(Blocks.red_mushroom), + ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.mushroom"), + Fluids.BIOMASS); - RecipeUtil.addFermenterRecipes(new ItemStack(Blocks.cactus), ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.cactus"), Fluids.BIOMASS); - RecipeUtil.addFermenterRecipes(new ItemStack(Items.wheat), ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); - RecipeUtil.addFermenterRecipes(new ItemStack(Items.potato), (2 * ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat")), Fluids.BIOMASS); - RecipeUtil.addFermenterRecipes(new ItemStack(Items.reeds), ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.cane"), Fluids.BIOMASS); - RecipeUtil.addFermenterRecipes(new ItemStack(Blocks.brown_mushroom), ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.mushroom"), Fluids.BIOMASS); - RecipeUtil.addFermenterRecipes(new ItemStack(Blocks.red_mushroom), ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.mushroom"), Fluids.BIOMASS); + // FABRICATOR - // FABRICATOR + RecipeManagers.fabricatorSmeltingManager.addSmelting( + new ItemStack(Blocks.glass), Fluids.GLASS.getFluid(1000), 1000); + RecipeManagers.fabricatorSmeltingManager.addSmelting( + new ItemStack(Blocks.glass_pane), Fluids.GLASS.getFluid(375), 1000); + RecipeManagers.fabricatorSmeltingManager.addSmelting( + new ItemStack(Blocks.sand), Fluids.GLASS.getFluid(1000), 3000); + RecipeManagers.fabricatorSmeltingManager.addSmelting( + new ItemStack(Blocks.sand, 1, 1), Fluids.GLASS.getFluid(1000), 3000); + RecipeManagers.fabricatorSmeltingManager.addSmelting( + new ItemStack(Blocks.sandstone), Fluids.GLASS.getFluid(4000), 4800); + RecipeManagers.fabricatorSmeltingManager.addSmelting( + new ItemStack(Blocks.sandstone, 1, 1), Fluids.GLASS.getFluid(4000), 4800); + RecipeManagers.fabricatorSmeltingManager.addSmelting( + new ItemStack(Blocks.sandstone, 1, 2), Fluids.GLASS.getFluid(4000), 4800); - RecipeManagers.fabricatorSmeltingManager.addSmelting(new ItemStack(Blocks.glass), Fluids.GLASS.getFluid(1000), 1000); - RecipeManagers.fabricatorSmeltingManager.addSmelting(new ItemStack(Blocks.glass_pane), Fluids.GLASS.getFluid(375), 1000); - RecipeManagers.fabricatorSmeltingManager.addSmelting(new ItemStack(Blocks.sand), Fluids.GLASS.getFluid(1000), 3000); - RecipeManagers.fabricatorSmeltingManager.addSmelting(new ItemStack(Blocks.sand,1,1), Fluids.GLASS.getFluid(1000), 3000); - RecipeManagers.fabricatorSmeltingManager.addSmelting(new ItemStack(Blocks.sandstone), Fluids.GLASS.getFluid(4000), 4800); - RecipeManagers.fabricatorSmeltingManager.addSmelting(new ItemStack(Blocks.sandstone,1,1), Fluids.GLASS.getFluid(4000), 4800); - RecipeManagers.fabricatorSmeltingManager.addSmelting(new ItemStack(Blocks.sandstone,1,2), Fluids.GLASS.getFluid(4000), 4800); + // / CARPENTER + RecipeManagers.carpenterManager.addRecipe( + 50, + Fluids.SEEDOIL.getFluid(250), + null, + PluginCore.items.impregnatedCasing.getItemStack(), + "###", + "# #", + "###", + '#', + "logWood"); + RecipeManagers.carpenterManager.addRecipe( + 50, + Fluids.SEEDOIL.getFluid(500), + null, + PluginCore.blocks.core.get(BlockCoreType.ESCRITOIRE), + "# ", + "###", + "# #", + '#', + "plankWood"); - // / CARPENTER - RecipeManagers.carpenterManager.addRecipe(50, Fluids.SEEDOIL.getFluid(250), null, PluginCore.items.impregnatedCasing.getItemStack(), - "###", - "# #", - "###", - '#', "logWood"); - RecipeManagers.carpenterManager.addRecipe(50, Fluids.SEEDOIL.getFluid(500), null, - PluginCore.blocks.core.get(BlockCoreType.ESCRITOIRE), - "# ", - "###", - "# #", - '#', "plankWood"); + // RESOURCES + RecipeManagers.carpenterManager.addRecipe( + 10, + Fluids.SEEDOIL.getFluid(100), + null, + PluginCore.items.stickImpregnated.getItemStack(2), + "#", + "#", + '#', + "logWood"); + RecipeManagers.carpenterManager.addRecipe( + 5, Fluids.WATER.getFluid(250), null, PluginCore.items.woodPulp.getItemStack(4), "#", '#', "logWood"); + RecipeManagers.carpenterManager.addRecipe( + 5, Fluids.WATER.getFluid(250), null, new ItemStack(Items.paper, 1), "#", "#", '#', "pulpWood"); + RecipeManagers.carpenterManager.addRecipe( + 5, + Fluids.WATER.getFluid(1000), + null, + PluginCore.blocks.soil.get(BlockSoil.SoilType.HUMUS, 9), + "###", + "#X#", + "###", + '#', + Blocks.dirt, + 'X', + PluginCore.items.mulch); + RecipeManagers.carpenterManager.addRecipe( + 5, + Fluids.WATER.getFluid(1000), + null, + PluginCore.blocks.soil.get(BlockSoil.SoilType.BOG_EARTH, 8), + "#X#", + "XYX", + "#X#", + '#', + Blocks.dirt, + 'X', + "sand", + 'Y', + PluginCore.items.mulch); + RecipeManagers.carpenterManager.addRecipe( + 75, + Fluids.WATER.getFluid(5000), + null, + PluginCore.items.hardenedCasing.getItemStack(), + "# #", + " Y ", + "# #", + '#', + "gemDiamond", + 'Y', + PluginCore.items.sturdyCasing); - // RESOURCES - RecipeManagers.carpenterManager.addRecipe(10, Fluids.SEEDOIL.getFluid(100), null, - PluginCore.items.stickImpregnated.getItemStack(2), - "#", - "#", - '#', "logWood"); - RecipeManagers.carpenterManager.addRecipe(5, Fluids.WATER.getFluid(250), null, - PluginCore.items.woodPulp.getItemStack(4), - "#", - '#', "logWood"); - RecipeManagers.carpenterManager.addRecipe(5, Fluids.WATER.getFluid(250), null, - new ItemStack(Items.paper, 1), - "#", - "#", - '#', "pulpWood"); - RecipeManagers.carpenterManager.addRecipe(5, Fluids.WATER.getFluid(1000), null, - PluginCore.blocks.soil.get(BlockSoil.SoilType.HUMUS, 9), - "###", - "#X#", - "###", - '#', Blocks.dirt, - 'X', PluginCore.items.mulch); - RecipeManagers.carpenterManager.addRecipe(5, Fluids.WATER.getFluid(1000), null, - PluginCore.blocks.soil.get(BlockSoil.SoilType.BOG_EARTH, 8), - "#X#", - "XYX", "#X#", - '#', Blocks.dirt, - 'X', "sand", - 'Y', PluginCore.items.mulch); - RecipeManagers.carpenterManager.addRecipe(75, Fluids.WATER.getFluid(5000), null, PluginCore.items.hardenedCasing.getItemStack(), - "# #", - " Y ", - "# #", - '#', "gemDiamond", - 'Y', PluginCore.items.sturdyCasing); + // / CHIPSETS + ItemCircuitBoard circuitBoard = PluginCore.items.circuitboards; + RecipeManagers.carpenterManager.addRecipe( + 20, + Fluids.WATER.getFluid(1000), + null, + circuitBoard.get(EnumCircuitBoardType.BASIC), + "R R", + "R#R", + "R R", + '#', + "ingotTin", + 'R', + "dustRedstone"); + RecipeManagers.carpenterManager.addRecipe( + 40, + Fluids.WATER.getFluid(1000), + null, + circuitBoard.get(EnumCircuitBoardType.ENHANCED), + "R#R", + "R#R", + "R#R", + '#', + "ingotBronze", + 'R', + "dustRedstone"); + RecipeManagers.carpenterManager.addRecipe( + 80, + Fluids.WATER.getFluid(1000), + null, + circuitBoard.get(EnumCircuitBoardType.REFINED), + "R#R", + "R#R", + "R#R", + '#', + "ingotIron", + 'R', + "dustRedstone"); + RecipeManagers.carpenterManager.addRecipe( + 80, + Fluids.WATER.getFluid(1000), + null, + circuitBoard.get(EnumCircuitBoardType.INTRICATE), + "R#R", + "R#R", + "R#R", + '#', + "ingotGold", + 'R', + "dustRedstone"); + RecipeManagers.carpenterManager.addRecipe( + 40, + Fluids.WATER.getFluid(1000), + null, + PluginCore.items.solderingIron.getItemStack(), + " # ", + "# #", + " B", + '#', + "ingotIron", + 'B', + "ingotBronze"); - // / CHIPSETS - ItemCircuitBoard circuitBoard = PluginCore.items.circuitboards; - RecipeManagers.carpenterManager.addRecipe(20, Fluids.WATER.getFluid(1000), null, circuitBoard.get(EnumCircuitBoardType.BASIC), - "R R", "R#R", "R R", '#', "ingotTin", 'R', "dustRedstone"); - RecipeManagers.carpenterManager.addRecipe(40, Fluids.WATER.getFluid(1000), null, circuitBoard.get(EnumCircuitBoardType.ENHANCED), - "R#R", "R#R", "R#R", '#', "ingotBronze", 'R', "dustRedstone"); - RecipeManagers.carpenterManager.addRecipe(80, Fluids.WATER.getFluid(1000), null, circuitBoard.get(EnumCircuitBoardType.REFINED), - "R#R", "R#R", "R#R", '#', "ingotIron", 'R', "dustRedstone"); - RecipeManagers.carpenterManager.addRecipe(80, Fluids.WATER.getFluid(1000), null, circuitBoard.get(EnumCircuitBoardType.INTRICATE), - "R#R", "R#R", "R#R", '#', "ingotGold", 'R', "dustRedstone"); - RecipeManagers.carpenterManager.addRecipe(40, Fluids.WATER.getFluid(1000), null, PluginCore.items.solderingIron.getItemStack(), - " # ", "# #", " B", '#', "ingotIron", 'B', "ingotBronze"); + // RAIN SUBSTRATES + ItemRegistryApiculture beeItems = PluginApiculture.items; + if (beeItems != null) { + RecipeManagers.carpenterManager.addRecipe( + 5, + Fluids.WATER.getFluid(1000), + null, + PluginCore.items.iodineCharge.getItemStack(), + "Z#Z", + "#Y#", + "X#X", + '#', + beeItems.pollenCluster.getWildcard(), + 'X', + Items.gunpowder, + 'Y', + PluginFluids.items.canEmpty, + 'Z', + beeItems.honeyDrop); + RecipeManagers.carpenterManager.addRecipe( + 5, + Fluids.WATER.getFluid(1000), + null, + PluginCore.items.craftingMaterial.getDissipationCharge(), + "Z#Z", + "#Y#", + "X#X", + '#', + beeItems.royalJelly, + 'X', + Items.gunpowder, + 'Y', + PluginFluids.items.canEmpty, + 'Z', + beeItems.honeydew); + } - // RAIN SUBSTRATES - ItemRegistryApiculture beeItems = PluginApiculture.items; - if (beeItems != null) { - RecipeManagers.carpenterManager.addRecipe(5, Fluids.WATER.getFluid(1000), null, PluginCore.items.iodineCharge.getItemStack(), - "Z#Z", - "#Y#", - "X#X", - '#', beeItems.pollenCluster.getWildcard(), - 'X', Items.gunpowder, - 'Y', PluginFluids.items.canEmpty, - 'Z', beeItems.honeyDrop); - RecipeManagers.carpenterManager.addRecipe(5, Fluids.WATER.getFluid(1000), null, PluginCore.items.craftingMaterial.getDissipationCharge(), - "Z#Z", - "#Y#", - "X#X", - '#', beeItems.royalJelly, - 'X', Items.gunpowder, - 'Y', PluginFluids.items.canEmpty, - 'Z', beeItems.honeydew); - } + // Ender pearl + RecipeManagers.carpenterManager.addRecipe( + 100, + null, + new ItemStack(Items.ender_pearl, 1), + " # ", + "###", + " # ", + '#', + PluginCore.items.craftingMaterial.getPulsatingMesh()); + // Woven Silk + RecipeManagers.carpenterManager.addRecipe( + 10, + Fluids.WATER.getFluid(500), + null, + PluginCore.items.craftingMaterial.getWovenSilk(), + "###", + "###", + "###", + '#', + PluginCore.items.craftingMaterial.getSilkWisp()); - // Ender pearl - RecipeManagers.carpenterManager.addRecipe(100, null, new ItemStack(Items.ender_pearl, 1), " # ", "###", " # ", '#', - PluginCore.items.craftingMaterial.getPulsatingMesh()); - // Woven Silk - RecipeManagers.carpenterManager.addRecipe(10, Fluids.WATER.getFluid(500), null, PluginCore.items.craftingMaterial.getWovenSilk(), - "###", "###", "###", '#', PluginCore.items.craftingMaterial.getSilkWisp()); + // Boxes + RecipeManagers.carpenterManager.addRecipe( + 5, + Fluids.WATER.getFluid(1000), + null, + PluginCore.items.carton.getItemStack(2), + " # ", + "# #", + " # ", + '#', + "pulpWood"); - // Boxes - RecipeManagers.carpenterManager.addRecipe(5, Fluids.WATER.getFluid(1000), null, PluginCore.items.carton.getItemStack(2), - " # ", "# #", " # ", '#', "pulpWood"); + // Assembly Kits + RecipeManagers.carpenterManager.addRecipe( + 20, + null, + PluginCore.items.carton.getItemStack(), + PluginCore.items.kitPickaxe.getItemStack(), + new Object[] {"###", " X ", " X ", '#', "ingotBronze", 'X', "stickWood"}); - // Assembly Kits - RecipeManagers.carpenterManager.addRecipe(20, null, PluginCore.items.carton.getItemStack(), PluginCore.items.kitPickaxe.getItemStack(), new Object[]{ - "###", - " X ", - " X ", - '#', "ingotBronze", - 'X', "stickWood"}); + RecipeManagers.carpenterManager.addRecipe( + 20, + null, + PluginCore.items.carton.getItemStack(), + PluginCore.items.kitShovel.getItemStack(), + new Object[] {" # ", " X ", " X ", '#', "ingotBronze", 'X', "stickWood"}); - RecipeManagers.carpenterManager.addRecipe(20, null, PluginCore.items.carton.getItemStack(), PluginCore.items.kitShovel.getItemStack(), - new Object[]{" # ", " X ", " X ", '#', "ingotBronze", 'X', "stickWood"}); + // Reclamation + RecipeManagers.carpenterManager.addRecipe( + null, PluginCore.items.ingotBronze.getItemStack(2), "#", '#', PluginCore.items.brokenBronzePickaxe); + RecipeManagers.carpenterManager.addRecipe( + null, PluginCore.items.ingotBronze.getItemStack(), "#", '#', PluginCore.items.brokenBronzeShovel); - // Reclamation - RecipeManagers.carpenterManager.addRecipe(null, PluginCore.items.ingotBronze.getItemStack(2), - "#", '#', PluginCore.items.brokenBronzePickaxe); - RecipeManagers.carpenterManager.addRecipe(null, PluginCore.items.ingotBronze.getItemStack(), "#", '#', PluginCore.items.brokenBronzeShovel); + // Crating and uncrating + if (PluginManager.Module.STORAGE.isEnabled()) { + PluginStorage.createCrateRecipes(); + } + ICircuitLayout layout = ChipsetManager.circuitRegistry.getLayout("forestry.machine.upgrade"); - // Crating and uncrating - if (PluginManager.Module.STORAGE.isEnabled()) { - PluginStorage.createCrateRecipes(); - } - ICircuitLayout layout = ChipsetManager.circuitRegistry.getLayout("forestry.machine.upgrade"); + // / Solder Manager + ChipsetManager.solderManager.addRecipe( + layout, PluginCore.items.tubes.get(EnumElectronTube.EMERALD, 1), Circuit.machineSpeedUpgrade1); + ChipsetManager.solderManager.addRecipe( + layout, PluginCore.items.tubes.get(EnumElectronTube.BLAZE, 1), Circuit.machineSpeedUpgrade2); + ChipsetManager.solderManager.addRecipe( + layout, PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), Circuit.machineEfficiencyUpgrade1); - // / Solder Manager - ChipsetManager.solderManager.addRecipe(layout, PluginCore.items.tubes.get(EnumElectronTube.EMERALD, 1), Circuit.machineSpeedUpgrade1); - ChipsetManager.solderManager.addRecipe(layout, PluginCore.items.tubes.get(EnumElectronTube.BLAZE, 1), Circuit.machineSpeedUpgrade2); - ChipsetManager.solderManager.addRecipe(layout, PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), Circuit.machineEfficiencyUpgrade1); + RecipeUtil.addRecipe( + blocks.factoryTESR.get(BlockFactoryTesrType.BOTTLER), + "X#X", + "#Y#", + "X#X", + '#', + "blockGlass", + 'X', + PluginFluids.items.canEmpty, + 'Y', + PluginCore.items.sturdyCasing); - RecipeUtil.addRecipe(blocks.factoryTESR.get(BlockFactoryTesrType.BOTTLER), - "X#X", - "#Y#", - "X#X", - '#', "blockGlass", - 'X', PluginFluids.items.canEmpty, - 'Y', PluginCore.items.sturdyCasing); + RecipeUtil.addRecipe( + blocks.factoryTESR.get(BlockFactoryTesrType.CARPENTER), + "X#X", + "XYX", + "X#X", + '#', + "blockGlass", + 'X', + "ingotBronze", + 'Y', + PluginCore.items.sturdyCasing); - RecipeUtil.addRecipe(blocks.factoryTESR.get(BlockFactoryTesrType.CARPENTER), - "X#X", - "XYX", - "X#X", - '#', "blockGlass", - 'X', "ingotBronze", - 'Y', PluginCore.items.sturdyCasing); + RecipeUtil.addRecipe( + blocks.factoryTESR.get(BlockFactoryTesrType.CENTRIFUGE), + "X#X", + "XYX", + "X#X", + '#', + "blockGlass", + 'X', + "ingotCopper", + 'Y', + PluginCore.items.sturdyCasing); - RecipeUtil.addRecipe(blocks.factoryTESR.get(BlockFactoryTesrType.CENTRIFUGE), - "X#X", - "XYX", - "X#X", - '#', "blockGlass", - 'X', "ingotCopper", - 'Y', PluginCore.items.sturdyCasing); + RecipeUtil.addRecipe( + blocks.factoryTESR.get(BlockFactoryTesrType.FERMENTER), + "X#X", + "#Y#", + "X#X", + '#', + "blockGlass", + 'X', + "gearBronze", + 'Y', + PluginCore.items.sturdyCasing); - RecipeUtil.addRecipe(blocks.factoryTESR.get(BlockFactoryTesrType.FERMENTER), - "X#X", - "#Y#", - "X#X", - '#', "blockGlass", - 'X', "gearBronze", - 'Y', PluginCore.items.sturdyCasing); + RecipeUtil.addRecipe( + blocks.factoryTESR.get(BlockFactoryTesrType.MOISTENER), + "X#X", + "#Y#", + "X#X", + '#', + "blockGlass", + 'X', + "gearCopper", + 'Y', + PluginCore.items.sturdyCasing); - RecipeUtil.addRecipe(blocks.factoryTESR.get(BlockFactoryTesrType.MOISTENER), - "X#X", - "#Y#", - "X#X", - '#', "blockGlass", - 'X', "gearCopper", - 'Y', PluginCore.items.sturdyCasing); + RecipeUtil.addRecipe( + blocks.factoryTESR.get(BlockFactoryTesrType.SQUEEZER), + "X#X", + "XYX", + "X#X", + '#', + "blockGlass", + 'X', + "ingotTin", + 'Y', + PluginCore.items.sturdyCasing); - RecipeUtil.addRecipe(blocks.factoryTESR.get(BlockFactoryTesrType.SQUEEZER), - "X#X", - "XYX", - "X#X", - '#', "blockGlass", - 'X', "ingotTin", - 'Y', PluginCore.items.sturdyCasing); + RecipeUtil.addRecipe( + blocks.factoryTESR.get(BlockFactoryTesrType.STILL), + "X#X", + "#Y#", + "X#X", + '#', + "blockGlass", + 'X', + "dustRedstone", + 'Y', + PluginCore.items.sturdyCasing); - RecipeUtil.addRecipe(blocks.factoryTESR.get(BlockFactoryTesrType.STILL), - "X#X", - "#Y#", - "X#X", - '#', "blockGlass", - 'X', "dustRedstone", - 'Y', PluginCore.items.sturdyCasing); + RecipeUtil.addRecipe( + blocks.factoryTESR.get(BlockFactoryTesrType.RAINMAKER), + "X#X", + "#Y#", + "X#X", + '#', + "blockGlass", + 'X', + "gearTin", + 'Y', + PluginCore.items.hardenedCasing); - RecipeUtil.addRecipe(blocks.factoryTESR.get(BlockFactoryTesrType.RAINMAKER), - "X#X", - "#Y#", - "X#X", - '#', "blockGlass", - 'X', "gearTin", - 'Y', PluginCore.items.hardenedCasing); + RecipeUtil.addRecipe( + blocks.factoryPlain.get(BlockFactoryPlainType.FABRICATOR), + "X#X", + "#Y#", + "XZX", + '#', + "blockGlass", + 'X', + "ingotGold", + 'Y', + PluginCore.items.sturdyCasing, + 'Z', + "chestWood"); - RecipeUtil.addRecipe(blocks.factoryPlain.get(BlockFactoryPlainType.FABRICATOR), - "X#X", - "#Y#", - "XZX", - '#', "blockGlass", - 'X', "ingotGold", - 'Y', PluginCore.items.sturdyCasing, - 'Z', "chestWood"); + RecipeUtil.addRecipe( + blocks.factoryPlain.get(BlockFactoryPlainType.RAINTANK), + "X#X", + "XYX", + "X#X", + '#', + "blockGlass", + 'X', + "ingotIron", + 'Y', + PluginCore.items.sturdyCasing); - RecipeUtil.addRecipe(blocks.factoryPlain.get(BlockFactoryPlainType.RAINTANK), - "X#X", - "XYX", - "X#X", - '#', "blockGlass", - 'X', "ingotIron", - 'Y', PluginCore.items.sturdyCasing); - - RecipeUtil.addRecipe(blocks.factoryPlain.get(BlockFactoryPlainType.WORKTABLE), - "B", - "W", - "C", - 'B', Items.book, - 'W', "craftingTableWood", - 'C', "chestWood"); - } + RecipeUtil.addRecipe( + blocks.factoryPlain.get(BlockFactoryPlainType.WORKTABLE), + "B", + "W", + "C", + 'B', + Items.book, + 'W', + "craftingTableWood", + 'C', + "chestWood"); + } } diff --git a/src/main/java/forestry/plugins/PluginFarming.java b/src/main/java/forestry/plugins/PluginFarming.java index 156c38c9e..84b1ce40a 100644 --- a/src/main/java/forestry/plugins/PluginFarming.java +++ b/src/main/java/forestry/plugins/PluginFarming.java @@ -10,25 +10,10 @@ ******************************************************************************/ package forestry.plugins; -import java.util.ArrayList; -import java.util.Collection; -import java.util.regex.MatchResult; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import forestry.farming.logic.*; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; import cpw.mods.fml.common.registry.GameData; import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.CircuitSocketType; import forestry.api.circuits.ICircuitLayout; @@ -43,6 +28,7 @@ import forestry.core.utils.Log; import forestry.farming.blocks.BlockFarmType; import forestry.farming.blocks.BlockRegistryFarming; import forestry.farming.circuits.CircuitFarmLogic; +import forestry.farming.logic.*; import forestry.farming.proxy.ProxyFarming; import forestry.farming.render.EnumFarmBlockTexture; import forestry.farming.tiles.TileFarmControl; @@ -51,282 +37,331 @@ import forestry.farming.tiles.TileFarmHatch; import forestry.farming.tiles.TileFarmPlain; import forestry.farming.tiles.TileFarmValve; import forestry.farming.triggers.FarmingTriggers; +import java.util.ArrayList; +import java.util.Collection; +import java.util.regex.MatchResult; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; -@Plugin(pluginID = "Farming", name = "Farming", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.farming.description") +@Plugin( + pluginID = "Farming", + name = "Farming", + author = "SirSengir", + url = Constants.URL, + unlocalizedDescription = "for.plugin.farming.description") public class PluginFarming extends ForestryPlugin { - @SidedProxy(clientSide = "forestry.farming.proxy.ProxyFarmingClient", serverSide = "forestry.farming.proxy.ProxyFarming") - public static ProxyFarming proxy; - public static int modelIdFarmBlock; + @SidedProxy( + clientSide = "forestry.farming.proxy.ProxyFarmingClient", + serverSide = "forestry.farming.proxy.ProxyFarming") + public static ProxyFarming proxy; - public static BlockRegistryFarming blocks; + public static int modelIdFarmBlock; - @Override - protected void registerItemsAndBlocks() { - blocks = new BlockRegistryFarming(); - } + public static BlockRegistryFarming blocks; - @Override - public void preInit() { - super.preInit(); - Farmables.farmables.put(FarmableReference.Arboreal.get(), new ArrayList<>()); - Farmables.farmables.get(FarmableReference.Arboreal.get()).add(new FarmableVanillaSapling()); - if (PluginManager.Module.ARBORICULTURE.isEnabled()) { - Farmables.farmables.get(FarmableReference.Arboreal.get()).add(new FarmableGE()); - } - - Farmables.farmables.put(FarmableReference.Orchard.get(), new ArrayList<>()); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(Blocks.wheat, 7)); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(Blocks.potatoes, 7)); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(Blocks.carrots, 7)); + @Override + protected void registerItemsAndBlocks() { + blocks = new BlockRegistryFarming(); + } - Farmables.farmables.put(FarmableReference.Shroom.get(), new ArrayList<>()); - Farmables.farmables.get(FarmableReference.Shroom.get()).add(new FarmableVanillaMushroom(Blocks.brown_mushroom, 0)); - Farmables.farmables.get(FarmableReference.Shroom.get()).add(new FarmableVanillaMushroom(Blocks.red_mushroom, 0)); + @Override + public void preInit() { + super.preInit(); + Farmables.farmables.put(FarmableReference.Arboreal.get(), new ArrayList<>()); + Farmables.farmables.get(FarmableReference.Arboreal.get()).add(new FarmableVanillaSapling()); + if (PluginManager.Module.ARBORICULTURE.isEnabled()) { + Farmables.farmables.get(FarmableReference.Arboreal.get()).add(new FarmableGE()); + } - Farmables.farmables.put(FarmableReference.Wheat.get(), new ArrayList<>()); - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(new ItemStack(Items.wheat_seeds), Blocks.wheat, 7)); + Farmables.farmables.put(FarmableReference.Orchard.get(), new ArrayList<>()); + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(Blocks.wheat, 7)); + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(Blocks.potatoes, 7)); + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(Blocks.carrots, 7)); - Farmables.farmables.put(FarmableReference.Gourd.get(), new ArrayList<>()); - Farmables.farmables.get(FarmableReference.Gourd.get()).add( - new FarmableGourd(new ItemStack(Items.pumpkin_seeds), new ItemStack(Blocks.pumpkin_stem), new ItemStack(Blocks.pumpkin))); - Farmables.farmables.get(FarmableReference.Gourd.get()).add(new FarmableGourd(new ItemStack(Items.melon_seeds), new ItemStack(Blocks.melon_stem), new ItemStack(Blocks.melon_block))); + Farmables.farmables.put(FarmableReference.Shroom.get(), new ArrayList<>()); + Farmables.farmables + .get(FarmableReference.Shroom.get()) + .add(new FarmableVanillaMushroom(Blocks.brown_mushroom, 0)); + Farmables.farmables + .get(FarmableReference.Shroom.get()) + .add(new FarmableVanillaMushroom(Blocks.red_mushroom, 0)); - Farmables.farmables.put(FarmableReference.Infernal.get(), new ArrayList<>()); - Farmables.farmables.get(FarmableReference.Infernal.get()).add(new FarmableGenericCrop(new ItemStack(Items.nether_wart), Blocks.nether_wart, 3)); + Farmables.farmables.put(FarmableReference.Wheat.get(), new ArrayList<>()); + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(new ItemStack(Items.wheat_seeds), Blocks.wheat, 7)); - Farmables.farmables.put(FarmableReference.Poales.get(), new ArrayList<>()); - Farmables.farmables.get(FarmableReference.Poales.get()).add(new FarmableStacked(Blocks.reeds, 3, 0)); + Farmables.farmables.put(FarmableReference.Gourd.get(), new ArrayList<>()); + Farmables.farmables + .get(FarmableReference.Gourd.get()) + .add(new FarmableGourd( + new ItemStack(Items.pumpkin_seeds), + new ItemStack(Blocks.pumpkin_stem), + new ItemStack(Blocks.pumpkin))); + Farmables.farmables + .get(FarmableReference.Gourd.get()) + .add(new FarmableGourd( + new ItemStack(Items.melon_seeds), + new ItemStack(Blocks.melon_stem), + new ItemStack(Blocks.melon_block))); - Farmables.farmables.put(FarmableReference.Succulentes.get(), new ArrayList<>()); - Farmables.farmables.get(FarmableReference.Succulentes.get()).add(new FarmableStacked(Blocks.cactus, 3, 0)); + Farmables.farmables.put(FarmableReference.Infernal.get(), new ArrayList<>()); + Farmables.farmables + .get(FarmableReference.Infernal.get()) + .add(new FarmableGenericCrop(new ItemStack(Items.nether_wart), Blocks.nether_wart, 3)); - Farmables.farmables.put(FarmableReference.Vegetables.get(), new ArrayList<>()); - Farmables.farmables.get(FarmableReference.Vegetables.get()).add(new FarmableGenericCrop(new ItemStack(Items.potato), Blocks.potatoes, 7)); - Farmables.farmables.get(FarmableReference.Vegetables.get()).add(new FarmableGenericCrop(new ItemStack(Items.carrot), Blocks.carrots, 7)); + Farmables.farmables.put(FarmableReference.Poales.get(), new ArrayList<>()); + Farmables.farmables.get(FarmableReference.Poales.get()).add(new FarmableStacked(Blocks.reeds, 3, 0)); - proxy.initializeRendering(); + Farmables.farmables.put(FarmableReference.Succulentes.get(), new ArrayList<>()); + Farmables.farmables.get(FarmableReference.Succulentes.get()).add(new FarmableStacked(Blocks.cactus, 3, 0)); - // Layouts - ICircuitLayout layoutManaged = new CircuitLayout("farms.managed", CircuitSocketType.FARM); - ChipsetManager.circuitRegistry.registerLayout(layoutManaged); - ICircuitLayout layoutManual = new CircuitLayout("farms.manual", CircuitSocketType.FARM); - ChipsetManager.circuitRegistry.registerLayout(layoutManual); - } + Farmables.farmables.put(FarmableReference.Vegetables.get(), new ArrayList<>()); + Farmables.farmables + .get(FarmableReference.Vegetables.get()) + .add(new FarmableGenericCrop(new ItemStack(Items.potato), Blocks.potatoes, 7)); + Farmables.farmables + .get(FarmableReference.Vegetables.get()) + .add(new FarmableGenericCrop(new ItemStack(Items.carrot), Blocks.carrots, 7)); - @Override - protected void registerTriggers() { - FarmingTriggers.initialize(); - } + proxy.initializeRendering(); - @Override - public void doInit() { - super.doInit(); + // Layouts + ICircuitLayout layoutManaged = new CircuitLayout("farms.managed", CircuitSocketType.FARM); + ChipsetManager.circuitRegistry.registerLayout(layoutManaged); + ICircuitLayout layoutManual = new CircuitLayout("farms.manual", CircuitSocketType.FARM); + ChipsetManager.circuitRegistry.registerLayout(layoutManual); + } - GameRegistry.registerTileEntity(TileFarmPlain.class, "forestry.Farm"); - GameRegistry.registerTileEntity(TileFarmGearbox.class, "forestry.FarmGearbox"); - GameRegistry.registerTileEntity(TileFarmHatch.class, "forestry.FarmHatch"); - GameRegistry.registerTileEntity(TileFarmValve.class, "forestry.FarmValve"); - GameRegistry.registerTileEntity(TileFarmControl.class, "forestry.FarmControl"); + @Override + protected void registerTriggers() { + FarmingTriggers.initialize(); + } - Circuit.farmArborealManaged = new CircuitFarmLogic("managedArboreal", FarmLogicArboreal.class); - Circuit.farmShroomManaged = new CircuitFarmLogic("managedShroom", FarmLogicShroom.class); - Circuit.farmPeatManaged = new CircuitFarmLogic("managedPeat", FarmLogicPeat.class); - Circuit.farmCerealManaged = new CircuitFarmLogic("managedCereal", FarmLogicCereal.class); - Circuit.farmVegetableManaged = new CircuitFarmLogic("managedVegetable", FarmLogicVegetable.class); - Circuit.farmInfernalManaged = new CircuitFarmLogic("managedInfernal", FarmLogicInfernal.class); + @Override + public void doInit() { + super.doInit(); - Circuit.farmPeatManual = new CircuitFarmLogic("manualPeat", FarmLogicPeat.class).setManual(); - Circuit.farmShroomManual = new CircuitFarmLogic("manualShroom", FarmLogicShroom.class).setManual(); - Circuit.farmCerealManual = new CircuitFarmLogic("manualCereal", FarmLogicCereal.class).setManual(); - Circuit.farmVegetableManual = new CircuitFarmLogic("manualVegetable", FarmLogicVegetable.class).setManual(); - Circuit.farmSucculentManual = new CircuitFarmLogic("manualSucculent", FarmLogicSucculent.class).setManual(); - Circuit.farmPoalesManual = new CircuitFarmLogic("manualPoales", FarmLogicReeds.class).setManual(); - Circuit.farmGourdManual = new CircuitFarmLogic("manualGourd", FarmLogicGourd.class).setManual(); - Circuit.farmCocoaManual = new CircuitFarmLogic("manualCocoa", FarmLogicCocoa.class).setManual(); + GameRegistry.registerTileEntity(TileFarmPlain.class, "forestry.Farm"); + GameRegistry.registerTileEntity(TileFarmGearbox.class, "forestry.FarmGearbox"); + GameRegistry.registerTileEntity(TileFarmHatch.class, "forestry.FarmHatch"); + GameRegistry.registerTileEntity(TileFarmValve.class, "forestry.FarmValve"); + GameRegistry.registerTileEntity(TileFarmControl.class, "forestry.FarmControl"); - Circuit.farmOrchardManual = new CircuitFarmLogic("manualOrchard", FarmLogicOrchard.class); + Circuit.farmArborealManaged = new CircuitFarmLogic("managedArboreal", FarmLogicArboreal.class); + Circuit.farmShroomManaged = new CircuitFarmLogic("managedShroom", FarmLogicShroom.class); + Circuit.farmPeatManaged = new CircuitFarmLogic("managedPeat", FarmLogicPeat.class); + Circuit.farmCerealManaged = new CircuitFarmLogic("managedCereal", FarmLogicCereal.class); + Circuit.farmVegetableManaged = new CircuitFarmLogic("managedVegetable", FarmLogicVegetable.class); + Circuit.farmInfernalManaged = new CircuitFarmLogic("managedInfernal", FarmLogicInfernal.class); - if (PluginManager.Module.FARMING.isEnabled() && GameRegistry.findBlock("IC2", "blockCrop") != null) - Circuit.farmIC2CropsManual = new CircuitFarmLogic("manualIC2Crop", FarmLogicIC2Crops.class).setManual(); - } + Circuit.farmPeatManual = new CircuitFarmLogic("manualPeat", FarmLogicPeat.class).setManual(); + Circuit.farmShroomManual = new CircuitFarmLogic("manualShroom", FarmLogicShroom.class).setManual(); + Circuit.farmCerealManual = new CircuitFarmLogic("manualCereal", FarmLogicCereal.class).setManual(); + Circuit.farmVegetableManual = new CircuitFarmLogic("manualVegetable", FarmLogicVegetable.class).setManual(); + Circuit.farmSucculentManual = new CircuitFarmLogic("manualSucculent", FarmLogicSucculent.class).setManual(); + Circuit.farmPoalesManual = new CircuitFarmLogic("manualPoales", FarmLogicReeds.class).setManual(); + Circuit.farmGourdManual = new CircuitFarmLogic("manualGourd", FarmLogicGourd.class).setManual(); + Circuit.farmCocoaManual = new CircuitFarmLogic("manualCocoa", FarmLogicCocoa.class).setManual(); - @Override - public boolean processIMCMessage(IMCMessage message) { + Circuit.farmOrchardManual = new CircuitFarmLogic("manualOrchard", FarmLogicOrchard.class); - if (message.key.equals("add-farmable-sapling")) { - String[] tokens = message.getStringValue().split("@"); - String errormsg = getInvalidIMCMessageText(message); - if (tokens.length != 2) { - Log.warning(errormsg); - return true; - } + if (PluginManager.Module.FARMING.isEnabled() && GameRegistry.findBlock("IC2", "blockCrop") != null) + Circuit.farmIC2CropsManual = new CircuitFarmLogic("manualIC2Crop", FarmLogicIC2Crops.class).setManual(); + } - if (!Farmables.farmables.containsKey(tokens[0])) { - Log.warning("%s For non-existent farm %s.", errormsg, tokens[0]); - return true; - } + @Override + public boolean processIMCMessage(IMCMessage message) { - Collection farmables = Farmables.farmables.get(tokens[0]); + if (message.key.equals("add-farmable-sapling")) { + String[] tokens = message.getStringValue().split("@"); + String errormsg = getInvalidIMCMessageText(message); + if (tokens.length != 2) { + Log.warning(errormsg); + return true; + } - String itemString = tokens[1]; + if (!Farmables.farmables.containsKey(tokens[0])) { + Log.warning("%s For non-existent farm %s.", errormsg, tokens[0]); + return true; + } - Matcher matcher = Pattern.compile("(.+?)\\.(-?[0-9][0-9]?)(?:\\.(.+?)\\.(-?[0-9][0-9]?))?").matcher(itemString); - if (!matcher.matches()) { - Log.warning("%s For farm '%s': unable to parse string.", errormsg, tokens[0]); - return true; - } + Collection farmables = Farmables.farmables.get(tokens[0]); - MatchResult matchResult = matcher.toMatchResult(); - String saplingString = matchResult.group(1); - String saplingMetaString = matchResult.group(2); - String windfallString = matchResult.group(3); - String windfallMetaString = matchResult.group(4); + String itemString = tokens[1]; - try { - Block sapling = GameData.getBlockRegistry().getRaw(saplingString); - if (sapling == null || sapling == Blocks.air) { - throw new RuntimeException("can't find block for " + saplingString); - } - int saplingMeta = Integer.parseInt(saplingMetaString); + Matcher matcher = Pattern.compile("(.+?)\\.(-?[0-9][0-9]?)(?:\\.(.+?)\\.(-?[0-9][0-9]?))?") + .matcher(itemString); + if (!matcher.matches()) { + Log.warning("%s For farm '%s': unable to parse string.", errormsg, tokens[0]); + return true; + } - if (windfallString == null) { - farmables.add(new FarmableGenericSapling(sapling, saplingMeta)); - } else { - Item windfall = GameData.getItemRegistry().getRaw(windfallString); - if (windfall == null) { - throw new RuntimeException("can't find item for " + windfallString); - } + MatchResult matchResult = matcher.toMatchResult(); + String saplingString = matchResult.group(1); + String saplingMetaString = matchResult.group(2); + String windfallString = matchResult.group(3); + String windfallMetaString = matchResult.group(4); - ItemStack windfallStack = new ItemStack(windfall, 1, Integer.parseInt(windfallMetaString)); + try { + Block sapling = GameData.getBlockRegistry().getRaw(saplingString); + if (sapling == null || sapling == Blocks.air) { + throw new RuntimeException("can't find block for " + saplingString); + } + int saplingMeta = Integer.parseInt(saplingMetaString); - farmables.add(new FarmableGenericSapling(sapling, saplingMeta, windfallStack)); - } - } catch (Exception ex) { - Log.warning("%s for farm '%s': %s", errormsg, tokens[0], ex.getMessage()); - } - return true; + if (windfallString == null) { + farmables.add(new FarmableGenericSapling(sapling, saplingMeta)); + } else { + Item windfall = GameData.getItemRegistry().getRaw(windfallString); + if (windfall == null) { + throw new RuntimeException("can't find item for " + windfallString); + } - } else if (message.key.equals("add-farmable-crop")) { + ItemStack windfallStack = new ItemStack(windfall, 1, Integer.parseInt(windfallMetaString)); - String[] tokens = message.getStringValue().split("@"); - String errormsg = getInvalidIMCMessageText(message); - if (tokens.length != 2) { - Log.warning(errormsg); - return true; - } + farmables.add(new FarmableGenericSapling(sapling, saplingMeta, windfallStack)); + } + } catch (Exception ex) { + Log.warning("%s for farm '%s': %s", errormsg, tokens[0], ex.getMessage()); + } + return true; - if (!Farmables.farmables.containsKey(tokens[0])) { - Log.warning("%s For non-existent farm %s.", errormsg, tokens[0]); - return true; - } + } else if (message.key.equals("add-farmable-crop")) { - String[] items = tokens[1].split("[\\.]+"); - if (items.length != 4) { - Log.warning("%s For farm '%s': id definitions did not match.", errormsg, tokens[0]); - return true; - } + String[] tokens = message.getStringValue().split("@"); + String errormsg = getInvalidIMCMessageText(message); + if (tokens.length != 2) { + Log.warning(errormsg); + return true; + } - try { - Item seed = GameData.getItemRegistry().getRaw(items[0]); - if (seed == null) { - throw new RuntimeException("can't find item for " + items[0]); - } - Block crop = GameData.getBlockRegistry().getRaw(items[2]); - if (crop == null || crop == Blocks.air) { - throw new RuntimeException("can't find block for " + items[2]); - } + if (!Farmables.farmables.containsKey(tokens[0])) { + Log.warning("%s For non-existent farm %s.", errormsg, tokens[0]); + return true; + } - Farmables.farmables.get(tokens[0]).add( - new FarmableGenericCrop(new ItemStack(seed, 1, Integer.parseInt(items[1])), - crop, - Integer.parseInt(items[3]))); - } catch (Exception ex) { - Log.warning("%s for farm '%s': %s", errormsg, tokens[0], ex.getMessage()); - } + String[] items = tokens[1].split("[\\.]+"); + if (items.length != 4) { + Log.warning("%s For farm '%s': id definitions did not match.", errormsg, tokens[0]); + return true; + } - return true; - } + try { + Item seed = GameData.getItemRegistry().getRaw(items[0]); + if (seed == null) { + throw new RuntimeException("can't find item for " + items[0]); + } + Block crop = GameData.getBlockRegistry().getRaw(items[2]); + if (crop == null || crop == Blocks.air) { + throw new RuntimeException("can't find block for " + items[2]); + } - return false; - } + Farmables.farmables + .get(tokens[0]) + .add(new FarmableGenericCrop( + new ItemStack(seed, 1, Integer.parseInt(items[1])), crop, Integer.parseInt(items[3]))); + } catch (Exception ex) { + Log.warning("%s for farm '%s': %s", errormsg, tokens[0], ex.getMessage()); + } - @Override - protected void registerRecipes() { + return true; + } - ItemStack basic = blocks.farm.get(BlockFarmType.BASIC, 1); - ItemStack gearbox = blocks.farm.get(BlockFarmType.GEARBOX, 1); - ItemStack hatch = blocks.farm.get(BlockFarmType.HATCH, 1); - ItemStack valve = blocks.farm.get(BlockFarmType.VALVE, 1); - ItemStack control = blocks.farm.get(BlockFarmType.CONTROL, 1); + return false; + } - for (EnumFarmBlockTexture block : EnumFarmBlockTexture.values()) { - NBTTagCompound compound = new NBTTagCompound(); - block.saveToCompound(compound); + @Override + protected void registerRecipes() { - basic.setTagCompound(compound); - gearbox.setTagCompound(compound); - hatch.setTagCompound(compound); - valve.setTagCompound(compound); - control.setTagCompound(compound); + ItemStack basic = blocks.farm.get(BlockFarmType.BASIC, 1); + ItemStack gearbox = blocks.farm.get(BlockFarmType.GEARBOX, 1); + ItemStack hatch = blocks.farm.get(BlockFarmType.HATCH, 1); + ItemStack valve = blocks.farm.get(BlockFarmType.VALVE, 1); + ItemStack control = blocks.farm.get(BlockFarmType.CONTROL, 1); - RecipeUtil.addRecipe(basic, - "I#I", - "WCW", - '#', block.getBase(), - 'W', "slabWood", - 'C', PluginCore.items.tubes.get(EnumElectronTube.TIN, 1), - 'I', "ingotCopper"); + for (EnumFarmBlockTexture block : EnumFarmBlockTexture.values()) { + NBTTagCompound compound = new NBTTagCompound(); + block.saveToCompound(compound); - RecipeUtil.addRecipe(gearbox, - " # ", - "TTT", - '#', basic, - 'T', "gearTin"); + basic.setTagCompound(compound); + gearbox.setTagCompound(compound); + hatch.setTagCompound(compound); + valve.setTagCompound(compound); + control.setTagCompound(compound); - RecipeUtil.addRecipe(hatch, - " # ", - "TDT", - '#', basic, - 'T', "gearTin", - 'D', Blocks.trapdoor); + RecipeUtil.addRecipe( + basic, + "I#I", + "WCW", + '#', + block.getBase(), + 'W', + "slabWood", + 'C', + PluginCore.items.tubes.get(EnumElectronTube.TIN, 1), + 'I', + "ingotCopper"); - RecipeUtil.addRecipe(valve, - " # ", - "XTX", - '#', basic, - 'T', "gearTin", - 'X', "blockGlass"); + RecipeUtil.addRecipe(gearbox, " # ", "TTT", '#', basic, 'T', "gearTin"); - RecipeUtil.addRecipe(control, - " # ", - "XTX", - '#', basic, - 'T', PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), - 'X', "dustRedstone"); - } + RecipeUtil.addRecipe(hatch, " # ", "TDT", '#', basic, 'T', "gearTin", 'D', Blocks.trapdoor); - // Circuits - ICircuitLayout layoutManaged = ChipsetManager.circuitRegistry.getLayout("forestry.farms.managed"); - ICircuitLayout layoutManual = ChipsetManager.circuitRegistry.getLayout("forestry.farms.manual"); + RecipeUtil.addRecipe(valve, " # ", "XTX", '#', basic, 'T', "gearTin", 'X', "blockGlass"); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.COPPER, 1), Circuit.farmArborealManaged); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.TIN, 1), Circuit.farmPeatManaged); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.BRONZE, 1), Circuit.farmCerealManaged); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.IRON, 1), Circuit.farmVegetableManaged); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.BLAZE, 1), Circuit.farmInfernalManaged); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.APATITE, 1), Circuit.farmShroomManaged); + RecipeUtil.addRecipe( + control, + " # ", + "XTX", + '#', + basic, + 'T', + PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), + 'X', + "dustRedstone"); + } - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.COPPER, 1), Circuit.farmOrchardManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.TIN, 1), Circuit.farmPeatManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.BRONZE, 1), Circuit.farmCerealManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.IRON, 1), Circuit.farmVegetableManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), Circuit.farmSucculentManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.DIAMOND, 1), Circuit.farmPoalesManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.OBSIDIAN, 1), Circuit.farmGourdManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.APATITE, 1), Circuit.farmShroomManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.LAPIS, 1), Circuit.farmCocoaManual); + // Circuits + ICircuitLayout layoutManaged = ChipsetManager.circuitRegistry.getLayout("forestry.farms.managed"); + ICircuitLayout layoutManual = ChipsetManager.circuitRegistry.getLayout("forestry.farms.manual"); + ChipsetManager.solderManager.addRecipe( + layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.COPPER, 1), Circuit.farmArborealManaged); + ChipsetManager.solderManager.addRecipe( + layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.TIN, 1), Circuit.farmPeatManaged); + ChipsetManager.solderManager.addRecipe( + layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.BRONZE, 1), Circuit.farmCerealManaged); + ChipsetManager.solderManager.addRecipe( + layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.IRON, 1), Circuit.farmVegetableManaged); + ChipsetManager.solderManager.addRecipe( + layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.BLAZE, 1), Circuit.farmInfernalManaged); + ChipsetManager.solderManager.addRecipe( + layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.APATITE, 1), Circuit.farmShroomManaged); - } + ChipsetManager.solderManager.addRecipe( + layoutManual, PluginCore.items.tubes.get(EnumElectronTube.COPPER, 1), Circuit.farmOrchardManual); + ChipsetManager.solderManager.addRecipe( + layoutManual, PluginCore.items.tubes.get(EnumElectronTube.TIN, 1), Circuit.farmPeatManual); + ChipsetManager.solderManager.addRecipe( + layoutManual, PluginCore.items.tubes.get(EnumElectronTube.BRONZE, 1), Circuit.farmCerealManual); + ChipsetManager.solderManager.addRecipe( + layoutManual, PluginCore.items.tubes.get(EnumElectronTube.IRON, 1), Circuit.farmVegetableManual); + ChipsetManager.solderManager.addRecipe( + layoutManual, PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), Circuit.farmSucculentManual); + ChipsetManager.solderManager.addRecipe( + layoutManual, PluginCore.items.tubes.get(EnumElectronTube.DIAMOND, 1), Circuit.farmPoalesManual); + ChipsetManager.solderManager.addRecipe( + layoutManual, PluginCore.items.tubes.get(EnumElectronTube.OBSIDIAN, 1), Circuit.farmGourdManual); + ChipsetManager.solderManager.addRecipe( + layoutManual, PluginCore.items.tubes.get(EnumElectronTube.APATITE, 1), Circuit.farmShroomManual); + ChipsetManager.solderManager.addRecipe( + layoutManual, PluginCore.items.tubes.get(EnumElectronTube.LAPIS, 1), Circuit.farmCocoaManual); + } } diff --git a/src/main/java/forestry/plugins/PluginFluids.java b/src/main/java/forestry/plugins/PluginFluids.java index 3f8546fdc..74f38125d 100644 --- a/src/main/java/forestry/plugins/PluginFluids.java +++ b/src/main/java/forestry/plugins/PluginFluids.java @@ -1,205 +1,216 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.plugins; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; -import net.minecraft.util.MovingObjectPosition; - -import net.minecraftforge.client.event.TextureStitchEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.entity.player.FillBucketEvent; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - -import cpw.mods.fml.common.eventhandler.Event; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.registry.GameRegistry; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import forestry.api.core.ForestryAPI; -import forestry.api.fuels.FuelManager; -import forestry.api.fuels.GeneratorFuel; -import forestry.api.recipes.RecipeManagers; -import forestry.core.config.Config; -import forestry.core.config.Constants; -import forestry.core.fluids.BlockForestryFluid; -import forestry.core.fluids.Fluids; -import forestry.core.fluids.LiquidRegistryHelper; -import forestry.core.items.EnumContainerType; -import forestry.core.items.ItemLiquidContainer; -import forestry.core.items.ItemRegistryFluids; -import forestry.core.utils.Log; -import forestry.core.utils.StringUtil; - -@Plugin(pluginID = "Fluids", name = "Fluids", author = "mezz", url = Constants.URL, unlocalizedDescription = "for.plugin.fluids.description") -public class PluginFluids extends ForestryPlugin { - - private static final List forestryFluidsWithBlocks = new ArrayList<>(); - - public static ItemRegistryFluids items; - - private static void createFluid(Fluids forestryFluid) { - if (forestryFluid.getFluid() == null && Config.isFluidEnabled(forestryFluid)) { - String fluidName = forestryFluid.getTag(); - if (!FluidRegistry.isFluidRegistered(fluidName)) { - Fluid fluid = new Fluid(fluidName).setDensity(forestryFluid.getDensity()).setViscosity(forestryFluid.getViscosity()).setTemperature(forestryFluid.getTemperature()); - FluidRegistry.registerFluid(fluid); - createBlock(forestryFluid); - } - } - } - - private static void createBlock(Fluids forestryFluid) { - Fluid fluid = forestryFluid.getFluid(); - Block fluidBlock = fluid.getBlock(); - - if (Config.isBlockEnabled(forestryFluid.getTag())) { - if (fluidBlock == null) { - fluidBlock = forestryFluid.makeBlock(); - if (fluidBlock != null) { - fluidBlock.setBlockName("forestry.fluid." + forestryFluid.getTag()); - GameRegistry.registerBlock(fluidBlock, ItemBlock.class, StringUtil.cleanBlockName(fluidBlock)); - forestryFluidsWithBlocks.add(forestryFluid); - } - } else { - GameRegistry.UniqueIdentifier blockID = GameRegistry.findUniqueIdentifierFor(fluidBlock); - Log.severe("Pre-existing {0} fluid block detected, deferring to {1}:{2}, " - + "this may cause issues if the server/client have different mod load orders, " - + "recommended that you disable all but one instance of {0} fluid blocks via your configs.", fluid.getName(), blockID.modId, blockID.name); - } - } - } - - @Override - public void registerItemsAndBlocks() { - for (Fluids fluidType : Fluids.forestryFluids) { - createFluid(fluidType); - } - - items = new ItemRegistryFluids(); - } - - @Override - public void preInit() { - MinecraftForge.EVENT_BUS.register(getTextureHook()); - MinecraftForge.EVENT_BUS.register(getFillBucketHook()); - } - - @Override - public void doInit() { - for (Fluids fluidType : Fluids.values()) { - if (fluidType.getFluid() == null) { - continue; - } - - for (EnumContainerType type : EnumContainerType.values()) { - ItemLiquidContainer container = items.getContainer(type, fluidType); - if (container == null) { - continue; - } - - LiquidRegistryHelper.registerLiquidContainer(fluidType, container.getItemStack()); - } - - for (ItemStack filledContainer : fluidType.getOtherContainers()) { - LiquidRegistryHelper.registerLiquidContainer(fluidType, filledContainer); - } - } - - if (RecipeManagers.squeezerManager != null) { - RecipeManagers.squeezerManager.addContainerRecipe(10, items.canEmpty.getItemStack(), PluginCore.items.ingotTin.getItemStack(), 0.05f); - RecipeManagers.squeezerManager.addContainerRecipe(10, items.waxCapsuleEmpty.getItemStack(), PluginCore.items.beeswax.getItemStack(), 0.10f); - RecipeManagers.squeezerManager.addContainerRecipe(10, items.refractoryEmpty.getItemStack(), PluginCore.items.refractoryWax.getItemStack(), 0.10f); - } - - FluidStack ethanol = Fluids.ETHANOL.getFluid(1); - GeneratorFuel ethanolFuel = new GeneratorFuel(ethanol, (int) (32 * ForestryAPI.activeMode.getFloatSetting("fuel.ethanol.generator")), 4); - FuelManager.generatorFuel.put(ethanol.getFluid(), ethanolFuel); - - FluidStack biomass = Fluids.BIOMASS.getFluid(1); - GeneratorFuel biomassFuel = new GeneratorFuel(biomass, (int) (8 * ForestryAPI.activeMode.getFloatSetting("fuel.biomass.generator")), 1); - FuelManager.generatorFuel.put(biomass.getFluid(), biomassFuel); - } - - public static class MissingFluidException extends RuntimeException { - public MissingFluidException(String tag) { - super("Fluid '" + tag + "' was not found. Please check your configs."); - } - } - - @Override - public void postInit() { - for (Fluids fluidType : Fluids.forestryFluids) { - if (fluidType.getFluid() == null && Config.isFluidEnabled(fluidType)) { - throw new MissingFluidException(fluidType.getTag()); - } - } - } - - public static class TextureHook { - @SubscribeEvent - @SideOnly(Side.CLIENT) - public void textureHook(TextureStitchEvent.Post event) { - if (event.map.getTextureType() == 0) { - for (Fluids fluidType : forestryFluidsWithBlocks) { - Fluid fluid = fluidType.getFluid(); - Block fluidBlock = fluidType.getBlock(); - if (fluid != null && fluidBlock != null) { - fluid.setIcons(fluidBlock.getBlockTextureFromSide(1), fluidBlock.getBlockTextureFromSide(2)); - } - } - } - } - } - - private static Object getTextureHook() { - return new TextureHook(); - } - - public static class FillBucketHook { - @SubscribeEvent - public void fillBucket(FillBucketEvent event) { - ItemStack bucket = event.current; - if (bucket == null || bucket.getItem() != Items.bucket) { - return; - } - - MovingObjectPosition movingObjectPosition = event.target; - int x = movingObjectPosition.blockX; - int y = movingObjectPosition.blockY; - int z = movingObjectPosition.blockZ; - Block targetedBlock = event.world.getBlock(x, y, z); - if (targetedBlock instanceof BlockForestryFluid) { - Item filledBucket = ItemLiquidContainer.getExistingBucket(targetedBlock); - if (filledBucket != null) { - event.result = new ItemStack(filledBucket); - event.setResult(Event.Result.ALLOW); - if (!event.world.isRemote) { - event.world.setBlockToAir(x, y, z); - } - } - } - } - } - - private static Object getFillBucketHook() { - return new FillBucketHook(); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.plugins; + +import cpw.mods.fml.common.eventhandler.Event; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import forestry.api.core.ForestryAPI; +import forestry.api.fuels.FuelManager; +import forestry.api.fuels.GeneratorFuel; +import forestry.api.recipes.RecipeManagers; +import forestry.core.config.Config; +import forestry.core.config.Constants; +import forestry.core.fluids.BlockForestryFluid; +import forestry.core.fluids.Fluids; +import forestry.core.fluids.LiquidRegistryHelper; +import forestry.core.items.EnumContainerType; +import forestry.core.items.ItemLiquidContainer; +import forestry.core.items.ItemRegistryFluids; +import forestry.core.utils.Log; +import forestry.core.utils.StringUtil; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.util.MovingObjectPosition; +import net.minecraftforge.client.event.TextureStitchEvent; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.entity.player.FillBucketEvent; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; + +@Plugin( + pluginID = "Fluids", + name = "Fluids", + author = "mezz", + url = Constants.URL, + unlocalizedDescription = "for.plugin.fluids.description") +public class PluginFluids extends ForestryPlugin { + + private static final List forestryFluidsWithBlocks = new ArrayList<>(); + + public static ItemRegistryFluids items; + + private static void createFluid(Fluids forestryFluid) { + if (forestryFluid.getFluid() == null && Config.isFluidEnabled(forestryFluid)) { + String fluidName = forestryFluid.getTag(); + if (!FluidRegistry.isFluidRegistered(fluidName)) { + Fluid fluid = new Fluid(fluidName) + .setDensity(forestryFluid.getDensity()) + .setViscosity(forestryFluid.getViscosity()) + .setTemperature(forestryFluid.getTemperature()); + FluidRegistry.registerFluid(fluid); + createBlock(forestryFluid); + } + } + } + + private static void createBlock(Fluids forestryFluid) { + Fluid fluid = forestryFluid.getFluid(); + Block fluidBlock = fluid.getBlock(); + + if (Config.isBlockEnabled(forestryFluid.getTag())) { + if (fluidBlock == null) { + fluidBlock = forestryFluid.makeBlock(); + if (fluidBlock != null) { + fluidBlock.setBlockName("forestry.fluid." + forestryFluid.getTag()); + GameRegistry.registerBlock(fluidBlock, ItemBlock.class, StringUtil.cleanBlockName(fluidBlock)); + forestryFluidsWithBlocks.add(forestryFluid); + } + } else { + GameRegistry.UniqueIdentifier blockID = GameRegistry.findUniqueIdentifierFor(fluidBlock); + Log.severe( + "Pre-existing {0} fluid block detected, deferring to {1}:{2}, " + + "this may cause issues if the server/client have different mod load orders, " + + "recommended that you disable all but one instance of {0} fluid blocks via your configs.", + fluid.getName(), blockID.modId, blockID.name); + } + } + } + + @Override + public void registerItemsAndBlocks() { + for (Fluids fluidType : Fluids.forestryFluids) { + createFluid(fluidType); + } + + items = new ItemRegistryFluids(); + } + + @Override + public void preInit() { + MinecraftForge.EVENT_BUS.register(getTextureHook()); + MinecraftForge.EVENT_BUS.register(getFillBucketHook()); + } + + @Override + public void doInit() { + for (Fluids fluidType : Fluids.values()) { + if (fluidType.getFluid() == null) { + continue; + } + + for (EnumContainerType type : EnumContainerType.values()) { + ItemLiquidContainer container = items.getContainer(type, fluidType); + if (container == null) { + continue; + } + + LiquidRegistryHelper.registerLiquidContainer(fluidType, container.getItemStack()); + } + + for (ItemStack filledContainer : fluidType.getOtherContainers()) { + LiquidRegistryHelper.registerLiquidContainer(fluidType, filledContainer); + } + } + + if (RecipeManagers.squeezerManager != null) { + RecipeManagers.squeezerManager.addContainerRecipe( + 10, items.canEmpty.getItemStack(), PluginCore.items.ingotTin.getItemStack(), 0.05f); + RecipeManagers.squeezerManager.addContainerRecipe( + 10, items.waxCapsuleEmpty.getItemStack(), PluginCore.items.beeswax.getItemStack(), 0.10f); + RecipeManagers.squeezerManager.addContainerRecipe( + 10, items.refractoryEmpty.getItemStack(), PluginCore.items.refractoryWax.getItemStack(), 0.10f); + } + + FluidStack ethanol = Fluids.ETHANOL.getFluid(1); + GeneratorFuel ethanolFuel = new GeneratorFuel( + ethanol, (int) (32 * ForestryAPI.activeMode.getFloatSetting("fuel.ethanol.generator")), 4); + FuelManager.generatorFuel.put(ethanol.getFluid(), ethanolFuel); + + FluidStack biomass = Fluids.BIOMASS.getFluid(1); + GeneratorFuel biomassFuel = new GeneratorFuel( + biomass, (int) (8 * ForestryAPI.activeMode.getFloatSetting("fuel.biomass.generator")), 1); + FuelManager.generatorFuel.put(biomass.getFluid(), biomassFuel); + } + + public static class MissingFluidException extends RuntimeException { + public MissingFluidException(String tag) { + super("Fluid '" + tag + "' was not found. Please check your configs."); + } + } + + @Override + public void postInit() { + for (Fluids fluidType : Fluids.forestryFluids) { + if (fluidType.getFluid() == null && Config.isFluidEnabled(fluidType)) { + throw new MissingFluidException(fluidType.getTag()); + } + } + } + + public static class TextureHook { + @SubscribeEvent + @SideOnly(Side.CLIENT) + public void textureHook(TextureStitchEvent.Post event) { + if (event.map.getTextureType() == 0) { + for (Fluids fluidType : forestryFluidsWithBlocks) { + Fluid fluid = fluidType.getFluid(); + Block fluidBlock = fluidType.getBlock(); + if (fluid != null && fluidBlock != null) { + fluid.setIcons(fluidBlock.getBlockTextureFromSide(1), fluidBlock.getBlockTextureFromSide(2)); + } + } + } + } + } + + private static Object getTextureHook() { + return new TextureHook(); + } + + public static class FillBucketHook { + @SubscribeEvent + public void fillBucket(FillBucketEvent event) { + ItemStack bucket = event.current; + if (bucket == null || bucket.getItem() != Items.bucket) { + return; + } + + MovingObjectPosition movingObjectPosition = event.target; + int x = movingObjectPosition.blockX; + int y = movingObjectPosition.blockY; + int z = movingObjectPosition.blockZ; + Block targetedBlock = event.world.getBlock(x, y, z); + if (targetedBlock instanceof BlockForestryFluid) { + Item filledBucket = ItemLiquidContainer.getExistingBucket(targetedBlock); + if (filledBucket != null) { + event.result = new ItemStack(filledBucket); + event.setResult(Event.Result.ALLOW); + if (!event.world.isRemote) { + event.world.setBlockToAir(x, y, z); + } + } + } + } + } + + private static Object getFillBucketHook() { + return new FillBucketHook(); + } +} diff --git a/src/main/java/forestry/plugins/PluginFood.java b/src/main/java/forestry/plugins/PluginFood.java index ee301304c..6c167897d 100755 --- a/src/main/java/forestry/plugins/PluginFood.java +++ b/src/main/java/forestry/plugins/PluginFood.java @@ -10,9 +10,6 @@ ******************************************************************************/ package forestry.plugins; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - import forestry.api.food.BeverageManager; import forestry.apiculture.items.EnumPollenCluster; import forestry.apiculture.items.ItemRegistryApiculture; @@ -25,51 +22,63 @@ import forestry.food.InfuserIngredientManager; import forestry.food.InfuserMixtureManager; import forestry.food.items.EnumBeverage; import forestry.food.items.ItemRegistryFood; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; -@Plugin(pluginID = "Food", name = "Food", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.food.description") +@Plugin( + pluginID = "Food", + name = "Food", + author = "SirSengir", + url = Constants.URL, + unlocalizedDescription = "for.plugin.food.description") public class PluginFood extends ForestryPlugin { - public static ItemRegistryFood items; + public static ItemRegistryFood items; - @Override - protected void setupAPI() { - super.setupAPI(); + @Override + protected void setupAPI() { + super.setupAPI(); - // Init seasoner - BeverageManager.infuserManager = new InfuserMixtureManager(); - BeverageManager.ingredientManager = new InfuserIngredientManager(); - } + // Init seasoner + BeverageManager.infuserManager = new InfuserMixtureManager(); + BeverageManager.ingredientManager = new InfuserIngredientManager(); + } - @Override - protected void registerItemsAndBlocks() { - items = new ItemRegistryFood(); - } + @Override + protected void registerItemsAndBlocks() { + items = new ItemRegistryFood(); + } - @Override - protected void preInit() { - super.preInit(); + @Override + protected void preInit() { + super.preInit(); - LiquidRegistryHelper.registerLiquidContainer(Fluids.SHORT_MEAD, Constants.BUCKET_VOLUME, items.beverage.get(EnumBeverage.MEAD_SHORT, 1), new ItemStack(Items.glass_bottle)); - LiquidRegistryHelper.registerLiquidContainer(Fluids.MEAD, Constants.BUCKET_VOLUME, items.beverage.get(EnumBeverage.MEAD, 1), new ItemStack(Items.glass_bottle)); + LiquidRegistryHelper.registerLiquidContainer( + Fluids.SHORT_MEAD, + Constants.BUCKET_VOLUME, + items.beverage.get(EnumBeverage.MEAD_SHORT, 1), + new ItemStack(Items.glass_bottle)); + LiquidRegistryHelper.registerLiquidContainer( + Fluids.MEAD, + Constants.BUCKET_VOLUME, + items.beverage.get(EnumBeverage.MEAD, 1), + new ItemStack(Items.glass_bottle)); - ItemRegistryApiculture beeItems = PluginApiculture.items; - if (beeItems != null) { - ItemStack normalPollenCluster = beeItems.pollenCluster.get(EnumPollenCluster.NORMAL, 1); - ItemStack crystallinePollenCluster = beeItems.pollenCluster.get(EnumPollenCluster.CRYSTALLINE, 1); + ItemRegistryApiculture beeItems = PluginApiculture.items; + if (beeItems != null) { + ItemStack normalPollenCluster = beeItems.pollenCluster.get(EnumPollenCluster.NORMAL, 1); + ItemStack crystallinePollenCluster = beeItems.pollenCluster.get(EnumPollenCluster.CRYSTALLINE, 1); - BeverageManager.ingredientManager.addIngredient(normalPollenCluster, "Strong Curative"); - BeverageManager.ingredientManager.addIngredient(crystallinePollenCluster, "Weak Curative"); - BeverageManager.infuserManager.addMixture(1, normalPollenCluster, BeverageEffect.strongAntidote); - BeverageManager.infuserManager.addMixture(1, crystallinePollenCluster, BeverageEffect.weakAntidote); - } - } + BeverageManager.ingredientManager.addIngredient(normalPollenCluster, "Strong Curative"); + BeverageManager.ingredientManager.addIngredient(crystallinePollenCluster, "Weak Curative"); + BeverageManager.infuserManager.addMixture(1, normalPollenCluster, BeverageEffect.strongAntidote); + BeverageManager.infuserManager.addMixture(1, crystallinePollenCluster, BeverageEffect.weakAntidote); + } + } - @Override - protected void registerRecipes() { - // INFUSER - RecipeUtil.addRecipe(items.infuser.getItemStack(), - "X", "#", "X", - '#', "ingotIron", - 'X', "ingotBronze"); - } + @Override + protected void registerRecipes() { + // INFUSER + RecipeUtil.addRecipe(items.infuser.getItemStack(), "X", "#", "X", '#', "ingotIron", 'X', "ingotBronze"); + } } diff --git a/src/main/java/forestry/plugins/PluginLepidopterology.java b/src/main/java/forestry/plugins/PluginLepidopterology.java index cdb258ecc..1248ff105 100755 --- a/src/main/java/forestry/plugins/PluginLepidopterology.java +++ b/src/main/java/forestry/plugins/PluginLepidopterology.java @@ -10,17 +10,7 @@ ******************************************************************************/ package forestry.plugins; -import java.io.File; -import java.util.EnumSet; - -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.CraftingManager; - -import net.minecraftforge.oredict.OreDictionary; -import net.minecraftforge.oredict.RecipeSorter; - import cpw.mods.fml.common.SidedProxy; - import forestry.Forestry; import forestry.api.arboriculture.TreeManager; import forestry.api.genetics.AlleleManager; @@ -46,102 +36,137 @@ import forestry.lepidopterology.genetics.MothDefinition; import forestry.lepidopterology.items.ItemRegistryLepidopterology; import forestry.lepidopterology.proxy.ProxyLepidopterology; import forestry.lepidopterology.recipes.MatingRecipe; +import java.io.File; +import java.util.EnumSet; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraftforge.oredict.OreDictionary; +import net.minecraftforge.oredict.RecipeSorter; -@Plugin(pluginID = "Lepidopterology", name = "Lepidopterology", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.lepidopterology.description") +@Plugin( + pluginID = "Lepidopterology", + name = "Lepidopterology", + author = "SirSengir", + url = Constants.URL, + unlocalizedDescription = "for.plugin.lepidopterology.description") public class PluginLepidopterology extends ForestryPlugin { - @SidedProxy(clientSide = "forestry.lepidopterology.proxy.ProxyLepidopterologyClient", serverSide = "forestry.lepidopterology.proxy.ProxyLepidopterology") - public static ProxyLepidopterology proxy; - private static final String CONFIG_CATEGORY = "lepidopterology"; - public static int spawnConstraint = 100; - public static int entityConstraint = 1000; - private static boolean allowPollination = true; + @SidedProxy( + clientSide = "forestry.lepidopterology.proxy.ProxyLepidopterologyClient", + serverSide = "forestry.lepidopterology.proxy.ProxyLepidopterology") + public static ProxyLepidopterology proxy; - public static ItemRegistryLepidopterology items; - public static BlockRegistryLepidopterology blocks; + private static final String CONFIG_CATEGORY = "lepidopterology"; + public static int spawnConstraint = 100; + public static int entityConstraint = 1000; + private static boolean allowPollination = true; - @Override - protected void setupAPI() { - super.setupAPI(); + public static ItemRegistryLepidopterology items; + public static BlockRegistryLepidopterology blocks; - ButterflyManager.butterflyRoot = new ButterflyHelper(); - AlleleManager.alleleRegistry.registerSpeciesRoot(ButterflyManager.butterflyRoot); + @Override + protected void setupAPI() { + super.setupAPI(); - ButterflyManager.butterflyFactory = new ButterflyFactory(); - } + ButterflyManager.butterflyRoot = new ButterflyHelper(); + AlleleManager.alleleRegistry.registerSpeciesRoot(ButterflyManager.butterflyRoot); - @Override - protected void registerItemsAndBlocks() { - items = new ItemRegistryLepidopterology(); - blocks = new BlockRegistryLepidopterology(); - } + ButterflyManager.butterflyFactory = new ButterflyFactory(); + } - @Override - public void preInit() { - ButterflyBranchDefinition.createAlleles(); - AlleleButterflyEffect.createAlleles(); + @Override + protected void registerItemsAndBlocks() { + items = new ItemRegistryLepidopterology(); + blocks = new BlockRegistryLepidopterology(); + } - MachineDefinition definitionChest = new MachineDefinition(BlockLepidopterologyType.LEPICHEST) - .setBoundingBox(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); - blocks.lepidopterology.addDefinition(definitionChest); - } + @Override + public void preInit() { + ButterflyBranchDefinition.createAlleles(); + AlleleButterflyEffect.createAlleles(); - @Override - public EnumSet getDependancies() { - EnumSet deps = super.getDependancies(); - deps.add(PluginManager.Module.ARBORICULTURE); - return deps; - } + MachineDefinition definitionChest = new MachineDefinition(BlockLepidopterologyType.LEPICHEST) + .setBoundingBox(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); + blocks.lepidopterology.addDefinition(definitionChest); + } - @Override - public void doInit() { - File configFile = new File(Forestry.instance.getConfigFolder(), CONFIG_CATEGORY + ".cfg"); - loadConfig(configFile); + @Override + public EnumSet getDependancies() { + EnumSet deps = super.getDependancies(); + deps.add(PluginManager.Module.ARBORICULTURE); + return deps; + } - PluginCore.rootCommand.addChildCommand(new CommandButterfly()); + @Override + public void doInit() { + File configFile = new File(Forestry.instance.getConfigFolder(), CONFIG_CATEGORY + ".cfg"); + loadConfig(configFile); - EntityUtil.registerEntity(EntityButterfly.class, "butterflyGE", 0, 0x000000, 0xffffff, 50, 1, true); - proxy.initializeRendering(); + PluginCore.rootCommand.addChildCommand(new CommandButterfly()); - MothDefinition.initMoths(); - ButterflyDefinition.initButterflies(); + EntityUtil.registerEntity(EntityButterfly.class, "butterflyGE", 0, 0x000000, 0xffffff, 50, 1, true); + proxy.initializeRendering(); - blocks.lepidopterology.init(); + MothDefinition.initMoths(); + ButterflyDefinition.initButterflies(); - TreeManager.treeRoot.registerLeafTickHandler(new ButterflySpawner()); + blocks.lepidopterology.init(); - RecipeSorter.register("forestry:lepidopterologymating", MatingRecipe.class, RecipeSorter.Category.SHAPELESS, "before:minecraft:shapeless"); - } + TreeManager.treeRoot.registerLeafTickHandler(new ButterflySpawner()); - private static void loadConfig(File configFile) { - LocalizedConfiguration config = new LocalizedConfiguration(configFile, "1.0.0"); + RecipeSorter.register( + "forestry:lepidopterologymating", + MatingRecipe.class, + RecipeSorter.Category.SHAPELESS, + "before:minecraft:shapeless"); + } - spawnConstraint = config.getIntLocalized("butterfly.entities", "spawn.limit", spawnConstraint, 0, 500); - entityConstraint = config.getIntLocalized("butterfly.entities", "maximum", entityConstraint, 0, 5000); - allowPollination = config.getBooleanLocalized("butterfly.entities", "pollination", allowPollination); + private static void loadConfig(File configFile) { + LocalizedConfiguration config = new LocalizedConfiguration(configFile, "1.0.0"); - config.save(); - } + spawnConstraint = config.getIntLocalized("butterfly.entities", "spawn.limit", spawnConstraint, 0, 500); + entityConstraint = config.getIntLocalized("butterfly.entities", "maximum", entityConstraint, 0, 5000); + allowPollination = config.getBooleanLocalized("butterfly.entities", "pollination", allowPollination); - @SuppressWarnings("unchecked") - @Override - protected void registerRecipes() { - CraftingManager.getInstance().getRecipeList().add(new MatingRecipe()); + config.save(); + } - RecipeManagers.carpenterManager.addRecipe(100, Fluids.WATER.getFluid(2000), null, items.flutterlyzer.getItemStack(), - "X#X", "X#X", "RDR", '#', "paneGlass", 'X', "ingotBronze", 'R', - "dustRedstone", 'D', "gemDiamond"); + @SuppressWarnings("unchecked") + @Override + protected void registerRecipes() { + CraftingManager.getInstance().getRecipeList().add(new MatingRecipe()); - RecipeUtil.addRecipe(blocks.lepidopterology.get(BlockLepidopterologyType.LEPICHEST), - " # ", - "XYX", - "XXX", - '#', "blockGlass", - 'X', new ItemStack(items.butterflyGE, 1, OreDictionary.WILDCARD_VALUE), - 'Y', "chestWood"); - } + RecipeManagers.carpenterManager.addRecipe( + 100, + Fluids.WATER.getFluid(2000), + null, + items.flutterlyzer.getItemStack(), + "X#X", + "X#X", + "RDR", + '#', + "paneGlass", + 'X', + "ingotBronze", + 'R', + "dustRedstone", + 'D', + "gemDiamond"); - public static boolean isPollinationAllowed() { - return allowPollination; - } + RecipeUtil.addRecipe( + blocks.lepidopterology.get(BlockLepidopterologyType.LEPICHEST), + " # ", + "XYX", + "XXX", + '#', + "blockGlass", + 'X', + new ItemStack(items.butterflyGE, 1, OreDictionary.WILDCARD_VALUE), + 'Y', + "chestWood"); + } + + public static boolean isPollinationAllowed() { + return allowPollination; + } } diff --git a/src/main/java/forestry/plugins/PluginMail.java b/src/main/java/forestry/plugins/PluginMail.java index b4d3d9b4f..2a39935a6 100755 --- a/src/main/java/forestry/plugins/PluginMail.java +++ b/src/main/java/forestry/plugins/PluginMail.java @@ -10,11 +10,7 @@ ******************************************************************************/ package forestry.plugins; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - import cpw.mods.fml.common.FMLCommonHandler; - import forestry.api.mail.EnumAddressee; import forestry.api.mail.PostManager; import forestry.api.recipes.RecipeManagers; @@ -39,129 +35,164 @@ import forestry.mail.items.EnumStampDefinition; import forestry.mail.items.ItemRegistryMail; import forestry.mail.network.PacketRegistryMail; import forestry.mail.triggers.MailTriggers; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; -@Plugin(pluginID = "Mail", name = "Mail", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.mail.description") +@Plugin( + pluginID = "Mail", + name = "Mail", + author = "SirSengir", + url = Constants.URL, + unlocalizedDescription = "for.plugin.mail.description") public class PluginMail extends ForestryPlugin { - public static ItemRegistryMail items; - public static BlockRegistryMail blocks; + public static ItemRegistryMail items; + public static BlockRegistryMail blocks; - @Override - protected void setupAPI() { - super.setupAPI(); + @Override + protected void setupAPI() { + super.setupAPI(); - PostManager.postRegistry = new PostRegistry(); - PostManager.postRegistry.registerCarrier(new PostalCarrier(EnumAddressee.PLAYER)); - PostManager.postRegistry.registerCarrier(new PostalCarrier(EnumAddressee.TRADER)); - } + PostManager.postRegistry = new PostRegistry(); + PostManager.postRegistry.registerCarrier(new PostalCarrier(EnumAddressee.PLAYER)); + PostManager.postRegistry.registerCarrier(new PostalCarrier(EnumAddressee.TRADER)); + } - @Override - protected void registerItemsAndBlocks() { - items = new ItemRegistryMail(); - blocks = new BlockRegistryMail(); - } + @Override + protected void registerItemsAndBlocks() { + items = new ItemRegistryMail(); + blocks = new BlockRegistryMail(); + } - @Override - public void preInit() { - super.preInit(); - - PluginCore.rootCommand.addChildCommand(new CommandMail()); + @Override + public void preInit() { + super.preInit(); - if (Config.mailAlertEnabled) { - FMLCommonHandler.instance().bus().register(new EventHandlerMailAlert()); - } + PluginCore.rootCommand.addChildCommand(new CommandMail()); - blocks.mail.addDefinitions( - new MachineDefinition(BlockMailType.MAILBOX).setFaces(0, 1, 2, 2, 2, 2, 0, 7), - new MachineDefinition(BlockMailType.TRADESTATION).setFaces(0, 1, 2, 3, 4, 4, 0, 7), - new MachineDefinition(BlockMailType.PHILATELIST).setFaces(0, 1, 2, 3, 2, 2, 0, 7) - ); - } + if (Config.mailAlertEnabled) { + FMLCommonHandler.instance().bus().register(new EventHandlerMailAlert()); + } - @Override - protected void registerTriggers() { - MailTriggers.initialize(); - } + blocks.mail.addDefinitions( + new MachineDefinition(BlockMailType.MAILBOX).setFaces(0, 1, 2, 2, 2, 2, 0, 7), + new MachineDefinition(BlockMailType.TRADESTATION).setFaces(0, 1, 2, 3, 4, 4, 0, 7), + new MachineDefinition(BlockMailType.PHILATELIST).setFaces(0, 1, 2, 3, 2, 2, 0, 7)); + } - @Override - public void doInit() { - super.doInit(); + @Override + protected void registerTriggers() { + MailTriggers.initialize(); + } - blocks.mail.init(); - } + @Override + public void doInit() { + super.doInit(); - @Override - public IPacketRegistry getPacketRegistry() { - return new PacketRegistryMail(); - } + blocks.mail.init(); + } - @Override - protected void registerRecipes() { - Object stampGlue; - Object letterGlue; + @Override + public IPacketRegistry getPacketRegistry() { + return new PacketRegistryMail(); + } - ItemRegistryApiculture beeItems = PluginApiculture.items; - if (beeItems != null) { - stampGlue = beeItems.honeyDrop; - letterGlue = beeItems.propolis.getWildcard(); - } else { - stampGlue = Items.slime_ball; - letterGlue = Items.slime_ball; - } + @Override + protected void registerRecipes() { + Object stampGlue; + Object letterGlue; - RecipeUtil.addShapelessRecipe(items.letters.getItemStack(), Items.paper, letterGlue); + ItemRegistryApiculture beeItems = PluginApiculture.items; + if (beeItems != null) { + stampGlue = beeItems.honeyDrop; + letterGlue = beeItems.propolis.getWildcard(); + } else { + stampGlue = Items.slime_ball; + letterGlue = Items.slime_ball; + } - if (Config.craftingStampsEnabled) { - for (EnumStampDefinition stampDefinition : EnumStampDefinition.VALUES) { - if (Config.collectorStamps.contains(stampDefinition.getName())) { - continue; - } + RecipeUtil.addShapelessRecipe(items.letters.getItemStack(), Items.paper, letterGlue); - ItemStack stamps = items.stamps.get(stampDefinition, 9); + if (Config.craftingStampsEnabled) { + for (EnumStampDefinition stampDefinition : EnumStampDefinition.VALUES) { + if (Config.collectorStamps.contains(stampDefinition.getName())) { + continue; + } - RecipeUtil.addRecipe(stamps, - "XXX", - "###", - "ZZZ", - 'X', stampDefinition.getCraftingIngredient(), - '#', Items.paper, - 'Z', stampGlue); - RecipeManagers.carpenterManager.addRecipe(10, Fluids.SEEDOIL.getFluid(300), null, stamps, - "XXX", - "###", - 'X', stampDefinition.getCraftingIngredient(), - '#', Items.paper); - } - } + ItemStack stamps = items.stamps.get(stampDefinition, 9); - // Recycling - RecipeUtil.addRecipe(new ItemStack(Items.paper), "###", '#', items.letters.getWildcard()); + RecipeUtil.addRecipe( + stamps, + "XXX", + "###", + "ZZZ", + 'X', + stampDefinition.getCraftingIngredient(), + '#', + Items.paper, + 'Z', + stampGlue); + RecipeManagers.carpenterManager.addRecipe( + 10, + Fluids.SEEDOIL.getFluid(300), + null, + stamps, + "XXX", + "###", + 'X', + stampDefinition.getCraftingIngredient(), + '#', + Items.paper); + } + } - // Carpenter - RecipeManagers.carpenterManager.addRecipe(10, Fluids.WATER.getFluid(250), null, items.letters.getItemStack(), "###", "###", '#', PluginCore.items.woodPulp); + // Recycling + RecipeUtil.addRecipe(new ItemStack(Items.paper), "###", '#', items.letters.getWildcard()); - RecipeUtil.addShapelessRecipe(items.catalogue.getItemStack(), items.stamps.getWildcard(), new ItemStack(Items.book)); + // Carpenter + RecipeManagers.carpenterManager.addRecipe( + 10, + Fluids.WATER.getFluid(250), + null, + items.letters.getItemStack(), + "###", + "###", + '#', + PluginCore.items.woodPulp); - RecipeUtil.addRecipe(blocks.mail.get(BlockMailType.MAILBOX), - " # ", - "#Y#", - "XXX", - '#', "ingotTin", - 'X', "chestWood", - 'Y', PluginCore.items.sturdyCasing); + RecipeUtil.addShapelessRecipe( + items.catalogue.getItemStack(), items.stamps.getWildcard(), new ItemStack(Items.book)); - RecipeUtil.addRecipe(blocks.mail.get(BlockMailType.TRADESTATION), - "Z#Z", - "#Y#", - "XWX", - '#', PluginCore.items.tubes.get(EnumElectronTube.BRONZE, 1), - 'X', "chestWood", - 'Y', PluginCore.items.sturdyCasing, - 'Z', PluginCore.items.tubes.get(EnumElectronTube.IRON, 1), - 'W', PluginCore.items.circuitboards.get(EnumCircuitBoardType.REFINED)); - } + RecipeUtil.addRecipe( + blocks.mail.get(BlockMailType.MAILBOX), + " # ", + "#Y#", + "XXX", + '#', + "ingotTin", + 'X', + "chestWood", + 'Y', + PluginCore.items.sturdyCasing); - @Override - public ISaveEventHandler getSaveEventHandler() { - return new SaveEventHandlerMail(); - } + RecipeUtil.addRecipe( + blocks.mail.get(BlockMailType.TRADESTATION), + "Z#Z", + "#Y#", + "XWX", + '#', + PluginCore.items.tubes.get(EnumElectronTube.BRONZE, 1), + 'X', + "chestWood", + 'Y', + PluginCore.items.sturdyCasing, + 'Z', + PluginCore.items.tubes.get(EnumElectronTube.IRON, 1), + 'W', + PluginCore.items.circuitboards.get(EnumCircuitBoardType.REFINED)); + } + + @Override + public ISaveEventHandler getSaveEventHandler() { + return new SaveEventHandlerMail(); + } } diff --git a/src/main/java/forestry/plugins/PluginManager.java b/src/main/java/forestry/plugins/PluginManager.java index c61fd6054..558423130 100644 --- a/src/main/java/forestry/plugins/PluginManager.java +++ b/src/main/java/forestry/plugins/PluginManager.java @@ -12,30 +12,9 @@ package forestry.plugins; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; - -import java.io.File; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Locale; -import java.util.Random; -import java.util.Set; - -import net.minecraft.command.CommandHandler; -import net.minecraft.command.ICommand; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.StatCollector; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; - -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.common.config.Property; - import cpw.mods.fml.common.IFuelHandler; import cpw.mods.fml.common.event.FMLInterModComms; import cpw.mods.fml.common.registry.GameRegistry; - import forestry.Forestry; import forestry.api.core.ForestryAPI; import forestry.core.IPickupHandler; @@ -62,309 +41,334 @@ import forestry.plugins.compat.PluginNatura; import forestry.plugins.compat.PluginPlantMegaPack; import forestry.plugins.compat.PluginRotaryCraft; import forestry.plugins.compat.PluginWitchery; +import java.io.File; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Locale; +import java.util.Random; +import java.util.Set; +import net.minecraft.command.CommandHandler; +import net.minecraft.command.ICommand; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.StatCollector; +import net.minecraft.world.World; +import net.minecraft.world.chunk.IChunkProvider; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; public class PluginManager { - private static final String MODULE_CONFIG_FILE_NAME = "modules.cfg"; - private static final String CATEGORY_MODULES = "modules"; + private static final String MODULE_CONFIG_FILE_NAME = "modules.cfg"; + private static final String CATEGORY_MODULES = "modules"; - public static final ArrayList pickupHandlers = Lists.newArrayList(); - public static final ArrayList saveEventHandlers = Lists.newArrayList(); - public static final ArrayList resupplyHandlers = Lists.newArrayList(); + public static final ArrayList pickupHandlers = Lists.newArrayList(); + public static final ArrayList saveEventHandlers = Lists.newArrayList(); + public static final ArrayList resupplyHandlers = Lists.newArrayList(); - private static final Set loadedModules = EnumSet.noneOf(Module.class); - private static final Set unloadedModules = EnumSet.allOf(Module.class); - private static Stage stage = Stage.SETUP; + private static final Set loadedModules = EnumSet.noneOf(Module.class); + private static final Set unloadedModules = EnumSet.allOf(Module.class); + private static Stage stage = Stage.SETUP; - public enum Stage { - SETUP, // setup API to make it functional, register basic blocks and items. GameMode Configs are not yet accessible - SETUP_DISABLED, // setup fallback API to avoid crashes - PRE_INIT, // register handlers, triggers, definitions, backpacks, crates, and anything that depends on basic items - INIT, // anything that depends on PreInit stages, recipe registration - POST_INIT, // stubborn mod integration, dungeon loot, and finalization of things that take input from mods - FINISHED - } + public enum Stage { + SETUP, // setup API to make it functional, register basic blocks and items. GameMode Configs are not yet + // accessible + SETUP_DISABLED, // setup fallback API to avoid crashes + PRE_INIT, // register handlers, triggers, definitions, backpacks, crates, and anything that depends on basic + // items + INIT, // anything that depends on PreInit stages, recipe registration + POST_INIT, // stubborn mod integration, dungeon loot, and finalization of things that take input from mods + FINISHED + } - public enum Module { + public enum Module { + CORE(new PluginCore(), false), + FLUIDS(new PluginFluids(), false), - CORE(new PluginCore(), false), - FLUIDS(new PluginFluids(), false), + APICULTURE(new PluginApiculture()), + ARBORICULTURE(new PluginArboriculture()), + ENERGY(new PluginEnergy()), + FACTORY(new PluginFactory()), + FARMING(new PluginFarming()), + FOOD(new PluginFood()), + LEPIDOPTEROLOGY(new PluginLepidopterology()), + MAIL(new PluginMail()), + STORAGE(new PluginStorage()), - APICULTURE(new PluginApiculture()), - ARBORICULTURE(new PluginArboriculture()), - ENERGY(new PluginEnergy()), - FACTORY(new PluginFactory()), - FARMING(new PluginFarming()), - FOOD(new PluginFood()), - LEPIDOPTEROLOGY(new PluginLepidopterology()), - MAIL(new PluginMail()), - STORAGE(new PluginStorage()), + BUILDCRAFT_FUELS(new PluginBuildCraftFuels()), + BUILDCRAFT_RECIPES(new PluginBuildCraftRecipes()), + BUILDCRAFT_STATEMENTS(new PluginBuildCraftStatements()), + BUILDCRAFT_TRANSPORT(new PluginBuildCraftTransport()), - BUILDCRAFT_FUELS(new PluginBuildCraftFuels()), - BUILDCRAFT_RECIPES(new PluginBuildCraftRecipes()), - BUILDCRAFT_STATEMENTS(new PluginBuildCraftStatements()), - BUILDCRAFT_TRANSPORT(new PluginBuildCraftTransport()), - - AGRICRAFT(new PluginAgriCraft()), - BIOMESOPLENTY(new PluginBiomesOPlenty()), - CHISEL(new PluginChisel()), - ENDERIO(new PluginEnderIO()), - EREBUS(new PluginErebus()), - EXTRAUTILITIES(new PluginExtraUtilities()), - GROWTHCRAFT(new PluginGrowthCraft()), - HARVESTCRAFT(new PluginHarvestCraft()), - IMMERSIVEENGINEERING(new PluginImmersiveEngineering()), - INDUSTRIALCRAFT(new PluginIC2()), - MAGICALCROPS(new PluginMagicalCrops()), - MINEFACTORYRELOADED(new PluginMineFactoryReloaded()), - NATURA(new PluginNatura()), - PLANTMEGAPACK(new PluginPlantMegaPack()), - ROTARYCRAFT(new PluginRotaryCraft()), - WITCHERY(new PluginWitchery()); + AGRICRAFT(new PluginAgriCraft()), + BIOMESOPLENTY(new PluginBiomesOPlenty()), + CHISEL(new PluginChisel()), + ENDERIO(new PluginEnderIO()), + EREBUS(new PluginErebus()), + EXTRAUTILITIES(new PluginExtraUtilities()), + GROWTHCRAFT(new PluginGrowthCraft()), + HARVESTCRAFT(new PluginHarvestCraft()), + IMMERSIVEENGINEERING(new PluginImmersiveEngineering()), + INDUSTRIALCRAFT(new PluginIC2()), + MAGICALCROPS(new PluginMagicalCrops()), + MINEFACTORYRELOADED(new PluginMineFactoryReloaded()), + NATURA(new PluginNatura()), + PLANTMEGAPACK(new PluginPlantMegaPack()), + ROTARYCRAFT(new PluginRotaryCraft()), + WITCHERY(new PluginWitchery()); - static { - ForestryAPI.enabledPlugins = new HashSet<>(); - } + static { + ForestryAPI.enabledPlugins = new HashSet<>(); + } - private final ForestryPlugin instance; - private final boolean canBeDisabled; + private final ForestryPlugin instance; + private final boolean canBeDisabled; - Module(ForestryPlugin plugin) { - this(plugin, true); - } + Module(ForestryPlugin plugin) { + this(plugin, true); + } - Module(ForestryPlugin plugin, boolean canBeDisabled) { - this.instance = plugin; - this.canBeDisabled = canBeDisabled; - } + Module(ForestryPlugin plugin, boolean canBeDisabled) { + this.instance = plugin; + this.canBeDisabled = canBeDisabled; + } - public ForestryPlugin instance() { - return instance; - } + public ForestryPlugin instance() { + return instance; + } - public boolean isEnabled() { - return ForestryAPI.enabledPlugins.contains(toString()); - } + public boolean isEnabled() { + return ForestryAPI.enabledPlugins.contains(toString()); + } - public boolean canBeDisabled() { - return canBeDisabled; - } + public boolean canBeDisabled() { + return canBeDisabled; + } - public String configName() { - return toString().toLowerCase(Locale.ENGLISH).replace('_', '.'); - } + public String configName() { + return toString().toLowerCase(Locale.ENGLISH).replace('_', '.'); + } + } - } + public static final EnumSet configDisabledModules = EnumSet.noneOf(Module.class); - public static final EnumSet configDisabledModules = EnumSet.noneOf(Module.class); + public static Stage getStage() { + return stage; + } - public static Stage getStage() { - return stage; - } + public static EnumSet getLoadedModules() { + return EnumSet.copyOf(loadedModules); + } - public static EnumSet getLoadedModules() { - return EnumSet.copyOf(loadedModules); - } + private static void registerHandlers(ForestryPlugin plugin) { + Log.fine("Registering Handlers for Plugin: {0}", plugin); - private static void registerHandlers(ForestryPlugin plugin) { - Log.fine("Registering Handlers for Plugin: {0}", plugin); + plugin.getPacketRegistry().registerPackets(); - plugin.getPacketRegistry().registerPackets(); + IPickupHandler pickupHandler = plugin.getPickupHandler(); + if (pickupHandler != null) { + pickupHandlers.add(pickupHandler); + } - IPickupHandler pickupHandler = plugin.getPickupHandler(); - if (pickupHandler != null) { - pickupHandlers.add(pickupHandler); - } + ISaveEventHandler saveHandler = plugin.getSaveEventHandler(); + if (saveHandler != null) { + saveEventHandlers.add(saveHandler); + } - ISaveEventHandler saveHandler = plugin.getSaveEventHandler(); - if (saveHandler != null) { - saveEventHandlers.add(saveHandler); - } + IResupplyHandler resupplyHandler = plugin.getResupplyHandler(); + if (resupplyHandler != null) { + resupplyHandlers.add(resupplyHandler); + } - IResupplyHandler resupplyHandler = plugin.getResupplyHandler(); - if (resupplyHandler != null) { - resupplyHandlers.add(resupplyHandler); - } + IFuelHandler fuelHandler = plugin.getFuelHandler(); + if (fuelHandler != null) { + GameRegistry.registerFuelHandler((fuelHandler)); + } + } - IFuelHandler fuelHandler = plugin.getFuelHandler(); - if (fuelHandler != null) { - GameRegistry.registerFuelHandler((fuelHandler)); - } - } + private static void configureModules() { + Locale locale = Locale.getDefault(); + Locale.setDefault(Locale.ENGLISH); - private static void configureModules() { - Locale locale = Locale.getDefault(); - Locale.setDefault(Locale.ENGLISH); + Configuration config = + new Configuration(new File(Forestry.instance.getConfigFolder(), MODULE_CONFIG_FILE_NAME)); - Configuration config = new Configuration(new File(Forestry.instance.getConfigFolder(), MODULE_CONFIG_FILE_NAME)); + config.load(); + config.addCustomCategoryComment( + CATEGORY_MODULES, + "Disabling these modules can greatly change how the mod functions.\n" + + "Your mileage may vary, please report any issues."); - config.load(); - config.addCustomCategoryComment(CATEGORY_MODULES, "Disabling these modules can greatly change how the mod functions.\n" - + "Your mileage may vary, please report any issues."); + Set toLoad = EnumSet.allOf(Module.class); + Iterator it = toLoad.iterator(); + while (it.hasNext()) { + Module m = it.next(); + if (!m.canBeDisabled()) { + continue; + } + if (!isEnabled(config, m)) { + it.remove(); + Log.info("Module disabled: {0}", m); + continue; + } + ForestryPlugin plugin = m.instance; + if (!plugin.isAvailable()) { + it.remove(); + Log.info("Module {0} failed to load: {1}", plugin, plugin.getFailMessage()); + continue; + } + } - Set toLoad = EnumSet.allOf(Module.class); - Iterator it = toLoad.iterator(); - while (it.hasNext()) { - Module m = it.next(); - if (!m.canBeDisabled()) { - continue; - } - if (!isEnabled(config, m)) { - it.remove(); - Log.info("Module disabled: {0}", m); - continue; - } - ForestryPlugin plugin = m.instance; - if (!plugin.isAvailable()) { - it.remove(); - Log.info("Module {0} failed to load: {1}", plugin, plugin.getFailMessage()); - continue; - } - } + boolean changed; + do { + changed = false; + it = toLoad.iterator(); + while (it.hasNext()) { + Module m = it.next(); + Set deps = m.instance().getDependancies(); + if (!toLoad.containsAll(deps)) { + it.remove(); + changed = true; + Log.warning("Module {0} is missing dependencies: {1}", m, deps); + continue; + } + } + } while (changed); - boolean changed; - do { - changed = false; - it = toLoad.iterator(); - while (it.hasNext()) { - Module m = it.next(); - Set deps = m.instance().getDependancies(); - if (!toLoad.containsAll(deps)) { - it.remove(); - changed = true; - Log.warning("Module {0} is missing dependencies: {1}", m, deps); - continue; - } - } - } while (changed); + unloadedModules.removeAll(toLoad); + loadedModules.addAll(toLoad); - unloadedModules.removeAll(toLoad); - loadedModules.addAll(toLoad); + for (Module m : loadedModules) { + ForestryAPI.enabledPlugins.add(m.toString()); + } - for (Module m : loadedModules) { - ForestryAPI.enabledPlugins.add(m.toString()); - } + if (config.hasChanged()) { + config.save(); + } - if (config.hasChanged()) { - config.save(); - } + Locale.setDefault(locale); + } - Locale.setDefault(locale); - } + public static void runSetup() { + stage = Stage.SETUP; + configureModules(); - public static void runSetup() { - stage = Stage.SETUP; - configureModules(); + for (Module m : loadedModules) { + ForestryPlugin plugin = m.instance; + Log.fine("Setup Start: {0}", plugin); + plugin.setupAPI(); + plugin.registerItemsAndBlocks(); + Log.fine("Setup Complete: {0}", plugin); + } - for (Module m : loadedModules) { - ForestryPlugin plugin = m.instance; - Log.fine("Setup Start: {0}", plugin); - plugin.setupAPI(); - plugin.registerItemsAndBlocks(); - Log.fine("Setup Complete: {0}", plugin); - } + stage = Stage.SETUP_DISABLED; + for (Module m : unloadedModules) { + ForestryPlugin plugin = m.instance; + Log.fine("Disabled-Setup Start: {0}", plugin); + plugin.disabledSetupAPI(); + Log.fine("Disabled-Setup Complete: {0}", plugin); + } + } - stage = Stage.SETUP_DISABLED; - for (Module m : unloadedModules) { - ForestryPlugin plugin = m.instance; - Log.fine("Disabled-Setup Start: {0}", plugin); - plugin.disabledSetupAPI(); - Log.fine("Disabled-Setup Complete: {0}", plugin); - } - } + public static void runPreInit() { + stage = Stage.PRE_INIT; + for (Module m : loadedModules) { + ForestryPlugin plugin = m.instance; + Log.fine("Pre-Init Start: {0}", plugin); + registerHandlers(plugin); + plugin.preInit(); + if (Module.BUILDCRAFT_STATEMENTS.isEnabled()) { + plugin.registerTriggers(); + } + if (Module.STORAGE.isEnabled()) { + plugin.registerBackpackItems(); + plugin.registerCrates(); + } + Log.fine("Pre-Init Complete: {0}", plugin); + } + } - public static void runPreInit() { - stage = Stage.PRE_INIT; - for (Module m : loadedModules) { - ForestryPlugin plugin = m.instance; - Log.fine("Pre-Init Start: {0}", plugin); - registerHandlers(plugin); - plugin.preInit(); - if (Module.BUILDCRAFT_STATEMENTS.isEnabled()) { - plugin.registerTriggers(); - } - if (Module.STORAGE.isEnabled()) { - plugin.registerBackpackItems(); - plugin.registerCrates(); - } - Log.fine("Pre-Init Complete: {0}", plugin); - } - } + public static void runInit() { + stage = Stage.INIT; + for (Module m : loadedModules) { + ForestryPlugin plugin = m.instance; + Log.fine("Init Start: {0}", plugin); + plugin.doInit(); + plugin.registerRecipes(); + Log.fine("Init Complete: {0}", plugin); + } + } - public static void runInit() { - stage = Stage.INIT; - for (Module m : loadedModules) { - ForestryPlugin plugin = m.instance; - Log.fine("Init Start: {0}", plugin); - plugin.doInit(); - plugin.registerRecipes(); - Log.fine("Init Complete: {0}", plugin); - } - } + public static void runPostInit() { + stage = Stage.POST_INIT; + for (Module m : loadedModules) { + ForestryPlugin plugin = m.instance; + Log.fine("Post-Init Start: {0}", plugin); + plugin.postInit(); + Log.fine("Post-Init Complete: {0}", plugin); + } - public static void runPostInit() { - stage = Stage.POST_INIT; - for (Module m : loadedModules) { - ForestryPlugin plugin = m.instance; - Log.fine("Post-Init Start: {0}", plugin); - plugin.postInit(); - Log.fine("Post-Init Complete: {0}", plugin); - } + stage = Stage.FINISHED; + } - stage = Stage.FINISHED; - } + public static void serverStarting(MinecraftServer server) { + CommandHandler commandManager = (CommandHandler) server.getCommandManager(); - public static void serverStarting(MinecraftServer server) { - CommandHandler commandManager = (CommandHandler) server.getCommandManager(); + for (Module m : loadedModules) { + ForestryPlugin plugin = m.instance; + ICommand[] commands = plugin.getConsoleCommands(); + if (commands == null) { + continue; + } + for (ICommand command : commands) { + commandManager.registerCommand(command); + } + } + } - for (Module m : loadedModules) { - ForestryPlugin plugin = m.instance; - ICommand[] commands = plugin.getConsoleCommands(); - if (commands == null) { - continue; - } - for (ICommand command : commands) { - commandManager.registerCommand(command); - } - } - } + public static void processIMCMessages(ImmutableList messages) { + for (FMLInterModComms.IMCMessage message : messages) { + for (Module m : loadedModules) { + ForestryPlugin plugin = m.instance; + if (plugin.processIMCMessage(message)) { + break; + } + } + } + } - public static void processIMCMessages(ImmutableList messages) { - for (FMLInterModComms.IMCMessage message : messages) { - for (Module m : loadedModules) { - ForestryPlugin plugin = m.instance; - if (plugin.processIMCMessage(message)) { - break; - } - } - } - } + public static void populateChunk( + IChunkProvider chunkProvider, + World world, + Random rand, + int chunkX, + int chunkZ, + boolean hasVillageGenerated) { + for (Module m : loadedModules) { + ForestryPlugin plugin = m.instance; + plugin.populateChunk(chunkProvider, world, rand, chunkX, chunkZ, hasVillageGenerated); + } + } - public static void populateChunk(IChunkProvider chunkProvider, World world, Random rand, int chunkX, int chunkZ, boolean hasVillageGenerated) { - for (Module m : loadedModules) { - ForestryPlugin plugin = m.instance; - plugin.populateChunk(chunkProvider, world, rand, chunkX, chunkZ, hasVillageGenerated); - } - } + public static void populateChunkRetroGen(World world, Random rand, int chunkX, int chunkZ) { + for (Module m : loadedModules) { + ForestryPlugin plugin = m.instance; + plugin.populateChunkRetroGen(world, rand, chunkX, chunkZ); + } + } - public static void populateChunkRetroGen(World world, Random rand, int chunkX, int chunkZ) { - for (Module m : loadedModules) { - ForestryPlugin plugin = m.instance; - plugin.populateChunkRetroGen(world, rand, chunkX, chunkZ); - } - } + private static boolean isEnabled(Configuration config, Module m) { + Plugin info = m.instance().getClass().getAnnotation(Plugin.class); - private static boolean isEnabled(Configuration config, Module m) { - Plugin info = m.instance().getClass().getAnnotation(Plugin.class); + String comment = StatCollector.translateToLocal(info.unlocalizedDescription()); + Property prop = config.get(CATEGORY_MODULES, m.configName(), true, comment); + boolean enabled = prop.getBoolean(); - String comment = StatCollector.translateToLocal(info.unlocalizedDescription()); - Property prop = config.get(CATEGORY_MODULES, m.configName(), true, comment); - boolean enabled = prop.getBoolean(); + if (!enabled) { + configDisabledModules.add(m); + } - if (!enabled) { - configDisabledModules.add(m); - } - - return enabled; - } + return enabled; + } } diff --git a/src/main/java/forestry/plugins/PluginStorage.java b/src/main/java/forestry/plugins/PluginStorage.java index 96b24d4ed..a52c1ad42 100755 --- a/src/main/java/forestry/plugins/PluginStorage.java +++ b/src/main/java/forestry/plugins/PluginStorage.java @@ -10,46 +10,8 @@ ******************************************************************************/ package forestry.plugins; -import java.awt.Color; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.regex.Pattern; - -import net.minecraft.block.BlockBasePressurePlate; -import net.minecraft.block.BlockButton; -import net.minecraft.block.BlockChest; -import net.minecraft.block.BlockDoor; -import net.minecraft.block.BlockFence; -import net.minecraft.block.BlockFenceGate; -import net.minecraft.block.BlockFurnace; -import net.minecraft.block.BlockLadder; -import net.minecraft.block.BlockLever; -import net.minecraft.block.BlockRedstoneDiode; -import net.minecraft.block.BlockSlab; -import net.minecraft.block.BlockStairs; -import net.minecraft.block.BlockTorch; -import net.minecraft.block.BlockTrapDoor; -import net.minecraft.block.BlockWall; -import net.minecraft.block.BlockWorkbench; -import net.minecraft.block.IGrowable; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemDoor; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.common.IPlantable; -import net.minecraftforge.common.IShearable; -import net.minecraftforge.common.config.Property; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.oredict.OreDictionary; - import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; - import forestry.Forestry; import forestry.api.recipes.RecipeManagers; import forestry.api.storage.BackpackManager; @@ -77,489 +39,515 @@ import forestry.storage.PickupHandlerStorage; import forestry.storage.ResupplyHandler; import forestry.storage.items.ItemRegistryStorage; import forestry.storage.proxy.ProxyStorage; +import java.awt.Color; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.regex.Pattern; +import net.minecraft.block.BlockBasePressurePlate; +import net.minecraft.block.BlockButton; +import net.minecraft.block.BlockChest; +import net.minecraft.block.BlockDoor; +import net.minecraft.block.BlockFence; +import net.minecraft.block.BlockFenceGate; +import net.minecraft.block.BlockFurnace; +import net.minecraft.block.BlockLadder; +import net.minecraft.block.BlockLever; +import net.minecraft.block.BlockRedstoneDiode; +import net.minecraft.block.BlockSlab; +import net.minecraft.block.BlockStairs; +import net.minecraft.block.BlockTorch; +import net.minecraft.block.BlockTrapDoor; +import net.minecraft.block.BlockWall; +import net.minecraft.block.BlockWorkbench; +import net.minecraft.block.IGrowable; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemDoor; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.IPlantable; +import net.minecraftforge.common.IShearable; +import net.minecraftforge.common.config.Property; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.oredict.OreDictionary; -@Plugin(pluginID = "Storage", name = "Storage", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.storage.description") +@Plugin( + pluginID = "Storage", + name = "Storage", + author = "SirSengir", + url = Constants.URL, + unlocalizedDescription = "for.plugin.storage.description") public class PluginStorage extends ForestryPlugin { - private static final List crates = new ArrayList<>(); - private static final String CONFIG_CATEGORY = "backpacks"; - - @SidedProxy(clientSide = "forestry.storage.proxy.ProxyStorageClient", serverSide = "forestry.storage.proxy.ProxyStorage") - public static ProxyStorage proxy; - private final ArrayList minerItems = new ArrayList<>(); - private final ArrayList diggerItems = new ArrayList<>(); - private final ArrayList foresterItems = new ArrayList<>(); - private final ArrayList hunterItems = new ArrayList<>(); - private final ArrayList adventurerItems = new ArrayList<>(); - private final ArrayList builderItems = new ArrayList<>(); - - public static ItemRegistryStorage items; - - @Override - @SuppressWarnings({"unchecked", "rawtypes"}) - protected void setupAPI() { - super.setupAPI(); - - StorageManager.crateRegistry = new CrateRegistry(); - - BackpackManager.backpackInterface = new BackpackInterface(); - - BackpackManager.backpackItems = new ArrayList[6]; - - BackpackManager.backpackItems[0] = minerItems; - BackpackManager.backpackItems[1] = diggerItems; - BackpackManager.backpackItems[2] = foresterItems; - BackpackManager.backpackItems[3] = hunterItems; - BackpackManager.backpackItems[4] = adventurerItems; - BackpackManager.backpackItems[5] = builderItems; - - BackpackDefinition definition; - - if (PluginManager.Module.APICULTURE.isEnabled()) { - definition = new BackpackDefinitionApiarist(new Color(0xc4923d).getRGB()); - BackpackManager.definitions.put(definition.getKey(), definition); - } - - if (PluginManager.Module.LEPIDOPTEROLOGY.isEnabled()) { - definition = new BackpackDefinitionLepidopterist(new Color(0x995b31).getRGB()); - BackpackManager.definitions.put(definition.getKey(), definition); - } - - definition = new BackpackDefinition("miner", new Color(0x36187d).getRGB()); - BackpackManager.definitions.put(definition.getKey(), definition); - - definition = new BackpackDefinition("digger", new Color(0x363cc5).getRGB()); - BackpackManager.definitions.put(definition.getKey(), definition); - - definition = new BackpackDefinition("forester", new Color(0x347427).getRGB()); - BackpackManager.definitions.put(definition.getKey(), definition); - - definition = new BackpackDefinition("hunter", new Color(0x412215).getRGB()); - BackpackManager.definitions.put(definition.getKey(), definition); - - definition = new BackpackDefinition("adventurer", new Color(0x7fb8c2).getRGB()); - BackpackManager.definitions.put(definition.getKey(), definition); - - definition = new BackpackDefinition("builder", new Color(0xdd3a3a).getRGB()); - BackpackManager.definitions.put(definition.getKey(), definition); - } - - @Override - @SuppressWarnings({"unchecked", "rawtypes"}) - protected void disabledSetupAPI() { - BackpackManager.backpackItems = new ArrayList[6]; - BackpackManager.backpackItems[0] = minerItems; - BackpackManager.backpackItems[1] = diggerItems; - BackpackManager.backpackItems[2] = foresterItems; - BackpackManager.backpackItems[3] = hunterItems; - BackpackManager.backpackItems[4] = adventurerItems; - BackpackManager.backpackItems[5] = builderItems; - } - - @Override - protected void registerItemsAndBlocks() { - items = new ItemRegistryStorage(); - } - - @Override - public void postInit() { - final String newConfig = CONFIG_CATEGORY + ".cfg"; - - File configFile = new File(Forestry.instance.getConfigFolder(), newConfig); - if (!configFile.exists()) { - setDefaultsForConfig(); - } - - LocalizedConfiguration config = new LocalizedConfiguration(configFile, "1.0.0"); - - handleBackpackConfig(config, "miner"); - handleBackpackConfig(config, "digger"); - handleBackpackConfig(config, "forester"); - handleBackpackConfig(config, "hunter"); - handleBackpackConfig(config, "adventurer"); - handleBackpackConfig(config, "builder"); - - config.save(); - - BackpackDefinition forester = (BackpackDefinition) BackpackManager.definitions.get("forester"); - forester.addValidBlockClasses(Arrays.asList( - IPlantable.class, - IGrowable.class, - IShearable.class - )); - forester.addValidItemClasses(Arrays.asList( - IPlantable.class, - IGrowable.class - )); - - BackpackDefinition builder = (BackpackDefinition) BackpackManager.definitions.get("builder"); - builder.addValidBlockClasses(Arrays.asList( - BlockStairs.class, - BlockFence.class, - BlockFenceGate.class, - BlockWall.class, - BlockBasePressurePlate.class, - BlockLever.class, - BlockButton.class, - BlockTorch.class, - BlockRedstoneDiode.class, - BlockChest.class, - BlockWorkbench.class, - BlockFurnace.class, - BlockLadder.class, - BlockTrapDoor.class, - BlockDoor.class, - BlockSlab.class - )); - builder.addValidItemClass(ItemDoor.class); - } - - private void setDefaultsForConfig() { - - final BackpackDefinition miner = (BackpackDefinition) BackpackManager.definitions.get("miner"); - final BackpackDefinition digger = (BackpackDefinition) BackpackManager.definitions.get("digger"); - final BackpackDefinition forester = (BackpackDefinition) BackpackManager.definitions.get("forester"); - final BackpackDefinition adventurer = (BackpackDefinition) BackpackManager.definitions.get("adventurer"); - final BackpackDefinition builder = (BackpackDefinition) BackpackManager.definitions.get("builder"); - final BackpackDefinition hunter = (BackpackDefinition) BackpackManager.definitions.get("hunter"); - - miner.addValidItems(minerItems); - digger.addValidItems(diggerItems); - forester.addValidItems(foresterItems); - hunter.addValidItems(hunterItems); - adventurer.addValidItems(adventurerItems); - builder.addValidItems(builderItems); - - final Pattern minerOreDictPattern = Pattern.compile("(ore|dust|gem|ingot|nugget|crushed|cluster|denseore)[A-Z].*"); - final Pattern diggerOreDictPattern = Pattern.compile("(stone)[A-Z].*"); - final Pattern foresterOreDictPattern = Pattern.compile("(crop|seed|tree)[A-Z].*"); - final Pattern builderOreDictPattern = Pattern.compile("(block|paneGlass|slabWood|stainedClay|stainedGlass)[A-Z].*"); - - final List minerOreDictNames = new ArrayList<>(); - final List diggerOreDictNames = new ArrayList<>(Arrays.asList( - "cobblestone", - "stone", - "sand" - )); - final List foresterOreDictNames = new ArrayList<>(Arrays.asList( - "logWood", - "stickWood", - "woodStick", - "saplingTree" - )); - final List builderOreDictNames = new ArrayList<>(Arrays.asList( - "stone", - "plankWood", - "stairWood", - "slabWood", - "fenceWood", - "glass", - "blockGlass", - "paneGlass" - )); - - for (String name : OreDictionary.getOreNames()) { - if (minerOreDictPattern.matcher(name).matches()) { - minerOreDictNames.add(name); - } else if (diggerOreDictPattern.matcher(name).matches()) { - if (name.equals("stoneRod")) { - continue; - } - diggerOreDictNames.add(name); - } else if (foresterOreDictPattern.matcher(name).matches()) { - foresterOreDictNames.add(name); - } else if (builderOreDictPattern.matcher(name).matches()) { - if (name.equals("blockHopper")) { - continue; - } - builderOreDictNames.add(name); - } - } - - miner.addValidOreDictNames(minerOreDictNames); - miner.addValidItems(Arrays.asList( - new ItemStack(Blocks.obsidian), - new ItemStack(Blocks.coal_ore), - new ItemStack(Items.coal), - PluginCore.items.bronzePickaxe.getItemStack(), - PluginCore.items.kitPickaxe.getItemStack(), - PluginCore.items.brokenBronzePickaxe.getItemStack() - )); - - digger.addValidOreDictNames(diggerOreDictNames); - digger.addValidItems(Arrays.asList( - new ItemStack(Blocks.dirt, 1, OreDictionary.WILDCARD_VALUE), - new ItemStack(Blocks.gravel), - new ItemStack(Items.flint), - new ItemStack(Blocks.netherrack), - new ItemStack(Blocks.sandstone, 1, 0), - new ItemStack(Items.clay_ball), - new ItemStack(Blocks.soul_sand), - PluginCore.items.bronzeShovel.getItemStack(), - PluginCore.items.kitShovel.getItemStack(), - PluginCore.items.brokenBronzeShovel.getItemStack() - )); - - forester.addValidOreDictNames(foresterOreDictNames); - forester.addValidItems(Arrays.asList( - new ItemStack(Blocks.red_mushroom), - new ItemStack(Blocks.brown_mushroom), - new ItemStack(Blocks.red_flower), - new ItemStack(Blocks.yellow_flower), - new ItemStack(Blocks.cactus), - new ItemStack(Blocks.tallgrass, 1, OreDictionary.WILDCARD_VALUE), - new ItemStack(Blocks.vine), - new ItemStack(Blocks.pumpkin), - new ItemStack(Blocks.melon_block), - new ItemStack(Items.golden_apple), - new ItemStack(Items.nether_wart), - new ItemStack(Items.pumpkin_seeds), - new ItemStack(Items.melon_seeds) - )); - - hunter.addValidItems(Arrays.asList( - new ItemStack(Items.feather), - new ItemStack(Items.gunpowder), - new ItemStack(Items.blaze_powder), - new ItemStack(Items.blaze_rod), - new ItemStack(Items.bone), - new ItemStack(Items.string), - new ItemStack(Items.rotten_flesh), - new ItemStack(Items.ghast_tear), - new ItemStack(Items.gold_nugget), - new ItemStack(Items.arrow), - new ItemStack(Items.porkchop), - new ItemStack(Items.cooked_porkchop), - new ItemStack(Items.beef), - new ItemStack(Items.cooked_beef), - new ItemStack(Items.chicken), - new ItemStack(Items.cooked_chicken), - new ItemStack(Items.leather), - new ItemStack(Items.egg), - new ItemStack(Items.ender_pearl), - new ItemStack(Items.spider_eye), - new ItemStack(Items.fermented_spider_eye), - new ItemStack(Items.slime_ball), - new ItemStack(Items.dye, 1, 0), - new ItemStack(Blocks.hay_block), - new ItemStack(Blocks.wool, 1, OreDictionary.WILDCARD_VALUE), - new ItemStack(Items.ender_eye), - new ItemStack(Items.magma_cream), - new ItemStack(Items.speckled_melon), - new ItemStack(Items.fish), - new ItemStack(Items.cooked_fished), - new ItemStack(Items.lead), - new ItemStack(Items.fishing_rod), - new ItemStack(Items.name_tag), - new ItemStack(Items.saddle), - new ItemStack(Items.diamond_horse_armor), - new ItemStack(Items.golden_horse_armor), - new ItemStack(Items.iron_horse_armor) - )); - - builder.addValidOreDictNames(builderOreDictNames); - builder.addValidItems(Arrays.asList( - new ItemStack(Blocks.torch), - new ItemStack(Blocks.redstone_torch), - new ItemStack(Blocks.redstone_lamp), - new ItemStack(Blocks.stonebrick, 1, OreDictionary.WILDCARD_VALUE), - new ItemStack(Blocks.sandstone, 1, 1), - new ItemStack(Blocks.sandstone, 1, 2), - new ItemStack(Blocks.brick_block), - new ItemStack(Blocks.clay), - new ItemStack(Blocks.hardened_clay, 1, OreDictionary.WILDCARD_VALUE), - new ItemStack(Blocks.stained_hardened_clay, 1, OreDictionary.WILDCARD_VALUE), - new ItemStack(Blocks.packed_ice), - new ItemStack(Blocks.nether_brick), - new ItemStack(Blocks.crafting_table), - new ItemStack(Blocks.furnace), - new ItemStack(Blocks.lever), - new ItemStack(Blocks.dispenser), - new ItemStack(Blocks.dropper), - new ItemStack(Blocks.ladder), - new ItemStack(Blocks.iron_bars), - new ItemStack(Blocks.quartz_block, 1, OreDictionary.WILDCARD_VALUE), - new ItemStack(Items.sign), - new ItemStack(Items.item_frame) - )); - - BlockRegistryApiculture beeBlocks = PluginApiculture.blocks; - if (beeBlocks != null) { - builder.addValidItem(new ItemStack(beeBlocks.candle, 1, OreDictionary.WILDCARD_VALUE)); - builder.addValidItem(new ItemStack(beeBlocks.stump, 1, OreDictionary.WILDCARD_VALUE)); - } - } - - private static void handleBackpackConfig(LocalizedConfiguration config, String backpackName) { - BackpackDefinition backpackDefinition = (BackpackDefinition) BackpackManager.definitions.get(backpackName); - - List backpackItems; - List backpackOreDict = new ArrayList<>(); - - { - List validItems = new ArrayList<>(backpackDefinition.getValidItemStacks()); - Collections.sort(validItems); - String[] defaultValidItems = validItems.toArray(new String[validItems.size()]); - - Property backpackConf = config.get("backpacks." + backpackName, "item.stacks", defaultValidItems); - backpackConf.comment = StringUtil.localizeAndFormat("config.backpacks.item.stacks.format", backpackName); - - String[] backpackItemList = backpackConf.getStringList(); - backpackItems = ItemStackUtil.parseItemStackStrings(backpackItemList, OreDictionary.WILDCARD_VALUE); - } - - { - List oreIds = new ArrayList<>(backpackDefinition.getValidOreIds()); - String[] defaultOreNames = new String[oreIds.size()]; - for (int i = 0; i < oreIds.size(); i++) { - int oreId = oreIds.get(i); - defaultOreNames[i] = OreDictionary.getOreName(oreId); - } - - List defaultOreNamesList = new ArrayList<>(); - Collections.addAll(defaultOreNamesList, defaultOreNames); - Collections.sort(defaultOreNamesList); - defaultOreNames = defaultOreNamesList.toArray(new String[defaultOreNamesList.size()]); - - Property backpackConf = config.get("backpacks." + backpackName, "ore.dict", defaultOreNames); - backpackConf.comment = StringUtil.localizeAndFormat("config.backpacks.ore.dict.format", backpackName); - - String[] oreDictNameList = backpackConf.getStringList(); - Collections.addAll(backpackOreDict, oreDictNameList); - } - - backpackDefinition.clearAllValid(); - - backpackDefinition.addValidItems(backpackItems); - backpackDefinition.addValidOreDictNames(backpackOreDict); - } - - public static void registerCrate(ItemCrated crate) { - proxy.registerCrateForRendering(crate); - crates.add(crate); - } - - public static void createCrateRecipes() { - for (ItemCrated crate : crates) { - ItemStack crateStack = new ItemStack(crate); - ItemStack uncrated = crate.getContained(); - if (crate.usesOreDict()) { - int[] oreIds = OreDictionary.getOreIDs(uncrated); - for (int oreId : oreIds) { - String oreName = OreDictionary.getOreName(oreId); - addCrating(crateStack, oreName); - } - } else { - addCrating(crateStack, uncrated); - } - addUncrating(crateStack, uncrated); - } - } - - private static void addCrating(ItemStack crateStack, Object uncrated) { - FluidStack water = Fluids.WATER.getFluid(Constants.CARPENTER_CRATING_LIQUID_QUANTITY); - ItemStack box = items.crate.getItemStack(); - RecipeManagers.carpenterManager.addRecipe(Constants.CARPENTER_CRATING_CYCLES, water, box, crateStack, "###", "###", "###", '#', uncrated); - } - - private static void addUncrating(ItemStack crateStack, ItemStack uncrated) { - ItemStack product = new ItemStack(uncrated.getItem(), 9, uncrated.getItemDamage()); - RecipeManagers.carpenterManager.addRecipe(Constants.CARPENTER_UNCRATING_CYCLES, null, product, "#", '#', crateStack); - } - - @Override - public boolean processIMCMessage(IMCMessage message) { - if (message.key.equals("add-backpack-items")) { - String[] tokens = message.getStringValue().split("@"); - if (tokens.length != 2) { - logInvalidIMCMessage(message); - return true; - } - - if (!BackpackManager.definitions.containsKey(tokens[0])) { - String errorMessage = getInvalidIMCMessageText(message); - Log.warning("%s For non-existent backpack %s.", errorMessage, tokens[0]); - return true; - } - - IBackpackDefinition backpackDefinition = BackpackManager.definitions.get(tokens[0]); - List itemStacks = ItemStackUtil.parseItemStackStrings(tokens[1], 0); - backpackDefinition.addValidItems(itemStacks); - - return true; - } - return false; - } - - @Override - public IPickupHandler getPickupHandler() { - return new PickupHandlerStorage(); - } - - @Override - public IResupplyHandler getResupplyHandler() { - return new ResupplyHandler(); - } - - @Override - protected void registerRecipes() { - BlockRegistryApiculture beeBlocks = PluginApiculture.blocks; - if (items.apiaristBackpack != null && beeBlocks != null) { - addBackpackRecipe(items.apiaristBackpack, "stickWood", beeBlocks.apicultureChest); - } - - BlockRegistryLepidopterology butterflyBlocks = PluginLepidopterology.blocks; - if (items.lepidopteristBackpack != null && butterflyBlocks != null) { - ItemStack chest = butterflyBlocks.lepidopterology.get(BlockLepidopterologyType.LEPICHEST); - addBackpackRecipe(items.lepidopteristBackpack, "stickWood", chest); - } - - addBackpackRecipe(items.minerBackpack, "ingotIron"); - addBackpackRecipe(items.diggerBackpack, "stone"); - addBackpackRecipe(items.foresterBackpack, "logWood"); - addBackpackRecipe(items.hunterBackpack, Items.feather); - addBackpackRecipe(items.adventurerBackpack, Items.bone); - addBackpackRecipe(items.builderBackpack, Items.clay_ball); - - // / CARPENTER - if (PluginManager.Module.FACTORY.isEnabled()) { - // / CRATES - RecipeManagers.carpenterManager.addRecipe(20, Fluids.WATER.getFluid(1000), null, items.crate.getItemStack(24), - " # ", "# #", " # ", '#', "logWood"); - - // / BACKPACKS T2 - addT2BackpackRecipe(items.minerBackpack, items.minerBackpackT2); - addT2BackpackRecipe(items.diggerBackpack, items.diggerBackpackT2); - addT2BackpackRecipe(items.foresterBackpack, items.foresterBackpackT2); - addT2BackpackRecipe(items.hunterBackpack, items.hunterBackpackT2); - addT2BackpackRecipe(items.adventurerBackpack, items.adventurerBackpackT2); - addT2BackpackRecipe(items.builderBackpack, items.builderBackpackT2); - } - } - - private static void addBackpackRecipe(Item backpack, Object material) { - addBackpackRecipe(backpack, material, "chestWood"); - } - - private static void addBackpackRecipe(Item backpack, Object material, Object chest) { - RecipeUtil.addRecipe(backpack, - "X#X", - "VYV", - "X#X", - '#', Blocks.wool, - 'X', Items.string, - 'V', material, - 'Y', chest); - } - - private static void addT2BackpackRecipe(Item backpackT1, Item backpackT2) { - ItemStack wovenSilk = PluginCore.items.craftingMaterial.getWovenSilk(); - RecipeManagers.carpenterManager.addRecipe(200, Fluids.WATER.getFluid(1000), null, new ItemStack(backpackT2), - "WXW", - "WTW", - "WWW", - 'X', "gemDiamond", - 'W', wovenSilk, - 'T', backpackT1); - } + private static final List crates = new ArrayList<>(); + private static final String CONFIG_CATEGORY = "backpacks"; + + @SidedProxy( + clientSide = "forestry.storage.proxy.ProxyStorageClient", + serverSide = "forestry.storage.proxy.ProxyStorage") + public static ProxyStorage proxy; + + private final ArrayList minerItems = new ArrayList<>(); + private final ArrayList diggerItems = new ArrayList<>(); + private final ArrayList foresterItems = new ArrayList<>(); + private final ArrayList hunterItems = new ArrayList<>(); + private final ArrayList adventurerItems = new ArrayList<>(); + private final ArrayList builderItems = new ArrayList<>(); + + public static ItemRegistryStorage items; + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + protected void setupAPI() { + super.setupAPI(); + + StorageManager.crateRegistry = new CrateRegistry(); + + BackpackManager.backpackInterface = new BackpackInterface(); + + BackpackManager.backpackItems = new ArrayList[6]; + + BackpackManager.backpackItems[0] = minerItems; + BackpackManager.backpackItems[1] = diggerItems; + BackpackManager.backpackItems[2] = foresterItems; + BackpackManager.backpackItems[3] = hunterItems; + BackpackManager.backpackItems[4] = adventurerItems; + BackpackManager.backpackItems[5] = builderItems; + + BackpackDefinition definition; + + if (PluginManager.Module.APICULTURE.isEnabled()) { + definition = new BackpackDefinitionApiarist(new Color(0xc4923d).getRGB()); + BackpackManager.definitions.put(definition.getKey(), definition); + } + + if (PluginManager.Module.LEPIDOPTEROLOGY.isEnabled()) { + definition = new BackpackDefinitionLepidopterist(new Color(0x995b31).getRGB()); + BackpackManager.definitions.put(definition.getKey(), definition); + } + + definition = new BackpackDefinition("miner", new Color(0x36187d).getRGB()); + BackpackManager.definitions.put(definition.getKey(), definition); + + definition = new BackpackDefinition("digger", new Color(0x363cc5).getRGB()); + BackpackManager.definitions.put(definition.getKey(), definition); + + definition = new BackpackDefinition("forester", new Color(0x347427).getRGB()); + BackpackManager.definitions.put(definition.getKey(), definition); + + definition = new BackpackDefinition("hunter", new Color(0x412215).getRGB()); + BackpackManager.definitions.put(definition.getKey(), definition); + + definition = new BackpackDefinition("adventurer", new Color(0x7fb8c2).getRGB()); + BackpackManager.definitions.put(definition.getKey(), definition); + + definition = new BackpackDefinition("builder", new Color(0xdd3a3a).getRGB()); + BackpackManager.definitions.put(definition.getKey(), definition); + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + protected void disabledSetupAPI() { + BackpackManager.backpackItems = new ArrayList[6]; + BackpackManager.backpackItems[0] = minerItems; + BackpackManager.backpackItems[1] = diggerItems; + BackpackManager.backpackItems[2] = foresterItems; + BackpackManager.backpackItems[3] = hunterItems; + BackpackManager.backpackItems[4] = adventurerItems; + BackpackManager.backpackItems[5] = builderItems; + } + + @Override + protected void registerItemsAndBlocks() { + items = new ItemRegistryStorage(); + } + + @Override + public void postInit() { + final String newConfig = CONFIG_CATEGORY + ".cfg"; + + File configFile = new File(Forestry.instance.getConfigFolder(), newConfig); + if (!configFile.exists()) { + setDefaultsForConfig(); + } + + LocalizedConfiguration config = new LocalizedConfiguration(configFile, "1.0.0"); + + handleBackpackConfig(config, "miner"); + handleBackpackConfig(config, "digger"); + handleBackpackConfig(config, "forester"); + handleBackpackConfig(config, "hunter"); + handleBackpackConfig(config, "adventurer"); + handleBackpackConfig(config, "builder"); + + config.save(); + + BackpackDefinition forester = (BackpackDefinition) BackpackManager.definitions.get("forester"); + forester.addValidBlockClasses(Arrays.asList(IPlantable.class, IGrowable.class, IShearable.class)); + forester.addValidItemClasses(Arrays.asList(IPlantable.class, IGrowable.class)); + + BackpackDefinition builder = (BackpackDefinition) BackpackManager.definitions.get("builder"); + builder.addValidBlockClasses(Arrays.asList( + BlockStairs.class, + BlockFence.class, + BlockFenceGate.class, + BlockWall.class, + BlockBasePressurePlate.class, + BlockLever.class, + BlockButton.class, + BlockTorch.class, + BlockRedstoneDiode.class, + BlockChest.class, + BlockWorkbench.class, + BlockFurnace.class, + BlockLadder.class, + BlockTrapDoor.class, + BlockDoor.class, + BlockSlab.class)); + builder.addValidItemClass(ItemDoor.class); + } + + private void setDefaultsForConfig() { + + final BackpackDefinition miner = (BackpackDefinition) BackpackManager.definitions.get("miner"); + final BackpackDefinition digger = (BackpackDefinition) BackpackManager.definitions.get("digger"); + final BackpackDefinition forester = (BackpackDefinition) BackpackManager.definitions.get("forester"); + final BackpackDefinition adventurer = (BackpackDefinition) BackpackManager.definitions.get("adventurer"); + final BackpackDefinition builder = (BackpackDefinition) BackpackManager.definitions.get("builder"); + final BackpackDefinition hunter = (BackpackDefinition) BackpackManager.definitions.get("hunter"); + + miner.addValidItems(minerItems); + digger.addValidItems(diggerItems); + forester.addValidItems(foresterItems); + hunter.addValidItems(hunterItems); + adventurer.addValidItems(adventurerItems); + builder.addValidItems(builderItems); + + final Pattern minerOreDictPattern = + Pattern.compile("(ore|dust|gem|ingot|nugget|crushed|cluster|denseore)[A-Z].*"); + final Pattern diggerOreDictPattern = Pattern.compile("(stone)[A-Z].*"); + final Pattern foresterOreDictPattern = Pattern.compile("(crop|seed|tree)[A-Z].*"); + final Pattern builderOreDictPattern = + Pattern.compile("(block|paneGlass|slabWood|stainedClay|stainedGlass)[A-Z].*"); + + final List minerOreDictNames = new ArrayList<>(); + final List diggerOreDictNames = new ArrayList<>(Arrays.asList("cobblestone", "stone", "sand")); + final List foresterOreDictNames = + new ArrayList<>(Arrays.asList("logWood", "stickWood", "woodStick", "saplingTree")); + final List builderOreDictNames = new ArrayList<>(Arrays.asList( + "stone", "plankWood", "stairWood", "slabWood", "fenceWood", "glass", "blockGlass", "paneGlass")); + + for (String name : OreDictionary.getOreNames()) { + if (minerOreDictPattern.matcher(name).matches()) { + minerOreDictNames.add(name); + } else if (diggerOreDictPattern.matcher(name).matches()) { + if (name.equals("stoneRod")) { + continue; + } + diggerOreDictNames.add(name); + } else if (foresterOreDictPattern.matcher(name).matches()) { + foresterOreDictNames.add(name); + } else if (builderOreDictPattern.matcher(name).matches()) { + if (name.equals("blockHopper")) { + continue; + } + builderOreDictNames.add(name); + } + } + + miner.addValidOreDictNames(minerOreDictNames); + miner.addValidItems(Arrays.asList( + new ItemStack(Blocks.obsidian), + new ItemStack(Blocks.coal_ore), + new ItemStack(Items.coal), + PluginCore.items.bronzePickaxe.getItemStack(), + PluginCore.items.kitPickaxe.getItemStack(), + PluginCore.items.brokenBronzePickaxe.getItemStack())); + + digger.addValidOreDictNames(diggerOreDictNames); + digger.addValidItems(Arrays.asList( + new ItemStack(Blocks.dirt, 1, OreDictionary.WILDCARD_VALUE), + new ItemStack(Blocks.gravel), + new ItemStack(Items.flint), + new ItemStack(Blocks.netherrack), + new ItemStack(Blocks.sandstone, 1, 0), + new ItemStack(Items.clay_ball), + new ItemStack(Blocks.soul_sand), + PluginCore.items.bronzeShovel.getItemStack(), + PluginCore.items.kitShovel.getItemStack(), + PluginCore.items.brokenBronzeShovel.getItemStack())); + + forester.addValidOreDictNames(foresterOreDictNames); + forester.addValidItems(Arrays.asList( + new ItemStack(Blocks.red_mushroom), + new ItemStack(Blocks.brown_mushroom), + new ItemStack(Blocks.red_flower), + new ItemStack(Blocks.yellow_flower), + new ItemStack(Blocks.cactus), + new ItemStack(Blocks.tallgrass, 1, OreDictionary.WILDCARD_VALUE), + new ItemStack(Blocks.vine), + new ItemStack(Blocks.pumpkin), + new ItemStack(Blocks.melon_block), + new ItemStack(Items.golden_apple), + new ItemStack(Items.nether_wart), + new ItemStack(Items.pumpkin_seeds), + new ItemStack(Items.melon_seeds))); + + hunter.addValidItems(Arrays.asList( + new ItemStack(Items.feather), + new ItemStack(Items.gunpowder), + new ItemStack(Items.blaze_powder), + new ItemStack(Items.blaze_rod), + new ItemStack(Items.bone), + new ItemStack(Items.string), + new ItemStack(Items.rotten_flesh), + new ItemStack(Items.ghast_tear), + new ItemStack(Items.gold_nugget), + new ItemStack(Items.arrow), + new ItemStack(Items.porkchop), + new ItemStack(Items.cooked_porkchop), + new ItemStack(Items.beef), + new ItemStack(Items.cooked_beef), + new ItemStack(Items.chicken), + new ItemStack(Items.cooked_chicken), + new ItemStack(Items.leather), + new ItemStack(Items.egg), + new ItemStack(Items.ender_pearl), + new ItemStack(Items.spider_eye), + new ItemStack(Items.fermented_spider_eye), + new ItemStack(Items.slime_ball), + new ItemStack(Items.dye, 1, 0), + new ItemStack(Blocks.hay_block), + new ItemStack(Blocks.wool, 1, OreDictionary.WILDCARD_VALUE), + new ItemStack(Items.ender_eye), + new ItemStack(Items.magma_cream), + new ItemStack(Items.speckled_melon), + new ItemStack(Items.fish), + new ItemStack(Items.cooked_fished), + new ItemStack(Items.lead), + new ItemStack(Items.fishing_rod), + new ItemStack(Items.name_tag), + new ItemStack(Items.saddle), + new ItemStack(Items.diamond_horse_armor), + new ItemStack(Items.golden_horse_armor), + new ItemStack(Items.iron_horse_armor))); + + builder.addValidOreDictNames(builderOreDictNames); + builder.addValidItems(Arrays.asList( + new ItemStack(Blocks.torch), + new ItemStack(Blocks.redstone_torch), + new ItemStack(Blocks.redstone_lamp), + new ItemStack(Blocks.stonebrick, 1, OreDictionary.WILDCARD_VALUE), + new ItemStack(Blocks.sandstone, 1, 1), + new ItemStack(Blocks.sandstone, 1, 2), + new ItemStack(Blocks.brick_block), + new ItemStack(Blocks.clay), + new ItemStack(Blocks.hardened_clay, 1, OreDictionary.WILDCARD_VALUE), + new ItemStack(Blocks.stained_hardened_clay, 1, OreDictionary.WILDCARD_VALUE), + new ItemStack(Blocks.packed_ice), + new ItemStack(Blocks.nether_brick), + new ItemStack(Blocks.crafting_table), + new ItemStack(Blocks.furnace), + new ItemStack(Blocks.lever), + new ItemStack(Blocks.dispenser), + new ItemStack(Blocks.dropper), + new ItemStack(Blocks.ladder), + new ItemStack(Blocks.iron_bars), + new ItemStack(Blocks.quartz_block, 1, OreDictionary.WILDCARD_VALUE), + new ItemStack(Items.sign), + new ItemStack(Items.item_frame))); + + BlockRegistryApiculture beeBlocks = PluginApiculture.blocks; + if (beeBlocks != null) { + builder.addValidItem(new ItemStack(beeBlocks.candle, 1, OreDictionary.WILDCARD_VALUE)); + builder.addValidItem(new ItemStack(beeBlocks.stump, 1, OreDictionary.WILDCARD_VALUE)); + } + } + + private static void handleBackpackConfig(LocalizedConfiguration config, String backpackName) { + BackpackDefinition backpackDefinition = (BackpackDefinition) BackpackManager.definitions.get(backpackName); + + List backpackItems; + List backpackOreDict = new ArrayList<>(); + + { + List validItems = new ArrayList<>(backpackDefinition.getValidItemStacks()); + Collections.sort(validItems); + String[] defaultValidItems = validItems.toArray(new String[validItems.size()]); + + Property backpackConf = config.get("backpacks." + backpackName, "item.stacks", defaultValidItems); + backpackConf.comment = StringUtil.localizeAndFormat("config.backpacks.item.stacks.format", backpackName); + + String[] backpackItemList = backpackConf.getStringList(); + backpackItems = ItemStackUtil.parseItemStackStrings(backpackItemList, OreDictionary.WILDCARD_VALUE); + } + + { + List oreIds = new ArrayList<>(backpackDefinition.getValidOreIds()); + String[] defaultOreNames = new String[oreIds.size()]; + for (int i = 0; i < oreIds.size(); i++) { + int oreId = oreIds.get(i); + defaultOreNames[i] = OreDictionary.getOreName(oreId); + } + + List defaultOreNamesList = new ArrayList<>(); + Collections.addAll(defaultOreNamesList, defaultOreNames); + Collections.sort(defaultOreNamesList); + defaultOreNames = defaultOreNamesList.toArray(new String[defaultOreNamesList.size()]); + + Property backpackConf = config.get("backpacks." + backpackName, "ore.dict", defaultOreNames); + backpackConf.comment = StringUtil.localizeAndFormat("config.backpacks.ore.dict.format", backpackName); + + String[] oreDictNameList = backpackConf.getStringList(); + Collections.addAll(backpackOreDict, oreDictNameList); + } + + backpackDefinition.clearAllValid(); + + backpackDefinition.addValidItems(backpackItems); + backpackDefinition.addValidOreDictNames(backpackOreDict); + } + + public static void registerCrate(ItemCrated crate) { + proxy.registerCrateForRendering(crate); + crates.add(crate); + } + + public static void createCrateRecipes() { + for (ItemCrated crate : crates) { + ItemStack crateStack = new ItemStack(crate); + ItemStack uncrated = crate.getContained(); + if (crate.usesOreDict()) { + int[] oreIds = OreDictionary.getOreIDs(uncrated); + for (int oreId : oreIds) { + String oreName = OreDictionary.getOreName(oreId); + addCrating(crateStack, oreName); + } + } else { + addCrating(crateStack, uncrated); + } + addUncrating(crateStack, uncrated); + } + } + + private static void addCrating(ItemStack crateStack, Object uncrated) { + FluidStack water = Fluids.WATER.getFluid(Constants.CARPENTER_CRATING_LIQUID_QUANTITY); + ItemStack box = items.crate.getItemStack(); + RecipeManagers.carpenterManager.addRecipe( + Constants.CARPENTER_CRATING_CYCLES, water, box, crateStack, "###", "###", "###", '#', uncrated); + } + + private static void addUncrating(ItemStack crateStack, ItemStack uncrated) { + ItemStack product = new ItemStack(uncrated.getItem(), 9, uncrated.getItemDamage()); + RecipeManagers.carpenterManager.addRecipe( + Constants.CARPENTER_UNCRATING_CYCLES, null, product, "#", '#', crateStack); + } + + @Override + public boolean processIMCMessage(IMCMessage message) { + if (message.key.equals("add-backpack-items")) { + String[] tokens = message.getStringValue().split("@"); + if (tokens.length != 2) { + logInvalidIMCMessage(message); + return true; + } + + if (!BackpackManager.definitions.containsKey(tokens[0])) { + String errorMessage = getInvalidIMCMessageText(message); + Log.warning("%s For non-existent backpack %s.", errorMessage, tokens[0]); + return true; + } + + IBackpackDefinition backpackDefinition = BackpackManager.definitions.get(tokens[0]); + List itemStacks = ItemStackUtil.parseItemStackStrings(tokens[1], 0); + backpackDefinition.addValidItems(itemStacks); + + return true; + } + return false; + } + + @Override + public IPickupHandler getPickupHandler() { + return new PickupHandlerStorage(); + } + + @Override + public IResupplyHandler getResupplyHandler() { + return new ResupplyHandler(); + } + + @Override + protected void registerRecipes() { + BlockRegistryApiculture beeBlocks = PluginApiculture.blocks; + if (items.apiaristBackpack != null && beeBlocks != null) { + addBackpackRecipe(items.apiaristBackpack, "stickWood", beeBlocks.apicultureChest); + } + + BlockRegistryLepidopterology butterflyBlocks = PluginLepidopterology.blocks; + if (items.lepidopteristBackpack != null && butterflyBlocks != null) { + ItemStack chest = butterflyBlocks.lepidopterology.get(BlockLepidopterologyType.LEPICHEST); + addBackpackRecipe(items.lepidopteristBackpack, "stickWood", chest); + } + + addBackpackRecipe(items.minerBackpack, "ingotIron"); + addBackpackRecipe(items.diggerBackpack, "stone"); + addBackpackRecipe(items.foresterBackpack, "logWood"); + addBackpackRecipe(items.hunterBackpack, Items.feather); + addBackpackRecipe(items.adventurerBackpack, Items.bone); + addBackpackRecipe(items.builderBackpack, Items.clay_ball); + + // / CARPENTER + if (PluginManager.Module.FACTORY.isEnabled()) { + // / CRATES + RecipeManagers.carpenterManager.addRecipe( + 20, + Fluids.WATER.getFluid(1000), + null, + items.crate.getItemStack(24), + " # ", + "# #", + " # ", + '#', + "logWood"); + + // / BACKPACKS T2 + addT2BackpackRecipe(items.minerBackpack, items.minerBackpackT2); + addT2BackpackRecipe(items.diggerBackpack, items.diggerBackpackT2); + addT2BackpackRecipe(items.foresterBackpack, items.foresterBackpackT2); + addT2BackpackRecipe(items.hunterBackpack, items.hunterBackpackT2); + addT2BackpackRecipe(items.adventurerBackpack, items.adventurerBackpackT2); + addT2BackpackRecipe(items.builderBackpack, items.builderBackpackT2); + } + } + + private static void addBackpackRecipe(Item backpack, Object material) { + addBackpackRecipe(backpack, material, "chestWood"); + } + + private static void addBackpackRecipe(Item backpack, Object material, Object chest) { + RecipeUtil.addRecipe( + backpack, "X#X", "VYV", "X#X", '#', Blocks.wool, 'X', Items.string, 'V', material, 'Y', chest); + } + + private static void addT2BackpackRecipe(Item backpackT1, Item backpackT2) { + ItemStack wovenSilk = PluginCore.items.craftingMaterial.getWovenSilk(); + RecipeManagers.carpenterManager.addRecipe( + 200, + Fluids.WATER.getFluid(1000), + null, + new ItemStack(backpackT2), + "WXW", + "WTW", + "WWW", + 'X', + "gemDiamond", + 'W', + wovenSilk, + 'T', + backpackT1); + } } diff --git a/src/main/java/forestry/plugins/compat/PluginAgriCraft.java b/src/main/java/forestry/plugins/compat/PluginAgriCraft.java index 308dca0eb..62046f36d 100644 --- a/src/main/java/forestry/plugins/compat/PluginAgriCraft.java +++ b/src/main/java/forestry/plugins/compat/PluginAgriCraft.java @@ -11,13 +11,7 @@ package forestry.plugins.compat; import com.google.common.collect.ImmutableList; - -import forestry.farming.logic.FarmableReference; -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; - import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; import forestry.api.recipes.RecipeManagers; @@ -25,77 +19,80 @@ import forestry.core.config.Constants; import forestry.core.fluids.Fluids; import forestry.core.utils.ModUtil; import forestry.farming.logic.FarmableBasicAgricraft; +import forestry.farming.logic.FarmableReference; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; import forestry.plugins.PluginManager; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; -@Plugin(pluginID = "AgriCraft", name = "AgriCraft", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.agricraft.description") +@Plugin( + pluginID = "AgriCraft", + name = "AgriCraft", + author = "Nirek", + url = Constants.URL, + unlocalizedDescription = "for.plugin.agricraft.description") public class PluginAgriCraft extends ForestryPlugin { - private static final String AgriCraft = "AgriCraft"; + private static final String AgriCraft = "AgriCraft"; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(AgriCraft); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(AgriCraft); + } - @Override - public String getFailMessage() { - return "AgriCraft not found"; - } + @Override + public String getFailMessage() { + return "AgriCraft not found"; + } - @Override - protected void registerRecipes() { + @Override + protected void registerRecipes() { - ImmutableList seeds = ImmutableList.of( - "Allium", //Vanilla - "Dandelion", - "Daisy", - "TulipRed", - "TulipPink", - "TulipOrange", - "TulipWhite", - "Sugarcane", - "Cactus", - "Carrot", - "Potato", - "Poppy", - "Orchid", - "ShroomRed", - "ShroomBrown", - - "BotaniaCyan", //Botania - "BotaniaLime", - "BotaniaRed", - "BotaniaLightGray", - "BotaniaOrange", - "BotaniaBlack", - "BotaniaLightBlue", - "BotaniaPink", - "BotaniaWhite", - "BotaniaGreen", - "BotaniaYellow", - "BotaniaMagenta", - "BotaniaBrown", - "BotaniaPurple", - "BotaniaBlue", - "BotaniaGray" - - - ); - int seedamount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - for (String seedName : seeds) { - ItemStack seed = GameRegistry.findItemStack(AgriCraft, "seed" + seedName, 1); - if (seed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{seed}, Fluids.SEEDOIL.getFluid(seedamount)); - } - } - - Block cropBlock = GameRegistry.findBlock(AgriCraft, "crops"); - if (cropBlock != null && PluginManager.Module.FARMING.isEnabled()) { - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicAgricraft(cropBlock, 7)); - } - } + ImmutableList seeds = ImmutableList.of( + "Allium", // Vanilla + "Dandelion", + "Daisy", + "TulipRed", + "TulipPink", + "TulipOrange", + "TulipWhite", + "Sugarcane", + "Cactus", + "Carrot", + "Potato", + "Poppy", + "Orchid", + "ShroomRed", + "ShroomBrown", + "BotaniaCyan", // Botania + "BotaniaLime", + "BotaniaRed", + "BotaniaLightGray", + "BotaniaOrange", + "BotaniaBlack", + "BotaniaLightBlue", + "BotaniaPink", + "BotaniaWhite", + "BotaniaGreen", + "BotaniaYellow", + "BotaniaMagenta", + "BotaniaBrown", + "BotaniaPurple", + "BotaniaBlue", + "BotaniaGray"); + int seedamount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); + for (String seedName : seeds) { + ItemStack seed = GameRegistry.findItemStack(AgriCraft, "seed" + seedName, 1); + if (seed != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {seed}, Fluids.SEEDOIL.getFluid(seedamount)); + } + } + Block cropBlock = GameRegistry.findBlock(AgriCraft, "crops"); + if (cropBlock != null && PluginManager.Module.FARMING.isEnabled()) { + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicAgricraft(cropBlock, 7)); + } + } } - diff --git a/src/main/java/forestry/plugins/compat/PluginBiomesOPlenty.java b/src/main/java/forestry/plugins/compat/PluginBiomesOPlenty.java index 819258c0a..d4cefbba7 100644 --- a/src/main/java/forestry/plugins/compat/PluginBiomesOPlenty.java +++ b/src/main/java/forestry/plugins/compat/PluginBiomesOPlenty.java @@ -10,20 +10,9 @@ ******************************************************************************/ package forestry.plugins.compat; -import java.util.ArrayList; -import java.util.List; - -import forestry.farming.logic.FarmableReference; -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.oredict.OreDictionary; - import cpw.mods.fml.common.event.FMLInterModComms; import cpw.mods.fml.common.registry.GameData; import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.apiculture.FlowerManager; import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; @@ -37,217 +26,273 @@ import forestry.core.utils.ModUtil; import forestry.farming.logic.FarmableBasicFruit; import forestry.farming.logic.FarmableGenericCrop; import forestry.farming.logic.FarmableGenericSapling; +import forestry.farming.logic.FarmableReference; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; import forestry.plugins.PluginCore; import forestry.plugins.PluginManager; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; -@Plugin(pluginID = "BiomesOPlenty", name = "BiomesOPlenty", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.biomesoplenty.description") +@Plugin( + pluginID = "BiomesOPlenty", + name = "BiomesOPlenty", + author = "Nirek", + url = Constants.URL, + unlocalizedDescription = "for.plugin.biomesoplenty.description") public class PluginBiomesOPlenty extends ForestryPlugin { - private static final String BoP = "BiomesOPlenty"; + private static final String BoP = "BiomesOPlenty"; - private static Block saplings; - private static Block colorizedSaplings; - private static Item food; - private static Item misc; - private static ItemStack persimmon; - private static int amount; + private static Block saplings; + private static Block colorizedSaplings; + private static Item food; + private static Item misc; + private static ItemStack persimmon; + private static int amount; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(BoP); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(BoP); + } - @Override - public String getFailMessage() { - return "BiomesOPlenty not found"; - } + @Override + public String getFailMessage() { + return "BiomesOPlenty not found"; + } - @Override - public void doInit() { - super.doInit(); + @Override + public void doInit() { + super.doInit(); - saplings = GameRegistry.findBlock(BoP, "saplings"); - colorizedSaplings = GameRegistry.findBlock(BoP, "colorizedSaplings"); - food = GameRegistry.findItem(BoP, "food"); - if (food != null) { - persimmon = new ItemStack(food, 1, 8); - } + saplings = GameRegistry.findBlock(BoP, "saplings"); + colorizedSaplings = GameRegistry.findBlock(BoP, "colorizedSaplings"); + food = GameRegistry.findItem(BoP, "food"); + if (food != null) { + persimmon = new ItemStack(food, 1, 8); + } - if (PluginManager.Module.APICULTURE.isEnabled()) { - addFlowers(); - } - if (PluginManager.Module.FARMING.isEnabled()) { - addFarmCrops(); - } - } + if (PluginManager.Module.APICULTURE.isEnabled()) { + addFlowers(); + } + if (PluginManager.Module.FARMING.isEnabled()) { + addFarmCrops(); + } + } - @Override - protected void registerRecipes() { - super.registerRecipes(); + @Override + protected void registerRecipes() { + super.registerRecipes(); - amount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - if (PluginManager.Module.FACTORY.isEnabled()) { - addFermenterRecipes(); - addSqueezerRecipes(); - } - } + amount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); + if (PluginManager.Module.FACTORY.isEnabled()) { + addFermenterRecipes(); + addSqueezerRecipes(); + } + } - private static void addFarmCrops() { - List saplingItemKeys = new ArrayList<>(); + private static void addFarmCrops() { + List saplingItemKeys = new ArrayList<>(); - if (saplings != null) { - saplingItemKeys.add("saplings"); - } - if (colorizedSaplings != null) { - saplingItemKeys.add("colorizedSaplings"); - } + if (saplings != null) { + saplingItemKeys.add("saplings"); + } + if (colorizedSaplings != null) { + saplingItemKeys.add("colorizedSaplings"); + } - for (String key : saplingItemKeys) { - Item saplingItem = GameRegistry.findItem(BoP, key); - String saplingName = GameData.getItemRegistry().getNameForObject(saplingItem); - FMLInterModComms.sendMessage(Constants.MOD, "add-farmable-sapling", String.format("farmArboreal@%s.-1", saplingName)); - } + for (String key : saplingItemKeys) { + Item saplingItem = GameRegistry.findItem(BoP, key); + String saplingName = GameData.getItemRegistry().getNameForObject(saplingItem); + FMLInterModComms.sendMessage( + Constants.MOD, "add-farmable-sapling", String.format("farmArboreal@%s.-1", saplingName)); + } - if (saplings != null && persimmon != null) { - Farmables.farmables.get(FarmableReference.Arboreal.get()).add(new FarmableGenericSapling(saplings, 15, persimmon)); - } + if (saplings != null && persimmon != null) { + Farmables.farmables + .get(FarmableReference.Arboreal.get()) + .add(new FarmableGenericSapling(saplings, 15, persimmon)); + } - Block boPTurnip = GameRegistry.findBlock(BoP, "turnip"); - if (boPTurnip != null) { - Item boPTurnipSeeds = GameRegistry.findItem(BoP, "turnipSeeds"); - ItemStack boPTurnipSeedStack = new ItemStack(boPTurnipSeeds, 1, 0); - if (boPTurnipSeeds != null) { - Farmables.farmables.get(FarmableReference.Vegetables.get()).add(new FarmableGenericCrop(boPTurnipSeedStack, boPTurnip, 7)); - if (PluginManager.Module.FACTORY.isEnabled()) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{boPTurnipSeedStack}, Fluids.SEEDOIL.getFluid(amount)); - } - } + Block boPTurnip = GameRegistry.findBlock(BoP, "turnip"); + if (boPTurnip != null) { + Item boPTurnipSeeds = GameRegistry.findItem(BoP, "turnipSeeds"); + ItemStack boPTurnipSeedStack = new ItemStack(boPTurnipSeeds, 1, 0); + if (boPTurnipSeeds != null) { + Farmables.farmables + .get(FarmableReference.Vegetables.get()) + .add(new FarmableGenericCrop(boPTurnipSeedStack, boPTurnip, 7)); + if (PluginManager.Module.FACTORY.isEnabled()) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {boPTurnipSeedStack}, Fluids.SEEDOIL.getFluid(amount)); + } + } - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(boPTurnip, 7)); - } - } + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(boPTurnip, 7)); + } + } - private static void addFermenterRecipes() { - int saplingYield = ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"); + private static void addFermenterRecipes() { + int saplingYield = ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"); - if (saplings != null) { - RecipeUtil.addFermenterRecipes(new ItemStack(saplings, 1, OreDictionary.WILDCARD_VALUE), saplingYield, Fluids.BIOMASS); - } + if (saplings != null) { + RecipeUtil.addFermenterRecipes( + new ItemStack(saplings, 1, OreDictionary.WILDCARD_VALUE), saplingYield, Fluids.BIOMASS); + } - if (colorizedSaplings != null) { - RecipeUtil.addFermenterRecipes(new ItemStack(colorizedSaplings, 1, OreDictionary.WILDCARD_VALUE), saplingYield, Fluids.BIOMASS); - } - } + if (colorizedSaplings != null) { + RecipeUtil.addFermenterRecipes( + new ItemStack(colorizedSaplings, 1, OreDictionary.WILDCARD_VALUE), saplingYield, Fluids.BIOMASS); + } + } - private static void addSqueezerRecipes() { - ItemStack mulch = new ItemStack(PluginCore.items.mulch); + private static void addSqueezerRecipes() { + ItemStack mulch = new ItemStack(PluginCore.items.mulch); - misc = GameRegistry.findItem(BoP, "misc"); - if (misc != null) { - ItemStack pinecone = new ItemStack(misc, 1, 13); - if (pinecone != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{pinecone}, Fluids.SEEDOIL.getFluid(3* amount)); - } - } + misc = GameRegistry.findItem(BoP, "misc"); + if (misc != null) { + ItemStack pinecone = new ItemStack(misc, 1, 13); + if (pinecone != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {pinecone}, Fluids.SEEDOIL.getFluid(3 * amount)); + } + } - if (food != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(food)}, Fluids.JUICE.getFluid(50), mulch, 5); - } + if (food != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {new ItemStack(food)}, Fluids.JUICE.getFluid(50), mulch, 5); + } - if (persimmon != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{persimmon}, Fluids.JUICE.getFluid(200), mulch, 20); - } - } + if (persimmon != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {persimmon}, Fluids.JUICE.getFluid(200), mulch, 20); + } + } - private static void addFlowers() { - Block flowers = GameRegistry.findBlock(BoP, "flowers"); - if (flowers != null) { - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 0, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); //Clover - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 1, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow, FlowerManager.FlowerTypeMushrooms); //Swampflower -// FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 2, 1.0, FlowerManager.FlowerTypeNether); //Deathbloom - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 3, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); //GlowFlower - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 4, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); //Blue Hydrangea - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 5, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow, FlowerManager.FlowerTypeJungle); //Orange Cosmos - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 6, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); //Pink Daffodil - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 7, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); //WildFlower - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 8, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); //Violet - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 9, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); // White Anemone - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 10, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); // Waterlily - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 11, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); //EnderLotus (does not actually spawn in the end) - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 12, 1.0, FlowerManager.FlowerTypeCacti); //Bromeliad - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 13, 1.0, FlowerManager.FlowerTypeNether); // EyeBulb -// FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 14, 1.0, FlowerManager.FlowerTypeNether); // Unlisted top of the eyebulb - FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 15, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); // Dandelion Puff - } + private static void addFlowers() { + Block flowers = GameRegistry.findBlock(BoP, "flowers"); + if (flowers != null) { + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, 0, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); // Clover + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, + 1, + 1.0, + FlowerManager.FlowerTypeVanilla, + FlowerManager.FlowerTypeSnow, + FlowerManager.FlowerTypeMushrooms); // Swampflower + // FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 2, 1.0, FlowerManager.FlowerTypeNether); + // //Deathbloom + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, 3, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); // GlowFlower + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, 4, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); // Blue Hydrangea + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, + 5, + 1.0, + FlowerManager.FlowerTypeVanilla, + FlowerManager.FlowerTypeSnow, + FlowerManager.FlowerTypeJungle); // Orange Cosmos + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, 6, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); // Pink Daffodil + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, 7, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); // WildFlower + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, 8, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); // Violet + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, 9, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); // White Anemone + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, 10, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); // Waterlily + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, + 11, + 1.0, + FlowerManager.FlowerTypeVanilla, + FlowerManager.FlowerTypeSnow); // EnderLotus (does not actually spawn in the end) + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, 12, 1.0, FlowerManager.FlowerTypeCacti); // Bromeliad + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, 13, 1.0, FlowerManager.FlowerTypeNether); // EyeBulb + // FlowerManager.flowerRegistry.registerPlantableFlower(flowers, 14, 1.0, FlowerManager.FlowerTypeNether); + // // Unlisted top of the eyebulb + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers, 15, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); // Dandelion Puff + } - Block flowers2 = GameRegistry.findBlock(BoP, "flowers2"); - if (flowers2 != null) { - FlowerManager.flowerRegistry.registerPlantableFlower(flowers2, 0, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeJungle); //Pink Hibiscus - FlowerManager.flowerRegistry.registerPlantableFlower(flowers2, 1, 1.0, FlowerManager.FlowerTypeVanilla); //Lily of the Valley - FlowerManager.flowerRegistry.registerPlantableFlower(flowers2, 2, 1.0, FlowerManager.FlowerTypeNether); // Burning Blososm - FlowerManager.flowerRegistry.registerPlantableFlower(flowers2, 3, 1.0, FlowerManager.FlowerTypeVanilla); // Lavender - FlowerManager.flowerRegistry.registerPlantableFlower(flowers2, 4, 1.0, FlowerManager.FlowerTypeVanilla); // Goldenrod - FlowerManager.flowerRegistry.registerPlantableFlower(flowers2, 5, 1.0, FlowerManager.FlowerTypeVanilla); //Bluebells - FlowerManager.flowerRegistry.registerPlantableFlower(flowers2, 6, 1.0, FlowerManager.FlowerTypeVanilla); //Miner's delight - FlowerManager.flowerRegistry.registerPlantableFlower(flowers2, 7, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); //Icy Iris - FlowerManager.flowerRegistry.registerPlantableFlower(flowers2, 8, 1.0, FlowerManager.FlowerTypeVanilla); // Rose - } - // Toadstool 0 Portobello 1 Blue Milk cap 2 Glowshroom 3 flat mushroom 4 shadow shroom 5 'plants:12' tiny cactus - Block mushrooms = GameRegistry.findBlock(BoP, "mushrooms"); - if (mushrooms != null) { - FlowerManager.flowerRegistry.registerPlantableFlower(mushrooms, OreDictionary.WILDCARD_VALUE, 1.0, FlowerManager.FlowerTypeMushrooms); - FlowerManager.flowerRegistry.registerPlantableFlower(mushrooms, 3, 1.0, FlowerManager.FlowerTypeNether); - } - Block plants = GameRegistry.findBlock(BoP, "plants"); - if (plants != null) { - FlowerManager.flowerRegistry.registerPlantableFlower(plants, 12, 1.0, FlowerManager.FlowerTypeCacti); - } - } + Block flowers2 = GameRegistry.findBlock(BoP, "flowers2"); + if (flowers2 != null) { + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers2, 0, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeJungle); // Pink Hibiscus + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers2, 1, 1.0, FlowerManager.FlowerTypeVanilla); // Lily of the Valley + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers2, 2, 1.0, FlowerManager.FlowerTypeNether); // Burning Blososm + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers2, 3, 1.0, FlowerManager.FlowerTypeVanilla); // Lavender + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers2, 4, 1.0, FlowerManager.FlowerTypeVanilla); // Goldenrod + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers2, 5, 1.0, FlowerManager.FlowerTypeVanilla); // Bluebells + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers2, 6, 1.0, FlowerManager.FlowerTypeVanilla); // Miner's delight + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers2, 7, 1.0, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); // Icy Iris + FlowerManager.flowerRegistry.registerPlantableFlower( + flowers2, 8, 1.0, FlowerManager.FlowerTypeVanilla); // Rose + } + // Toadstool 0 Portobello 1 Blue Milk cap 2 Glowshroom 3 flat mushroom 4 shadow shroom 5 'plants:12' tiny + // cactus + Block mushrooms = GameRegistry.findBlock(BoP, "mushrooms"); + if (mushrooms != null) { + FlowerManager.flowerRegistry.registerPlantableFlower( + mushrooms, OreDictionary.WILDCARD_VALUE, 1.0, FlowerManager.FlowerTypeMushrooms); + FlowerManager.flowerRegistry.registerPlantableFlower(mushrooms, 3, 1.0, FlowerManager.FlowerTypeNether); + } + Block plants = GameRegistry.findBlock(BoP, "plants"); + if (plants != null) { + FlowerManager.flowerRegistry.registerPlantableFlower(plants, 12, 1.0, FlowerManager.FlowerTypeCacti); + } + } - @Override - protected void registerBackpackItems() { - // most blocks are covered by the oreDictionary + @Override + protected void registerBackpackItems() { + // most blocks are covered by the oreDictionary - final int MINER = 0; - final int DIGGER = 1; - final int FORESTER = 2; + final int MINER = 0; + final int DIGGER = 1; + final int FORESTER = 2; - addBlocksToBackpack(MINER, - "driedDirt", - "overgrownNetherrack", - "cragRock", - "ashStone" - ); + addBlocksToBackpack(MINER, "driedDirt", "overgrownNetherrack", "cragRock", "ashStone"); - addBlocksToBackpack(DIGGER, - "bopGrass", - "newBopGrass", - "longGrass", - "mud", - "hardDirt", - "hardSand", - "originGrass", - "ash", - "newBopDirt" - ); + addBlocksToBackpack( + DIGGER, + "bopGrass", + "newBopGrass", + "longGrass", + "mud", + "hardDirt", + "hardSand", + "originGrass", + "ash", + "newBopDirt"); - addBlocksToBackpack(FORESTER, - "petals" - ); - } - - private static void addBlocksToBackpack(int backpackId, String... blockNames) { - for (String blockName : blockNames) { - Block block = GameRegistry.findBlock(BoP, blockName); - if (block != null) { - ItemStack blockStack = new ItemStack(block, 1, OreDictionary.WILDCARD_VALUE); - BackpackManager.backpackItems[backpackId].add(blockStack); - } else { - Log.warning("Missing block: ", blockName); - } - } - } + addBlocksToBackpack(FORESTER, "petals"); + } + private static void addBlocksToBackpack(int backpackId, String... blockNames) { + for (String blockName : blockNames) { + Block block = GameRegistry.findBlock(BoP, blockName); + if (block != null) { + ItemStack blockStack = new ItemStack(block, 1, OreDictionary.WILDCARD_VALUE); + BackpackManager.backpackItems[backpackId].add(blockStack); + } else { + Log.warning("Missing block: ", blockName); + } + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginBuildCraftFuels.java b/src/main/java/forestry/plugins/compat/PluginBuildCraftFuels.java index 53e173d28..7388f36e8 100644 --- a/src/main/java/forestry/plugins/compat/PluginBuildCraftFuels.java +++ b/src/main/java/forestry/plugins/compat/PluginBuildCraftFuels.java @@ -10,49 +10,51 @@ ******************************************************************************/ package forestry.plugins.compat; -import net.minecraftforge.fluids.Fluid; - +import buildcraft.api.fuels.BuildcraftFuelRegistry; +import buildcraft.api.fuels.ICoolant; +import buildcraft.api.fuels.ICoolantManager; import cpw.mods.fml.common.Optional; - import forestry.api.core.ForestryAPI; import forestry.core.config.Constants; import forestry.core.fluids.Fluids; import forestry.core.utils.ModUtil; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; +import net.minecraftforge.fluids.Fluid; -import buildcraft.api.fuels.BuildcraftFuelRegistry; -import buildcraft.api.fuels.ICoolant; -import buildcraft.api.fuels.ICoolantManager; - -@Plugin(pluginID = "BC6|Fuels", name = "BuildCraft 6 Fuels", author = "mezz", url = Constants.URL, unlocalizedDescription = "for.plugin.buildcraft6.description") +@Plugin( + pluginID = "BC6|Fuels", + name = "BuildCraft 6 Fuels", + author = "mezz", + url = Constants.URL, + unlocalizedDescription = "for.plugin.buildcraft6.description") public class PluginBuildCraftFuels extends ForestryPlugin { - @Override - public boolean isAvailable() { - return ModUtil.isAPILoaded("buildcraft.api.fuels", "[2.0, 3.0)"); - } + @Override + public boolean isAvailable() { + return ModUtil.isAPILoaded("buildcraft.api.fuels", "[2.0, 3.0)"); + } - @Override - public String getFailMessage() { - return "Compatible BuildCraftAPI|fuels version not found"; - } + @Override + public String getFailMessage() { + return "Compatible BuildCraftAPI|fuels version not found"; + } - @Optional.Method(modid = "BuildCraftAPI|fuels") - @Override - public void doInit() { - ICoolantManager coolantManager = BuildcraftFuelRegistry.coolant; - ICoolant waterCoolant = coolantManager.getCoolant(Fluids.WATER.getFluid()); - float waterCooling = waterCoolant.getDegreesCoolingPerMB(100); + @Optional.Method(modid = "BuildCraftAPI|fuels") + @Override + public void doInit() { + ICoolantManager coolantManager = BuildcraftFuelRegistry.coolant; + ICoolant waterCoolant = coolantManager.getCoolant(Fluids.WATER.getFluid()); + float waterCooling = waterCoolant.getDegreesCoolingPerMB(100); - coolantManager.addCoolant(Fluids.ICE.getFluid(), Constants.ICE_COOLING_MULTIPLIER * waterCooling); - - Fluid ethanol = Fluids.ETHANOL.getFluid(); - if (ethanol != null) { - int ethanolPower = 40; - int ethanolBurnTime = Math.round(Constants.ENGINE_CYCLE_DURATION_ETHANOL * ForestryAPI.activeMode.getFloatSetting("fuel.ethanol.combustion")); - BuildcraftFuelRegistry.fuel.addFuel(ethanol, ethanolPower, ethanolBurnTime); - } - } + coolantManager.addCoolant(Fluids.ICE.getFluid(), Constants.ICE_COOLING_MULTIPLIER * waterCooling); + Fluid ethanol = Fluids.ETHANOL.getFluid(); + if (ethanol != null) { + int ethanolPower = 40; + int ethanolBurnTime = Math.round(Constants.ENGINE_CYCLE_DURATION_ETHANOL + * ForestryAPI.activeMode.getFloatSetting("fuel.ethanol.combustion")); + BuildcraftFuelRegistry.fuel.addFuel(ethanol, ethanolPower, ethanolBurnTime); + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginBuildCraftRecipes.java b/src/main/java/forestry/plugins/compat/PluginBuildCraftRecipes.java index cb4986e85..78076ed8b 100644 --- a/src/main/java/forestry/plugins/compat/PluginBuildCraftRecipes.java +++ b/src/main/java/forestry/plugins/compat/PluginBuildCraftRecipes.java @@ -10,33 +10,37 @@ ******************************************************************************/ package forestry.plugins.compat; +import buildcraft.api.recipes.BuildcraftRecipeRegistry; import cpw.mods.fml.common.Optional; - import forestry.core.config.Constants; import forestry.core.fluids.Fluids; import forestry.core.utils.ModUtil; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; -import buildcraft.api.recipes.BuildcraftRecipeRegistry; - -@Plugin(pluginID = "BC6|Recipes", name = "BuildCraft 6 Recipes", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.buildcraft6.description") +@Plugin( + pluginID = "BC6|Recipes", + name = "BuildCraft 6 Recipes", + author = "SirSengir", + url = Constants.URL, + unlocalizedDescription = "for.plugin.buildcraft6.description") public class PluginBuildCraftRecipes extends ForestryPlugin { - @Override - public boolean isAvailable() { - return ModUtil.isAPILoaded("buildcraft.api.recipes", "[2.0, 4.0)"); - } + @Override + public boolean isAvailable() { + return ModUtil.isAPILoaded("buildcraft.api.recipes", "[2.0, 4.0)"); + } - @Override - public String getFailMessage() { - return "Compatible BuildCraftAPI|recipes version not found"; - } + @Override + public String getFailMessage() { + return "Compatible BuildCraftAPI|recipes version not found"; + } - @Optional.Method(modid = "BuildCraftAPI|recipes") - @Override - protected void registerRecipes() { - // Add recipe for ethanol - BuildcraftRecipeRegistry.refinery.addRecipe("forestry:BiomassToEthanol", Fluids.BIOMASS.getFluid(4), Fluids.ETHANOL.getFluid(1), 100, 1); - } + @Optional.Method(modid = "BuildCraftAPI|recipes") + @Override + protected void registerRecipes() { + // Add recipe for ethanol + BuildcraftRecipeRegistry.refinery.addRecipe( + "forestry:BiomassToEthanol", Fluids.BIOMASS.getFluid(4), Fluids.ETHANOL.getFluid(1), 100, 1); + } } diff --git a/src/main/java/forestry/plugins/compat/PluginBuildCraftStatements.java b/src/main/java/forestry/plugins/compat/PluginBuildCraftStatements.java index 86c440d0d..468fd9f90 100644 --- a/src/main/java/forestry/plugins/compat/PluginBuildCraftStatements.java +++ b/src/main/java/forestry/plugins/compat/PluginBuildCraftStatements.java @@ -10,66 +10,66 @@ ******************************************************************************/ package forestry.plugins.compat; -import java.util.Collection; - -import net.minecraft.tileentity.TileEntity; - -import net.minecraftforge.common.util.ForgeDirection; - -import cpw.mods.fml.common.Optional; - -import forestry.core.config.Constants; -import forestry.core.utils.ModUtil; -import forestry.plugins.ForestryPlugin; -import forestry.plugins.Plugin; - import buildcraft.api.statements.IStatementContainer; import buildcraft.api.statements.ITriggerExternal; import buildcraft.api.statements.ITriggerInternal; import buildcraft.api.statements.ITriggerProvider; import buildcraft.api.statements.StatementManager; +import cpw.mods.fml.common.Optional; +import forestry.core.config.Constants; +import forestry.core.utils.ModUtil; +import forestry.plugins.ForestryPlugin; +import forestry.plugins.Plugin; +import java.util.Collection; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; -@Plugin(pluginID = "BC6|Statements", name = "BuildCraft 6 Statements", author = "mezz", url = Constants.URL, unlocalizedDescription = "for.plugin.buildcraft6.description") +@Plugin( + pluginID = "BC6|Statements", + name = "BuildCraft 6 Statements", + author = "mezz", + url = Constants.URL, + unlocalizedDescription = "for.plugin.buildcraft6.description") @Optional.Interface(iface = "buildcraft.api.statements.ITriggerProvider", modid = "BuildCraftAPI|statements") public class PluginBuildCraftStatements extends ForestryPlugin implements ITriggerProvider { - @Override - public boolean isAvailable() { - return ModUtil.isAPILoaded("buildcraft.api.statements", "[1.0, 2.0)"); - } + @Override + public boolean isAvailable() { + return ModUtil.isAPILoaded("buildcraft.api.statements", "[1.0, 2.0)"); + } - @Override - public String getFailMessage() { - return "Compatible BuildCraftAPI|statements version not found"; - } + @Override + public String getFailMessage() { + return "Compatible BuildCraftAPI|statements version not found"; + } - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public void doInit() { - // Add custom trigger handler - StatementManager.registerTriggerProvider(this); - } + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public void doInit() { + // Add custom trigger handler + StatementManager.registerTriggerProvider(this); + } - /* ITriggerProvider */ + /* ITriggerProvider */ - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getInternalTriggers(IStatementContainer container) { - TileEntity tile = container.getTile(); - if (tile instanceof ITriggerProvider) { - return ((ITriggerProvider) tile).getInternalTriggers(container); - } + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getInternalTriggers(IStatementContainer container) { + TileEntity tile = container.getTile(); + if (tile instanceof ITriggerProvider) { + return ((ITriggerProvider) tile).getInternalTriggers(container); + } - return null; - } + return null; + } - @Optional.Method(modid = "BuildCraftAPI|statements") - @Override - public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { - if (tile instanceof ITriggerProvider) { - return ((ITriggerProvider) tile).getExternalTriggers(side, tile); - } + @Optional.Method(modid = "BuildCraftAPI|statements") + @Override + public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { + if (tile instanceof ITriggerProvider) { + return ((ITriggerProvider) tile).getExternalTriggers(side, tile); + } - return null; - } + return null; + } } diff --git a/src/main/java/forestry/plugins/compat/PluginBuildCraftTransport.java b/src/main/java/forestry/plugins/compat/PluginBuildCraftTransport.java index 9e2acd049..42f2a546a 100644 --- a/src/main/java/forestry/plugins/compat/PluginBuildCraftTransport.java +++ b/src/main/java/forestry/plugins/compat/PluginBuildCraftTransport.java @@ -10,11 +10,7 @@ ******************************************************************************/ package forestry.plugins.compat; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - import cpw.mods.fml.common.registry.GameRegistry; - import forestry.core.config.Constants; import forestry.core.recipes.RecipeUtil; import forestry.core.utils.Log; @@ -22,30 +18,37 @@ import forestry.core.utils.ModUtil; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; import forestry.plugins.PluginCore; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; -@Plugin(pluginID = "BC6|Transport", name = "BuildCraft 6 Transport", author = "mezz", url = Constants.URL, unlocalizedDescription = "for.plugin.buildcraft6.description") +@Plugin( + pluginID = "BC6|Transport", + name = "BuildCraft 6 Transport", + author = "mezz", + url = Constants.URL, + unlocalizedDescription = "for.plugin.buildcraft6.description") public class PluginBuildCraftTransport extends ForestryPlugin { - private static final String BCT = "BuildCraft|Transport"; + private static final String BCT = "BuildCraft|Transport"; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(BCT); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(BCT); + } - @Override - public String getFailMessage() { - return "BuildCraft|Transport not found"; - } + @Override + public String getFailMessage() { + return "BuildCraft|Transport not found"; + } - @Override - protected void registerRecipes() { - Item beeswax = PluginCore.items.beeswax; - Item pipeWaterproof = GameRegistry.findItem(BCT, "pipeWaterproof"); - if (pipeWaterproof != null) { - RecipeUtil.addShapelessRecipe(new ItemStack(pipeWaterproof), beeswax); - } else { - Log.fine("No BuildCraft pipe waterproof found."); - } - } + @Override + protected void registerRecipes() { + Item beeswax = PluginCore.items.beeswax; + Item pipeWaterproof = GameRegistry.findItem(BCT, "pipeWaterproof"); + if (pipeWaterproof != null) { + RecipeUtil.addShapelessRecipe(new ItemStack(pipeWaterproof), beeswax); + } else { + Log.fine("No BuildCraft pipe waterproof found."); + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginChisel.java b/src/main/java/forestry/plugins/compat/PluginChisel.java index 6370d7de1..99c25fab0 100644 --- a/src/main/java/forestry/plugins/compat/PluginChisel.java +++ b/src/main/java/forestry/plugins/compat/PluginChisel.java @@ -11,42 +11,40 @@ package forestry.plugins.compat; import com.google.common.collect.ImmutableList; - import cpw.mods.fml.common.event.FMLInterModComms; - import forestry.core.config.Constants; import forestry.core.utils.ModUtil; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; -@Plugin(pluginID = "Chisel", name = "Chisel", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.chisel.description") +@Plugin( + pluginID = "Chisel", + name = "Chisel", + author = "Nirek", + url = Constants.URL, + unlocalizedDescription = "for.plugin.chisel.description") public class PluginChisel extends ForestryPlugin { - private static final String Chisel = "chisel"; + private static final String Chisel = "chisel"; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(Chisel); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(Chisel); + } - @Override - public String getFailMessage() { - return "Chisel not found"; - } + @Override + public String getFailMessage() { + return "Chisel not found"; + } - @Override - protected void registerRecipes() { + @Override + protected void registerRecipes() { - ImmutableList worldgenBlocks = ImmutableList.of( - "granite", - "limestone", - "marble", - "andesite", - "diorite" - ); - for (String wBlocks : worldgenBlocks) { - FMLInterModComms.sendMessage(Constants.MOD, "add-backpack-items", String.format("digger@%s:%s", Chisel, wBlocks)); - } - - } + ImmutableList worldgenBlocks = + ImmutableList.of("granite", "limestone", "marble", "andesite", "diorite"); + for (String wBlocks : worldgenBlocks) { + FMLInterModComms.sendMessage( + Constants.MOD, "add-backpack-items", String.format("digger@%s:%s", Chisel, wBlocks)); + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginEnderIO.java b/src/main/java/forestry/plugins/compat/PluginEnderIO.java index 23e8a6515..b16b883f7 100644 --- a/src/main/java/forestry/plugins/compat/PluginEnderIO.java +++ b/src/main/java/forestry/plugins/compat/PluginEnderIO.java @@ -1,72 +1,75 @@ -package forestry.plugins.compat; - -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.fluids.Fluid; - -import cpw.mods.fml.common.event.FMLInterModComms; - -import forestry.api.core.ForestryAPI; -import forestry.core.config.Constants; -import forestry.core.fluids.Fluids; -import forestry.core.utils.ModUtil; -import forestry.plugins.ForestryPlugin; -import forestry.plugins.Plugin; - -@Plugin(pluginID = "EnderIO", name = "EnderIO", author = "mezz", url = Constants.URL, unlocalizedDescription = "for.plugin.enderIO.description") -public class PluginEnderIO extends ForestryPlugin { - - private static final String EnderIO = "EnderIO"; - - private static final String FLUID_FUEL_ADD = "fluidFuel:add"; - private static final String FLUID_COOLANT_ADD = "fluidCoolant:add"; - - private static final String KEY_FLUID_NAME = "fluidName"; - private static final String KEY_POWER_PER_CYCLE = "powerPerCycle"; - private static final String KEY_TOTAL_BURN_TIME = "totalBurnTime"; - private static final String KEY_COOLING_PER_MB = "coolingPerMb"; - - private static final float WATER_COOLING_PER_MB = 0.0023f; - - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(EnderIO); - } - - @Override - public String getFailMessage() { - return "EnderIO not found"; - } - - @Override - public void doInit() { - Fluid ethanol = Fluids.ETHANOL.getFluid(); - if (ethanol != null) { - int ethanolBurnTime = Math.round(Constants.ENGINE_CYCLE_DURATION_ETHANOL * ForestryAPI.activeMode.getFloatSetting("fuel.ethanol.combustion")); - addFuel(ethanol, 40, ethanolBurnTime); - } - - Fluid crushedIce = Fluids.ICE.getFluid(); - if (crushedIce != null) { - addCoolant(crushedIce, Constants.ICE_COOLING_MULTIPLIER); - } - } - - private static void addFuel(Fluid fluid, int powerPerCycle, int totalBurnTime) { - NBTTagCompound fuelTag = new NBTTagCompound(); - fuelTag.setString(KEY_FLUID_NAME, fluid.getName()); - fuelTag.setInteger(KEY_POWER_PER_CYCLE, powerPerCycle); - fuelTag.setInteger(KEY_TOTAL_BURN_TIME, totalBurnTime); - - FMLInterModComms.sendMessage(EnderIO, FLUID_FUEL_ADD, fuelTag); - } - - private static void addCoolant(Fluid fluid, float coolingMultiplier) { - float coolingPerMb = coolingMultiplier * WATER_COOLING_PER_MB; - NBTTagCompound coolantTag = new NBTTagCompound(); - coolantTag.setString(KEY_FLUID_NAME, fluid.getName()); - coolantTag.setFloat(KEY_COOLING_PER_MB, coolingPerMb); - - FMLInterModComms.sendMessage(EnderIO, FLUID_COOLANT_ADD, coolantTag); - } -} +package forestry.plugins.compat; + +import cpw.mods.fml.common.event.FMLInterModComms; +import forestry.api.core.ForestryAPI; +import forestry.core.config.Constants; +import forestry.core.fluids.Fluids; +import forestry.core.utils.ModUtil; +import forestry.plugins.ForestryPlugin; +import forestry.plugins.Plugin; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.Fluid; + +@Plugin( + pluginID = "EnderIO", + name = "EnderIO", + author = "mezz", + url = Constants.URL, + unlocalizedDescription = "for.plugin.enderIO.description") +public class PluginEnderIO extends ForestryPlugin { + + private static final String EnderIO = "EnderIO"; + + private static final String FLUID_FUEL_ADD = "fluidFuel:add"; + private static final String FLUID_COOLANT_ADD = "fluidCoolant:add"; + + private static final String KEY_FLUID_NAME = "fluidName"; + private static final String KEY_POWER_PER_CYCLE = "powerPerCycle"; + private static final String KEY_TOTAL_BURN_TIME = "totalBurnTime"; + private static final String KEY_COOLING_PER_MB = "coolingPerMb"; + + private static final float WATER_COOLING_PER_MB = 0.0023f; + + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(EnderIO); + } + + @Override + public String getFailMessage() { + return "EnderIO not found"; + } + + @Override + public void doInit() { + Fluid ethanol = Fluids.ETHANOL.getFluid(); + if (ethanol != null) { + int ethanolBurnTime = Math.round(Constants.ENGINE_CYCLE_DURATION_ETHANOL + * ForestryAPI.activeMode.getFloatSetting("fuel.ethanol.combustion")); + addFuel(ethanol, 40, ethanolBurnTime); + } + + Fluid crushedIce = Fluids.ICE.getFluid(); + if (crushedIce != null) { + addCoolant(crushedIce, Constants.ICE_COOLING_MULTIPLIER); + } + } + + private static void addFuel(Fluid fluid, int powerPerCycle, int totalBurnTime) { + NBTTagCompound fuelTag = new NBTTagCompound(); + fuelTag.setString(KEY_FLUID_NAME, fluid.getName()); + fuelTag.setInteger(KEY_POWER_PER_CYCLE, powerPerCycle); + fuelTag.setInteger(KEY_TOTAL_BURN_TIME, totalBurnTime); + + FMLInterModComms.sendMessage(EnderIO, FLUID_FUEL_ADD, fuelTag); + } + + private static void addCoolant(Fluid fluid, float coolingMultiplier) { + float coolingPerMb = coolingMultiplier * WATER_COOLING_PER_MB; + NBTTagCompound coolantTag = new NBTTagCompound(); + coolantTag.setString(KEY_FLUID_NAME, fluid.getName()); + coolantTag.setFloat(KEY_COOLING_PER_MB, coolingPerMb); + + FMLInterModComms.sendMessage(EnderIO, FLUID_COOLANT_ADD, coolantTag); + } +} diff --git a/src/main/java/forestry/plugins/compat/PluginErebus.java b/src/main/java/forestry/plugins/compat/PluginErebus.java index aca378563..5eceb04e8 100644 --- a/src/main/java/forestry/plugins/compat/PluginErebus.java +++ b/src/main/java/forestry/plugins/compat/PluginErebus.java @@ -10,13 +10,7 @@ ******************************************************************************/ package forestry.plugins.compat; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.recipes.RecipeManagers; import forestry.apiculture.items.EnumPropolis; import forestry.core.config.Constants; @@ -26,34 +20,42 @@ import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; import forestry.plugins.PluginApiculture; import forestry.plugins.PluginManager; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; -@Plugin(pluginID = "Erebus", name = "Erebus", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.erebus.description") +@Plugin( + pluginID = "Erebus", + name = "Erebus", + author = "Nirek", + url = Constants.URL, + unlocalizedDescription = "for.plugin.erebus.description") public class PluginErebus extends ForestryPlugin { - private static final String EREBUS = "erebus"; + private static final String EREBUS = "erebus"; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(EREBUS); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(EREBUS); + } - @Override - public String getFailMessage() { - return "Erebus not found"; - } + @Override + public String getFailMessage() { + return "Erebus not found"; + } - @Override - protected void registerRecipes() { - super.registerRecipes(); - Item materials = GameRegistry.findItem(EREBUS, "materials"); - ItemStack honeyDrip = new ItemStack(materials, 1, 21); - FluidStack honeyOutput = Fluids.HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP); - if (PluginManager.Module.FACTORY.isEnabled()) { - ItemStack remnants = null; - if (PluginManager.Module.APICULTURE.isEnabled()) { - remnants = PluginApiculture.items.propolis.get(EnumPropolis.NORMAL, 1); - } - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{honeyDrip}, honeyOutput, remnants, 5); - } - } + @Override + protected void registerRecipes() { + super.registerRecipes(); + Item materials = GameRegistry.findItem(EREBUS, "materials"); + ItemStack honeyDrip = new ItemStack(materials, 1, 21); + FluidStack honeyOutput = Fluids.HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP); + if (PluginManager.Module.FACTORY.isEnabled()) { + ItemStack remnants = null; + if (PluginManager.Module.APICULTURE.isEnabled()) { + remnants = PluginApiculture.items.propolis.get(EnumPropolis.NORMAL, 1); + } + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[] {honeyDrip}, honeyOutput, remnants, 5); + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginExtraUtilities.java b/src/main/java/forestry/plugins/compat/PluginExtraUtilities.java index 33ea7fc96..5c08c28ca 100644 --- a/src/main/java/forestry/plugins/compat/PluginExtraUtilities.java +++ b/src/main/java/forestry/plugins/compat/PluginExtraUtilities.java @@ -10,14 +10,7 @@ ******************************************************************************/ package forestry.plugins.compat; -import java.util.ArrayList; - -import forestry.farming.logic.FarmableReference; -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; - import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.ICircuitLayout; import forestry.api.farming.Farmables; @@ -30,45 +23,57 @@ import forestry.core.utils.ModUtil; import forestry.farming.circuits.CircuitFarmLogic; import forestry.farming.logic.FarmLogicEnder; import forestry.farming.logic.FarmableGenericCrop; +import forestry.farming.logic.FarmableReference; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; import forestry.plugins.PluginCore; import forestry.plugins.PluginManager; +import java.util.ArrayList; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; -@Plugin(pluginID = "ExtraUtilities", name = "ExtraUtilities", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.extrautilities.description") +@Plugin( + pluginID = "ExtraUtilities", + name = "ExtraUtilities", + author = "Nirek", + url = Constants.URL, + unlocalizedDescription = "for.plugin.extrautilities.description") public class PluginExtraUtilities extends ForestryPlugin { - private static final String ExU = "ExtraUtilities"; + private static final String ExU = "ExtraUtilities"; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(ExU); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(ExU); + } - @Override - public String getFailMessage() { - return "ExtraUtilities not found"; - } + @Override + public String getFailMessage() { + return "ExtraUtilities not found"; + } - @Override - public void doInit() { - super.doInit(); + @Override + public void doInit() { + super.doInit(); - Block exUEnderLilly = GameRegistry.findBlock(ExU, "plant/ender_lilly"); - Farmables.farmables.put(FarmableReference.Ender.get(), new ArrayList()); - if (Config.isExUtilEnderLilyEnabled()) { - Circuit.farmEnderManaged = new CircuitFarmLogic("managedEnder", FarmLogicEnder.class); - Farmables.farmables.get(FarmableReference.Ender.get()).add(new FarmableGenericCrop(new ItemStack(exUEnderLilly, 1, 0), exUEnderLilly, 7)); - } - } + Block exUEnderLilly = GameRegistry.findBlock(ExU, "plant/ender_lilly"); + Farmables.farmables.put(FarmableReference.Ender.get(), new ArrayList()); + if (Config.isExUtilEnderLilyEnabled()) { + Circuit.farmEnderManaged = new CircuitFarmLogic("managedEnder", FarmLogicEnder.class); + Farmables.farmables + .get(FarmableReference.Ender.get()) + .add(new FarmableGenericCrop(new ItemStack(exUEnderLilly, 1, 0), exUEnderLilly, 7)); + } + } - @Override - protected void registerRecipes() { - super.registerRecipes(); + @Override + protected void registerRecipes() { + super.registerRecipes(); - if (PluginManager.Module.FARMING.isEnabled() && Config.isExUtilEnderLilyEnabled()) { - ICircuitLayout layoutManaged = ChipsetManager.circuitRegistry.getLayout("forestry.farms.managed"); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.ENDER, 1), Circuit.farmEnderManaged); - } - } + if (PluginManager.Module.FARMING.isEnabled() && Config.isExUtilEnderLilyEnabled()) { + ICircuitLayout layoutManaged = ChipsetManager.circuitRegistry.getLayout("forestry.farms.managed"); + ChipsetManager.solderManager.addRecipe( + layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.ENDER, 1), Circuit.farmEnderManaged); + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginGrowthCraft.java b/src/main/java/forestry/plugins/compat/PluginGrowthCraft.java index ce3f38385..c4c5b451e 100644 --- a/src/main/java/forestry/plugins/compat/PluginGrowthCraft.java +++ b/src/main/java/forestry/plugins/compat/PluginGrowthCraft.java @@ -11,14 +11,7 @@ package forestry.plugins.compat; import com.google.common.collect.ImmutableMap; - -import forestry.farming.logic.FarmableReference; -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; import forestry.api.recipes.RecipeManagers; @@ -28,119 +21,137 @@ import forestry.core.fluids.Fluids; import forestry.core.recipes.RecipeUtil; import forestry.core.utils.ModUtil; import forestry.farming.logic.FarmableBasicGrowthCraft; +import forestry.farming.logic.FarmableReference; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; import forestry.plugins.PluginApiculture; import forestry.plugins.PluginCore; import forestry.plugins.PluginManager; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; -@Plugin(pluginID = "Growthcraft", name = "Growthcraft", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.growthcraft.description") +@Plugin( + pluginID = "Growthcraft", + name = "Growthcraft", + author = "Nirek", + url = Constants.URL, + unlocalizedDescription = "for.plugin.growthcraft.description") public class PluginGrowthCraft extends ForestryPlugin { - private static final String GC = "Growthcraft"; + private static final String GC = "Growthcraft"; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(GC, "[1.7.10-1.0.0,1.7.10-2.5.0)"); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(GC, "[1.7.10-1.0.0,1.7.10-2.5.0)"); + } - @Override - public String getFailMessage() { - return "GrowthCraft not found"; - } + @Override + public String getFailMessage() { + return "GrowthCraft not found"; + } - @Override - protected void registerRecipes() { + @Override + protected void registerRecipes() { - int saplingYield = ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"); - int juiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); - int seedamount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); + int saplingYield = ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"); + int juiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); + int seedamount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - ItemStack appleSeed = GameRegistry.findItemStack("Growthcraft|Apples", "grc.appleSeeds", 1); - ItemStack grapeSeed = GameRegistry.findItemStack("Growthcraft|Grapes", "grc.grapeSeeds", 1); - ItemStack hopSeed = GameRegistry.findItemStack("Growthcraft|Hops", "grc.hopSeeds", 1); - ItemStack riceSeed = GameRegistry.findItemStack("Growthcraft|Rice", "grc.rice", 1); + ItemStack appleSeed = GameRegistry.findItemStack("Growthcraft|Apples", "grc.appleSeeds", 1); + ItemStack grapeSeed = GameRegistry.findItemStack("Growthcraft|Grapes", "grc.grapeSeeds", 1); + ItemStack hopSeed = GameRegistry.findItemStack("Growthcraft|Hops", "grc.hopSeeds", 1); + ItemStack riceSeed = GameRegistry.findItemStack("Growthcraft|Rice", "grc.rice", 1); - if (appleSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{appleSeed}, Fluids.SEEDOIL.getFluid(seedamount)); - BackpackManager.backpackItems[2].add(appleSeed); - } - if (grapeSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{grapeSeed}, Fluids.SEEDOIL.getFluid(seedamount)); - BackpackManager.backpackItems[2].add(grapeSeed); - } - if (hopSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{hopSeed}, Fluids.SEEDOIL.getFluid(seedamount)); - BackpackManager.backpackItems[2].add(hopSeed); - } - if (riceSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{riceSeed}, Fluids.SEEDOIL.getFluid(seedamount)); - BackpackManager.backpackItems[2].add(riceSeed); - } + if (appleSeed != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {appleSeed}, Fluids.SEEDOIL.getFluid(seedamount)); + BackpackManager.backpackItems[2].add(appleSeed); + } + if (grapeSeed != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {grapeSeed}, Fluids.SEEDOIL.getFluid(seedamount)); + BackpackManager.backpackItems[2].add(grapeSeed); + } + if (hopSeed != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {hopSeed}, Fluids.SEEDOIL.getFluid(seedamount)); + BackpackManager.backpackItems[2].add(hopSeed); + } + if (riceSeed != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {riceSeed}, Fluids.SEEDOIL.getFluid(seedamount)); + BackpackManager.backpackItems[2].add(riceSeed); + } - ItemStack hops = GameRegistry.findItemStack("Growthcraft|Hops", "grc.hops", 1); + ItemStack hops = GameRegistry.findItemStack("Growthcraft|Hops", "grc.hops", 1); - if (hops != null) { - RecipeUtil.addFermenterRecipes(hops, saplingYield, Fluids.BIOMASS); - BackpackManager.backpackItems[2].add(hops); + if (hops != null) { + RecipeUtil.addFermenterRecipes(hops, saplingYield, Fluids.BIOMASS); + BackpackManager.backpackItems[2].add(hops); + } + Block hopVine = GameRegistry.findBlock("Growthcraft|Hops", "grc.hopVine"); + if (hopVine != null) { + Farmables.farmables + .get(FarmableReference.Orchard.get()) + .add(new FarmableBasicGrowthCraft(hopVine, 3, false, false)); // need custom fruit to weed out rope + } + Block riceBlock = GameRegistry.findBlock("Growthcraft|Rice", "grc.riceBlock"); + if (riceBlock != null) { + Farmables.farmables + .get(FarmableReference.Orchard.get()) + .add(new FarmableBasicGrowthCraft(riceBlock, 7, true, false)); // need to set paddyfield to 7 + } - } - Block hopVine = GameRegistry.findBlock("Growthcraft|Hops", "grc.hopVine"); - if (hopVine != null) { - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicGrowthCraft(hopVine, 3, false, false)); // need custom fruit to weed out rope - } - Block riceBlock = GameRegistry.findBlock("Growthcraft|Rice", "grc.riceBlock"); - if (riceBlock != null) { - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicGrowthCraft(riceBlock, 7, true, false)); //need to set paddyfield to 7 - } + if (PluginManager.Module.APICULTURE.isEnabled()) { + Item comb = GameRegistry.findItem("Growthcraft|Bees", "grc.honeyComb"); + if (comb != null) { + ItemStack emptyComb = new ItemStack(comb, 1, 0); + RecipeManagers.centrifugeManager.addRecipe( + 20, emptyComb, ImmutableMap.of(PluginCore.items.beeswax.getItemStack(), 1.0f)); + ItemStack fullComb = new ItemStack(comb, 1, 1); + RecipeManagers.centrifugeManager.addRecipe( + 20, + fullComb, + ImmutableMap.of( + PluginCore.items.beeswax.getItemStack(), 1.0f, + PluginApiculture.items.honeyDrop.getItemStack(), 0.9f, + PluginApiculture.items.honeydew.getItemStack(), 0.1f)); + } + } - if (PluginManager.Module.APICULTURE.isEnabled()) { - Item comb = GameRegistry.findItem("Growthcraft|Bees", "grc.honeyComb"); - if (comb != null) { - ItemStack emptyComb = new ItemStack(comb, 1, 0); - RecipeManagers.centrifugeManager.addRecipe(20, emptyComb, ImmutableMap.of( - PluginCore.items.beeswax.getItemStack(), 1.0f) - ); - ItemStack fullComb = new ItemStack(comb, 1, 1); - RecipeManagers.centrifugeManager.addRecipe(20, fullComb, ImmutableMap.of( - PluginCore.items.beeswax.getItemStack(), 1.0f, - PluginApiculture.items.honeyDrop.getItemStack(), 0.9f, - PluginApiculture.items.honeydew.getItemStack(), 0.1f) - ); - } - } + ItemStack bamboo = GameRegistry.findItemStack("Growthcraft|Bamboo", "grc.bamboo", 1); + ItemStack bambooShoot = GameRegistry.findItemStack("Growthcraft|Bamboo", "grc.bambooShoot", 1); + ItemStack bambooShootFood = GameRegistry.findItemStack("Growthcraft|Bamboo", "grc.bambooShootFood", 1); + if (bamboo != null) { + RecipeUtil.addFermenterRecipes(bamboo, saplingYield, Fluids.BIOMASS); + BackpackManager.backpackItems[2].add(bamboo); + } + if (bambooShoot != null) { + RecipeUtil.addFermenterRecipes(bambooShoot, saplingYield, Fluids.BIOMASS); + BackpackManager.backpackItems[2].add(bambooShoot); + } + if (bambooShootFood != null) { + RecipeUtil.addFermenterRecipes(bambooShootFood, saplingYield, Fluids.BIOMASS); + BackpackManager.backpackItems[2].add(bambooShootFood); + } - ItemStack bamboo = GameRegistry.findItemStack("Growthcraft|Bamboo", "grc.bamboo", 1); - ItemStack bambooShoot = GameRegistry.findItemStack("Growthcraft|Bamboo", "grc.bambooShoot", 1); - ItemStack bambooShootFood = GameRegistry.findItemStack("Growthcraft|Bamboo", "grc.bambooShootFood", 1); - if (bamboo != null) { - RecipeUtil.addFermenterRecipes(bamboo, saplingYield, Fluids.BIOMASS); - BackpackManager.backpackItems[2].add(bamboo); - } - if (bambooShoot != null) { - RecipeUtil.addFermenterRecipes(bambooShoot, saplingYield, Fluids.BIOMASS); - BackpackManager.backpackItems[2].add(bambooShoot); - } - if (bambooShootFood != null) { - RecipeUtil.addFermenterRecipes(bambooShootFood, saplingYield, Fluids.BIOMASS); - BackpackManager.backpackItems[2].add(bambooShootFood); - } + ItemStack grapes = GameRegistry.findItemStack("Growthcraft|Grapes", "grc.grapes", 1); // squeeze - ItemStack grapes = GameRegistry.findItemStack("Growthcraft|Grapes", "grc.grapes", 1); //squeeze + if (grapes.getItem() != null) { + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[] {grapes}, Fluids.JUICE.getFluid(juiceAmount)); + BackpackManager.backpackItems[2].add(grapes); + } + Block grapeBlock = GameRegistry.findBlock("Growthcraft|Grapes", "grc.grapeBlock"); + if (grapeBlock != null) { + Farmables.farmables + .get(FarmableReference.Orchard.get()) + .add(new FarmableBasicGrowthCraft(grapeBlock, 0, false, true)); + } - if (grapes.getItem() != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{grapes}, Fluids.JUICE.getFluid(juiceAmount)); - BackpackManager.backpackItems[2].add(grapes); - } - Block grapeBlock = GameRegistry.findBlock("Growthcraft|Grapes", "grc.grapeBlock"); - if (grapeBlock != null) { - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicGrowthCraft(grapeBlock, 0, false, true)); - } - - ItemStack bambooLeaves = GameRegistry.findItemStack("Growthcraft|Bamboo", "grc.bambooLeaves", 1); - if (bambooLeaves != null) { - BackpackManager.backpackItems[2].add(bambooLeaves); - } - - } + ItemStack bambooLeaves = GameRegistry.findItemStack("Growthcraft|Bamboo", "grc.bambooLeaves", 1); + if (bambooLeaves != null) { + BackpackManager.backpackItems[2].add(bambooLeaves); + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginHarvestCraft.java b/src/main/java/forestry/plugins/compat/PluginHarvestCraft.java index b8b030e98..864b902ec 100644 --- a/src/main/java/forestry/plugins/compat/PluginHarvestCraft.java +++ b/src/main/java/forestry/plugins/compat/PluginHarvestCraft.java @@ -11,14 +11,7 @@ package forestry.plugins.compat; import com.google.common.collect.ImmutableList; - -import forestry.farming.logic.FarmableReference; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; - import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; import forestry.api.fuels.FuelManager; @@ -30,379 +23,396 @@ import forestry.core.recipes.RecipeUtil; import forestry.core.utils.ModUtil; import forestry.farming.logic.FarmableBasicFruit; import forestry.farming.logic.FarmableGenericCrop; +import forestry.farming.logic.FarmableReference; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; import forestry.plugins.PluginCore; import forestry.plugins.PluginManager; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; -@Plugin(pluginID = "HarvestCraft", name = "HarvestCraft", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.harvestcraft.description") +@Plugin( + pluginID = "HarvestCraft", + name = "HarvestCraft", + author = "Nirek", + url = Constants.URL, + unlocalizedDescription = "for.plugin.harvestcraft.description") public class PluginHarvestCraft extends ForestryPlugin { - private static final String HC = "harvestcraft"; - private static final String HCN = "harvestthenether"; + private static final String HC = "harvestcraft"; + private static final String HCN = "harvestthenether"; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(HC); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(HC); + } - @Override - public String getFailMessage() { - return "HarvestCraft not found"; - } + @Override + public String getFailMessage() { + return "HarvestCraft not found"; + } - @Override - protected void registerRecipes() { + @Override + protected void registerRecipes() { - ImmutableList berries = ImmutableList.of( - "cranberry", - "blackberry", - "blueberry", - "raspberry", - "strawberry" - ); + ImmutableList berries = + ImmutableList.of("cranberry", "blackberry", "blueberry", "raspberry", "strawberry"); - ImmutableList fruits = ImmutableList.of( - "pineapple", - "cactusfruit", - "cantaloupe", - "grape", - "kiwi", - "chilipepper" - ); + ImmutableList fruits = + ImmutableList.of("pineapple", "cactusfruit", "cantaloupe", "grape", "kiwi", "chilipepper"); - ImmutableList treeFruits = ImmutableList.of( - "banana", - "dragonfruit", - "lemon", - "lime", - "mango", - "orange", - "papaya", - "peach", - "pear", - "plum", - "pomegranate", - "starfruit", - "apricot", - "date", - "fig", - "grapefruit", - "persimmon", - "avocado", - "coconut", - "durian", - "gooseberry" - ); + ImmutableList treeFruits = ImmutableList.of( + "banana", + "dragonfruit", + "lemon", + "lime", + "mango", + "orange", + "papaya", + "peach", + "pear", + "plum", + "pomegranate", + "starfruit", + "apricot", + "date", + "fig", + "grapefruit", + "persimmon", + "avocado", + "coconut", + "durian", + "gooseberry"); - ImmutableList trees = ImmutableList.of( - "nutmeg", - "olive", - "peppercorn" - ); + ImmutableList trees = ImmutableList.of("nutmeg", "olive", "peppercorn"); - ImmutableList treesSpecial = ImmutableList.of( - "cinnamon", - "maple", - "paperbark", - "vanillabean", - "apple" // to prevent apples from getting double registered - ); + ImmutableList treesSpecial = ImmutableList.of( + "cinnamon", + "maple", + "paperbark", + "vanillabean", + "apple" // to prevent apples from getting double registered + ); - ImmutableList herbs = ImmutableList.of( - "garlic" - ); + ImmutableList herbs = ImmutableList.of("garlic"); - ImmutableList spices = ImmutableList.of( - "ginger", - "spiceleaf", - "curryleaf" - //"mustardseed" Mustard is inconsistent and annoying. - ); + ImmutableList spices = ImmutableList.of( + "ginger", "spiceleaf", "curryleaf" + // "mustardseed" Mustard is inconsistent and annoying. + ); - ImmutableList vegetables = ImmutableList.of( - "asparagus", - "bean", - "beet", - "broccoli", - "cauliflower", - "celery", - "leek", - "lettuce", - "onion", - "parsnip", - "radish", - "rutabaga", - "scallion", - "soybean", - "sweetpotato", - "turnip", - "whitemushroom", - "artichoke", - "bellpepper", - "brusselsprout", - "cabbage", - "corn", - "cucumber", - "eggplant", - "okra", - "peas", - "rhubarb", - "seaweed", - "tomato", - "wintersquash", - "zucchini", - "bambooshoot", - "spinach", - "waterchestnut" - ); + ImmutableList vegetables = ImmutableList.of( + "asparagus", + "bean", + "beet", + "broccoli", + "cauliflower", + "celery", + "leek", + "lettuce", + "onion", + "parsnip", + "radish", + "rutabaga", + "scallion", + "soybean", + "sweetpotato", + "turnip", + "whitemushroom", + "artichoke", + "bellpepper", + "brusselsprout", + "cabbage", + "corn", + "cucumber", + "eggplant", + "okra", + "peas", + "rhubarb", + "seaweed", + "tomato", + "wintersquash", + "zucchini", + "bambooshoot", + "spinach", + "waterchestnut"); - ImmutableList grains = ImmutableList.of( - "barley", - "oats", - "rye" - ); + ImmutableList grains = ImmutableList.of("barley", "oats", "rye"); - ImmutableList cropNuts = ImmutableList.of( - "peanut", - "sesameseeds" - ); + ImmutableList cropNuts = ImmutableList.of("peanut", "sesameseeds"); - ImmutableList nuts = ImmutableList.of( - "walnut", - "almond", - "cashew", - "chestnut", - "pecan", - "pistachio", - "cherry" //Cherries in forestry make seed oil - ); + ImmutableList nuts = ImmutableList.of( + "walnut", + "almond", + "cashew", + "chestnut", + "pecan", + "pistachio", + "cherry" // Cherries in forestry make seed oil + ); - ImmutableList.Builder genericCropsBuilder = ImmutableList.builder(); - genericCropsBuilder.add( - "cotton", - "rice", - "tea", - "coffee", - "candleberry" - ); - genericCropsBuilder.addAll(herbs); - genericCropsBuilder.addAll(spices); + ImmutableList.Builder genericCropsBuilder = ImmutableList.builder(); + genericCropsBuilder.add("cotton", "rice", "tea", "coffee", "candleberry"); + genericCropsBuilder.addAll(herbs); + genericCropsBuilder.addAll(spices); - ImmutableList genericCrops = genericCropsBuilder.build(); + ImmutableList genericCrops = genericCropsBuilder.build(); - // Pam's Harvest The Nether Crops - ImmutableList.Builder genericNetherCropsBuilder = ImmutableList.builder(); - genericNetherCropsBuilder.add( - "glowflower", - "fleshroot", - "bloodleaf", - "marrowberry" - ); - - ImmutableList genericNetherCrops = genericNetherCropsBuilder.build(); + // Pam's Harvest The Nether Crops + ImmutableList.Builder genericNetherCropsBuilder = ImmutableList.builder(); + genericNetherCropsBuilder.add("glowflower", "fleshroot", "bloodleaf", "marrowberry"); - ImmutableList.Builder plants = ImmutableList.builder(); + ImmutableList genericNetherCrops = genericNetherCropsBuilder.build(); - int juiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple") / 25; - int seedamount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - ItemStack wheatamount = ForestryAPI.activeMode.getStackSetting("recipe.output.compost.wheat"); + ImmutableList.Builder plants = ImmutableList.builder(); - juiceAmount = Math.max(juiceAmount, 1); // Produce at least 1 mb of juice. - for (String berryName : berries) { - ItemStack berry = GameRegistry.findItemStack(HC, berryName + "Item", 1); - ItemStack berrySeed = GameRegistry.findItemStack(HC, berryName + "seedItem", 1); - Block berryBlock = GameRegistry.findBlock(HC, "pam" + berryName + "Crop"); - if (berry != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{berry}, Fluids.JUICE.getFluid(juiceAmount)); - } - if (berrySeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{berrySeed}, Fluids.SEEDOIL.getFluid(seedamount)); - } - if (PluginManager.Module.FARMING.isEnabled() && berrySeed != null && berryBlock != null) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(berrySeed, berryBlock, 7)); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(berryBlock, 7)); - } - plants.add(berryName); - } + int juiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple") / 25; + int seedamount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); + ItemStack wheatamount = ForestryAPI.activeMode.getStackSetting("recipe.output.compost.wheat"); - juiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); - for (String fruitName : fruits) { - ItemStack fruit = GameRegistry.findItemStack(HC, fruitName + "Item", 1); - ItemStack fruitSeed = GameRegistry.findItemStack(HC, fruitName + "seedItem", 1); - Block fruitBlock = GameRegistry.findBlock(HC, "pam" + fruitName + "Crop"); - if (fruit != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{fruit}, Fluids.JUICE.getFluid(juiceAmount)); - } - if (fruitSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{fruitSeed}, Fluids.SEEDOIL.getFluid(seedamount)); - } - if (PluginManager.Module.FARMING.isEnabled() && fruitSeed != null && fruitBlock != null) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(fruitSeed, fruitBlock, 7)); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(fruitBlock, 7)); - } - plants.add(fruitName); - } + juiceAmount = Math.max(juiceAmount, 1); // Produce at least 1 mb of juice. + for (String berryName : berries) { + ItemStack berry = GameRegistry.findItemStack(HC, berryName + "Item", 1); + ItemStack berrySeed = GameRegistry.findItemStack(HC, berryName + "seedItem", 1); + Block berryBlock = GameRegistry.findBlock(HC, "pam" + berryName + "Crop"); + if (berry != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {berry}, Fluids.JUICE.getFluid(juiceAmount)); + } + if (berrySeed != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {berrySeed}, Fluids.SEEDOIL.getFluid(seedamount)); + } + if (PluginManager.Module.FARMING.isEnabled() && berrySeed != null && berryBlock != null) { + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(berrySeed, berryBlock, 7)); + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(berryBlock, 7)); + } + plants.add(berryName); + } - juiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple") / 2; // vegetables produce less juice - juiceAmount = Math.max(juiceAmount, 1); // Produce at least 1 mb of juice. - for (String vegetableName : vegetables) { - ItemStack vegetable = GameRegistry.findItemStack(HC, vegetableName + "Item", 1); - ItemStack vegetableSeed = GameRegistry.findItemStack(HC, vegetableName + "seedItem", 1); - Block vegetableBlock = GameRegistry.findBlock(HC, "pam" + vegetableName + "Crop"); - if (vegetable != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{vegetable}, Fluids.JUICE.getFluid(juiceAmount)); - } - if (vegetableSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{vegetableSeed}, Fluids.SEEDOIL.getFluid(seedamount)); - } - if (PluginManager.Module.FARMING.isEnabled() && vegetableSeed != null && vegetableBlock != null) { - Farmables.farmables.get(FarmableReference.Vegetables.get()).add(new FarmableGenericCrop(vegetableSeed, vegetableBlock, 7)); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(vegetableBlock, 7)); - } - plants.add(vegetableName); - } + juiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); + for (String fruitName : fruits) { + ItemStack fruit = GameRegistry.findItemStack(HC, fruitName + "Item", 1); + ItemStack fruitSeed = GameRegistry.findItemStack(HC, fruitName + "seedItem", 1); + Block fruitBlock = GameRegistry.findBlock(HC, "pam" + fruitName + "Crop"); + if (fruit != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {fruit}, Fluids.JUICE.getFluid(juiceAmount)); + } + if (fruitSeed != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {fruitSeed}, Fluids.SEEDOIL.getFluid(seedamount)); + } + if (PluginManager.Module.FARMING.isEnabled() && fruitSeed != null && fruitBlock != null) { + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(fruitSeed, fruitBlock, 7)); + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(fruitBlock, 7)); + } + plants.add(fruitName); + } - for (String grainName : grains) { - ItemStack grain = GameRegistry.findItemStack(HC, grainName + "Item", 1); - ItemStack grainSeed = GameRegistry.findItemStack(HC, grainName + "seedItem", 1); - Block grainBlock = GameRegistry.findBlock(HC, "pam" + grainName + "Crop"); - if (grain != null && wheatamount.stackSize > 0) { - RecipeUtil.addRecipe(wheatamount, " X ", "X#X", " X ", '#', Blocks.dirt, 'X', grain); - FuelManager.moistenerResource.put(grain, new MoistenerFuel(grain, PluginCore.items.mouldyWheat.getItemStack(), 0, 300)); - } - if (grainSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{grainSeed}, Fluids.SEEDOIL.getFluid(seedamount)); - RecipeManagers.moistenerManager.addRecipe(grainSeed, new ItemStack(Blocks.mycelium), 5000); - } - if (PluginManager.Module.FARMING.isEnabled() && grainSeed != null && grainBlock != null) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(grainSeed, grainBlock, 7)); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(grainBlock, 7)); - } - plants.add(grainName); - } + juiceAmount = + ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple") / 2; // vegetables produce less juice + juiceAmount = Math.max(juiceAmount, 1); // Produce at least 1 mb of juice. + for (String vegetableName : vegetables) { + ItemStack vegetable = GameRegistry.findItemStack(HC, vegetableName + "Item", 1); + ItemStack vegetableSeed = GameRegistry.findItemStack(HC, vegetableName + "seedItem", 1); + Block vegetableBlock = GameRegistry.findBlock(HC, "pam" + vegetableName + "Crop"); + if (vegetable != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {vegetable}, Fluids.JUICE.getFluid(juiceAmount)); + } + if (vegetableSeed != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {vegetableSeed}, Fluids.SEEDOIL.getFluid(seedamount)); + } + if (PluginManager.Module.FARMING.isEnabled() && vegetableSeed != null && vegetableBlock != null) { + Farmables.farmables + .get(FarmableReference.Vegetables.get()) + .add(new FarmableGenericCrop(vegetableSeed, vegetableBlock, 7)); + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(vegetableBlock, 7)); + } + plants.add(vegetableName); + } - for (String treeFruitName : treeFruits) { - ItemStack treeFruit = GameRegistry.findItemStack(HC, treeFruitName + "Item", 1); - Block treeFruitBlock = GameRegistry.findBlock(HC, "pam" + (Character.toUpperCase(treeFruitName.charAt(0)) + treeFruitName.substring(1))); - if (PluginManager.Module.FARMING.isEnabled() && treeFruitBlock != null) { - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(treeFruitBlock, 2)); - } - if (treeFruit != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{treeFruit}, Fluids.JUICE.getFluid(juiceAmount)); - } - plants.add(treeFruitName); - } + for (String grainName : grains) { + ItemStack grain = GameRegistry.findItemStack(HC, grainName + "Item", 1); + ItemStack grainSeed = GameRegistry.findItemStack(HC, grainName + "seedItem", 1); + Block grainBlock = GameRegistry.findBlock(HC, "pam" + grainName + "Crop"); + if (grain != null && wheatamount.stackSize > 0) { + RecipeUtil.addRecipe(wheatamount, " X ", "X#X", " X ", '#', Blocks.dirt, 'X', grain); + FuelManager.moistenerResource.put( + grain, new MoistenerFuel(grain, PluginCore.items.mouldyWheat.getItemStack(), 0, 300)); + } + if (grainSeed != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {grainSeed}, Fluids.SEEDOIL.getFluid(seedamount)); + RecipeManagers.moistenerManager.addRecipe(grainSeed, new ItemStack(Blocks.mycelium), 5000); + } + if (PluginManager.Module.FARMING.isEnabled() && grainSeed != null && grainBlock != null) { + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(grainSeed, grainBlock, 7)); + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(grainBlock, 7)); + } + plants.add(grainName); + } - for (String treeName : trees) { - Block fruitBlock = GameRegistry.findBlock(HC, "pam" + (Character.toUpperCase(treeName.charAt(0)) + treeName.substring(1))); - if (PluginManager.Module.FARMING.isEnabled() && fruitBlock != null) { - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(fruitBlock, 2)); - } - plants.add(treeName); - } + for (String treeFruitName : treeFruits) { + ItemStack treeFruit = GameRegistry.findItemStack(HC, treeFruitName + "Item", 1); + Block treeFruitBlock = GameRegistry.findBlock( + HC, "pam" + (Character.toUpperCase(treeFruitName.charAt(0)) + treeFruitName.substring(1))); + if (PluginManager.Module.FARMING.isEnabled() && treeFruitBlock != null) { + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(treeFruitBlock, 2)); + } + if (treeFruit != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {treeFruit}, Fluids.JUICE.getFluid(juiceAmount)); + } + plants.add(treeFruitName); + } - for (String treeName : treesSpecial) { - Block fruitBlock = GameRegistry.findBlock(HC, "pam" + (Character.toUpperCase(treeName.charAt(0)) + treeName.substring(1))); - if (PluginManager.Module.FARMING.isEnabled() && fruitBlock != null) { - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(fruitBlock, 2)); - } - } + for (String treeName : trees) { + Block fruitBlock = GameRegistry.findBlock( + HC, "pam" + (Character.toUpperCase(treeName.charAt(0)) + treeName.substring(1))); + if (PluginManager.Module.FARMING.isEnabled() && fruitBlock != null) { + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(fruitBlock, 2)); + } + plants.add(treeName); + } - for (String cropName : genericCrops) { - ItemStack genericCropSeed = GameRegistry.findItemStack(HC, cropName + "seedItem", 1); - Block genericCropBlock = GameRegistry.findBlock(HC, "pam" + cropName + "Crop"); - if (genericCropSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{genericCropSeed}, Fluids.SEEDOIL.getFluid(seedamount)); - } - if (PluginManager.Module.FARMING.isEnabled() && genericCropSeed != null && genericCropBlock != null) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(genericCropSeed, genericCropBlock, 7)); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(genericCropBlock, 7)); - } - plants.add(cropName); - } + for (String treeName : treesSpecial) { + Block fruitBlock = GameRegistry.findBlock( + HC, "pam" + (Character.toUpperCase(treeName.charAt(0)) + treeName.substring(1))); + if (PluginManager.Module.FARMING.isEnabled() && fruitBlock != null) { + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(fruitBlock, 2)); + } + } - ItemStack mustardCropSeed = GameRegistry.findItemStack(HC, "mustard" + "seedItem", 1); - Block mustardCropBlock = GameRegistry.findBlock(HC, "pam" + "mustardseeds" + "Crop"); - ItemStack mustardFruit = GameRegistry.findItemStack(HC, "mustard" + "seedsItem", 1); - if (mustardCropSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{mustardCropSeed}, Fluids.SEEDOIL.getFluid(seedamount)); - } - if (PluginManager.Module.FARMING.isEnabled() && mustardCropSeed != null && mustardCropBlock != null) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(mustardCropSeed, mustardCropBlock, 7)); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(mustardCropBlock, 7)); - } - if (mustardFruit != null) { - RecipeUtil.addFermenterRecipes(mustardFruit, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); - } + for (String cropName : genericCrops) { + ItemStack genericCropSeed = GameRegistry.findItemStack(HC, cropName + "seedItem", 1); + Block genericCropBlock = GameRegistry.findBlock(HC, "pam" + cropName + "Crop"); + if (genericCropSeed != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {genericCropSeed}, Fluids.SEEDOIL.getFluid(seedamount)); + } + if (PluginManager.Module.FARMING.isEnabled() && genericCropSeed != null && genericCropBlock != null) { + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(genericCropSeed, genericCropBlock, 7)); + Farmables.farmables + .get(FarmableReference.Orchard.get()) + .add(new FarmableBasicFruit(genericCropBlock, 7)); + } + plants.add(cropName); + } - for (String plantName : plants.build()) { - ItemStack plant = GameRegistry.findItemStack(HC, plantName + "Item", 1); - if (plant != null) { - RecipeUtil.addFermenterRecipes(plant, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); - } - } + ItemStack mustardCropSeed = GameRegistry.findItemStack(HC, "mustard" + "seedItem", 1); + Block mustardCropBlock = GameRegistry.findBlock(HC, "pam" + "mustardseeds" + "Crop"); + ItemStack mustardFruit = GameRegistry.findItemStack(HC, "mustard" + "seedsItem", 1); + if (mustardCropSeed != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {mustardCropSeed}, Fluids.SEEDOIL.getFluid(seedamount)); + } + if (PluginManager.Module.FARMING.isEnabled() && mustardCropSeed != null && mustardCropBlock != null) { + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(mustardCropSeed, mustardCropBlock, 7)); + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(mustardCropBlock, 7)); + } + if (mustardFruit != null) { + RecipeUtil.addFermenterRecipes( + mustardFruit, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); + } - for (String cropnutName : cropNuts) { - ItemStack cropnut = GameRegistry.findItemStack(HC, cropnutName + "Item", 1); - ItemStack cropnutSeed = GameRegistry.findItemStack(HC, cropnutName + "seedItem", 1); - Block cropnutBlock = GameRegistry.findBlock(HC, "pam" + cropnutName + "Crop"); - if (cropnutSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{cropnutSeed}, Fluids.SEEDOIL.getFluid(seedamount)); - } - if (PluginManager.Module.FARMING.isEnabled() && cropnutSeed != null && cropnutBlock != null) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(cropnutSeed, cropnutBlock, 7)); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(cropnutBlock, 7)); - } - if (cropnut != null) { - RecipeManagers.squeezerManager.addRecipe(20, new ItemStack[]{cropnut}, Fluids.SEEDOIL.getFluid(12 * seedamount)); - } - } + for (String plantName : plants.build()) { + ItemStack plant = GameRegistry.findItemStack(HC, plantName + "Item", 1); + if (plant != null) { + RecipeUtil.addFermenterRecipes( + plant, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); + } + } - for (String nutName : nuts) { - ItemStack nut = GameRegistry.findItemStack(HC, nutName + "Item", 1); - Block nutBlock = GameRegistry.findBlock(HC, "pam" + (Character.toUpperCase(nutName.charAt(0)) + nutName.substring(1))); - if (PluginManager.Module.FARMING.isEnabled() && nutBlock != null) { - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(nutBlock, 2)); - } - if (nut != null) { - RecipeManagers.squeezerManager.addRecipe(20, new ItemStack[]{nut}, Fluids.SEEDOIL.getFluid(15 * seedamount)); - } - } + for (String cropnutName : cropNuts) { + ItemStack cropnut = GameRegistry.findItemStack(HC, cropnutName + "Item", 1); + ItemStack cropnutSeed = GameRegistry.findItemStack(HC, cropnutName + "seedItem", 1); + Block cropnutBlock = GameRegistry.findBlock(HC, "pam" + cropnutName + "Crop"); + if (cropnutSeed != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {cropnutSeed}, Fluids.SEEDOIL.getFluid(seedamount)); + } + if (PluginManager.Module.FARMING.isEnabled() && cropnutSeed != null && cropnutBlock != null) { + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(cropnutSeed, cropnutBlock, 7)); + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(cropnutBlock, 7)); + } + if (cropnut != null) { + RecipeManagers.squeezerManager.addRecipe( + 20, new ItemStack[] {cropnut}, Fluids.SEEDOIL.getFluid(12 * seedamount)); + } + } - ItemStack hcHoneyItem = GameRegistry.findItemStack(HC, "honeyItem", 1); - if (hcHoneyItem != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{hcHoneyItem}, Fluids.HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP)); - } + for (String nutName : nuts) { + ItemStack nut = GameRegistry.findItemStack(HC, nutName + "Item", 1); + Block nutBlock = GameRegistry.findBlock( + HC, "pam" + (Character.toUpperCase(nutName.charAt(0)) + nutName.substring(1))); + if (PluginManager.Module.FARMING.isEnabled() && nutBlock != null) { + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(nutBlock, 2)); + } + if (nut != null) { + RecipeManagers.squeezerManager.addRecipe( + 20, new ItemStack[] {nut}, Fluids.SEEDOIL.getFluid(15 * seedamount)); + } + } - ItemStack hcBeeswaxItem = GameRegistry.findItemStack(HC, "beeswaxItem", 1); - if (hcBeeswaxItem != null) { - RecipeUtil.addRecipe(ForestryAPI.activeMode.getStackSetting("recipe.output.capsule"), "XXX ", 'X', hcBeeswaxItem); - } + ItemStack hcHoneyItem = GameRegistry.findItemStack(HC, "honeyItem", 1); + if (hcHoneyItem != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {hcHoneyItem}, Fluids.HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP)); + } - // Recipe registering for Pam's Harvest the Nether - if (ModUtil.isModLoaded(HCN)) { - for (String netherCropName : genericNetherCrops) { - ItemStack genericNetherCropSeed = GameRegistry.findItemStack(HCN, netherCropName + "seedItem", 1); - Block genericNetherCropBlock = GameRegistry.findBlock(HCN, netherCropName + "Crop"); - if (genericNetherCropSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{genericNetherCropSeed}, Fluids.SEEDOIL.getFluid(seedamount)); - } + ItemStack hcBeeswaxItem = GameRegistry.findItemStack(HC, "beeswaxItem", 1); + if (hcBeeswaxItem != null) { + RecipeUtil.addRecipe( + ForestryAPI.activeMode.getStackSetting("recipe.output.capsule"), "XXX ", 'X', hcBeeswaxItem); + } - if (PluginManager.Module.FARMING.isEnabled() && genericNetherCropSeed != null && genericNetherCropBlock != null) { - // Add all crops to orchard farms - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(genericNetherCropBlock, 7)); - - if (netherCropName == "glowflower") { - // Add glowflowers to managed and manual crop farms - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(genericNetherCropSeed, genericNetherCropBlock, 7)); - } else { - // Add every other crop to infernal farms, since they only grow on soul sand - Farmables.farmables.get(FarmableReference.Infernal.get()).add(new FarmableGenericCrop(genericNetherCropSeed, genericNetherCropBlock, 7)); - } - } - } - } - } + // Recipe registering for Pam's Harvest the Nether + if (ModUtil.isModLoaded(HCN)) { + for (String netherCropName : genericNetherCrops) { + ItemStack genericNetherCropSeed = GameRegistry.findItemStack(HCN, netherCropName + "seedItem", 1); + Block genericNetherCropBlock = GameRegistry.findBlock(HCN, netherCropName + "Crop"); + if (genericNetherCropSeed != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {genericNetherCropSeed}, Fluids.SEEDOIL.getFluid(seedamount)); + } + if (PluginManager.Module.FARMING.isEnabled() + && genericNetherCropSeed != null + && genericNetherCropBlock != null) { + // Add all crops to orchard farms + Farmables.farmables + .get(FarmableReference.Orchard.get()) + .add(new FarmableBasicFruit(genericNetherCropBlock, 7)); + + if (netherCropName == "glowflower") { + // Add glowflowers to managed and manual crop farms + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(genericNetherCropSeed, genericNetherCropBlock, 7)); + } else { + // Add every other crop to infernal farms, since they only grow on soul sand + Farmables.farmables + .get(FarmableReference.Infernal.get()) + .add(new FarmableGenericCrop(genericNetherCropSeed, genericNetherCropBlock, 7)); + } + } + } + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginIC2.java b/src/main/java/forestry/plugins/compat/PluginIC2.java index 89afc9a7b..2ee521682 100644 --- a/src/main/java/forestry/plugins/compat/PluginIC2.java +++ b/src/main/java/forestry/plugins/compat/PluginIC2.java @@ -11,33 +11,15 @@ package forestry.plugins.compat; import com.google.common.collect.ImmutableMap; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumSet; - -import cpw.mods.fml.common.registry.GameRegistry; -import forestry.api.farming.Farmables; -import forestry.core.config.Config; -import forestry.farming.logic.FarmableBasicIC2Crop; -import forestry.farming.logic.FarmableReference; -import ic2.api.crops.ICropTile; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; - -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - import cpw.mods.fml.common.Optional; import cpw.mods.fml.common.event.FMLInterModComms; import cpw.mods.fml.common.registry.GameData; - +import cpw.mods.fml.common.registry.GameRegistry; import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.CircuitSocketType; import forestry.api.circuits.ICircuitLayout; import forestry.api.core.ForestryAPI; +import forestry.api.farming.Farmables; import forestry.api.fuels.EngineBronzeFuel; import forestry.api.fuels.FuelManager; import forestry.api.recipes.RecipeManagers; @@ -64,352 +46,392 @@ import forestry.energy.circuits.CircuitElectricEfficiency; import forestry.energy.tiles.EngineDefinition; import forestry.farming.circuits.CircuitFarmLogic; import forestry.farming.logic.FarmLogicRubber; +import forestry.farming.logic.FarmableBasicIC2Crop; +import forestry.farming.logic.FarmableReference; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; import forestry.plugins.PluginApiculture; import forestry.plugins.PluginCore; import forestry.plugins.PluginEnergy; import forestry.plugins.PluginManager; - +import ic2.api.crops.ICropTile; import ic2.api.item.IC2Items; import ic2.api.recipe.RecipeInputItemStack; import ic2.api.recipe.Recipes; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumSet; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; -@Plugin(pluginID = "IC2", name = "IndustrialCraft2", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.ic2.description") +@Plugin( + pluginID = "IC2", + name = "IndustrialCraft2", + author = "SirSengir", + url = Constants.URL, + unlocalizedDescription = "for.plugin.ic2.description") public class PluginIC2 extends ForestryPlugin { - public static PluginIC2 instance; + public static PluginIC2 instance; - private static ItemStack plantBall; - private static ItemStack compressedPlantBall; - private static ItemStack wrench; - private static ItemStack treetap; - private static ItemStack rubbersapling; - private static ItemStack rubberleaves; - private static ItemStack emptyCell; - private static ItemStack lavaCell; - private static ItemStack uran238; - private static ItemStack waterCell; - private static ItemStack rubber; - private static ItemStack scrap; - private static ItemStack silver; - private static ItemStack brass; - private static ItemStack uuMatter; + private static ItemStack plantBall; + private static ItemStack compressedPlantBall; + private static ItemStack wrench; + private static ItemStack treetap; + private static ItemStack rubbersapling; + private static ItemStack rubberleaves; + private static ItemStack emptyCell; + private static ItemStack lavaCell; + private static ItemStack uran238; + private static ItemStack waterCell; + private static ItemStack rubber; + private static ItemStack scrap; + private static ItemStack silver; + private static ItemStack brass; + private static ItemStack uuMatter; - public static ItemStack resin; - public static ItemStack rubberwood; + public static ItemStack resin; + public static ItemStack rubberwood; - public PluginIC2() { - if (PluginIC2.instance == null) { - PluginIC2.instance = this; - } - } + public PluginIC2() { + if (PluginIC2.instance == null) { + PluginIC2.instance = this; + } + } - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded("IC2"); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded("IC2"); + } - @Override - public String getFailMessage() { - return "IndustrialCraft2 not found"; - } + @Override + public String getFailMessage() { + return "IndustrialCraft2 not found"; + } - @Override - public EnumSet getDependancies() { - EnumSet deps = super.getDependancies(); - deps.add(PluginManager.Module.FARMING); - deps.add(PluginManager.Module.FACTORY); - return deps; - } + @Override + public EnumSet getDependancies() { + EnumSet deps = super.getDependancies(); + deps.add(PluginManager.Module.FARMING); + deps.add(PluginManager.Module.FACTORY); + return deps; + } - @Override - @Optional.Method(modid = "IC2") - public void preInit() { - super.preInit(); + @Override + @Optional.Method(modid = "IC2") + public void preInit() { + super.preInit(); - BlockRegistryEnergy energyBlocks = PluginEnergy.blocks; - if (energyBlocks != null) { - energyBlocks.engine.addDefinitions( - new EngineDefinition(BlockEngineType.ELECTRIC), - new EngineDefinition(BlockEngineType.GENERATOR) - ); - } + BlockRegistryEnergy energyBlocks = PluginEnergy.blocks; + if (energyBlocks != null) { + energyBlocks.engine.addDefinitions( + new EngineDefinition(BlockEngineType.ELECTRIC), new EngineDefinition(BlockEngineType.GENERATOR)); + } - emptyCell = IC2Items.getItem("cell"); - if (emptyCell != null) { - lavaCell = IC2Items.getItem("lavaCell"); - waterCell = IC2Items.getItem("waterCell"); - } else { - Log.fine("IC2 empty cell could not be found. Skipped adding IC2 liquid containers."); - } + emptyCell = IC2Items.getItem("cell"); + if (emptyCell != null) { + lavaCell = IC2Items.getItem("lavaCell"); + waterCell = IC2Items.getItem("waterCell"); + } else { + Log.fine("IC2 empty cell could not be found. Skipped adding IC2 liquid containers."); + } - // rubber chain - treetap = IC2Items.getItem("treetap"); - rubberwood = IC2Items.getItem("rubberWood"); - resin = IC2Items.getItem("resin"); - rubbersapling = IC2Items.getItem("rubberSapling"); - rubberleaves = IC2Items.getItem("rubberLeaves"); + // rubber chain + treetap = IC2Items.getItem("treetap"); + rubberwood = IC2Items.getItem("rubberWood"); + resin = IC2Items.getItem("resin"); + rubbersapling = IC2Items.getItem("rubberSapling"); + rubberleaves = IC2Items.getItem("rubberLeaves"); - // fermentation - plantBall = IC2Items.getItem("plantBall"); - compressedPlantBall = IC2Items.getItem("compressedPlantBall"); + // fermentation + plantBall = IC2Items.getItem("plantBall"); + compressedPlantBall = IC2Items.getItem("compressedPlantBall"); - // crated - resin = IC2Items.getItem("resin"); - rubber = IC2Items.getItem("rubber"); - scrap = IC2Items.getItem("scrap"); - uuMatter = IC2Items.getItem("matter"); - silver = IC2Items.getItem("silverIngot"); - brass = IC2Items.getItem("bronzeIngot"); + // crated + resin = IC2Items.getItem("resin"); + rubber = IC2Items.getItem("rubber"); + scrap = IC2Items.getItem("scrap"); + uuMatter = IC2Items.getItem("matter"); + silver = IC2Items.getItem("silverIngot"); + brass = IC2Items.getItem("bronzeIngot"); - uran238 = IC2Items.getItem("Uran238"); + uran238 = IC2Items.getItem("Uran238"); - Circuit.farmRubberManual = new CircuitFarmLogic("manualRubber", FarmLogicRubber.class); + Circuit.farmRubberManual = new CircuitFarmLogic("manualRubber", FarmLogicRubber.class); - ICircuitLayout layoutEngineTin = new CircuitLayout("engine.tin", CircuitSocketType.ELECTRIC_ENGINE); - ChipsetManager.circuitRegistry.registerLayout(layoutEngineTin); - } + ICircuitLayout layoutEngineTin = new CircuitLayout("engine.tin", CircuitSocketType.ELECTRIC_ENGINE); + ChipsetManager.circuitRegistry.registerLayout(layoutEngineTin); + } - @Override - @Optional.Method(modid = "IC2") - public void doInit() { - super.doInit(); + @Override + @Optional.Method(modid = "IC2") + public void doInit() { + super.doInit(); - // Remove some items from the recycler - if (Recipes.recyclerBlacklist != null) { - if (PluginManager.Module.APICULTURE.isEnabled()) { - ItemRegistryApiculture beeItems = PluginApiculture.items; - Recipes.recyclerBlacklist.add(new RecipeInputItemStack(new ItemStack(beeItems.beeQueenGE))); - Recipes.recyclerBlacklist.add(new RecipeInputItemStack(new ItemStack(beeItems.beePrincessGE))); - } - } else { - Log.severe("IC2 Recipes.recyclerBlacklist not found."); - } + // Remove some items from the recycler + if (Recipes.recyclerBlacklist != null) { + if (PluginManager.Module.APICULTURE.isEnabled()) { + ItemRegistryApiculture beeItems = PluginApiculture.items; + Recipes.recyclerBlacklist.add(new RecipeInputItemStack(new ItemStack(beeItems.beeQueenGE))); + Recipes.recyclerBlacklist.add(new RecipeInputItemStack(new ItemStack(beeItems.beePrincessGE))); + } + } else { + Log.severe("IC2 Recipes.recyclerBlacklist not found."); + } - Circuit.energyElectricChoke1 = new CircuitElectricChoke("electric.choke.1"); - Circuit.energyElectricEfficiency1 = new CircuitElectricEfficiency("electric.efficiency.1"); - Circuit.energyElectricBoost1 = new CircuitElectricBoost("electric.boost.1", 2, 7, 20); - Circuit.energyElectricBoost2 = new CircuitElectricBoost("electric.boost.2", 2, 15, 40); - } + Circuit.energyElectricChoke1 = new CircuitElectricChoke("electric.choke.1"); + Circuit.energyElectricEfficiency1 = new CircuitElectricEfficiency("electric.efficiency.1"); + Circuit.energyElectricBoost1 = new CircuitElectricBoost("electric.boost.1", 2, 7, 20); + Circuit.energyElectricBoost2 = new CircuitElectricBoost("electric.boost.2", 2, 15, 40); + } - @Override - @Optional.Method(modid = "IC2") - protected void registerBackpackItems() { - if (BackpackManager.definitions == null) { - return; - } + @Override + @Optional.Method(modid = "IC2") + protected void registerBackpackItems() { + if (BackpackManager.definitions == null) { + return; + } - IBackpackDefinition forester = BackpackManager.definitions.get("forester"); + IBackpackDefinition forester = BackpackManager.definitions.get("forester"); - if (resin != null) { - forester.addValidItem(resin); - } - if (rubber != null) { - forester.addValidItem(rubber); - } - if (rubbersapling != null) { - forester.addValidItem(rubbersapling); - } - if (rubberleaves != null) { - forester.addValidItem(rubberleaves); - } - } + if (resin != null) { + forester.addValidItem(resin); + } + if (rubber != null) { + forester.addValidItem(rubber); + } + if (rubbersapling != null) { + forester.addValidItem(rubbersapling); + } + if (rubberleaves != null) { + forester.addValidItem(rubberleaves); + } + } - @Override - @Optional.Method(modid = "IC2") - protected void registerCrates() { - ICrateRegistry crateRegistry = StorageManager.crateRegistry; - if (resin != null) { - crateRegistry.registerCrate(resin, "cratedResin"); - } + @Override + @Optional.Method(modid = "IC2") + protected void registerCrates() { + ICrateRegistry crateRegistry = StorageManager.crateRegistry; + if (resin != null) { + crateRegistry.registerCrate(resin, "cratedResin"); + } - if (rubber != null) { - crateRegistry.registerCrate(rubber, "cratedRubber"); - } + if (rubber != null) { + crateRegistry.registerCrate(rubber, "cratedRubber"); + } - if (scrap != null) { - crateRegistry.registerCrate(scrap, "cratedScrap"); - } + if (scrap != null) { + crateRegistry.registerCrate(scrap, "cratedScrap"); + } - if (uuMatter != null) { - crateRegistry.registerCrate(uuMatter, "cratedUUM"); - } + if (uuMatter != null) { + crateRegistry.registerCrate(uuMatter, "cratedUUM"); + } - if (silver != null) { - crateRegistry.registerCrateUsingOreDict(silver, "cratedSilver"); - } + if (silver != null) { + crateRegistry.registerCrateUsingOreDict(silver, "cratedSilver"); + } - if (brass != null) { - crateRegistry.registerCrateUsingOreDict(brass, "cratedBrass"); - } - } + if (brass != null) { + crateRegistry.registerCrateUsingOreDict(brass, "cratedBrass"); + } + } - @Optional.Method(modid = "IC2") - protected void registerRecipes() { + @Optional.Method(modid = "IC2") + protected void registerRecipes() { - EnumElectronTube.RUBBER.registerTubeRecipe(rubber); - EnumElectronTube.URANIUM.registerTubeRecipe(uran238); + EnumElectronTube.RUBBER.registerTubeRecipe(rubber); + EnumElectronTube.URANIUM.registerTubeRecipe(uran238); - if (plantBall != null) { - RecipeUtil.addFermenterRecipes(plantBall, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat") * 9, Fluids.BIOMASS); - } - if (compressedPlantBall != null) { - RecipeUtil.addFermenterRecipes(compressedPlantBall, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat") * 9, Fluids.BIOMASS); - } + if (plantBall != null) { + RecipeUtil.addFermenterRecipes( + plantBall, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat") * 9, Fluids.BIOMASS); + } + if (compressedPlantBall != null) { + RecipeUtil.addFermenterRecipes( + compressedPlantBall, + ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat") * 9, + Fluids.BIOMASS); + } - if (PluginManager.Module.APICULTURE.isEnabled()) { - if (resin != null) { - ItemRegistryApiculture beeItems = PluginApiculture.items; - RecipeManagers.centrifugeManager.addRecipe(20, beeItems.propolis.get(EnumPropolis.NORMAL, 1), ImmutableMap.of(resin, 1.0f)); - } else { - Log.fine("Missing IC2 resin, skipping centrifuge recipe for propolis to resin."); - } - } + if (PluginManager.Module.APICULTURE.isEnabled()) { + if (resin != null) { + ItemRegistryApiculture beeItems = PluginApiculture.items; + RecipeManagers.centrifugeManager.addRecipe( + 20, beeItems.propolis.get(EnumPropolis.NORMAL, 1), ImmutableMap.of(resin, 1.0f)); + } else { + Log.fine("Missing IC2 resin, skipping centrifuge recipe for propolis to resin."); + } + } - if (rubbersapling != null) { - RecipeUtil.addFermenterRecipes(rubbersapling, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); - } else { - Log.fine("Missing IC2 rubber sapling, skipping fermenter recipe for converting rubber sapling to biomass."); - } + if (rubbersapling != null) { + RecipeUtil.addFermenterRecipes( + rubbersapling, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); + } else { + Log.fine("Missing IC2 rubber sapling, skipping fermenter recipe for converting rubber sapling to biomass."); + } - if (rubbersapling != null && resin != null) { - String saplingName = GameData.getBlockRegistry().getNameForObject(ItemStackUtil.getBlock(rubbersapling)); - String resinName = GameData.getItemRegistry().getNameForObject(resin.getItem()); - String imc = String.format("farmArboreal@%s.%s.%s.%s", - saplingName, rubbersapling.getItemDamage(), - resinName, resin.getItemDamage()); - Log.finest("Sending IMC '%s'.", imc); - FMLInterModComms.sendMessage(Constants.MOD, "add-farmable-sapling", imc); - } + if (rubbersapling != null && resin != null) { + String saplingName = GameData.getBlockRegistry().getNameForObject(ItemStackUtil.getBlock(rubbersapling)); + String resinName = GameData.getItemRegistry().getNameForObject(resin.getItem()); + String imc = String.format( + "farmArboreal@%s.%s.%s.%s", + saplingName, rubbersapling.getItemDamage(), resinName, resin.getItemDamage()); + Log.finest("Sending IMC '%s'.", imc); + FMLInterModComms.sendMessage(Constants.MOD, "add-farmable-sapling", imc); + } - FluidStack biogas = FluidRegistry.getFluidStack("ic2biogas", 1000); - if (biogas != null && PluginManager.Module.ENERGY.isEnabled()) { - FuelManager.bronzeEngineFuel.put(biogas.getFluid(), new EngineBronzeFuel(Fluids.BIOMASS.getFluid(), - Constants.ENGINE_FUEL_VALUE_BIOMASS, (int) ((Constants.ENGINE_CYCLE_DURATION_BIOMASS * ForestryAPI.activeMode.getFloatSetting("fuel.biomass.biogas"))), 1)); - } + FluidStack biogas = FluidRegistry.getFluidStack("ic2biogas", 1000); + if (biogas != null && PluginManager.Module.ENERGY.isEnabled()) { + FuelManager.bronzeEngineFuel.put( + biogas.getFluid(), + new EngineBronzeFuel( + Fluids.BIOMASS.getFluid(), + Constants.ENGINE_FUEL_VALUE_BIOMASS, + (int) ((Constants.ENGINE_CYCLE_DURATION_BIOMASS + * ForestryAPI.activeMode.getFloatSetting("fuel.biomass.biogas"))), + 1)); + } - if (waterCell != null) { - ItemStack bogEarthCan = ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.can"); - if (bogEarthCan.stackSize > 0) { - RecipeUtil.addRecipe(bogEarthCan, "#Y#", "YXY", "#Y#", '#', Blocks.dirt, 'X', waterCell, 'Y', "sand"); - } - } + if (waterCell != null) { + ItemStack bogEarthCan = ForestryAPI.activeMode.getStackSetting("recipe.output.bogearth.can"); + if (bogEarthCan.stackSize > 0) { + RecipeUtil.addRecipe(bogEarthCan, "#Y#", "YXY", "#Y#", '#', Blocks.dirt, 'X', waterCell, 'Y', "sand"); + } + } - ICircuitLayout layout = ChipsetManager.circuitRegistry.getLayout("forestry.engine.tin"); + ICircuitLayout layout = ChipsetManager.circuitRegistry.getLayout("forestry.engine.tin"); - // / Solder Manager - ChipsetManager.solderManager.addRecipe(layout, PluginCore.items.tubes.get(EnumElectronTube.COPPER, 1), Circuit.energyElectricChoke1); - ChipsetManager.solderManager.addRecipe(layout, PluginCore.items.tubes.get(EnumElectronTube.TIN, 1), Circuit.energyElectricBoost1); - ChipsetManager.solderManager.addRecipe(layout, PluginCore.items.tubes.get(EnumElectronTube.BRONZE, 1), Circuit.energyElectricBoost2); - ChipsetManager.solderManager.addRecipe(layout, PluginCore.items.tubes.get(EnumElectronTube.IRON, 1), Circuit.energyElectricEfficiency1); - - if (PluginManager.Module.FARMING.isEnabled() && resin != null && rubberwood != null) { - ICircuitLayout layoutManual = ChipsetManager.circuitRegistry.getLayout("forestry.farms.manual"); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.RUBBER, 1), Circuit.farmRubberManual); - } + // / Solder Manager + ChipsetManager.solderManager.addRecipe( + layout, PluginCore.items.tubes.get(EnumElectronTube.COPPER, 1), Circuit.energyElectricChoke1); + ChipsetManager.solderManager.addRecipe( + layout, PluginCore.items.tubes.get(EnumElectronTube.TIN, 1), Circuit.energyElectricBoost1); + ChipsetManager.solderManager.addRecipe( + layout, PluginCore.items.tubes.get(EnumElectronTube.BRONZE, 1), Circuit.energyElectricBoost2); + ChipsetManager.solderManager.addRecipe( + layout, PluginCore.items.tubes.get(EnumElectronTube.IRON, 1), Circuit.energyElectricEfficiency1); - Block ic2Crop = GameRegistry.findBlock("IC2", "blockCrop"); - if (PluginManager.Module.FARMING.isEnabled() && ic2Crop != null) { - ICircuitLayout layoutManaged = ChipsetManager.circuitRegistry.getLayout("forestry.farms.manual"); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.URANIUM, 1), Circuit.farmIC2CropsManual); - Farmables.farmables.put(FarmableReference.IC2Crops.get(), new ArrayList<>()); - Farmables.farmables.get(FarmableReference.IC2Crops.get()).add(new FarmableBasicIC2Crop()); - } + if (PluginManager.Module.FARMING.isEnabled() && resin != null && rubberwood != null) { + ICircuitLayout layoutManual = ChipsetManager.circuitRegistry.getLayout("forestry.farms.manual"); + ChipsetManager.solderManager.addRecipe( + layoutManual, PluginCore.items.tubes.get(EnumElectronTube.RUBBER, 1), Circuit.farmRubberManual); + } - BlockRegistryEnergy energyBlocks = PluginEnergy.blocks; - if (energyBlocks != null) { - RecipeUtil.addRecipe(energyBlocks.engine.get(BlockEngineType.GENERATOR), - "X#X", - "XYX", - "X#X", - '#', "blockGlass", - 'X', "ingotGold", - 'Y', PluginCore.items.sturdyCasing); + Block ic2Crop = GameRegistry.findBlock("IC2", "blockCrop"); + if (PluginManager.Module.FARMING.isEnabled() && ic2Crop != null) { + ICircuitLayout layoutManaged = ChipsetManager.circuitRegistry.getLayout("forestry.farms.manual"); + ChipsetManager.solderManager.addRecipe( + layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.URANIUM, 1), Circuit.farmIC2CropsManual); + Farmables.farmables.put(FarmableReference.IC2Crops.get(), new ArrayList<>()); + Farmables.farmables.get(FarmableReference.IC2Crops.get()).add(new FarmableBasicIC2Crop()); + } - RecipeUtil.addRecipe(energyBlocks.engine.get(BlockEngineType.ELECTRIC), - "###", - " X ", - "YVY", - '#', "ingotTin", - 'X', "blockGlass", - 'Y', "gearTin", - 'V', Blocks.piston); - } - } + BlockRegistryEnergy energyBlocks = PluginEnergy.blocks; + if (energyBlocks != null) { + RecipeUtil.addRecipe( + energyBlocks.engine.get(BlockEngineType.GENERATOR), + "X#X", + "XYX", + "X#X", + '#', + "blockGlass", + 'X', + "ingotGold", + 'Y', + PluginCore.items.sturdyCasing); - /** - * Check if there is an instance of ICropTile. - * @param tileEntity tile entity to be checked. - * @return true if there is an IC2 crop and false otherwise. - */ - @Optional.Method(modid = "IC2") - public boolean isIC2Crop(TileEntity tileEntity) { - return tileEntity instanceof ICropTile; - } + RecipeUtil.addRecipe( + energyBlocks.engine.get(BlockEngineType.ELECTRIC), + "###", + " X ", + "YVY", + '#', + "ingotTin", + 'X', + "blockGlass", + 'Y', + "gearTin", + 'V', + Blocks.piston); + } + } - /** - * Check if an IC2 crop is ready to be harvested. - * @param tileEntity tile entity to be checked. - * @return true if crop size is optimal for harvest and false otherwise. - */ - @Optional.Method(modid = "IC2") - public boolean canHarvestCrop(TileEntity tileEntity) { - if (isIC2Crop(tileEntity)) { - ICropTile crop = (ICropTile)tileEntity; - if (crop.getCrop() == null) { - return false; - } - return crop.getSize() == crop.getCrop().getOptimalHavestSize(crop); - } - return false; - } + /** + * Check if there is an instance of ICropTile. + * @param tileEntity tile entity to be checked. + * @return true if there is an IC2 crop and false otherwise. + */ + @Optional.Method(modid = "IC2") + public boolean isIC2Crop(TileEntity tileEntity) { + return tileEntity instanceof ICropTile; + } - /** - * Perform some of the actions of the crop-matron. - * @param tileEntity - */ - @Optional.Method(modid = "IC2") - public void babysitCrop(TileEntity tileEntity) { - if (isIC2Crop(tileEntity)) { - ICropTile crop = (ICropTile)tileEntity; - /* - This part might be unbalanced until a custom farm logic is added and makes use of weed-ex. - if (crop.getCrop() != null) { - if (crop.getCrop().isWeed(crop)) { - crop.reset(); - } - }*/ - if (crop.getHydrationStorage() <= 200) { - crop.setHydrationStorage(200); - } - if (crop.getNutrientStorage() <= 100) { - crop.setNutrientStorage(crop.getNutrientStorage() + 100); - } - } - } + /** + * Check if an IC2 crop is ready to be harvested. + * @param tileEntity tile entity to be checked. + * @return true if crop size is optimal for harvest and false otherwise. + */ + @Optional.Method(modid = "IC2") + public boolean canHarvestCrop(TileEntity tileEntity) { + if (isIC2Crop(tileEntity)) { + ICropTile crop = (ICropTile) tileEntity; + if (crop.getCrop() == null) { + return false; + } + return crop.getSize() == crop.getCrop().getOptimalHavestSize(crop); + } + return false; + } - /** - * This function takes care of everything related to the harvesting of the - * crop meaning it will calculate the drops and also do setSizeAfterHarvest(). - * @param tileEntity tile entity to be checked. - * @return arraylist containing the drops. - */ - @Optional.Method(modid = "IC2") - public ArrayList getCropDrops(TileEntity tileEntity) { - if (isIC2Crop(tileEntity)) { - ICropTile crop = (ICropTile)tileEntity; - if (crop == null || crop.getCrop() == null) - return null; - ItemStack[] cropDrops; - if ((crop.getCrop().canGrow(crop) && crop.getSize() < crop.getCrop().getOptimalHavestSize(crop)) || crop.getSize() == crop.getCrop().getOptimalHavestSize(crop)) - cropDrops = crop.harvest_automated(true); - else - cropDrops = crop.harvest_automated(false); - if (cropDrops != null) { - return new ArrayList<>(Arrays.asList(cropDrops)); - } - } - return null; - } + /** + * Perform some of the actions of the crop-matron. + * @param tileEntity + */ + @Optional.Method(modid = "IC2") + public void babysitCrop(TileEntity tileEntity) { + if (isIC2Crop(tileEntity)) { + ICropTile crop = (ICropTile) tileEntity; + /* + This part might be unbalanced until a custom farm logic is added and makes use of weed-ex. + if (crop.getCrop() != null) { + if (crop.getCrop().isWeed(crop)) { + crop.reset(); + } + }*/ + if (crop.getHydrationStorage() <= 200) { + crop.setHydrationStorage(200); + } + if (crop.getNutrientStorage() <= 100) { + crop.setNutrientStorage(crop.getNutrientStorage() + 100); + } + } + } + + /** + * This function takes care of everything related to the harvesting of the + * crop meaning it will calculate the drops and also do setSizeAfterHarvest(). + * @param tileEntity tile entity to be checked. + * @return arraylist containing the drops. + */ + @Optional.Method(modid = "IC2") + public ArrayList getCropDrops(TileEntity tileEntity) { + if (isIC2Crop(tileEntity)) { + ICropTile crop = (ICropTile) tileEntity; + if (crop == null || crop.getCrop() == null) return null; + ItemStack[] cropDrops; + if ((crop.getCrop().canGrow(crop) && crop.getSize() < crop.getCrop().getOptimalHavestSize(crop)) + || crop.getSize() == crop.getCrop().getOptimalHavestSize(crop)) + cropDrops = crop.harvest_automated(true); + else cropDrops = crop.harvest_automated(false); + if (cropDrops != null) { + return new ArrayList<>(Arrays.asList(cropDrops)); + } + } + return null; + } } diff --git a/src/main/java/forestry/plugins/compat/PluginImmersiveEngineering.java b/src/main/java/forestry/plugins/compat/PluginImmersiveEngineering.java index 65e8d7a1e..0659b043f 100644 --- a/src/main/java/forestry/plugins/compat/PluginImmersiveEngineering.java +++ b/src/main/java/forestry/plugins/compat/PluginImmersiveEngineering.java @@ -10,12 +10,7 @@ ******************************************************************************/ package forestry.plugins.compat; -import forestry.farming.logic.FarmableReference; -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; - import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; import forestry.api.recipes.RecipeManagers; @@ -23,35 +18,45 @@ import forestry.core.config.Constants; import forestry.core.fluids.Fluids; import forestry.core.utils.ModUtil; import forestry.farming.logic.FarmableGenericCrop; +import forestry.farming.logic.FarmableReference; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; -@Plugin(pluginID = "ImmersiveEngineering", name = "ImmersiveEngineering", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.immersiveengineering.description") +@Plugin( + pluginID = "ImmersiveEngineering", + name = "ImmersiveEngineering", + author = "Nirek", + url = Constants.URL, + unlocalizedDescription = "for.plugin.immersiveengineering.description") public class PluginImmersiveEngineering extends ForestryPlugin { - private static final String ImEng = "ImmersiveEngineering"; + private static final String ImEng = "ImmersiveEngineering"; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(ImEng); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(ImEng); + } - @Override - public String getFailMessage() { - return "Immersive Engineering not found"; - } + @Override + public String getFailMessage() { + return "Immersive Engineering not found"; + } - @Override - protected void postInit() { - - ItemStack hempSeed = GameRegistry.findItemStack(ImEng, "seed", 1); - Block hempCrop = GameRegistry.findBlock(ImEng, "hemp"); - ItemStack hempFiber = new ItemStack(GameRegistry.findItem(ImEng, "material"), 1, 3); - int seedAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - if (hempSeed != null && hempCrop != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{hempSeed}, Fluids.SEEDOIL.getFluid(seedAmount)); - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(hempSeed, hempCrop, 4, hempFiber)); - } - } + @Override + protected void postInit() { + ItemStack hempSeed = GameRegistry.findItemStack(ImEng, "seed", 1); + Block hempCrop = GameRegistry.findBlock(ImEng, "hemp"); + ItemStack hempFiber = new ItemStack(GameRegistry.findItem(ImEng, "material"), 1, 3); + int seedAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); + if (hempSeed != null && hempCrop != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {hempSeed}, Fluids.SEEDOIL.getFluid(seedAmount)); + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(hempSeed, hempCrop, 4, hempFiber)); + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginMagicalCrops.java b/src/main/java/forestry/plugins/compat/PluginMagicalCrops.java index b18101e08..64d21af91 100644 --- a/src/main/java/forestry/plugins/compat/PluginMagicalCrops.java +++ b/src/main/java/forestry/plugins/compat/PluginMagicalCrops.java @@ -11,16 +11,7 @@ package forestry.plugins.compat; import com.google.common.collect.ImmutableList; - -import forestry.farming.logic.FarmableReference; -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.oredict.OreDictionary; - import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; import forestry.api.recipes.RecipeManagers; @@ -30,254 +21,242 @@ import forestry.core.fluids.Fluids; import forestry.core.recipes.RecipeUtil; import forestry.core.utils.ModUtil; import forestry.farming.logic.FarmableGenericCrop; +import forestry.farming.logic.FarmableReference; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; -@Plugin(pluginID = "MagicalCrops", name = "MagicalCrops", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.magicalcrops.description") +@Plugin( + pluginID = "MagicalCrops", + name = "MagicalCrops", + author = "Nirek", + url = Constants.URL, + unlocalizedDescription = "for.plugin.magicalcrops.description") public class PluginMagicalCrops extends ForestryPlugin { - private static final String MagCrop = "magicalcrops"; + private static final String MagCrop = "magicalcrops"; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(MagCrop); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(MagCrop); + } - @Override - public String getFailMessage() { - return "Magical Crops not found"; - } + @Override + public String getFailMessage() { + return "Magical Crops not found"; + } - @Override - protected void postInit() { + @Override + protected void postInit() { - ImmutableList magicSeeds = ImmutableList.of( - "Essence", - "Coal", - "Dye", - "Redstone", - "Glowstone", - "Obsidian", - "Iron", - "Gold", - "Lapis", - "Ender", - "Nether", - "Experience", - "Blaze", - "Diamond", - "Emerald" - ); + ImmutableList magicSeeds = ImmutableList.of( + "Essence", + "Coal", + "Dye", + "Redstone", + "Glowstone", + "Obsidian", + "Iron", + "Gold", + "Lapis", + "Ender", + "Nether", + "Experience", + "Blaze", + "Diamond", + "Emerald"); - ImmutableList elementSeeds = ImmutableList.of( - "Air", - "Water", - "Earth", - "Fire" - ); + ImmutableList elementSeeds = ImmutableList.of("Air", "Water", "Earth", "Fire"); - ImmutableList modMagicSeeds = ImmutableList.of( - "Copper", - "Tin", - "Silver", - "Lead", - "Quartz", - "Sapphire", - "Ruby", - "Peridot", - "Aluminium", - "Force", - "Cobalt", - "Ardite", - "Nickel", - "Platinum", - "ThaumcraftShard", - "Uranium", - "Oil", - "Rubber", - "Vinteum", - "BlueTopaz", - "Chimerite", - "Moonstone", - "Sunstone", - "Iridium", - "Yellorite", - "Osmium", - "Manganese", - "Sulfur", - "Darkiron" - ); + ImmutableList modMagicSeeds = ImmutableList.of( + "Copper", + "Tin", + "Silver", + "Lead", + "Quartz", + "Sapphire", + "Ruby", + "Peridot", + "Aluminium", + "Force", + "Cobalt", + "Ardite", + "Nickel", + "Platinum", + "ThaumcraftShard", + "Uranium", + "Oil", + "Rubber", + "Vinteum", + "BlueTopaz", + "Chimerite", + "Moonstone", + "Sunstone", + "Iridium", + "Yellorite", + "Osmium", + "Manganese", + "Sulfur", + "Darkiron"); - ImmutableList soulSeeds = ImmutableList.of( - "Cow", - "Creeper", - "Magma", - "Skeleton", - "Slime", - "Spider", - "Ghast", - "Wither" - ); + ImmutableList soulSeeds = + ImmutableList.of("Cow", "Creeper", "Magma", "Skeleton", "Slime", "Spider", "Ghast", "Wither"); - ImmutableList potionSeeds = ImmutableList.of( - "Fire", - "Water", - "Strength", - "Regen", - "Night", - "Speed" - ); + ImmutableList potionSeeds = ImmutableList.of("Fire", "Water", "Strength", "Regen", "Night", "Speed"); - ImmutableList seeds = ImmutableList.of( - "Blackberry", - "Blueberry", - "Chili", - "Cucumber", - "Grape", - "Raspberry", - "Strawberry", - "Sweetcorn", - "Tomato", - "SugarCane" - ); + ImmutableList seeds = ImmutableList.of( + "Blackberry", + "Blueberry", + "Chili", + "Cucumber", + "Grape", + "Raspberry", + "Strawberry", + "Sweetcorn", + "Tomato", + "SugarCane"); - ImmutableList betaSeeds = ImmutableList.of( - "Air", - "Airshard", - "Aluminium", - "Alumite", - "Amber", - "Ardite", - "Blaze", - "Blizz", - "Bronze", - "CertusQuartz", - "Chicken", - "Coal", - "Cobalt", - "ConductiveIron", - "Copper", - "Cow", - "Creeper", - "DarkSteel", - "Diamond", - "Draconium", - "Dye", - "Earth", - "Earthshard", - "ElectricalSteel", - "Electrum", - "Emerald", - "Enderium", - "Enderman", - "EnergeticAlloy", - "Experience", - "Fire", - "Fireshard", - "Fluix", - "Ghast", - "Glowstone", - "Gold", - "Invar", - "Iron", - "Lapis", - "Lead", - "Lumium", - "Manasteel", - "Manyullyn", - "Minicio", - "Nature", - "Nether", - "Nickel", - "Obsidian", - "Ordershard", - "Osmium", - "Peridot", - "Pig", - "Platinum", - "PulsatingIron", - "Quartz", - "Quicksilver", - "RedstoneAlloy", - "Redstone", - "Rubber", - "Ruby", - "Saltpeter", - "Sapphire", - "Sheep", - "Signalum", - "Silver", - "Skeleton", - "Slime", - "Soularium", - "Spider", - "Steel", - "Sulfur", - "Terrasteel", - "Thaumium", - "Tin", - "VibrantAlloy", - "Water", - "Watershard", - "Wither", - "Yellorite" - ); + ImmutableList betaSeeds = ImmutableList.of( + "Air", + "Airshard", + "Aluminium", + "Alumite", + "Amber", + "Ardite", + "Blaze", + "Blizz", + "Bronze", + "CertusQuartz", + "Chicken", + "Coal", + "Cobalt", + "ConductiveIron", + "Copper", + "Cow", + "Creeper", + "DarkSteel", + "Diamond", + "Draconium", + "Dye", + "Earth", + "Earthshard", + "ElectricalSteel", + "Electrum", + "Emerald", + "Enderium", + "Enderman", + "EnergeticAlloy", + "Experience", + "Fire", + "Fireshard", + "Fluix", + "Ghast", + "Glowstone", + "Gold", + "Invar", + "Iron", + "Lapis", + "Lead", + "Lumium", + "Manasteel", + "Manyullyn", + "Minicio", + "Nature", + "Nether", + "Nickel", + "Obsidian", + "Ordershard", + "Osmium", + "Peridot", + "Pig", + "Platinum", + "PulsatingIron", + "Quartz", + "Quicksilver", + "RedstoneAlloy", + "Redstone", + "Rubber", + "Ruby", + "Saltpeter", + "Sapphire", + "Sheep", + "Signalum", + "Silver", + "Skeleton", + "Slime", + "Soularium", + "Spider", + "Steel", + "Sulfur", + "Terrasteel", + "Thaumium", + "Tin", + "VibrantAlloy", + "Water", + "Watershard", + "Wither", + "Yellorite"); - int seedAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); + int seedAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - for (String magicSeedName : magicSeeds) { - addRecipes("_MagicSeeds", "_MagicCrop", magicSeedName, seedAmount); - } + for (String magicSeedName : magicSeeds) { + addRecipes("_MagicSeeds", "_MagicCrop", magicSeedName, seedAmount); + } - for (String elementSeedName : elementSeeds) { - addRecipes("_ElementSeeds", "_ElementCrop", elementSeedName, seedAmount); - } + for (String elementSeedName : elementSeeds) { + addRecipes("_ElementSeeds", "_ElementCrop", elementSeedName, seedAmount); + } - for (String modMagicSeedName : modMagicSeeds) { - addRecipes("_ModMagicSeeds", "_ModMagicCrop", modMagicSeedName, seedAmount); - } + for (String modMagicSeedName : modMagicSeeds) { + addRecipes("_ModMagicSeeds", "_ModMagicCrop", modMagicSeedName, seedAmount); + } - for (String soulSeedName : soulSeeds) { - addRecipes("_SoulSeeds", "_SoulCrop", soulSeedName, seedAmount); - } + for (String soulSeedName : soulSeeds) { + addRecipes("_SoulSeeds", "_SoulCrop", soulSeedName, seedAmount); + } - for (String potionSeedName : potionSeeds) { - addRecipes("_PotionSeeds", "_PotionCrop", potionSeedName, seedAmount); - } + for (String potionSeedName : potionSeeds) { + addRecipes("_PotionSeeds", "_PotionCrop", potionSeedName, seedAmount); + } - for (String seedName : seeds) { - addRecipes("_Seeds", "_Crop", seedName, seedAmount); - } - for (String seedName : betaSeeds) { - addBetaRecipes("Seeds", "Crop", seedName, ""); - addBetaRecipes("Seeds", "Crop", seedName, "magicalcrops_"); - } + for (String seedName : seeds) { + addRecipes("_Seeds", "_Crop", seedName, seedAmount); + } + for (String seedName : betaSeeds) { + addBetaRecipes("Seeds", "Crop", seedName, ""); + addBetaRecipes("Seeds", "Crop", seedName, "magicalcrops_"); + } - Item cropProduce = GameRegistry.findItem(MagCrop, MagCrop + "_CropProduce"); - if (cropProduce != null) { - int juiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); - ItemStack produce = new ItemStack(GameRegistry.findItem(MagCrop, MagCrop + "_CropProduce"), 1, OreDictionary.WILDCARD_VALUE); - RecipeUtil.addFermenterRecipes(produce, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{produce}, Fluids.JUICE.getFluid(juiceAmount)); - } - } + Item cropProduce = GameRegistry.findItem(MagCrop, MagCrop + "_CropProduce"); + if (cropProduce != null) { + int juiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); + ItemStack produce = new ItemStack( + GameRegistry.findItem(MagCrop, MagCrop + "_CropProduce"), 1, OreDictionary.WILDCARD_VALUE); + RecipeUtil.addFermenterRecipes( + produce, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[] {produce}, Fluids.JUICE.getFluid(juiceAmount)); + } + } - private static void addRecipes(String seedPrefix, String cropPrefix, String name, int fluidAmount) { - ItemStack seed = GameRegistry.findItemStack(MagCrop, MagCrop + seedPrefix + name, 1); - Block crop = GameRegistry.findBlock(MagCrop, MagCrop + cropPrefix + name); - if (seed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{seed}, Fluids.SEEDOIL.getFluid(fluidAmount)); - } - if (seed != null && crop != null && Config.isMagicalCropsSupportEnabled()) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(seed, crop, 7)); - } - } + private static void addRecipes(String seedPrefix, String cropPrefix, String name, int fluidAmount) { + ItemStack seed = GameRegistry.findItemStack(MagCrop, MagCrop + seedPrefix + name, 1); + Block crop = GameRegistry.findBlock(MagCrop, MagCrop + cropPrefix + name); + if (seed != null) { + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[] {seed}, Fluids.SEEDOIL.getFluid(fluidAmount)); + } + if (seed != null && crop != null && Config.isMagicalCropsSupportEnabled()) { + Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(seed, crop, 7)); + } + } - private static void addBetaRecipes(String seedSuffix, String cropSuffix, String name, String middlefix) { - ItemStack seed = GameRegistry.findItemStack(MagCrop, middlefix + name + seedSuffix, 1); - Block crop = GameRegistry.findBlock(MagCrop, middlefix + name + cropSuffix); - if (seed != null && crop != null && Config.isMagicalCropsSupportEnabled()) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(seed, crop, 7)); - } - } + private static void addBetaRecipes(String seedSuffix, String cropSuffix, String name, String middlefix) { + ItemStack seed = GameRegistry.findItemStack(MagCrop, middlefix + name + seedSuffix, 1); + Block crop = GameRegistry.findBlock(MagCrop, middlefix + name + cropSuffix); + if (seed != null && crop != null && Config.isMagicalCropsSupportEnabled()) { + Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(seed, crop, 7)); + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginMineFactoryReloaded.java b/src/main/java/forestry/plugins/compat/PluginMineFactoryReloaded.java index f2b1dd32a..4966758e7 100644 --- a/src/main/java/forestry/plugins/compat/PluginMineFactoryReloaded.java +++ b/src/main/java/forestry/plugins/compat/PluginMineFactoryReloaded.java @@ -11,15 +11,9 @@ package forestry.plugins.compat; import com.google.common.collect.ImmutableMap; - -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - import cpw.mods.fml.common.event.FMLInterModComms; import cpw.mods.fml.common.registry.GameData; import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.core.ForestryAPI; import forestry.api.recipes.RecipeManagers; import forestry.apiculture.items.EnumPropolis; @@ -32,41 +26,51 @@ import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; import forestry.plugins.PluginApiculture; import forestry.plugins.PluginManager; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; -@Plugin(pluginID = "MinefactoryReloaded", name = "MineFactoryReloaded", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.minefactoryreloaded.description") +@Plugin( + pluginID = "MinefactoryReloaded", + name = "MineFactoryReloaded", + author = "Nirek", + url = Constants.URL, + unlocalizedDescription = "for.plugin.minefactoryreloaded.description") public class PluginMineFactoryReloaded extends ForestryPlugin { - private static final String MFR = "MineFactoryReloaded"; + private static final String MFR = "MineFactoryReloaded"; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(MFR); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(MFR); + } - @Override - public String getFailMessage() { - return "MineFactoryReloaded not found"; - } + @Override + public String getFailMessage() { + return "MineFactoryReloaded not found"; + } - @Override - protected void registerRecipes() { - Block rubbersapling = GameRegistry.findBlock(MFR, "rubberwood.sapling"); - Item saplingItem = GameRegistry.findItem(MFR, "rubberwood.sapling"); - ItemStack saplingStack = new ItemStack(saplingItem, 1, 0); - ItemStack rubberRaw = GameRegistry.findItemStack(MFR,"rubber.raw", 1); - GameRegistry.findItemStack(MFR,"rubber.raw", 1); - - if (PluginManager.Module.APICULTURE.isEnabled() && !PluginManager.Module.INDUSTRIALCRAFT.isEnabled()) { - if (rubberRaw != null) { - ItemRegistryApiculture beeItems = PluginApiculture.items; - RecipeManagers.centrifugeManager.addRecipe(20, beeItems.propolis.get(EnumPropolis.NORMAL, 1), ImmutableMap.of(rubberRaw, 1.0f)); - } - } - if (rubbersapling != null && rubberRaw != null) { - RecipeUtil.addFermenterRecipes(saplingStack, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); - String saplingName = GameData.getItemRegistry().getNameForObject(saplingItem); - FMLInterModComms.sendMessage(Constants.MOD, "add-farmable-sapling", String.format("farmArboreal@%s.-1", saplingName)); - } - } + @Override + protected void registerRecipes() { + Block rubbersapling = GameRegistry.findBlock(MFR, "rubberwood.sapling"); + Item saplingItem = GameRegistry.findItem(MFR, "rubberwood.sapling"); + ItemStack saplingStack = new ItemStack(saplingItem, 1, 0); + ItemStack rubberRaw = GameRegistry.findItemStack(MFR, "rubber.raw", 1); + GameRegistry.findItemStack(MFR, "rubber.raw", 1); + if (PluginManager.Module.APICULTURE.isEnabled() && !PluginManager.Module.INDUSTRIALCRAFT.isEnabled()) { + if (rubberRaw != null) { + ItemRegistryApiculture beeItems = PluginApiculture.items; + RecipeManagers.centrifugeManager.addRecipe( + 20, beeItems.propolis.get(EnumPropolis.NORMAL, 1), ImmutableMap.of(rubberRaw, 1.0f)); + } + } + if (rubbersapling != null && rubberRaw != null) { + RecipeUtil.addFermenterRecipes( + saplingStack, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); + String saplingName = GameData.getItemRegistry().getNameForObject(saplingItem); + FMLInterModComms.sendMessage( + Constants.MOD, "add-farmable-sapling", String.format("farmArboreal@%s.-1", saplingName)); + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginNatura.java b/src/main/java/forestry/plugins/compat/PluginNatura.java index c3e46147e..4bb72a48c 100644 --- a/src/main/java/forestry/plugins/compat/PluginNatura.java +++ b/src/main/java/forestry/plugins/compat/PluginNatura.java @@ -10,21 +10,9 @@ ******************************************************************************/ package forestry.plugins.compat; -import java.util.ArrayList; -import java.util.List; - -import forestry.farming.logic.FarmableReference; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.oredict.OreDictionary; - import cpw.mods.fml.common.event.FMLInterModComms; import cpw.mods.fml.common.registry.GameData; import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; import forestry.api.fuels.FuelManager; @@ -37,238 +25,259 @@ import forestry.core.fluids.Fluids; import forestry.core.recipes.RecipeUtil; import forestry.core.utils.ModUtil; import forestry.farming.logic.FarmableGenericCrop; +import forestry.farming.logic.FarmableReference; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; import forestry.plugins.PluginCore; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; -@Plugin(pluginID = "Natura", name = "Natura", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.natura.description") +@Plugin( + pluginID = "Natura", + name = "Natura", + author = "SirSengir", + url = Constants.URL, + unlocalizedDescription = "for.plugin.natura.description") public class PluginNatura extends ForestryPlugin { - private static final String NATURA = "Natura"; + private static final String NATURA = "Natura"; - private static Block logNatura; - private static Block logWillow; + private static Block logNatura; + private static Block logWillow; - private static Block leavesNatura; - private static Block saplingNatura; - private static Block saplingNaturaRare; - private static ItemStack berryBlight; - private static ItemStack berryDusk; - private static ItemStack berrySky; - private static ItemStack berrySting; - private static ItemStack berryRasp; - private static ItemStack berryBlue; - private static ItemStack berryBlack; - private static ItemStack berryMalo; - private static ItemStack itemBarley; + private static Block leavesNatura; + private static Block saplingNatura; + private static Block saplingNaturaRare; + private static ItemStack berryBlight; + private static ItemStack berryDusk; + private static ItemStack berrySky; + private static ItemStack berrySting; + private static ItemStack berryRasp; + private static ItemStack berryBlue; + private static ItemStack berryBlack; + private static ItemStack berryMalo; + private static ItemStack itemBarley; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(NATURA); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(NATURA); + } - @Override - public String getFailMessage() { - return "Natura not found"; - } + @Override + public String getFailMessage() { + return "Natura not found"; + } - @Override - public void preInit() { - super.preInit(); + @Override + public void preInit() { + super.preInit(); - logNatura = GameRegistry.findBlock(NATURA, "tree"); - logWillow = GameRegistry.findBlock(NATURA, "willow"); - leavesNatura = GameRegistry.findBlock(NATURA, "floraleaves"); - saplingNatura = GameRegistry.findBlock(NATURA, "florasapling"); - saplingNaturaRare = GameRegistry.findBlock(NATURA, "Rare Sapling"); + logNatura = GameRegistry.findBlock(NATURA, "tree"); + logWillow = GameRegistry.findBlock(NATURA, "willow"); + leavesNatura = GameRegistry.findBlock(NATURA, "floraleaves"); + saplingNatura = GameRegistry.findBlock(NATURA, "florasapling"); + saplingNaturaRare = GameRegistry.findBlock(NATURA, "Rare Sapling"); - ArrayList saplingItemKeys = new ArrayList<>(); + ArrayList saplingItemKeys = new ArrayList<>(); - if (saplingNatura != null) { - saplingItemKeys.add("florasapling"); - } - if (saplingNaturaRare != null) { - saplingItemKeys.add("Rare Sapling"); - } + if (saplingNatura != null) { + saplingItemKeys.add("florasapling"); + } + if (saplingNaturaRare != null) { + saplingItemKeys.add("Rare Sapling"); + } - for (String key : saplingItemKeys) { - Item saplingItem = GameRegistry.findItem(NATURA, key); + for (String key : saplingItemKeys) { + Item saplingItem = GameRegistry.findItem(NATURA, key); - ItemStack saplingWild = new ItemStack(saplingItem, 1, OreDictionary.WILDCARD_VALUE); - RecipeUtil.addFermenterRecipes(saplingWild, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); + ItemStack saplingWild = new ItemStack(saplingItem, 1, OreDictionary.WILDCARD_VALUE); + RecipeUtil.addFermenterRecipes( + saplingWild, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); - String saplingName = GameData.getItemRegistry().getNameForObject(saplingItem); - FMLInterModComms.sendMessage(Constants.MOD, "add-farmable-sapling", String.format("farmArboreal@%s.-1", saplingName)); - } + String saplingName = GameData.getItemRegistry().getNameForObject(saplingItem); + FMLInterModComms.sendMessage( + Constants.MOD, "add-farmable-sapling", String.format("farmArboreal@%s.-1", saplingName)); + } - berryBlight = GameRegistry.findItemStack(NATURA, "berryBlight", 1); - berryDusk = GameRegistry.findItemStack(NATURA, "berryDusk", 1); - berrySky = GameRegistry.findItemStack(NATURA, "berrySky", 1); - berrySting = GameRegistry.findItemStack(NATURA, "berrySting", 1); - berryRasp = GameRegistry.findItemStack(NATURA, "berryRasp", 1); - berryBlue = GameRegistry.findItemStack(NATURA, "berryBlue", 1); - berryBlack = GameRegistry.findItemStack(NATURA, "berryBlack", 1); - berryMalo = GameRegistry.findItemStack(NATURA, "berryMalo", 1); - itemBarley = GameRegistry.findItemStack(NATURA, "barleyFood", 1); - } + berryBlight = GameRegistry.findItemStack(NATURA, "berryBlight", 1); + berryDusk = GameRegistry.findItemStack(NATURA, "berryDusk", 1); + berrySky = GameRegistry.findItemStack(NATURA, "berrySky", 1); + berrySting = GameRegistry.findItemStack(NATURA, "berrySting", 1); + berryRasp = GameRegistry.findItemStack(NATURA, "berryRasp", 1); + berryBlue = GameRegistry.findItemStack(NATURA, "berryBlue", 1); + berryBlack = GameRegistry.findItemStack(NATURA, "berryBlack", 1); + berryMalo = GameRegistry.findItemStack(NATURA, "berryMalo", 1); + itemBarley = GameRegistry.findItemStack(NATURA, "barleyFood", 1); + } - @Override - protected void registerCrates() { - super.registerCrates(); + @Override + protected void registerCrates() { + super.registerCrates(); - ICrateRegistry crateRegistry = StorageManager.crateRegistry; + ICrateRegistry crateRegistry = StorageManager.crateRegistry; - if (berryBlight != null) { - crateRegistry.registerCrate(berryBlight, "cratedNaturaBerryBlight"); - } - if (berryDusk != null) { - crateRegistry.registerCrate(berryDusk, "cratedNaturaBerryDusk"); - } - if (berrySky != null) { - crateRegistry.registerCrate(berrySky, "cratedNaturaBerrySky"); - } - if (berrySting != null) { - crateRegistry.registerCrate(berrySting, "cratedNaturaBerrySting"); - } - if (berryRasp != null) { - crateRegistry.registerCrate(berryRasp, "cratedNaturaBerryRasp"); - } - if (berryBlue != null) { - crateRegistry.registerCrate(berryBlue, "cratedNaturaBerryBlue"); - } - if (berryBlack != null) { - crateRegistry.registerCrate(berryBlack, "cratedNaturaBerryBlack"); - } - if (berryMalo != null) { - crateRegistry.registerCrate(berryMalo, "cratedNaturaBerryMalo"); - } - if (itemBarley != null) { - crateRegistry.registerCrate(itemBarley, "cratedNaturaBarley"); - } - if (saplingNatura != null) { - crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 0), "cratedNaturaSaplingRedwood"); - crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 1), "cratedNaturaSaplingEucalyptus"); - crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 2), "cratedNaturaSaplingHopseed"); - crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 3), "cratedNaturaSaplingSakura"); - crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 4), "cratedNaturaSaplingGhostwood"); - crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 5), "cratedNaturaSaplingBlood"); - crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 6), "cratedNaturaSaplingDarkwood"); - crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 7), "cratedNaturaSaplingFusewood"); - } + if (berryBlight != null) { + crateRegistry.registerCrate(berryBlight, "cratedNaturaBerryBlight"); + } + if (berryDusk != null) { + crateRegistry.registerCrate(berryDusk, "cratedNaturaBerryDusk"); + } + if (berrySky != null) { + crateRegistry.registerCrate(berrySky, "cratedNaturaBerrySky"); + } + if (berrySting != null) { + crateRegistry.registerCrate(berrySting, "cratedNaturaBerrySting"); + } + if (berryRasp != null) { + crateRegistry.registerCrate(berryRasp, "cratedNaturaBerryRasp"); + } + if (berryBlue != null) { + crateRegistry.registerCrate(berryBlue, "cratedNaturaBerryBlue"); + } + if (berryBlack != null) { + crateRegistry.registerCrate(berryBlack, "cratedNaturaBerryBlack"); + } + if (berryMalo != null) { + crateRegistry.registerCrate(berryMalo, "cratedNaturaBerryMalo"); + } + if (itemBarley != null) { + crateRegistry.registerCrate(itemBarley, "cratedNaturaBarley"); + } + if (saplingNatura != null) { + crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 0), "cratedNaturaSaplingRedwood"); + crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 1), "cratedNaturaSaplingEucalyptus"); + crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 2), "cratedNaturaSaplingHopseed"); + crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 3), "cratedNaturaSaplingSakura"); + crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 4), "cratedNaturaSaplingGhostwood"); + crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 5), "cratedNaturaSaplingBlood"); + crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 6), "cratedNaturaSaplingDarkwood"); + crateRegistry.registerCrate(new ItemStack(saplingNatura, 1, 7), "cratedNaturaSaplingFusewood"); + } - if (saplingNaturaRare != null) { - crateRegistry.registerCrate(new ItemStack(saplingNaturaRare, 1, 0), "cratedNaturaSaplingMaple"); - crateRegistry.registerCrate(new ItemStack(saplingNaturaRare, 1, 1), "cratedNaturaSaplingSilverbell"); - crateRegistry.registerCrate(new ItemStack(saplingNaturaRare, 1, 2), "cratedNaturaSaplingPurpleheart"); - crateRegistry.registerCrate(new ItemStack(saplingNaturaRare, 1, 3), "cratedNaturaSaplingTiger"); - crateRegistry.registerCrate(new ItemStack(saplingNaturaRare, 1, 4), "cratedNaturaSaplingWillow"); - } - Item potashApple = GameRegistry.findItem(NATURA, "Natura.netherfood"); - if (potashApple != null) { - crateRegistry.registerCrate(new ItemStack(potashApple, 1, 0), "cratedNaturaPotashApple"); - } - Item glowShroom = GameRegistry.findItem(NATURA, "Glowshroom"); - if (glowShroom != null) { - crateRegistry.registerCrate(new ItemStack(glowShroom, 1, 0), "cratedNaturaGreenGlowshroom"); - crateRegistry.registerCrate(new ItemStack(glowShroom, 1, 1), "cratedNaturaPurpleGlowshroom"); - crateRegistry.registerCrate(new ItemStack(glowShroom, 1, 2), "cratedNaturaBlueGlowshroom"); - } - if (logNatura != null) { - crateRegistry.registerCrate(new ItemStack(logNatura, 1, 0), "cratedNaturaLogEucalyptus"); - crateRegistry.registerCrate(new ItemStack(logNatura, 1, 1), "cratedNaturaLogSakura"); - crateRegistry.registerCrate(new ItemStack(logNatura, 1, 2), "cratedNaturaLogGhostwood"); - crateRegistry.registerCrate(new ItemStack(logNatura, 1, 3), "cratedNaturaLogHopseed"); - crateRegistry.registerCrate(new ItemStack(logWillow, 1, 0), "cratedNaturaLogWillow"); - } - Item bloodWood = GameRegistry.findItem(NATURA, "bloodwood"); - if (bloodWood != null) { - crateRegistry.registerCrate(new ItemStack(bloodWood, 1, 0), "cratedNaturaLogBloodwood"); - } - Item darkTree = GameRegistry.findItem(NATURA, "Dark Tree"); - if (darkTree != null) { - crateRegistry.registerCrate(new ItemStack(darkTree, 1, 0), "cratedNaturaLogDarkwood"); - crateRegistry.registerCrate(new ItemStack(darkTree, 1, 1), "cratedNaturaLogFusewood"); - } - Item heatSand = GameRegistry.findItem(NATURA, "heatsand"); - if (heatSand != null) { - crateRegistry.registerCrate(new ItemStack(heatSand, 1, 0), "cratedNaturaBlockHeatsand"); - } - Item taintedSoil = GameRegistry.findItem(NATURA, "soil.tainted"); - if (taintedSoil != null) { - crateRegistry.registerCrate(new ItemStack(taintedSoil, 1, 0), "cratedNaturaBlockTainted"); - } - } + if (saplingNaturaRare != null) { + crateRegistry.registerCrate(new ItemStack(saplingNaturaRare, 1, 0), "cratedNaturaSaplingMaple"); + crateRegistry.registerCrate(new ItemStack(saplingNaturaRare, 1, 1), "cratedNaturaSaplingSilverbell"); + crateRegistry.registerCrate(new ItemStack(saplingNaturaRare, 1, 2), "cratedNaturaSaplingPurpleheart"); + crateRegistry.registerCrate(new ItemStack(saplingNaturaRare, 1, 3), "cratedNaturaSaplingTiger"); + crateRegistry.registerCrate(new ItemStack(saplingNaturaRare, 1, 4), "cratedNaturaSaplingWillow"); + } + Item potashApple = GameRegistry.findItem(NATURA, "Natura.netherfood"); + if (potashApple != null) { + crateRegistry.registerCrate(new ItemStack(potashApple, 1, 0), "cratedNaturaPotashApple"); + } + Item glowShroom = GameRegistry.findItem(NATURA, "Glowshroom"); + if (glowShroom != null) { + crateRegistry.registerCrate(new ItemStack(glowShroom, 1, 0), "cratedNaturaGreenGlowshroom"); + crateRegistry.registerCrate(new ItemStack(glowShroom, 1, 1), "cratedNaturaPurpleGlowshroom"); + crateRegistry.registerCrate(new ItemStack(glowShroom, 1, 2), "cratedNaturaBlueGlowshroom"); + } + if (logNatura != null) { + crateRegistry.registerCrate(new ItemStack(logNatura, 1, 0), "cratedNaturaLogEucalyptus"); + crateRegistry.registerCrate(new ItemStack(logNatura, 1, 1), "cratedNaturaLogSakura"); + crateRegistry.registerCrate(new ItemStack(logNatura, 1, 2), "cratedNaturaLogGhostwood"); + crateRegistry.registerCrate(new ItemStack(logNatura, 1, 3), "cratedNaturaLogHopseed"); + crateRegistry.registerCrate(new ItemStack(logWillow, 1, 0), "cratedNaturaLogWillow"); + } + Item bloodWood = GameRegistry.findItem(NATURA, "bloodwood"); + if (bloodWood != null) { + crateRegistry.registerCrate(new ItemStack(bloodWood, 1, 0), "cratedNaturaLogBloodwood"); + } + Item darkTree = GameRegistry.findItem(NATURA, "Dark Tree"); + if (darkTree != null) { + crateRegistry.registerCrate(new ItemStack(darkTree, 1, 0), "cratedNaturaLogDarkwood"); + crateRegistry.registerCrate(new ItemStack(darkTree, 1, 1), "cratedNaturaLogFusewood"); + } + Item heatSand = GameRegistry.findItem(NATURA, "heatsand"); + if (heatSand != null) { + crateRegistry.registerCrate(new ItemStack(heatSand, 1, 0), "cratedNaturaBlockHeatsand"); + } + Item taintedSoil = GameRegistry.findItem(NATURA, "soil.tainted"); + if (taintedSoil != null) { + crateRegistry.registerCrate(new ItemStack(taintedSoil, 1, 0), "cratedNaturaBlockTainted"); + } + } - @Override - protected void registerRecipes() { - ItemStack seedBarley = GameRegistry.findItemStack(NATURA, "seedBarley", 1); - ItemStack seedCotton = GameRegistry.findItemStack(NATURA, "seedCotton", 1); + @Override + protected void registerRecipes() { + ItemStack seedBarley = GameRegistry.findItemStack(NATURA, "seedBarley", 1); + ItemStack seedCotton = GameRegistry.findItemStack(NATURA, "seedCotton", 1); - ArrayList seedList = new ArrayList<>(); - if (seedBarley != null) { - seedList.add(seedBarley); - RecipeManagers.moistenerManager.addRecipe(seedBarley, new ItemStack(Blocks.mycelium), 5000); - } - if (seedCotton != null) { - seedList.add(seedCotton); - } + ArrayList seedList = new ArrayList<>(); + if (seedBarley != null) { + seedList.add(seedBarley); + RecipeManagers.moistenerManager.addRecipe(seedBarley, new ItemStack(Blocks.mycelium), 5000); + } + if (seedCotton != null) { + seedList.add(seedCotton); + } - int amount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - for (ItemStack aSeedList : seedList) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{aSeedList}, Fluids.SEEDOIL.getFluid(amount)); - } + int amount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); + for (ItemStack aSeedList : seedList) { + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[] {aSeedList}, Fluids.SEEDOIL.getFluid(amount)); + } - Block cropBlock = GameRegistry.findBlock(NATURA, "N Crops"); - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(seedBarley, cropBlock, 3)); - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(seedCotton, cropBlock, 8)); - - List berries = new ArrayList<>(); - if (berryBlight != null) { - berries.add(berryBlight); - } - if (berryDusk != null) { - berries.add(berryDusk); - } - if (berrySky != null) { - berries.add(berrySky); - } - if (berrySting != null) { - berries.add(berrySting); - } - if (berryRasp != null) { - berries.add(berryRasp); - } - if (berryBlue != null) { - berries.add(berryBlue); - } - if (berryBlack != null) { - berries.add(berryBlack); - } - if (berryMalo != null) { - berries.add(berryMalo); - } + Block cropBlock = GameRegistry.findBlock(NATURA, "N Crops"); + Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(seedBarley, cropBlock, 3)); + Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(seedCotton, cropBlock, 8)); - amount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple") / 2; - amount = Math.max(amount, 1); // Produce at least 1 mb of juice. - ItemStack netherFood = new ItemStack(GameRegistry.findItem(NATURA, "Natura.netherfood"), 1, 0); - ItemStack mulch = PluginCore.items.mulch.getItemStack(); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{netherFood}, Fluids.JUICE.getFluid(amount), mulch, ForestryAPI.activeMode.getIntegerSetting("squeezer.mulch.apple")); + List berries = new ArrayList<>(); + if (berryBlight != null) { + berries.add(berryBlight); + } + if (berryDusk != null) { + berries.add(berryDusk); + } + if (berrySky != null) { + berries.add(berrySky); + } + if (berrySting != null) { + berries.add(berrySting); + } + if (berryRasp != null) { + berries.add(berryRasp); + } + if (berryBlue != null) { + berries.add(berryBlue); + } + if (berryBlack != null) { + berries.add(berryBlack); + } + if (berryMalo != null) { + berries.add(berryMalo); + } - amount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple") / 25; - amount = Math.max(amount, 1); // Produce at least 1 mb of juice. + amount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple") / 2; + amount = Math.max(amount, 1); // Produce at least 1 mb of juice. + ItemStack netherFood = new ItemStack(GameRegistry.findItem(NATURA, "Natura.netherfood"), 1, 0); + ItemStack mulch = PluginCore.items.mulch.getItemStack(); + RecipeManagers.squeezerManager.addRecipe( + 10, + new ItemStack[] {netherFood}, + Fluids.JUICE.getFluid(amount), + mulch, + ForestryAPI.activeMode.getIntegerSetting("squeezer.mulch.apple")); - for (ItemStack berry : berries) { - RecipeManagers.squeezerManager.addRecipe(3, new ItemStack[]{berry}, Fluids.JUICE.getFluid(amount)); - } + amount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple") / 25; + amount = Math.max(amount, 1); // Produce at least 1 mb of juice. - if (itemBarley != null) { - RecipeUtil.addFermenterRecipes(itemBarley, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); - if (ForestryAPI.activeMode.getStackSetting("recipe.output.compost.wheat").stackSize > 0) { - ItemStack compostWheat = ForestryAPI.activeMode.getStackSetting("recipe.output.compost.wheat"); - RecipeUtil.addRecipe(compostWheat, " X ", "X#X", " X ", '#', Blocks.dirt, 'X', itemBarley); - } - FuelManager.moistenerResource.put(itemBarley, new MoistenerFuel(itemBarley, PluginCore.items.mouldyWheat.getItemStack(), 0, 300)); - } - } + for (ItemStack berry : berries) { + RecipeManagers.squeezerManager.addRecipe(3, new ItemStack[] {berry}, Fluids.JUICE.getFluid(amount)); + } + if (itemBarley != null) { + RecipeUtil.addFermenterRecipes( + itemBarley, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); + if (ForestryAPI.activeMode.getStackSetting("recipe.output.compost.wheat").stackSize > 0) { + ItemStack compostWheat = ForestryAPI.activeMode.getStackSetting("recipe.output.compost.wheat"); + RecipeUtil.addRecipe(compostWheat, " X ", "X#X", " X ", '#', Blocks.dirt, 'X', itemBarley); + } + FuelManager.moistenerResource.put( + itemBarley, new MoistenerFuel(itemBarley, PluginCore.items.mouldyWheat.getItemStack(), 0, 300)); + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginPlantMegaPack.java b/src/main/java/forestry/plugins/compat/PluginPlantMegaPack.java index 7d9bf8a98..3d0f6b9ce 100644 --- a/src/main/java/forestry/plugins/compat/PluginPlantMegaPack.java +++ b/src/main/java/forestry/plugins/compat/PluginPlantMegaPack.java @@ -12,15 +12,7 @@ package forestry.plugins.compat; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -import forestry.farming.logic.FarmableReference; -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; - import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.apiculture.FlowerManager; import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; @@ -31,447 +23,469 @@ import forestry.core.recipes.RecipeUtil; import forestry.core.utils.ModUtil; import forestry.farming.logic.FarmableBasicFruit; import forestry.farming.logic.FarmableGenericCrop; +import forestry.farming.logic.FarmableReference; import forestry.farming.logic.FarmableStacked; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; import forestry.plugins.PluginManager; +import java.util.Map; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; -@Plugin(pluginID = "PlantMegaPack", name = "PlantMegaPack", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.plantmegapack.description") +@Plugin( + pluginID = "PlantMegaPack", + name = "PlantMegaPack", + author = "Nirek", + url = Constants.URL, + unlocalizedDescription = "for.plugin.plantmegapack.description") public class PluginPlantMegaPack extends ForestryPlugin { - private static final String PlantMP = "plantmegapack"; + private static final String PlantMP = "plantmegapack"; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(PlantMP); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(PlantMP); + } - @Override - public String getFailMessage() { - return "Plant Mega Pack not found"; - } + @Override + public String getFailMessage() { + return "Plant Mega Pack not found"; + } - @Override - protected void registerRecipes() { + @Override + protected void registerRecipes() { - ImmutableList reedLikePlant = ImmutableList.of( - "bambooAsper", - "bambooFargesiaRobusta", - "bambooGiantTimber", - "bambooGolden", - "bambooMoso", - "bambooShortTassled", - "bambooTimorBlack", - "bambooTropicalBlue", - "bambooWetForest" - ); + ImmutableList reedLikePlant = ImmutableList.of( + "bambooAsper", + "bambooFargesiaRobusta", + "bambooGiantTimber", + "bambooGolden", + "bambooMoso", + "bambooShortTassled", + "bambooTimorBlack", + "bambooTropicalBlue", + "bambooWetForest"); - ImmutableList landCropPlant = ImmutableList.of( - "Beet", - "BellPepperOrange", - "BellPepperRed", - "BellPepperYellow", - "Broccoli", - "Cassava", - "Celery", - "Corn", - "Cucumber", - "Eggplant", - "GreenBean", - "Leek", - "Lettuce", - "Onion", - "Sorrel", - "Spinach", - "Tomato" - ); + ImmutableList landCropPlant = ImmutableList.of( + "Beet", + "BellPepperOrange", + "BellPepperRed", + "BellPepperYellow", + "Broccoli", + "Cassava", + "Celery", + "Corn", + "Cucumber", + "Eggplant", + "GreenBean", + "Leek", + "Lettuce", + "Onion", + "Sorrel", + "Spinach", + "Tomato"); - ImmutableMap desertPlant = ImmutableMap.builder() - .put("cactusArmatocereusMatucanensis", 6) - .put("cactusBaseballBat", 6) - .put("cactusEchinocereusMetornii", 2) - .put("cactusGoldenCereus", 3) - .put("cactusGoldenSaguaro", 6) - .put("cactusMatucanaAureiflora", 1) - .put("cactusPricklyPear", 5) - .put("cactusSnowPole", 6) - .put("cactusToothpick", 6) + ImmutableMap desertPlant = ImmutableMap.builder() + .put("cactusArmatocereusMatucanensis", 6) + .put("cactusBaseballBat", 6) + .put("cactusEchinocereusMetornii", 2) + .put("cactusGoldenCereus", 3) + .put("cactusGoldenSaguaro", 6) + .put("cactusMatucanaAureiflora", 1) + .put("cactusPricklyPear", 5) + .put("cactusSnowPole", 6) + .put("cactusToothpick", 6) + .put("desertApachePlume", 4) + .put("desertBrittlebush", 4) + .put("desertBroadLeafGilia", 4) + .put("desertBroomSnakeweed", 4) + .put("desertKangarooPaw", 4) + .put("desertOcotillo", 4) + .put("desertPeninsulaOnion", 4) + .put("desertSeepwood", 4) + .put("desertWhiteSage", 4) + .build(); - .put("desertApachePlume", 4) - .put("desertBrittlebush", 4) - .put("desertBroadLeafGilia", 4) - .put("desertBroomSnakeweed", 4) - .put("desertKangarooPaw", 4) - .put("desertOcotillo", 4) - .put("desertPeninsulaOnion", 4) - .put("desertSeepwood", 4) - .put("desertWhiteSage", 4) - .build(); + ImmutableMap nonGrowingFlowers = ImmutableMap.builder() + .put("flowerAchillea", 9) // number of flowers in the block, usually meta+1 + .put("flowerAlpineThistle", 1) + .put("flowerAzalea", 13) + .put("flowerBegonia", 9) + .put("flowerBell", 10) + .put("flowerBirdofParadise", 1) + .put("flowerBlueStar", 1) + .put("flowerBurningLove", 1) + .put("flowerCandelabraAloe", 1) + .put("flowerCarnation", 7) + .put("flowerCelosia", 7) + // .put("flowerColumbine", 5) //poisonous + .put("flowerDahlia", 8) + .put("flowerDaisy", 8) + .put("flowerDelphinium", 4) + .put("flowerDottedBlazingstar", 1) + .put("flowerElephantEars", 1) + .put("flowerFoamFlower", 1) + .put("flowerFuchsia", 1) + .put("flowerGeranium", 5) + .put("flowerGladiolus", 9) + .put("flowerHawkweed", 4) + .put("flowerHydrangea", 6) + .put("flowerJacobsLadder", 1) + .put("flowerLily", 5) + .put("flowerLionsTail", 1) + .put("flowerLupine", 10) + .put("flowerMarigold", 2) + .put("flowerMediterraneanSeaHolly", 1) + // .put("flowerMezereon", 1) //poisonous + .put("flowerNemesia", 12) + .put("flowerNewGuineaImpatiens", 1) + .put("flowerParrotsBeak", 1) + .put("flowerPeruvianLily", 1) + .put("flowerPurpleConeflower", 1) + .put("flowerRose", 13) + .put("flowerRoseCampion", 1) + .put("flowerStreamsideBluebells", 1) + .put("flowerTorchLily", 1) + .put("flowerTulip", 7) + .put("flowerViolet", 1) + .put("flowerWildCarrot", 1) // is not actually a carrot + .put("flowerWildDaffodil", 1) + .put("flowerWoodlandPinkroot", 1) + .put("flowerYellowToadflax", 1) + .put("floatingWaterHyacinth", 1) + .put("floatingWaterLily", 13) + .build(); - ImmutableMap nonGrowingFlowers = ImmutableMap.builder() - .put("flowerAchillea", 9) // number of flowers in the block, usually meta+1 - .put("flowerAlpineThistle", 1) - .put("flowerAzalea", 13) - .put("flowerBegonia", 9) - .put("flowerBell", 10) - .put("flowerBirdofParadise", 1) - .put("flowerBlueStar", 1) - .put("flowerBurningLove", 1) - .put("flowerCandelabraAloe", 1) - .put("flowerCarnation", 7) - .put("flowerCelosia", 7) - //.put("flowerColumbine", 5) //poisonous - .put("flowerDahlia", 8) - .put("flowerDaisy", 8) - .put("flowerDelphinium", 4) - .put("flowerDottedBlazingstar", 1) - .put("flowerElephantEars", 1) - .put("flowerFoamFlower", 1) - .put("flowerFuchsia", 1) - .put("flowerGeranium", 5) - .put("flowerGladiolus", 9) - .put("flowerHawkweed", 4) - .put("flowerHydrangea", 6) - .put("flowerJacobsLadder", 1) - .put("flowerLily", 5) - .put("flowerLionsTail", 1) - .put("flowerLupine", 10) - .put("flowerMarigold", 2) - .put("flowerMediterraneanSeaHolly", 1) - //.put("flowerMezereon", 1) //poisonous - .put("flowerNemesia", 12) - .put("flowerNewGuineaImpatiens", 1) - .put("flowerParrotsBeak", 1) - .put("flowerPeruvianLily", 1) - .put("flowerPurpleConeflower", 1) - .put("flowerRose", 13) - .put("flowerRoseCampion", 1) - .put("flowerStreamsideBluebells", 1) - .put("flowerTorchLily", 1) - .put("flowerTulip", 7) - .put("flowerViolet", 1) - .put("flowerWildCarrot", 1) //is not actually a carrot - .put("flowerWildDaffodil", 1) - .put("flowerWoodlandPinkroot", 1) - .put("flowerYellowToadflax", 1) - .put("floatingWaterHyacinth", 1) - .put("floatingWaterLily", 13) - .build(); + ImmutableMap floatingWaterPlant = ImmutableMap.builder() + .put("cropSacredLotus", 4) + .put("cropWatercress", 4) + .put("cropTaro", 4) + .put("cropWasabi", 4) + .put("cropLaksaLeaf", 4) + .put("cropCentella", 4) + .put("cropRice", 4) + .put("cropWaterSpinach", 4) + .put("cropWildRice", 4) + .put("immersedArrowArum", 4) + .put("immersedCommonReed", 4) + .put("immersedDuckPotato", 4) + .put("immersedEuropeanBurReed", 4) + .put("immersedGreySedge", 4) + .put("immersedSimplestemBurReed", 4) + .put("immersedSoftstemBulrush", 4) + .put("immersedWaterMannagrass", 4) + .put("immersedYellowFlag", 4) + .build(); - ImmutableMap floatingWaterPlant = ImmutableMap.builder() - .put("cropSacredLotus", 4) - .put("cropWatercress", 4) - .put("cropTaro", 4) - .put("cropWasabi", 4) - .put("cropLaksaLeaf", 4) - .put("cropCentella", 4) - .put("cropRice", 4) - .put("cropWaterSpinach", 4) - .put("cropWildRice", 4) + ImmutableMap fungusPlant = ImmutableMap.builder() + .put("fungusBlackPowderpuff", 1) + .put("fungusChanterelle", 1) + // .put("fungusDeathCap", 1) poisonous + .put("fungusGiantClub", 1) + .put("fungusParasol", 2) + .put("fungusStinkhorn", 1) + .put("fungusWeepingMilkCap", 1) + .put("fungusWoodBlewit", 1) + // .put("fungusWoollyGomphus", 2) poisonous + .build(); - .put("immersedArrowArum", 4) - .put("immersedCommonReed", 4) - .put("immersedDuckPotato", 4) - .put("immersedEuropeanBurReed", 4) - .put("immersedGreySedge", 4) - .put("immersedSimplestemBurReed", 4) - .put("immersedSoftstemBulrush", 4) - .put("immersedWaterMannagrass", 4) - .put("immersedYellowFlag", 4) - .build(); + ImmutableMap junglePlant = ImmutableMap.builder() + .put("jungleConeHeadedGuzmania", 2) + .put("jungleDevilsTongue", 6) + .put("jungleHoneySpurge", 1) + .put("jungleJungleLantern", 6) + .put("jungleLazarusBell", 2) + .put("jungleLobsterClaws", 6) + .put("jungleLollipopPlant", 2) + .put("jungleMadagascarPalm", 6) + .put("junglePalmLily", 6) + .put("junglePanamaQueen", 2) + .put("junglePorteaAlatisepala", 2) + .put("jungleRacinaeaFraseri", 6) + .put("jungleRicheaDracophylla", 2) + // .put("jungleShellflower", 4) 2 tall needs specialcase + .put("jungleSilverVase", 2) + .put("jungleStaghornClubmoss", 2) + .put("jungleTorchGinger", 2) + .put("jungleVoodooLily", 6) + .put("leafyEmeraldPhilodendron", 2) // jungle plant + .build(); - ImmutableMap fungusPlant = ImmutableMap.builder() - .put("fungusBlackPowderpuff", 1) - .put("fungusChanterelle", 1) - //.put("fungusDeathCap", 1) poisonous - .put("fungusGiantClub", 1) - .put("fungusParasol", 2) - .put("fungusStinkhorn", 1) - .put("fungusWeepingMilkCap", 1) - .put("fungusWoodBlewit", 1) - //.put("fungusWoollyGomphus", 2) poisonous - .build(); + ImmutableMap vanillaPlant = ImmutableMap.builder() + .put("beachHighTideBush", 6) + .put("beachSeaLavender", 4) + .put("beachSeaSandwort", 4) + .put("leafyDustyMiller", 1) // beach plant + .put("fernCretanBrake", 1) + // .put("fernDwarfPalmetto", 0) doesn't grow + .put("fernHayScented", 2) + .put("fernKangaroo", 2) + .put("fernMaidenhairSpleenwort", 3) + .put("fernOstrich", 6) + .put("fernScalyTree", 6) + .put("fernSword", 6) + .put("fernWoodsia", 2) + .put("forestArcticGentian", 1) + .put("forestAustralianBugle", 2) + .put("forestBroadleafMeadowsweet", 2) + .put("forestDeadnettle", 2) + .put("forestDeceivingTrillium", 2) + .put("forestFairySlipper", 2) + .put("forestHorseweed", 2) + .put("forestKneelingAngelica", 2) + // .put("forestLilyoftheValley", //poisonous + .put("forestNorthernPitcherPlant", 2) + .put("forestPinesap", 2) + .put("forestRedHelleborine", 2) + .put("forestSalal", 2) + .put("forestVanillaLeaf", 1) + .put("forestWesternWallflower", 2) + .put("forestWildColumbine", 2) + .put("forestWildMint", 2) + .put("forestWolfsFootClubmoss", 1) + .put("leafyColeus", 1) // forest plant + .put("leafyStonecrop", 1) // forest plant + .put("grassBlueWheatgrass", 1) + .put("grassCord", 6) + .put("grassFountain", 2) + .put("grassMeadow", 2) + .put("grassMeadowFoxtail", 1) + .put("grassPrairie", 1) + .put("grassSilverMoor", 2) + .put("grassSwitch", 6) + .put("mountainAlpineArmeria", 2) + .put("mountainAlpineBellflower", 2) + .put("mountainBistort", 2) + .put("mountainEdelweiss", 2) + .put("mountainHouseleek", 2) + .put("mountainIris", 1) + .put("mountainNorthernWillowherb", 2) + .put("mountainScarletTrumpet", 2) + .put("mountainYellowBellflower", 1) + .put("leafyKrisPlant", 2) // mountain plaint + .put("plainsPrairieBrome", 6) // skips some metas + .put("plainsPrairieSage", 4) + .put("plainsReedCanaryGrass", 6) // skips some metas + .put("plainsShortrayFleabane", 4) + .put("plainsSmallPasqueFlower", 4) + .put("plainsSmoothAster", 4) + .put("plainsThreeFloweredAvens", 4) + .put("leafyPricklyLettuce", 1) // plains plant + // .put("leafyStingingNettle", 2) plains plant, poisonous - ImmutableMap junglePlant = ImmutableMap.builder() - .put("jungleConeHeadedGuzmania", 2) - .put("jungleDevilsTongue", 6) - .put("jungleHoneySpurge", 1) - .put("jungleJungleLantern", 6) - .put("jungleLazarusBell", 2) - .put("jungleLobsterClaws", 6) - .put("jungleLollipopPlant", 2) - .put("jungleMadagascarPalm", 6) - .put("junglePalmLily", 6) - .put("junglePanamaQueen", 2) - .put("junglePorteaAlatisepala", 2) - .put("jungleRacinaeaFraseri", 6) - .put("jungleRicheaDracophylla", 2) - //.put("jungleShellflower", 4) 2 tall needs specialcase - .put("jungleSilverVase", 2) - .put("jungleStaghornClubmoss", 2) - .put("jungleTorchGinger", 2) - .put("jungleVoodooLily", 6) - .put("leafyEmeraldPhilodendron", 2) //jungle plant - .build(); + .put("savannaButterflyWeed", 2) + .put("savannaHoaryVervain", 2) + .put("savannaLeadplant", 2) + .put("savannaMarcela", 2) + .put("savannaNorthernBedstraw", 1) + .put("savannaPiersonsMilkVetch", 2) + .put("savannaPropellerPlant", 2) + .put("savannaShonaCabbage", 2) + .put("savannaTexasTickseed", 2) + .put("leafyPaleYucca", 2) // savanna Plant + .put("leafyDevilsShoestring", 2) + .put("shrubAlpineCurrant", 2) + .put("shrubBarberry", 2) + .put("shrubBoxwood", 2) + .put("shrubButterfly", 2) + .put("shrubCanyonCreekAbelia", 2) + .put("shrubCapeJasmine", 2) + .put("shrubCedarCylinder", 6) + .put("shrubCedarGlobe", 2) + .put("shrubCedarPyramid", 6) + .put("shrubCypressGreen", 1) + .put("shrubCypressYellow", 1) + .put("shrubDaphne", 2) + // .put("shrubDwarfElder", 4) poisonous, also grows 2 tall at meta 4 + .put("shrubHolly", 2) + .put("shrubHummingbirdBush", 2) + .put("shrubJuniperSavin", 2) + .put("shrubKerria", 2) + .put("shrubLavender", 2) + .put("shrubLindera", 3) + .put("shrubMeadowsweet", 2) + .put("shrubMottlecah", 2) + .put("shrubNinebark", 2) + .put("shrubSargentViburnum", 2) + // .put("shrubSpicebush",2) poisonous + .put("shrubWeepingForsythia", 2) + .put("shrubWinterberry", 2) + .put("shrubWolfWillow", 2) + .put("wetlandsCattails", 6) + .put("wetlandsClubrush", 2) + .put("wetlandsCommonRush", 2) + .put("wetlandsFloweringRush", 2) + .put("wetlandsPickerelweed", 2) + .put("wetlandsReedMannagrass", 2) + .put("wetlandsSwampMilkweed", 2) + .put("wetlandsWaterHorsetail", 1) + .put("wetlandsWhiteTurtlehead", 2) + .build(); - ImmutableMap vanillaPlant = ImmutableMap.builder() - .put("beachHighTideBush", 6) - .put("beachSeaLavender", 4) - .put("beachSeaSandwort", 4) - .put("leafyDustyMiller", 1) //beach plant + ImmutableMap berryBushPlant = ImmutableMap.builder() + .put("Beauty", 4) + .put("Black", 4) + .put("Blue", 4) + .put("Elder", 4) + .put("Goose", 4) + .put("Huckle", 4) + .put("Orange", 4) + .put("Snow", 4) + .put("Straw", 4) + .build(); - .put("fernCretanBrake", 1) - //.put("fernDwarfPalmetto", 0) doesn't grow - .put("fernHayScented", 2) - .put("fernKangaroo", 2) - .put("fernMaidenhairSpleenwort", 3) - .put("fernOstrich", 6) - .put("fernScalyTree", 6) - .put("fernSword", 6) - .put("fernWoodsia", 2) + ImmutableList waterPlant = ImmutableList.of( + "oceanCommonEelgrass", + "oceanCoralWeed", + "oceanMozuku", + "oceanRockweed", + "oceanSeaGrapes", + "oceanSeaLettuce", + "oceanTangle", + "riverAmazonSword", + "riverCanadianWaterweed", + "riverCoonsTail", + "riverEelgrass", + "riverWaterWisteria", + "riverWrightsWaternymph", + "waterKelpGiantGRN", + "waterKelpGiantYEL"); - .put("forestArcticGentian", 1) - .put("forestAustralianBugle", 2) - .put("forestBroadleafMeadowsweet", 2) - .put("forestDeadnettle", 2) - .put("forestDeceivingTrillium", 2) - .put("forestFairySlipper", 2) - .put("forestHorseweed", 2) - .put("forestKneelingAngelica", 2) - //.put("forestLilyoftheValley", //poisonous - .put("forestNorthernPitcherPlant", 2) - .put("forestPinesap", 2) - .put("forestRedHelleborine", 2) - .put("forestSalal", 2) - .put("forestVanillaLeaf", 1) - .put("forestWesternWallflower", 2) - .put("forestWildColumbine", 2) - .put("forestWildMint", 2) - .put("forestWolfsFootClubmoss", 1) - .put("leafyColeus", 1) //forest plant - .put("leafyStonecrop", 1) //forest plant + ImmutableMap specialCaseTwoTall = ImmutableMap.builder() + .put("grassSeaOats", FlowerManager.FlowerTypeVanilla) + .put("jungleShellflower", FlowerManager.FlowerTypeJungle) + .build(); - .put("grassBlueWheatgrass", 1) - .put("grassCord", 6) - .put("grassFountain", 2) - .put("grassMeadow", 2) - .put("grassMeadowFoxtail", 1) - .put("grassPrairie", 1) - .put("grassSilverMoor", 2) - .put("grassSwitch", 6) + int seedamount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); + int juiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); - .put("mountainAlpineArmeria", 2) - .put("mountainAlpineBellflower", 2) - .put("mountainBistort", 2) - .put("mountainEdelweiss", 2) - .put("mountainHouseleek", 2) - .put("mountainIris", 1) - .put("mountainNorthernWillowherb", 2) - .put("mountainScarletTrumpet", 2) - .put("mountainYellowBellflower", 1) - .put("leafyKrisPlant", 2) // mountain plaint + for (String reedLike : reedLikePlant) { + Block reedBlock = GameRegistry.findBlock(PlantMP, reedLike); + ItemStack reedStack = GameRegistry.findItemStack(PlantMP, reedLike, 1); + if (reedBlock != null && reedStack != null) { + RecipeUtil.addFermenterRecipes( + reedStack, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); + if (PluginManager.Module.FARMING.isEnabled()) { + Farmables.farmables.get(FarmableReference.Poales.get()).add(new FarmableStacked(reedBlock, 14, 4)); + } + } + } - .put("plainsPrairieBrome", 6) //skips some metas - .put("plainsPrairieSage", 4) - .put("plainsReedCanaryGrass", 6) //skips some metas - .put("plainsShortrayFleabane", 4) - .put("plainsSmallPasqueFlower", 4) - .put("plainsSmoothAster", 4) - .put("plainsThreeFloweredAvens", 4) - .put("leafyPricklyLettuce", 1) //plains plant - //.put("leafyStingingNettle", 2) plains plant, poisonous + for (String landCrop : landCropPlant) { + Block landCropBlock = GameRegistry.findBlock(PlantMP, "crop" + landCrop); + ItemStack seedStack = GameRegistry.findItemStack(PlantMP, "seed" + landCrop, 1); + ItemStack foodStack = GameRegistry.findItemStack(PlantMP, "food" + landCrop, 1); + if (landCropBlock != null) { + if (foodStack != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {foodStack}, Fluids.JUICE.getFluid(juiceAmount)); + } + if (seedStack != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {seedStack}, Fluids.SEEDOIL.getFluid(seedamount)); + } + if (PluginManager.Module.FARMING.isEnabled()) { + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(seedStack, landCropBlock, 4)); + Farmables.farmables + .get(FarmableReference.Orchard.get()) + .add(new FarmableBasicFruit(landCropBlock, 4)); + } + } + } - .put("savannaButterflyWeed", 2) - .put("savannaHoaryVervain", 2) - .put("savannaLeadplant", 2) - .put("savannaMarcela", 2) - .put("savannaNorthernBedstraw", 1) - .put("savannaPiersonsMilkVetch", 2) - .put("savannaPropellerPlant", 2) - .put("savannaShonaCabbage", 2) - .put("savannaTexasTickseed", 2) - .put("leafyPaleYucca", 2) //savanna Plant - .put("leafyDevilsShoestring", 2) + for (Map.Entry flower : nonGrowingFlowers.entrySet()) { + Block flowerPlantBlock = GameRegistry.findBlock(PlantMP, flower.getKey()); + if (flowerPlantBlock != null) { + for (int i = 0; i < flower.getValue(); i++) { + FlowerManager.flowerRegistry.registerPlantableFlower( + flowerPlantBlock, i, 0.75, FlowerManager.FlowerTypeVanilla); + } + } + } - .put("shrubAlpineCurrant", 2) - .put("shrubBarberry", 2) - .put("shrubBoxwood", 2) - .put("shrubButterfly", 2) - .put("shrubCanyonCreekAbelia", 2) - .put("shrubCapeJasmine", 2) - .put("shrubCedarCylinder", 6) - .put("shrubCedarGlobe", 2) - .put("shrubCedarPyramid", 6) - .put("shrubCypressGreen", 1) - .put("shrubCypressYellow", 1) - .put("shrubDaphne", 2) - //.put("shrubDwarfElder", 4) poisonous, also grows 2 tall at meta 4 - .put("shrubHolly", 2) - .put("shrubHummingbirdBush", 2) - .put("shrubJuniperSavin", 2) - .put("shrubKerria", 2) - .put("shrubLavender", 2) - .put("shrubLindera", 3) - .put("shrubMeadowsweet", 2) - .put("shrubMottlecah", 2) - .put("shrubNinebark", 2) - .put("shrubSargentViburnum", 2) - //.put("shrubSpicebush",2) poisonous - .put("shrubWeepingForsythia", 2) - .put("shrubWinterberry", 2) - .put("shrubWolfWillow", 2) + for (Map.Entry wPlant : floatingWaterPlant.entrySet()) { + Block waterPlantBlock = GameRegistry.findBlock(PlantMP, wPlant.getKey()); + if (PluginManager.Module.FARMING.isEnabled() && waterPlantBlock != null) { + Farmables.farmables + .get(FarmableReference.Orchard.get()) + .add(new FarmableBasicFruit(waterPlantBlock, wPlant.getValue())); + } + } - .put("wetlandsCattails", 6) - .put("wetlandsClubrush", 2) - .put("wetlandsCommonRush", 2) - .put("wetlandsFloweringRush", 2) - .put("wetlandsPickerelweed", 2) - .put("wetlandsReedMannagrass", 2) - .put("wetlandsSwampMilkweed", 2) - .put("wetlandsWaterHorsetail", 1) - .put("wetlandsWhiteTurtlehead", 2) - .build(); + juiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple") / 25; + juiceAmount = Math.max(juiceAmount, 1); // Produce at least 1 mb of juice. - ImmutableMap berryBushPlant = ImmutableMap.builder() - .put("Beauty", 4) - .put("Black", 4) - .put("Blue", 4) - .put("Elder", 4) - .put("Goose", 4) - .put("Huckle", 4) - .put("Orange", 4) - .put("Snow", 4) - .put("Straw", 4) - .build(); + for (Map.Entry berryBushCrop : berryBushPlant.entrySet()) { + Block berryBushCropBlock = GameRegistry.findBlock(PlantMP, "berrybush" + berryBushCrop.getKey()); + ItemStack berryBushStack = GameRegistry.findItemStack(PlantMP, "berrybush" + berryBushCrop.getKey(), 1); + ItemStack foodStack = GameRegistry.findItemStack(PlantMP, "berries" + berryBushCrop.getKey(), 1); + if (berryBushCropBlock != null) { + if (foodStack != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {foodStack}, Fluids.JUICE.getFluid(juiceAmount)); + } + if (PluginManager.Module.FARMING.isEnabled()) { + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(berryBushStack, berryBushCropBlock, berryBushCrop.getValue())); + Farmables.farmables + .get(FarmableReference.Orchard.get()) + .add(new FarmableBasicFruit(berryBushCropBlock, berryBushCrop.getValue())); + } + } + } - ImmutableList waterPlant = ImmutableList.of( - "oceanCommonEelgrass", - "oceanCoralWeed", - "oceanMozuku", - "oceanRockweed", - "oceanSeaGrapes", - "oceanSeaLettuce", - "oceanTangle", - "riverAmazonSword", - "riverCanadianWaterweed", - "riverCoonsTail", - "riverEelgrass", - "riverWaterWisteria", - "riverWrightsWaternymph", - "waterKelpGiantGRN", - "waterKelpGiantYEL" - ); + addMetaFlower(desertPlant, false, FlowerManager.FlowerTypeCacti); + addMetaFlower(junglePlant, false, FlowerManager.FlowerTypeJungle); + addMetaFlower(vanillaPlant, true, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); + addMetaFlower(fungusPlant, true, FlowerManager.FlowerTypeMushrooms); - ImmutableMap specialCaseTwoTall = ImmutableMap.builder() - .put("grassSeaOats", FlowerManager.FlowerTypeVanilla) - .put("jungleShellflower", FlowerManager.FlowerTypeJungle) - .build(); + for (Map.Entry special : specialCaseTwoTall.entrySet()) { + Block plantBlock = GameRegistry.findBlock(PlantMP, special.getKey()); + ItemStack specialStack = GameRegistry.findItemStack(PlantMP, special.getKey(), 1); + if (plantBlock != null && plantBlock != null) { + FlowerManager.flowerRegistry.registerAcceptableFlower(plantBlock, special.getValue()); + FlowerManager.flowerRegistry.registerPlantableFlower(plantBlock, 0, 0.75, special.getValue()); + if (PluginManager.Module.FARMING.isEnabled()) { + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(specialStack, plantBlock, 4)); + } + } + } - int seedamount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - int juiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); + for (String wPlant : waterPlant) { + ItemStack waterPlantStack = GameRegistry.findItemStack(PlantMP, wPlant, 1); + if (waterPlantStack != null) { + RecipeUtil.addFermenterRecipes( + waterPlantStack, + ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), + Fluids.BIOMASS); + } + } + } - for (String reedLike : reedLikePlant) { - Block reedBlock = GameRegistry.findBlock(PlantMP, reedLike); - ItemStack reedStack = GameRegistry.findItemStack(PlantMP, reedLike, 1); - if (reedBlock != null && reedStack != null) { - RecipeUtil.addFermenterRecipes(reedStack, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); - if (PluginManager.Module.FARMING.isEnabled()) { - Farmables.farmables.get(FarmableReference.Poales.get()).add(new FarmableStacked(reedBlock, 14, 4)); - } - } - } - - for (String landCrop : landCropPlant) { - Block landCropBlock = GameRegistry.findBlock(PlantMP, "crop" + landCrop); - ItemStack seedStack = GameRegistry.findItemStack(PlantMP, "seed" + landCrop, 1); - ItemStack foodStack = GameRegistry.findItemStack(PlantMP, "food" + landCrop, 1); - if (landCropBlock != null) { - if (foodStack != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{foodStack}, Fluids.JUICE.getFluid(juiceAmount)); - } - if (seedStack != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{seedStack}, Fluids.SEEDOIL.getFluid(seedamount)); - } - if (PluginManager.Module.FARMING.isEnabled()) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(seedStack, landCropBlock, 4)); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(landCropBlock, 4)); - } - } - } - - for (Map.Entry flower : nonGrowingFlowers.entrySet()) { - Block flowerPlantBlock = GameRegistry.findBlock(PlantMP, flower.getKey()); - if (flowerPlantBlock != null) { - for (int i = 0; i < flower.getValue(); i++) { - FlowerManager.flowerRegistry.registerPlantableFlower(flowerPlantBlock, i, 0.75, FlowerManager.FlowerTypeVanilla); - } - } - } - - for (Map.Entry wPlant : floatingWaterPlant.entrySet()) { - Block waterPlantBlock = GameRegistry.findBlock(PlantMP, wPlant.getKey()); - if (PluginManager.Module.FARMING.isEnabled() && waterPlantBlock != null) { - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(waterPlantBlock, wPlant.getValue())); - } - } - - juiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple") / 25; - juiceAmount = Math.max(juiceAmount, 1); // Produce at least 1 mb of juice. - - for (Map.Entry berryBushCrop : berryBushPlant.entrySet()) { - Block berryBushCropBlock = GameRegistry.findBlock(PlantMP, "berrybush" + berryBushCrop.getKey()); - ItemStack berryBushStack = GameRegistry.findItemStack(PlantMP, "berrybush" + berryBushCrop.getKey(), 1); - ItemStack foodStack = GameRegistry.findItemStack(PlantMP, "berries" + berryBushCrop.getKey(), 1); - if (berryBushCropBlock != null) { - if (foodStack != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{foodStack}, Fluids.JUICE.getFluid(juiceAmount)); - } - if (PluginManager.Module.FARMING.isEnabled()) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(berryBushStack, berryBushCropBlock, berryBushCrop.getValue())); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(berryBushCropBlock, berryBushCrop.getValue())); - } - } - } - - addMetaFlower(desertPlant, false, FlowerManager.FlowerTypeCacti); - addMetaFlower(junglePlant, false, FlowerManager.FlowerTypeJungle); - addMetaFlower(vanillaPlant, true, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); - addMetaFlower(fungusPlant, true, FlowerManager.FlowerTypeMushrooms); - - for (Map.Entry special : specialCaseTwoTall.entrySet()) { - Block plantBlock = GameRegistry.findBlock(PlantMP, special.getKey()); - ItemStack specialStack = GameRegistry.findItemStack(PlantMP, special.getKey(), 1); - if (plantBlock != null && plantBlock != null) { - FlowerManager.flowerRegistry.registerAcceptableFlower(plantBlock, special.getValue()); - FlowerManager.flowerRegistry.registerPlantableFlower(plantBlock, 0, 0.75, special.getValue()); - if (PluginManager.Module.FARMING.isEnabled()) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(specialStack, plantBlock, 4)); - } - } - } - - for (String wPlant : waterPlant) { - ItemStack waterPlantStack = GameRegistry.findItemStack(PlantMP, wPlant, 1); - if (waterPlantStack != null) { - RecipeUtil.addFermenterRecipes(waterPlantStack, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); - } - } - } - - private static void addMetaFlower(ImmutableMap flowerMap, boolean plantable, String... flowertype) { - for (Map.Entry flower : flowerMap.entrySet()) { - Block flowerBlock = GameRegistry.findBlock(PlantMP, flower.getKey()); - ItemStack flowerStack = GameRegistry.findItemStack(PlantMP, flower.getKey(), 1); - FlowerManager.flowerRegistry.registerAcceptableFlower(flowerBlock, flowertype); - if (plantable && flowerBlock != null) { - FlowerManager.flowerRegistry.registerPlantableFlower(flowerBlock, 0, 0.75, flowertype); - } - if (PluginManager.Module.FARMING.isEnabled() && flowerStack != null && flowerBlock != null) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(flowerStack, flowerBlock, flower.getValue())); - if (flower.getValue() < 5) { - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(flowerBlock, flower.getValue())); - } - } - } - } + private static void addMetaFlower( + ImmutableMap flowerMap, boolean plantable, String... flowertype) { + for (Map.Entry flower : flowerMap.entrySet()) { + Block flowerBlock = GameRegistry.findBlock(PlantMP, flower.getKey()); + ItemStack flowerStack = GameRegistry.findItemStack(PlantMP, flower.getKey(), 1); + FlowerManager.flowerRegistry.registerAcceptableFlower(flowerBlock, flowertype); + if (plantable && flowerBlock != null) { + FlowerManager.flowerRegistry.registerPlantableFlower(flowerBlock, 0, 0.75, flowertype); + } + if (PluginManager.Module.FARMING.isEnabled() && flowerStack != null && flowerBlock != null) { + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(flowerStack, flowerBlock, flower.getValue())); + if (flower.getValue() < 5) { + Farmables.farmables + .get(FarmableReference.Orchard.get()) + .add(new FarmableBasicFruit(flowerBlock, flower.getValue())); + } + } + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginRotaryCraft.java b/src/main/java/forestry/plugins/compat/PluginRotaryCraft.java index 8ba5f4121..53a983a80 100644 --- a/src/main/java/forestry/plugins/compat/PluginRotaryCraft.java +++ b/src/main/java/forestry/plugins/compat/PluginRotaryCraft.java @@ -10,12 +10,7 @@ ******************************************************************************/ package forestry.plugins.compat; -import forestry.farming.logic.FarmableReference; -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; - import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; import forestry.api.recipes.RecipeManagers; @@ -24,42 +19,52 @@ import forestry.core.fluids.Fluids; import forestry.core.utils.ModUtil; import forestry.farming.logic.FarmableBasicFruit; import forestry.farming.logic.FarmableGenericCrop; +import forestry.farming.logic.FarmableReference; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; import forestry.plugins.PluginManager; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; -@Plugin(pluginID = "RotaryCraft", name = "RotaryCraft", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.rotarycraft.description") +@Plugin( + pluginID = "RotaryCraft", + name = "RotaryCraft", + author = "Nirek", + url = Constants.URL, + unlocalizedDescription = "for.plugin.rotarycraft.description") public class PluginRotaryCraft extends ForestryPlugin { - private static final String RC = "RotaryCraft"; + private static final String RC = "RotaryCraft"; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(RC); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(RC); + } - @Override - public String getFailMessage() { - return "RotaryCraft not found"; - } + @Override + public String getFailMessage() { + return "RotaryCraft not found"; + } - @Override - protected void registerRecipes() { + @Override + protected void registerRecipes() { - ItemStack canolaSeed = GameRegistry.findItemStack(RC, "rotarycraft_item_canola", 1); - Block canolaCrop = GameRegistry.findBlock(RC, "rotarycraft_block_canola"); - - int seedAmount = (ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed") / 16); - seedAmount = Math.max(seedAmount, 1); // Produce at least 1 mb. - if (canolaSeed != null && canolaCrop != null) { - if(PluginManager.Module.FACTORY.isEnabled()) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{canolaSeed}, Fluids.SEEDOIL.getFluid(seedAmount)); - } - if(PluginManager.Module.FARMING.isEnabled()) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(canolaSeed, canolaCrop, 9)); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(canolaCrop, 9)); - } - } - } + ItemStack canolaSeed = GameRegistry.findItemStack(RC, "rotarycraft_item_canola", 1); + Block canolaCrop = GameRegistry.findBlock(RC, "rotarycraft_block_canola"); + int seedAmount = (ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed") / 16); + seedAmount = Math.max(seedAmount, 1); // Produce at least 1 mb. + if (canolaSeed != null && canolaCrop != null) { + if (PluginManager.Module.FACTORY.isEnabled()) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {canolaSeed}, Fluids.SEEDOIL.getFluid(seedAmount)); + } + if (PluginManager.Module.FARMING.isEnabled()) { + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(canolaSeed, canolaCrop, 9)); + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(canolaCrop, 9)); + } + } + } } diff --git a/src/main/java/forestry/plugins/compat/PluginWitchery.java b/src/main/java/forestry/plugins/compat/PluginWitchery.java index f0f90fe32..27a63aeac 100644 --- a/src/main/java/forestry/plugins/compat/PluginWitchery.java +++ b/src/main/java/forestry/plugins/compat/PluginWitchery.java @@ -12,20 +12,9 @@ package forestry.plugins.compat; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -import forestry.farming.logic.FarmableReference; -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.oredict.OreDictionary; - import cpw.mods.fml.common.event.FMLInterModComms; import cpw.mods.fml.common.registry.GameData; import cpw.mods.fml.common.registry.GameRegistry; - import forestry.api.apiculture.FlowerManager; import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; @@ -36,78 +25,95 @@ import forestry.core.recipes.RecipeUtil; import forestry.core.utils.ModUtil; import forestry.farming.logic.FarmableBasicFruit; import forestry.farming.logic.FarmableGenericCrop; +import forestry.farming.logic.FarmableReference; import forestry.plugins.ForestryPlugin; import forestry.plugins.Plugin; +import java.util.Map; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; -@Plugin(pluginID = "Witchery", name = "Witchery", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.witchery.description") +@Plugin( + pluginID = "Witchery", + name = "Witchery", + author = "Nirek", + url = Constants.URL, + unlocalizedDescription = "for.plugin.witchery.description") public class PluginWitchery extends ForestryPlugin { - private static final String Witch = "witchery"; + private static final String Witch = "witchery"; - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(Witch); - } + @Override + public boolean isAvailable() { + return ModUtil.isModLoaded(Witch); + } - @Override - public String getFailMessage() { - return "Witchery not found"; - } + @Override + public String getFailMessage() { + return "Witchery not found"; + } - @Override - protected void registerRecipes() { + @Override + protected void registerRecipes() { - ImmutableList flowersAccept = ImmutableList.of( - "bloodrose", - "plantmine", - "glintweed" - ); + ImmutableList flowersAccept = ImmutableList.of("bloodrose", "plantmine", "glintweed"); - ImmutableMap cropSeed = ImmutableMap.builder() - .put("belladonna", 4) - .put("mandrake", 4) - .put("mindrake", 4) - .put("snowbell", 4) - .put("wolfsbane", 7) - .put("wormwood", 4) - .build(); - ImmutableList cropDirect = ImmutableList.of( - "garlic" //meta 5 - ); - int seedamount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); + ImmutableMap cropSeed = ImmutableMap.builder() + .put("belladonna", 4) + .put("mandrake", 4) + .put("mindrake", 4) + .put("snowbell", 4) + .put("wolfsbane", 7) + .put("wormwood", 4) + .build(); + ImmutableList cropDirect = ImmutableList.of( + "garlic" // meta 5 + ); + int seedamount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - Item saplingItem = GameRegistry.findItem(Witch, "witchsapling"); - ItemStack saplingStack = new ItemStack(saplingItem, 1, OreDictionary.WILDCARD_VALUE); - RecipeUtil.addFermenterRecipes(saplingStack, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); - String saplingName = GameData.getItemRegistry().getNameForObject(saplingItem); - FMLInterModComms.sendMessage(Constants.MOD, "add-farmable-sapling", String.format("farmArboreal@%s.-1", saplingName)); + Item saplingItem = GameRegistry.findItem(Witch, "witchsapling"); + ItemStack saplingStack = new ItemStack(saplingItem, 1, OreDictionary.WILDCARD_VALUE); + RecipeUtil.addFermenterRecipes( + saplingStack, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); + String saplingName = GameData.getItemRegistry().getNameForObject(saplingItem); + FMLInterModComms.sendMessage( + Constants.MOD, "add-farmable-sapling", String.format("farmArboreal@%s.-1", saplingName)); - for (String flowerAcceptName : flowersAccept) { - Block flowerBlock = GameRegistry.findBlock(Witch, flowerAcceptName); - if (flowerBlock != null) { - FlowerManager.flowerRegistry.registerAcceptableFlower(flowerBlock, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); - } - } - for (String cropDirectName : cropDirect) { - Block cropDirectBlock = GameRegistry.findBlock(Witch, cropDirectName + "plant"); - ItemStack cropDirectStack = GameRegistry.findItemStack(Witch, cropDirectName, 1); - if (cropDirectStack != null && cropDirectBlock != null) { - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(cropDirectStack, cropDirectBlock, 5)); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(cropDirectBlock, 5)); - } - } - for (Map.Entry cropSeedName : cropSeed.entrySet()) { - Block cropSeedBlock = GameRegistry.findBlock(Witch, cropSeedName.getKey()); - ItemStack cropSeedStack = GameRegistry.findItemStack(Witch, "seeds" + cropSeedName.getKey(), 1); - if (cropSeedStack != null && cropSeedBlock != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{cropSeedStack}, Fluids.SEEDOIL.getFluid(seedamount)); - Farmables.farmables.get(FarmableReference.Wheat.get()).add(new FarmableGenericCrop(cropSeedStack, cropSeedBlock, cropSeedName.getValue())); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(cropSeedBlock, cropSeedName.getValue())); - } - - } - Block artichokeBlock = GameRegistry.findBlock(Witch, "artichoke"); - Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(artichokeBlock, 4)); - - } + for (String flowerAcceptName : flowersAccept) { + Block flowerBlock = GameRegistry.findBlock(Witch, flowerAcceptName); + if (flowerBlock != null) { + FlowerManager.flowerRegistry.registerAcceptableFlower( + flowerBlock, FlowerManager.FlowerTypeVanilla, FlowerManager.FlowerTypeSnow); + } + } + for (String cropDirectName : cropDirect) { + Block cropDirectBlock = GameRegistry.findBlock(Witch, cropDirectName + "plant"); + ItemStack cropDirectStack = GameRegistry.findItemStack(Witch, cropDirectName, 1); + if (cropDirectStack != null && cropDirectBlock != null) { + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(cropDirectStack, cropDirectBlock, 5)); + Farmables.farmables + .get(FarmableReference.Orchard.get()) + .add(new FarmableBasicFruit(cropDirectBlock, 5)); + } + } + for (Map.Entry cropSeedName : cropSeed.entrySet()) { + Block cropSeedBlock = GameRegistry.findBlock(Witch, cropSeedName.getKey()); + ItemStack cropSeedStack = GameRegistry.findItemStack(Witch, "seeds" + cropSeedName.getKey(), 1); + if (cropSeedStack != null && cropSeedBlock != null) { + RecipeManagers.squeezerManager.addRecipe( + 10, new ItemStack[] {cropSeedStack}, Fluids.SEEDOIL.getFluid(seedamount)); + Farmables.farmables + .get(FarmableReference.Wheat.get()) + .add(new FarmableGenericCrop(cropSeedStack, cropSeedBlock, cropSeedName.getValue())); + Farmables.farmables + .get(FarmableReference.Orchard.get()) + .add(new FarmableBasicFruit(cropSeedBlock, cropSeedName.getValue())); + } + } + Block artichokeBlock = GameRegistry.findBlock(Witch, "artichoke"); + Farmables.farmables.get(FarmableReference.Orchard.get()).add(new FarmableBasicFruit(artichokeBlock, 4)); + } } diff --git a/src/main/java/forestry/storage/BackpackDefinition.java b/src/main/java/forestry/storage/BackpackDefinition.java index e5a7fe6b8..8e94e11a6 100755 --- a/src/main/java/forestry/storage/BackpackDefinition.java +++ b/src/main/java/forestry/storage/BackpackDefinition.java @@ -10,236 +10,234 @@ ******************************************************************************/ package forestry.storage; +import cpw.mods.fml.common.registry.GameData; +import forestry.api.apiculture.BeeManager; +import forestry.api.lepidopterology.ButterflyManager; +import forestry.api.storage.IBackpackDefinition; import java.util.HashSet; import java.util.List; import java.util.Set; - import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.StatCollector; - import net.minecraftforge.oredict.OreDictionary; -import cpw.mods.fml.common.registry.GameData; - -import forestry.api.apiculture.BeeManager; -import forestry.api.lepidopterology.ButterflyManager; -import forestry.api.storage.IBackpackDefinition; - public class BackpackDefinition implements IBackpackDefinition { - private final String name; + private final String name; - private final int primaryColor; // - c03384 - private final int secondaryColor; + private final int primaryColor; // - c03384 + private final int secondaryColor; - private final Set validItemStacks = new HashSet<>(); - private final Set validOreIds = new HashSet<>(); - private final Set validItemClasses = new HashSet<>(); - private final Set validBlockClasses = new HashSet<>(); + private final Set validItemStacks = new HashSet<>(); + private final Set validOreIds = new HashSet<>(); + private final Set validItemClasses = new HashSet<>(); + private final Set validBlockClasses = new HashSet<>(); - public BackpackDefinition(String name, int primaryColor) { - this(name, primaryColor, 0xffffff); - } + public BackpackDefinition(String name, int primaryColor) { + this(name, primaryColor, 0xffffff); + } - public BackpackDefinition(String name, int primaryColor, int secondaryColor) { - this.name = name; - this.primaryColor = primaryColor; - this.secondaryColor = secondaryColor; - } + public BackpackDefinition(String name, int primaryColor, int secondaryColor) { + this.name = name; + this.primaryColor = primaryColor; + this.secondaryColor = secondaryColor; + } - @Override - public String getKey() { - return name; - } + @Override + public String getKey() { + return name; + } - @Override - public String getName(ItemStack backpack) { - Item item = backpack.getItem(); - String display = ("" + StatCollector.translateToLocal(item.getUnlocalizedNameInefficiently(backpack) + ".name")).trim(); + @Override + public String getName(ItemStack backpack) { + Item item = backpack.getItem(); + String display = + ("" + StatCollector.translateToLocal(item.getUnlocalizedNameInefficiently(backpack) + ".name")).trim(); - if (backpack.stackTagCompound != null && backpack.stackTagCompound.hasKey("display", 10)) { - NBTTagCompound nbt = backpack.stackTagCompound.getCompoundTag("display"); + if (backpack.stackTagCompound != null && backpack.stackTagCompound.hasKey("display", 10)) { + NBTTagCompound nbt = backpack.stackTagCompound.getCompoundTag("display"); - if (nbt.hasKey("Name", 8)) { - display = nbt.getString("Name"); - } - } + if (nbt.hasKey("Name", 8)) { + display = nbt.getString("Name"); + } + } - return display; - } + return display; + } - @Override - public int getPrimaryColour() { - return primaryColor; - } + @Override + public int getPrimaryColour() { + return primaryColor; + } - @Override - public int getSecondaryColour() { - return secondaryColor; - } + @Override + public int getSecondaryColour() { + return secondaryColor; + } - @Override - public void addValidItem(ItemStack validItem) { - if (validItem == null) { - return; - } + @Override + public void addValidItem(ItemStack validItem) { + if (validItem == null) { + return; + } - Item item = validItem.getItem(); - if (item == null) { - return; - } + Item item = validItem.getItem(); + if (item == null) { + return; + } - String itemStackString = GameData.getItemRegistry().getNameForObject(item); + String itemStackString = GameData.getItemRegistry().getNameForObject(item); - int meta = validItem.getItemDamage(); - if (meta != OreDictionary.WILDCARD_VALUE) { - itemStackString = itemStackString + ':' + meta; - } + int meta = validItem.getItemDamage(); + if (meta != OreDictionary.WILDCARD_VALUE) { + itemStackString = itemStackString + ':' + meta; + } - this.validItemStacks.add(itemStackString); - } + this.validItemStacks.add(itemStackString); + } - public void clearAllValid() { - validItemStacks.clear(); - validOreIds.clear(); - } + public void clearAllValid() { + validItemStacks.clear(); + validOreIds.clear(); + } - @Override - public void addValidItems(List validItems) { - for (ItemStack validItem : validItems) { - addValidItem(validItem); - } - } + @Override + public void addValidItems(List validItems) { + for (ItemStack validItem : validItems) { + addValidItem(validItem); + } + } - public void addValidOreDictName(String oreDictName) { - // if (OreDictionary.doesOreNameExist(oreDictName)) { //TODO: add this back when using a forge version that supports it - int oreId = OreDictionary.getOreID(oreDictName); - validOreIds.add(oreId); - // } - } + public void addValidOreDictName(String oreDictName) { + // if (OreDictionary.doesOreNameExist(oreDictName)) { //TODO: add this back when using a forge version that + // supports it + int oreId = OreDictionary.getOreID(oreDictName); + validOreIds.add(oreId); + // } + } - public void addValidOreDictNames(List oreDictNames) { - for (String oreDictName : oreDictNames) { - addValidOreDictName(oreDictName); - } - } + public void addValidOreDictNames(List oreDictNames) { + for (String oreDictName : oreDictNames) { + addValidOreDictName(oreDictName); + } + } - public void addValidItemClass(Class itemClass) { - if (itemClass != null) { - validItemClasses.add(itemClass); - } - } + public void addValidItemClass(Class itemClass) { + if (itemClass != null) { + validItemClasses.add(itemClass); + } + } - public void addValidItemClasses(List itemClasses) { - for (Class itemClass : itemClasses) { - addValidItemClass(itemClass); - } - } + public void addValidItemClasses(List itemClasses) { + for (Class itemClass : itemClasses) { + addValidItemClass(itemClass); + } + } - public void addValidBlockClass(Class blockClass) { - if (blockClass != null) { - validBlockClasses.add(blockClass); - } - } + public void addValidBlockClass(Class blockClass) { + if (blockClass != null) { + validBlockClasses.add(blockClass); + } + } - public void addValidBlockClasses(List blockClasses) { - for (Class blockClass : blockClasses) { - addValidBlockClass(blockClass); - } - } + public void addValidBlockClasses(List blockClasses) { + for (Class blockClass : blockClasses) { + addValidBlockClass(blockClass); + } + } - public Set getValidItemStacks() { - return validItemStacks; - } + public Set getValidItemStacks() { + return validItemStacks; + } - public Set getValidOreIds() { - return validOreIds; - } + public Set getValidOreIds() { + return validOreIds; + } - public Set getValidBlockClasses() { - return validBlockClasses; - } + public Set getValidBlockClasses() { + return validBlockClasses; + } - public Set getValidItemClasses() { - return validItemClasses; - } + public Set getValidItemClasses() { + return validItemClasses; + } - @Override - public boolean isValidItem(ItemStack itemStack) { - if (itemStack == null) { - return false; - } + @Override + public boolean isValidItem(ItemStack itemStack) { + if (itemStack == null) { + return false; + } - Item item = itemStack.getItem(); - if (item == null) { - return false; - } + Item item = itemStack.getItem(); + if (item == null) { + return false; + } - String itemStackStringWild = GameData.getItemRegistry().getNameForObject(item); - if (validItemStacks.contains(itemStackStringWild)) { - return true; - } + String itemStackStringWild = GameData.getItemRegistry().getNameForObject(item); + if (validItemStacks.contains(itemStackStringWild)) { + return true; + } - int meta = itemStack.getItemDamage(); - if (meta != OreDictionary.WILDCARD_VALUE) { - String itemStackString = itemStackStringWild + ':' + meta; - if (validItemStacks.contains(itemStackString)) { - return true; - } - } + int meta = itemStack.getItemDamage(); + if (meta != OreDictionary.WILDCARD_VALUE) { + String itemStackString = itemStackStringWild + ':' + meta; + if (validItemStacks.contains(itemStackString)) { + return true; + } + } - int[] oreIds = OreDictionary.getOreIDs(itemStack); - for (int oreId : oreIds) { - if (validOreIds.contains(oreId)) { - validItemStacks.add(itemStackStringWild); - return true; - } - } + int[] oreIds = OreDictionary.getOreIDs(itemStack); + for (int oreId : oreIds) { + if (validOreIds.contains(oreId)) { + validItemStacks.add(itemStackStringWild); + return true; + } + } - for (Class itemClass : validItemClasses) { - if (itemClass.isInstance(item)) { - validItemStacks.add(itemStackStringWild); - return true; - } - } + for (Class itemClass : validItemClasses) { + if (itemClass.isInstance(item)) { + validItemStacks.add(itemStackStringWild); + return true; + } + } - Block block = Block.getBlockFromItem(item); - if (block != null) { - for (Class blockClass : validBlockClasses) { - if (blockClass.isInstance(block)) { - validItemStacks.add(itemStackStringWild); - return true; - } - } - } + Block block = Block.getBlockFromItem(item); + if (block != null) { + for (Class blockClass : validBlockClasses) { + if (blockClass.isInstance(block)) { + validItemStacks.add(itemStackStringWild); + return true; + } + } + } - return false; - } + return false; + } - public static class BackpackDefinitionApiarist extends BackpackDefinition { + public static class BackpackDefinitionApiarist extends BackpackDefinition { - public BackpackDefinitionApiarist(int primaryColor) { - super("apiarist", primaryColor); - } + public BackpackDefinitionApiarist(int primaryColor) { + super("apiarist", primaryColor); + } - @Override - public boolean isValidItem(ItemStack itemStack) { - return BeeManager.beeRoot.isMember(itemStack); - } - } + @Override + public boolean isValidItem(ItemStack itemStack) { + return BeeManager.beeRoot.isMember(itemStack); + } + } - public static class BackpackDefinitionLepidopterist extends BackpackDefinition { + public static class BackpackDefinitionLepidopterist extends BackpackDefinition { - public BackpackDefinitionLepidopterist(int primaryColor) { - super("lepidopterist", primaryColor); - } + public BackpackDefinitionLepidopterist(int primaryColor) { + super("lepidopterist", primaryColor); + } - @Override - public boolean isValidItem(ItemStack itemStack) { - return ButterflyManager.butterflyRoot.isMember(itemStack); - } - } + @Override + public boolean isValidItem(ItemStack itemStack) { + return ButterflyManager.butterflyRoot.isMember(itemStack); + } + } } diff --git a/src/main/java/forestry/storage/BackpackInterface.java b/src/main/java/forestry/storage/BackpackInterface.java index 6a0e0dc69..1bdde9834 100644 --- a/src/main/java/forestry/storage/BackpackInterface.java +++ b/src/main/java/forestry/storage/BackpackInterface.java @@ -10,18 +10,17 @@ ******************************************************************************/ package forestry.storage; -import net.minecraft.item.Item; - import forestry.api.storage.BackpackManager; import forestry.api.storage.EnumBackpackType; import forestry.api.storage.IBackpackDefinition; import forestry.api.storage.IBackpackInterface; import forestry.storage.items.ItemBackpack; +import net.minecraft.item.Item; public class BackpackInterface implements IBackpackInterface { - @Override - public Item addBackpack(IBackpackDefinition definition, EnumBackpackType type) { - BackpackManager.definitions.put(definition.getKey(), definition); - return new ItemBackpack(definition, type); - } + @Override + public Item addBackpack(IBackpackDefinition definition, EnumBackpackType type) { + BackpackManager.definitions.put(definition.getKey(), definition); + return new ItemBackpack(definition, type); + } } diff --git a/src/main/java/forestry/storage/BackpackMode.java b/src/main/java/forestry/storage/BackpackMode.java index 267d61233..2d2204826 100755 --- a/src/main/java/forestry/storage/BackpackMode.java +++ b/src/main/java/forestry/storage/BackpackMode.java @@ -11,5 +11,8 @@ package forestry.storage; public enum BackpackMode { - NORMAL, LOCKED, RECEIVE, RESUPPLY + NORMAL, + LOCKED, + RECEIVE, + RESUPPLY } diff --git a/src/main/java/forestry/storage/CrateRegistry.java b/src/main/java/forestry/storage/CrateRegistry.java index ba3bdf43d..b7a92fcd3 100644 --- a/src/main/java/forestry/storage/CrateRegistry.java +++ b/src/main/java/forestry/storage/CrateRegistry.java @@ -1,73 +1,71 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.storage; - -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import cpw.mods.fml.common.registry.GameRegistry; - -import forestry.api.storage.ICrateRegistry; -import forestry.core.items.ItemCrated; -import forestry.core.utils.Log; -import forestry.core.utils.StringUtil; -import forestry.plugins.PluginStorage; - -public class CrateRegistry implements ICrateRegistry { - - private static void registerCrate(ItemStack stack, String uid, boolean useOreDict) { - if (stack == null || stack.getItem() == null) { - Log.severe("Tried to make a crate without an item"); - return; - } - - if (uid == null) { - Log.severe("Tried to make a crate without a uid"); - return; - } - - ItemCrated crate = new ItemCrated(stack, useOreDict); - crate.setUnlocalizedName(uid); - GameRegistry.registerItem(crate, StringUtil.cleanItemName(crate)); - PluginStorage.registerCrate(crate); - } - - @Override - public void registerCrate(Item item, String uid) { - registerCrate(new ItemStack(item), uid, false); - } - - @Override - public void registerCrateUsingOreDict(Item item, String uid) { - registerCrate(new ItemStack(item), uid, true); - } - - @Override - public void registerCrate(Block block, String uid) { - registerCrate(new ItemStack(block), uid, false); - } - - @Override - public void registerCrateUsingOreDict(Block block, String uid) { - registerCrate(new ItemStack(block), uid, true); - } - - @Override - public void registerCrate(ItemStack stack, String uid) { - registerCrate(stack, uid, false); - } - - @Override - public void registerCrateUsingOreDict(ItemStack stack, String uid) { - registerCrate(stack, uid, true); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.storage; + +import cpw.mods.fml.common.registry.GameRegistry; +import forestry.api.storage.ICrateRegistry; +import forestry.core.items.ItemCrated; +import forestry.core.utils.Log; +import forestry.core.utils.StringUtil; +import forestry.plugins.PluginStorage; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +public class CrateRegistry implements ICrateRegistry { + + private static void registerCrate(ItemStack stack, String uid, boolean useOreDict) { + if (stack == null || stack.getItem() == null) { + Log.severe("Tried to make a crate without an item"); + return; + } + + if (uid == null) { + Log.severe("Tried to make a crate without a uid"); + return; + } + + ItemCrated crate = new ItemCrated(stack, useOreDict); + crate.setUnlocalizedName(uid); + GameRegistry.registerItem(crate, StringUtil.cleanItemName(crate)); + PluginStorage.registerCrate(crate); + } + + @Override + public void registerCrate(Item item, String uid) { + registerCrate(new ItemStack(item), uid, false); + } + + @Override + public void registerCrateUsingOreDict(Item item, String uid) { + registerCrate(new ItemStack(item), uid, true); + } + + @Override + public void registerCrate(Block block, String uid) { + registerCrate(new ItemStack(block), uid, false); + } + + @Override + public void registerCrateUsingOreDict(Block block, String uid) { + registerCrate(new ItemStack(block), uid, true); + } + + @Override + public void registerCrate(ItemStack stack, String uid) { + registerCrate(stack, uid, false); + } + + @Override + public void registerCrateUsingOreDict(ItemStack stack, String uid) { + registerCrate(stack, uid, true); + } +} diff --git a/src/main/java/forestry/storage/PickupHandlerStorage.java b/src/main/java/forestry/storage/PickupHandlerStorage.java index f1d688ea8..a4f37bf86 100755 --- a/src/main/java/forestry/storage/PickupHandlerStorage.java +++ b/src/main/java/forestry/storage/PickupHandlerStorage.java @@ -10,94 +10,92 @@ ******************************************************************************/ package forestry.storage; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - import forestry.api.storage.IBackpackDefinition; import forestry.core.IPickupHandler; import forestry.storage.gui.ContainerBackpack; import forestry.storage.gui.ContainerNaturalistBackpack; import forestry.storage.items.ItemBackpack; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; public class PickupHandlerStorage implements IPickupHandler { - @Override - public boolean onItemPickup(EntityPlayer player, EntityItem entityitem) { + @Override + public boolean onItemPickup(EntityPlayer player, EntityItem entityitem) { - ItemStack itemstack = entityitem.getEntityItem(); - if (itemstack == null || itemstack.stackSize <= 0) { - return false; - } + ItemStack itemstack = entityitem.getEntityItem(); + if (itemstack == null || itemstack.stackSize <= 0) { + return false; + } - // Do not pick up if a backpack is open - if (player.openContainer instanceof ContainerBackpack || player.openContainer instanceof ContainerNaturalistBackpack) { - return false; - } + // Do not pick up if a backpack is open + if (player.openContainer instanceof ContainerBackpack + || player.openContainer instanceof ContainerNaturalistBackpack) { + return false; + } - // Make sure to top off manually placed itemstacks in player inventory first - topOffPlayerInventory(player, itemstack); + // Make sure to top off manually placed itemstacks in player inventory first + topOffPlayerInventory(player, itemstack); - for (ItemStack pack : player.inventory.mainInventory) { + for (ItemStack pack : player.inventory.mainInventory) { - if (pack == null || pack.stackSize <= 0) { - continue; - } + if (pack == null || pack.stackSize <= 0) { + continue; + } - if (itemstack.stackSize <= 0) { - break; - } + if (itemstack.stackSize <= 0) { + break; + } - if (!(pack.getItem() instanceof ItemBackpack)) { - continue; - } + if (!(pack.getItem() instanceof ItemBackpack)) { + continue; + } - ItemBackpack backpack = ((ItemBackpack) pack.getItem()); - IBackpackDefinition backpackDefinition = backpack.getDefinition(); - if (backpackDefinition.isValidItem(itemstack)) { - ItemBackpack.tryStowing(player, pack, itemstack); - } - } + ItemBackpack backpack = ((ItemBackpack) pack.getItem()); + IBackpackDefinition backpackDefinition = backpack.getDefinition(); + if (backpackDefinition.isValidItem(itemstack)) { + ItemBackpack.tryStowing(player, pack, itemstack); + } + } - return itemstack.stackSize == 0; - } + return itemstack.stackSize == 0; + } - /** - * This tops off existing stacks in the player's inventory. That way you can keep f.e. a stack of dirt or cobblestone in your inventory which gets refreshed - * constantly by picked up items. - */ - private static void topOffPlayerInventory(EntityPlayer player, ItemStack itemstack) { + /** + * This tops off existing stacks in the player's inventory. That way you can keep f.e. a stack of dirt or cobblestone in your inventory which gets refreshed + * constantly by picked up items. + */ + private static void topOffPlayerInventory(EntityPlayer player, ItemStack itemstack) { - // Add to player inventory first, if there is an incomplete stack in - // there. - for (int i = 0; i < player.inventory.getSizeInventory(); i++) { - ItemStack inventoryStack = player.inventory.getStackInSlot(i); - // We only add to existing stacks. - if (inventoryStack == null) { - continue; - } + // Add to player inventory first, if there is an incomplete stack in + // there. + for (int i = 0; i < player.inventory.getSizeInventory(); i++) { + ItemStack inventoryStack = player.inventory.getStackInSlot(i); + // We only add to existing stacks. + if (inventoryStack == null) { + continue; + } - // Already full - if (inventoryStack.stackSize >= inventoryStack.getMaxStackSize()) { - continue; - } + // Already full + if (inventoryStack.stackSize >= inventoryStack.getMaxStackSize()) { + continue; + } - if (inventoryStack.isItemEqual(itemstack) && ItemStack.areItemStackTagsEqual(inventoryStack, itemstack)) { - int space = inventoryStack.getMaxStackSize() - inventoryStack.stackSize; - - // Enough space to add all - if (space > itemstack.stackSize) { - inventoryStack.stackSize += itemstack.stackSize; - itemstack.stackSize = 0; - break; - // Only part can be added - } else { - inventoryStack.stackSize = inventoryStack.getMaxStackSize(); - itemstack.stackSize -= space; - } - } - } - - } + if (inventoryStack.isItemEqual(itemstack) && ItemStack.areItemStackTagsEqual(inventoryStack, itemstack)) { + int space = inventoryStack.getMaxStackSize() - inventoryStack.stackSize; + // Enough space to add all + if (space > itemstack.stackSize) { + inventoryStack.stackSize += itemstack.stackSize; + itemstack.stackSize = 0; + break; + // Only part can be added + } else { + inventoryStack.stackSize = inventoryStack.getMaxStackSize(); + itemstack.stackSize -= space; + } + } + } + } } diff --git a/src/main/java/forestry/storage/ResupplyHandler.java b/src/main/java/forestry/storage/ResupplyHandler.java index 70988e6b4..9f8d5ab4a 100755 --- a/src/main/java/forestry/storage/ResupplyHandler.java +++ b/src/main/java/forestry/storage/ResupplyHandler.java @@ -10,112 +10,107 @@ ******************************************************************************/ package forestry.storage; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.ContainerPlayer; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.common.MinecraftForge; - import cpw.mods.fml.common.eventhandler.Event; - import forestry.api.storage.BackpackResupplyEvent; import forestry.core.IResupplyHandler; import forestry.core.inventory.ItemInventory; import forestry.storage.inventory.ItemInventoryBackpack; import forestry.storage.items.ItemBackpack; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.ContainerPlayer; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.MinecraftForge; public class ResupplyHandler implements IResupplyHandler { - private static List backpacks(InventoryPlayer playerInventory) { - List backpacks = new ArrayList<>(); - for (ItemStack itemStack : playerInventory.mainInventory) { - if (itemStack != null && itemStack.stackSize > 0 && (itemStack.getItem() instanceof ItemBackpack)) { - backpacks.add(itemStack); - } - } - return backpacks; - } + private static List backpacks(InventoryPlayer playerInventory) { + List backpacks = new ArrayList<>(); + for (ItemStack itemStack : playerInventory.mainInventory) { + if (itemStack != null && itemStack.stackSize > 0 && (itemStack.getItem() instanceof ItemBackpack)) { + backpacks.add(itemStack); + } + } + return backpacks; + } - @Override - public void resupply(EntityPlayer player) { + @Override + public void resupply(EntityPlayer player) { - // Do not attempt resupplying if this backpack is already opened. - if (!(player.openContainer instanceof ContainerPlayer)) { - return; - } + // Do not attempt resupplying if this backpack is already opened. + if (!(player.openContainer instanceof ContainerPlayer)) { + return; + } - for (ItemStack backpack : backpacks(player.inventory)) { + for (ItemStack backpack : backpacks(player.inventory)) { - // Only handle those in resupply mode - if (ItemBackpack.getMode(backpack) != BackpackMode.RESUPPLY) { - continue; - } + // Only handle those in resupply mode + if (ItemBackpack.getMode(backpack) != BackpackMode.RESUPPLY) { + continue; + } - // Delay before resupplying - if (backpack.getItemDamage() < 40) { - backpack.setItemDamage(backpack.getItemDamage() + 1); - continue; - } + // Delay before resupplying + if (backpack.getItemDamage() < 40) { + backpack.setItemDamage(backpack.getItemDamage() + 1); + continue; + } - // Load their inventory - ItemBackpack backpackItem = ((ItemBackpack) backpack.getItem()); - ItemInventory backpackInventory = new ItemInventoryBackpack(player, backpackItem.getBackpackSize(), backpack); + // Load their inventory + ItemBackpack backpackItem = ((ItemBackpack) backpack.getItem()); + ItemInventory backpackInventory = + new ItemInventoryBackpack(player, backpackItem.getBackpackSize(), backpack); - Event event = new BackpackResupplyEvent(player, backpackItem.getDefinition(), backpackInventory); - MinecraftForge.EVENT_BUS.post(event); - if (event.isCanceled()) { - continue; - } + Event event = new BackpackResupplyEvent(player, backpackItem.getDefinition(), backpackInventory); + MinecraftForge.EVENT_BUS.post(event); + if (event.isCanceled()) { + continue; + } - // Cycle through their contents - for (int i = 0; i < backpackInventory.getSizeInventory(); i++) { + // Cycle through their contents + for (int i = 0; i < backpackInventory.getSizeInventory(); i++) { - ItemStack itemStack = backpackInventory.getStackInSlot(i); - if (itemStack == null || itemStack.stackSize <= 0) { - continue; - } + ItemStack itemStack = backpackInventory.getStackInSlot(i); + if (itemStack == null || itemStack.stackSize <= 0) { + continue; + } - // Try to add it to the player's inventory and note any change - boolean change = topOffPlayerInventory(player, itemStack); + // Try to add it to the player's inventory and note any change + boolean change = topOffPlayerInventory(player, itemStack); - if (change) { - backpackInventory.setInventorySlotContents(i, itemStack); - } - } - } - } + if (change) { + backpackInventory.setInventorySlotContents(i, itemStack); + } + } + } + } - /** - * This tops off existing stacks in the player's inventory. - */ - private static boolean topOffPlayerInventory(EntityPlayer player, ItemStack itemstack) { + /** + * This tops off existing stacks in the player's inventory. + */ + private static boolean topOffPlayerInventory(EntityPlayer player, ItemStack itemstack) { - // Add to player inventory first, if there is an incomplete stack in - // there. - for (int i = 0; i < player.inventory.getSizeInventory(); i++) { - ItemStack inventoryStack = player.inventory.getStackInSlot(i); - // We only add to existing stacks. - if (inventoryStack == null) { - continue; - } + // Add to player inventory first, if there is an incomplete stack in + // there. + for (int i = 0; i < player.inventory.getSizeInventory(); i++) { + ItemStack inventoryStack = player.inventory.getStackInSlot(i); + // We only add to existing stacks. + if (inventoryStack == null) { + continue; + } - // Already full - if (inventoryStack.stackSize >= inventoryStack.getMaxStackSize()) { - continue; - } - - if (inventoryStack.isItemEqual(itemstack) && ItemStack.areItemStackTagsEqual(inventoryStack, itemstack)) { - inventoryStack.stackSize++; - itemstack.stackSize--; - return true; - } - } - return false; - - } + // Already full + if (inventoryStack.stackSize >= inventoryStack.getMaxStackSize()) { + continue; + } + if (inventoryStack.isItemEqual(itemstack) && ItemStack.areItemStackTagsEqual(inventoryStack, itemstack)) { + inventoryStack.stackSize++; + itemstack.stackSize--; + return true; + } + } + return false; + } } diff --git a/src/main/java/forestry/storage/gui/ContainerBackpack.java b/src/main/java/forestry/storage/gui/ContainerBackpack.java index 196ca6c0b..1350384f0 100755 --- a/src/main/java/forestry/storage/gui/ContainerBackpack.java +++ b/src/main/java/forestry/storage/gui/ContainerBackpack.java @@ -10,45 +10,49 @@ ******************************************************************************/ package forestry.storage.gui; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.slots.SlotFilteredInventory; import forestry.storage.inventory.ItemInventoryBackpack; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; public class ContainerBackpack extends ContainerItemInventory { - public enum Size { - DEFAULT(3, 5, 44, 19), - T2(5, 9, 8, 8); + public enum Size { + DEFAULT(3, 5, 44, 19), + T2(5, 9, 8, 8); - final int rows; - final int columns; - final int startX; - final int startY; + final int rows; + final int columns; + final int startX; + final int startY; - Size(int rows, int columns, int startX, int startY) { - this.rows = rows; - this.columns = columns; - this.startX = startX; - this.startY = startY; - } + Size(int rows, int columns, int startX, int startY) { + this.rows = rows; + this.columns = columns; + this.startX = startX; + this.startY = startY; + } - public int getSize() { - return rows * columns; - } - } + public int getSize() { + return rows * columns; + } + } - public ContainerBackpack(EntityPlayer player, Size size, ItemStack parent) { - super(new ItemInventoryBackpack(player, size.getSize(), parent), player.inventory, 8, 11 + size.startY + size.rows * 18); + public ContainerBackpack(EntityPlayer player, Size size, ItemStack parent) { + super( + new ItemInventoryBackpack(player, size.getSize(), parent), + player.inventory, + 8, + 11 + size.startY + size.rows * 18); - // Inventory - for (int j = 0; j < size.rows; j++) { - for (int k = 0; k < size.columns; k++) { - int slot = k + j * size.columns; - addSlotToContainer(new SlotFilteredInventory(inventory, slot, size.startX + k * 18, size.startY + j * 18)); - } - } - } + // Inventory + for (int j = 0; j < size.rows; j++) { + for (int k = 0; k < size.columns; k++) { + int slot = k + j * size.columns; + addSlotToContainer( + new SlotFilteredInventory(inventory, slot, size.startX + k * 18, size.startY + j * 18)); + } + } + } } diff --git a/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java b/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java index 69e1ce44f..439e25bcd 100755 --- a/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java +++ b/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java @@ -10,25 +10,25 @@ ******************************************************************************/ package forestry.storage.gui; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; - import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.ContainerNaturalistInventory; import forestry.core.gui.IGuiSelectable; import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.storage.inventory.ItemInventoryBackpackPaged; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; -public class ContainerNaturalistBackpack extends ContainerItemInventory implements IGuiSelectable { +public class ContainerNaturalistBackpack extends ContainerItemInventory + implements IGuiSelectable { - public ContainerNaturalistBackpack(EntityPlayer player, ItemInventoryBackpackPaged inventory, int selectedPage) { - super(inventory, player.inventory, 18, 120); + public ContainerNaturalistBackpack(EntityPlayer player, ItemInventoryBackpackPaged inventory, int selectedPage) { + super(inventory, player.inventory, 18, 120); - ContainerNaturalistInventory.addInventory(this, inventory, selectedPage); - } + ContainerNaturalistInventory.addInventory(this, inventory, selectedPage); + } - @Override - public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { - inventory.flipPage(player, (short) packet.getPrimaryIndex()); - } + @Override + public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { + inventory.flipPage(player, (short) packet.getPrimaryIndex()); + } } diff --git a/src/main/java/forestry/storage/gui/GuiBackpack.java b/src/main/java/forestry/storage/gui/GuiBackpack.java index b0557120d..18d27b31c 100755 --- a/src/main/java/forestry/storage/gui/GuiBackpack.java +++ b/src/main/java/forestry/storage/gui/GuiBackpack.java @@ -10,18 +10,17 @@ ******************************************************************************/ package forestry.storage.gui; -import net.minecraft.inventory.IInventory; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestry; +import net.minecraft.inventory.IInventory; public class GuiBackpack extends GuiForestry { - public GuiBackpack(ContainerBackpack container) { - this(Constants.TEXTURE_PATH_GUI + "/backpack.png", container); - } + public GuiBackpack(ContainerBackpack container) { + this(Constants.TEXTURE_PATH_GUI + "/backpack.png", container); + } - protected GuiBackpack(String texture, ContainerBackpack container) { - super(texture, container, null); - } + protected GuiBackpack(String texture, ContainerBackpack container) { + super(texture, container, null); + } } diff --git a/src/main/java/forestry/storage/gui/GuiBackpackT2.java b/src/main/java/forestry/storage/gui/GuiBackpackT2.java index 89317a4ae..1e21a0379 100755 --- a/src/main/java/forestry/storage/gui/GuiBackpackT2.java +++ b/src/main/java/forestry/storage/gui/GuiBackpackT2.java @@ -14,10 +14,10 @@ import forestry.core.config.Constants; public class GuiBackpackT2 extends GuiBackpack { - public GuiBackpackT2(ContainerBackpack container) { - super(Constants.TEXTURE_PATH_GUI + "/backpackT2.png", container); + public GuiBackpackT2(ContainerBackpack container) { + super(Constants.TEXTURE_PATH_GUI + "/backpackT2.png", container); - xSize = 176; - ySize = 192; - } + xSize = 176; + ySize = 192; + } } diff --git a/src/main/java/forestry/storage/inventory/ItemInventoryBackpack.java b/src/main/java/forestry/storage/inventory/ItemInventoryBackpack.java index b90fa600b..5bc7a6d61 100644 --- a/src/main/java/forestry/storage/inventory/ItemInventoryBackpack.java +++ b/src/main/java/forestry/storage/inventory/ItemInventoryBackpack.java @@ -1,38 +1,37 @@ -package forestry.storage.inventory; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import forestry.api.storage.IBackpackDefinition; -import forestry.core.inventory.ItemInventory; -import forestry.storage.items.ItemBackpack; - -public class ItemInventoryBackpack extends ItemInventory { - - private final IBackpackDefinition backpackDefinition; - - public ItemInventoryBackpack(EntityPlayer player, int size, ItemStack parent) { - super(player, size, parent); - - if (parent == null) { - throw new IllegalArgumentException("Parent cannot be null."); - } - - Item item = parent.getItem(); - if (!(item instanceof ItemBackpack)) { - throw new IllegalArgumentException("Parent must be a backpack."); - } - - this.backpackDefinition = ((ItemBackpack) item).getDefinition(); - - if (this.backpackDefinition == null) { - throw new IllegalArgumentException("Backpack must have a backpack definition."); - } - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return backpackDefinition.isValidItem(itemStack); - } -} +package forestry.storage.inventory; + +import forestry.api.storage.IBackpackDefinition; +import forestry.core.inventory.ItemInventory; +import forestry.storage.items.ItemBackpack; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +public class ItemInventoryBackpack extends ItemInventory { + + private final IBackpackDefinition backpackDefinition; + + public ItemInventoryBackpack(EntityPlayer player, int size, ItemStack parent) { + super(player, size, parent); + + if (parent == null) { + throw new IllegalArgumentException("Parent cannot be null."); + } + + Item item = parent.getItem(); + if (!(item instanceof ItemBackpack)) { + throw new IllegalArgumentException("Parent must be a backpack."); + } + + this.backpackDefinition = ((ItemBackpack) item).getDefinition(); + + if (this.backpackDefinition == null) { + throw new IllegalArgumentException("Backpack must have a backpack definition."); + } + } + + @Override + public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return backpackDefinition.isValidItem(itemStack); + } +} diff --git a/src/main/java/forestry/storage/inventory/ItemInventoryBackpackPaged.java b/src/main/java/forestry/storage/inventory/ItemInventoryBackpackPaged.java index cf357fc2a..3176bc557 100644 --- a/src/main/java/forestry/storage/inventory/ItemInventoryBackpackPaged.java +++ b/src/main/java/forestry/storage/inventory/ItemInventoryBackpackPaged.java @@ -1,32 +1,32 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.storage.inventory; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.core.gui.GuiHandler; -import forestry.core.gui.IPagedInventory; -import forestry.storage.items.ItemBackpackNaturalist; - -public class ItemInventoryBackpackPaged extends ItemInventoryBackpack implements IPagedInventory { - private final ItemBackpackNaturalist backpackNaturalist; - - public ItemInventoryBackpackPaged(EntityPlayer player, int size, ItemStack itemstack, ItemBackpackNaturalist backpackNaturalist) { - super(player, size, itemstack); - this.backpackNaturalist = backpackNaturalist; - } - - @Override - public void flipPage(EntityPlayer player, short page) { - GuiHandler.openGui(player, backpackNaturalist, page); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.storage.inventory; + +import forestry.core.gui.GuiHandler; +import forestry.core.gui.IPagedInventory; +import forestry.storage.items.ItemBackpackNaturalist; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class ItemInventoryBackpackPaged extends ItemInventoryBackpack implements IPagedInventory { + private final ItemBackpackNaturalist backpackNaturalist; + + public ItemInventoryBackpackPaged( + EntityPlayer player, int size, ItemStack itemstack, ItemBackpackNaturalist backpackNaturalist) { + super(player, size, itemstack); + this.backpackNaturalist = backpackNaturalist; + } + + @Override + public void flipPage(EntityPlayer player, short page) { + GuiHandler.openGui(player, backpackNaturalist, page); + } +} diff --git a/src/main/java/forestry/storage/items/ItemBackpack.java b/src/main/java/forestry/storage/items/ItemBackpack.java index 9bdcea510..45a237088 100755 --- a/src/main/java/forestry/storage/items/ItemBackpack.java +++ b/src/main/java/forestry/storage/items/ItemBackpack.java @@ -10,24 +10,9 @@ ******************************************************************************/ package forestry.storage.items; -import java.util.List; -import java.util.Locale; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.IIcon; -import net.minecraft.world.World; - -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.util.ForgeDirection; - import cpw.mods.fml.common.eventhandler.Event; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import forestry.api.storage.BackpackStowEvent; import forestry.api.storage.EnumBackpackType; import forestry.api.storage.IBackpackDefinition; @@ -47,303 +32,335 @@ import forestry.storage.gui.ContainerBackpack; import forestry.storage.gui.GuiBackpack; import forestry.storage.gui.GuiBackpackT2; import forestry.storage.inventory.ItemInventoryBackpack; +import java.util.List; +import java.util.Locale; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.ForgeDirection; public class ItemBackpack extends ItemWithGui { - private final IBackpackDefinition definition; - private final EnumBackpackType type; + private final IBackpackDefinition definition; + private final EnumBackpackType type; - public ItemBackpack(IBackpackDefinition definition, EnumBackpackType type) { - this.definition = definition; - this.type = type; - } + public ItemBackpack(IBackpackDefinition definition, EnumBackpackType type) { + this.definition = definition; + this.type = type; + } - public IBackpackDefinition getDefinition() { - return definition; - } + public IBackpackDefinition getDefinition() { + return definition; + } - @Override - public boolean getShareTag() { - return true; - } + @Override + public boolean getShareTag() { + return true; + } - @Override - protected void openGui(EntityPlayer entityplayer) { - GuiHandler.openGui(entityplayer, this, (short) type.ordinal()); - } + @Override + protected void openGui(EntityPlayer entityplayer) { + GuiHandler.openGui(entityplayer, this, (short) type.ordinal()); + } - @Override - public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer player) { - if (!world.isRemote) { - if (!player.isSneaking()) { - openGui(player); - } else { - switchMode(itemstack); - } - } + @Override + public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer player) { + if (!world.isRemote) { + if (!player.isSneaking()) { + openGui(player); + } else { + switchMode(itemstack); + } + } - return itemstack; - } + return itemstack; + } - @Override - public boolean onItemUse(ItemStack itemstack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { - return getInventoryHit(world, x, y, z, side) != null; - } + @Override + public boolean onItemUse( + ItemStack itemstack, + EntityPlayer player, + World world, + int x, + int y, + int z, + int side, + float hitX, + float hitY, + float hitZ) { + return getInventoryHit(world, x, y, z, side) != null; + } - @Override - public boolean onItemUseFirst(ItemStack itemstack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { + @Override + public boolean onItemUseFirst( + ItemStack itemstack, + EntityPlayer player, + World world, + int x, + int y, + int z, + int side, + float hitX, + float hitY, + float hitZ) { - if (world.isRemote) { - return false; - } + if (world.isRemote) { + return false; + } - // We only do this when shift is clicked - if (!player.isSneaking()) { - return false; - } + // We only do this when shift is clicked + if (!player.isSneaking()) { + return false; + } - return evaluateTileHit(itemstack, player, world, x, y, z, side); - } + return evaluateTileHit(itemstack, player, world, x, y, z, side); + } - public static ItemStack tryStowing(EntityPlayer player, ItemStack backpackStack, ItemStack stack) { + public static ItemStack tryStowing(EntityPlayer player, ItemStack backpackStack, ItemStack stack) { - ItemBackpack backpack = ((ItemBackpack) backpackStack.getItem()); - ItemInventory inventory = new ItemInventoryBackpack(player, backpack.getBackpackSize(), backpackStack); - if (backpackStack.getItemDamage() == 1) { - return stack; - } + ItemBackpack backpack = ((ItemBackpack) backpackStack.getItem()); + ItemInventory inventory = new ItemInventoryBackpack(player, backpack.getBackpackSize(), backpackStack); + if (backpackStack.getItemDamage() == 1) { + return stack; + } - Event event = new BackpackStowEvent(player, backpack.getDefinition(), inventory, stack); - MinecraftForge.EVENT_BUS.post(event); - if (stack.stackSize <= 0) { - return null; - } - if (event.isCanceled()) { - return stack; - } + Event event = new BackpackStowEvent(player, backpack.getDefinition(), inventory, stack); + MinecraftForge.EVENT_BUS.post(event); + if (stack.stackSize <= 0) { + return null; + } + if (event.isCanceled()) { + return stack; + } - ItemStack remainder = InventoryUtil.moveItemStack(stack, inventory); - stack.stackSize = remainder == null ? 0 : remainder.stackSize; + ItemStack remainder = InventoryUtil.moveItemStack(stack, inventory); + stack.stackSize = remainder == null ? 0 : remainder.stackSize; - return null; - } + return null; + } - private static void switchMode(ItemStack itemstack) { - BackpackMode mode = getMode(itemstack); - int nextMode = mode.ordinal() + 1; - if (!Config.enableBackpackResupply && nextMode == BackpackMode.RESUPPLY.ordinal()) { - nextMode++; - } - nextMode %= BackpackMode.values().length; - itemstack.setItemDamage(nextMode); - } + private static void switchMode(ItemStack itemstack) { + BackpackMode mode = getMode(itemstack); + int nextMode = mode.ordinal() + 1; + if (!Config.enableBackpackResupply && nextMode == BackpackMode.RESUPPLY.ordinal()) { + nextMode++; + } + nextMode %= BackpackMode.values().length; + itemstack.setItemDamage(nextMode); + } - private static IInventory getInventoryHit(World world, int x, int y, int z, int side) { - TileEntity targeted = world.getTileEntity(x, y, z); - return TileUtil.getInventoryFromTile(targeted, ForgeDirection.getOrientation(side)); - } + private static IInventory getInventoryHit(World world, int x, int y, int z, int side) { + TileEntity targeted = world.getTileEntity(x, y, z); + return TileUtil.getInventoryFromTile(targeted, ForgeDirection.getOrientation(side)); + } - private boolean evaluateTileHit(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side) { + private boolean evaluateTileHit(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side) { - // Shift right-clicking on an inventory tile will attempt to transfer - // items contained in the backpack - IInventory inventory = getInventoryHit(world, x, y, z, side); - // Process only inventories - if (inventory != null) { + // Shift right-clicking on an inventory tile will attempt to transfer + // items contained in the backpack + IInventory inventory = getInventoryHit(world, x, y, z, side); + // Process only inventories + if (inventory != null) { - // Must have inventory slots - if (inventory.getSizeInventory() <= 0) { - return true; - } + // Must have inventory slots + if (inventory.getSizeInventory() <= 0) { + return true; + } - // Create our own backpack inventory - ItemInventoryBackpack backpackInventory = new ItemInventoryBackpack(player, getBackpackSize(), stack); + // Create our own backpack inventory + ItemInventoryBackpack backpackInventory = new ItemInventoryBackpack(player, getBackpackSize(), stack); - BackpackMode mode = getMode(stack); - if (mode == BackpackMode.RECEIVE) { - tryChestReceive(backpackInventory, inventory); - } else { - tryChestTransfer(backpackInventory, inventory); - } + BackpackMode mode = getMode(stack); + if (mode == BackpackMode.RECEIVE) { + tryChestReceive(backpackInventory, inventory); + } else { + tryChestTransfer(backpackInventory, inventory); + } - return true; - } + return true; + } - return false; - } + return false; + } - private static void tryChestTransfer(ItemInventoryBackpack backpackInventory, IInventory target) { + private static void tryChestTransfer(ItemInventoryBackpack backpackInventory, IInventory target) { - for (IInvSlot slot : InventoryIterator.getIterable(backpackInventory)) { - ItemStack packStack = slot.getStackInSlot(); - if (packStack == null) { - continue; - } + for (IInvSlot slot : InventoryIterator.getIterable(backpackInventory)) { + ItemStack packStack = slot.getStackInSlot(); + if (packStack == null) { + continue; + } - ItemStack remaining = InventoryUtil.moveItemStack(packStack, target); - slot.setStackInSlot(remaining); - } - } + ItemStack remaining = InventoryUtil.moveItemStack(packStack, target); + slot.setStackInSlot(remaining); + } + } - private void tryChestReceive(ItemInventoryBackpack backpackInventory, IInventory target) { + private void tryChestReceive(ItemInventoryBackpack backpackInventory, IInventory target) { - for (IInvSlot slot : InventoryIterator.getIterable(target)) { - ItemStack targetStack = slot.getStackInSlot(); - if (targetStack == null) { - continue; - } + for (IInvSlot slot : InventoryIterator.getIterable(target)) { + ItemStack targetStack = slot.getStackInSlot(); + if (targetStack == null) { + continue; + } - if (!definition.isValidItem(targetStack)) { - continue; - } + if (!definition.isValidItem(targetStack)) { + continue; + } - ItemStack remaining = InventoryUtil.moveItemStack(targetStack, backpackInventory); - slot.setStackInSlot(remaining); - } - } + ItemStack remaining = InventoryUtil.moveItemStack(targetStack, backpackInventory); + slot.setStackInSlot(remaining); + } + } - public int getBackpackSize() { - return getSlotsForType(type); - } + public int getBackpackSize() { + return getSlotsForType(type); + } - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { - int occupied = ItemInventory.getOccupiedSlotCount(itemstack); + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { + int occupied = ItemInventory.getOccupiedSlotCount(itemstack); - BackpackMode mode = getMode(itemstack); - if (mode == BackpackMode.LOCKED) { - list.add(StringUtil.localize("storage.backpack.mode.locked")); - } else if (mode == BackpackMode.RECEIVE) { - list.add(StringUtil.localize("storage.backpack.mode.receiving")); - } else if (mode == BackpackMode.RESUPPLY) { - list.add(StringUtil.localize("storage.backpack.mode.resupply")); - } - list.add(StringUtil.localize("gui.slots").replaceAll("%USED", String.valueOf(occupied)).replaceAll("%SIZE", String.valueOf(getBackpackSize()))); + BackpackMode mode = getMode(itemstack); + if (mode == BackpackMode.LOCKED) { + list.add(StringUtil.localize("storage.backpack.mode.locked")); + } else if (mode == BackpackMode.RECEIVE) { + list.add(StringUtil.localize("storage.backpack.mode.receiving")); + } else if (mode == BackpackMode.RESUPPLY) { + list.add(StringUtil.localize("storage.backpack.mode.resupply")); + } + list.add(StringUtil.localize("gui.slots") + .replaceAll("%USED", String.valueOf(occupied)) + .replaceAll("%SIZE", String.valueOf(getBackpackSize()))); + } - } + @Override + public String getItemStackDisplayName(ItemStack itemstack) { + return definition.getName(itemstack); + } - @Override - public String getItemStackDisplayName(ItemStack itemstack) { - return definition.getName(itemstack); - } + /* ICONS */ + @SideOnly(Side.CLIENT) + private IIcon[] icons; - /* ICONS */ - @SideOnly(Side.CLIENT) - private IIcon[] icons; + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) { + icons = new IIcon[6]; - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister register) { - icons = new IIcon[6]; + EnumBackpackType t = type == EnumBackpackType.APIARIST ? EnumBackpackType.T1 : type; + String typeTag = "backpacks/" + t.toString().toLowerCase(Locale.ENGLISH); - EnumBackpackType t = type == EnumBackpackType.APIARIST ? EnumBackpackType.T1 : type; - String typeTag = "backpacks/" + t.toString().toLowerCase(Locale.ENGLISH); + icons[0] = TextureManager.registerTex(register, typeTag + ".cloth"); + icons[1] = TextureManager.registerTex(register, typeTag + ".outline"); + icons[2] = TextureManager.registerTex(register, "backpacks/neutral"); + icons[3] = TextureManager.registerTex(register, "backpacks/locked"); + icons[4] = TextureManager.registerTex(register, "backpacks/receive"); + icons[5] = TextureManager.registerTex(register, "backpacks/resupply"); + } - icons[0] = TextureManager.registerTex(register, typeTag + ".cloth"); - icons[1] = TextureManager.registerTex(register, typeTag + ".outline"); - icons[2] = TextureManager.registerTex(register, "backpacks/neutral"); - icons[3] = TextureManager.registerTex(register, "backpacks/locked"); - icons[4] = TextureManager.registerTex(register, "backpacks/receive"); - icons[5] = TextureManager.registerTex(register, "backpacks/resupply"); - } + // Return true to enable color overlay - client side only + @Override + public boolean requiresMultipleRenderPasses() { + return true; + } - // Return true to enable color overlay - client side only - @Override - public boolean requiresMultipleRenderPasses() { - return true; - } + @Override + public int getRenderPasses(int metadata) { + return 3; + } - @Override - public int getRenderPasses(int metadata) { - return 3; - } + @Override + public int getColorFromItemStack(ItemStack itemstack, int j) { - @Override - public int getColorFromItemStack(ItemStack itemstack, int j) { + if (j == 0) { + return definition.getPrimaryColour(); + } else if (j == 1) { + return definition.getSecondaryColour(); + } else { + return 0xffffff; + } + } - if (j == 0) { - return definition.getPrimaryColour(); - } else if (j == 1) { - return definition.getSecondaryColour(); - } else { - return 0xffffff; - } - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIconFromDamageForRenderPass(int i, int j) { + if (j == 0) { + return icons[0]; + } + if (j == 1) { + return icons[1]; + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamageForRenderPass(int i, int j) { - if (j == 0) { - return icons[0]; - } - if (j == 1) { - return icons[1]; - } + if (i > 2) { + return icons[5]; + } else if (i > 1) { + return icons[4]; + } else if (i > 0) { + return icons[3]; + } else { + return icons[2]; + } + } - if (i > 2) { - return icons[5]; - } else if (i > 1) { - return icons[4]; - } else if (i > 0) { - return icons[3]; - } else { - return icons[2]; - } - } + private static int getSlotsForType(EnumBackpackType type) { + switch (type) { + case APIARIST: + return Constants.SLOTS_BACKPACK_APIARIST; + case T2: + return Constants.SLOTS_BACKPACK_T2; + case T1: + default: + return Constants.SLOTS_BACKPACK_DEFAULT; + } + } - private static int getSlotsForType(EnumBackpackType type) { - switch (type) { - case APIARIST: - return Constants.SLOTS_BACKPACK_APIARIST; - case T2: - return Constants.SLOTS_BACKPACK_T2; - case T1: - default: - return Constants.SLOTS_BACKPACK_DEFAULT; - } - } + public static BackpackMode getMode(ItemStack backpack) { + int meta = backpack.getItemDamage(); - public static BackpackMode getMode(ItemStack backpack) { - int meta = backpack.getItemDamage(); + if (meta >= 3) { + return BackpackMode.RESUPPLY; + } else if (meta >= 2) { + return BackpackMode.RECEIVE; + } else if (meta >= 1) { + return BackpackMode.LOCKED; + } else { + return BackpackMode.NORMAL; + } + } - if (meta >= 3) { - return BackpackMode.RESUPPLY; - } else if (meta >= 2) { - return BackpackMode.RECEIVE; - } else if (meta >= 1) { - return BackpackMode.LOCKED; - } else { - return BackpackMode.NORMAL; - } - } + @Override + public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { + if (data > EnumBackpackType.values().length) { + return null; + } + EnumBackpackType type = EnumBackpackType.values()[data]; + switch (type) { + case T1: + return new GuiBackpack(new ContainerBackpack(player, ContainerBackpack.Size.DEFAULT, heldItem)); + case T2: + return new GuiBackpackT2(new ContainerBackpack(player, ContainerBackpack.Size.T2, heldItem)); + } + return null; + } - @Override - public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { - if (data > EnumBackpackType.values().length) { - return null; - } - EnumBackpackType type = EnumBackpackType.values()[data]; - switch (type) { - case T1: - return new GuiBackpack(new ContainerBackpack(player, ContainerBackpack.Size.DEFAULT, heldItem)); - case T2: - return new GuiBackpackT2(new ContainerBackpack(player, ContainerBackpack.Size.T2, heldItem)); - } - return null; - } - - @Override - public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { - if (data > EnumBackpackType.values().length) { - return null; - } - EnumBackpackType type = EnumBackpackType.values()[data]; - switch (type) { - case T1: - return new ContainerBackpack(player, ContainerBackpack.Size.DEFAULT, heldItem); - case T2: - return new ContainerBackpack(player, ContainerBackpack.Size.T2, heldItem); - } - return null; - } + @Override + public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { + if (data > EnumBackpackType.values().length) { + return null; + } + EnumBackpackType type = EnumBackpackType.values()[data]; + switch (type) { + case T1: + return new ContainerBackpack(player, ContainerBackpack.Size.DEFAULT, heldItem); + case T2: + return new ContainerBackpack(player, ContainerBackpack.Size.T2, heldItem); + } + return null; + } } diff --git a/src/main/java/forestry/storage/items/ItemBackpackNaturalist.java b/src/main/java/forestry/storage/items/ItemBackpackNaturalist.java index 7b8f7e18a..9acc5d21f 100644 --- a/src/main/java/forestry/storage/items/ItemBackpackNaturalist.java +++ b/src/main/java/forestry/storage/items/ItemBackpackNaturalist.java @@ -1,50 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.storage.items; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -import forestry.api.genetics.ISpeciesRoot; -import forestry.api.storage.EnumBackpackType; -import forestry.api.storage.IBackpackDefinition; -import forestry.core.config.Constants; -import forestry.core.gui.GuiHandler; -import forestry.core.gui.GuiNaturalistInventory; -import forestry.storage.gui.ContainerNaturalistBackpack; -import forestry.storage.inventory.ItemInventoryBackpackPaged; - -public class ItemBackpackNaturalist extends ItemBackpack { - private final ISpeciesRoot speciesRoot; - - public ItemBackpackNaturalist(ISpeciesRoot speciesRoot, IBackpackDefinition definition, EnumBackpackType type) { - super(definition, type); - this.speciesRoot = speciesRoot; - } - - @Override - protected void openGui(EntityPlayer entityplayer) { - GuiHandler.openGui(entityplayer, this); - } - - @Override - public Object getGui(EntityPlayer player, ItemStack heldItem, int page) { - ItemInventoryBackpackPaged inventory = new ItemInventoryBackpackPaged(player, Constants.SLOTS_BACKPACK_APIARIST, heldItem, this); - ContainerNaturalistBackpack container = new ContainerNaturalistBackpack(player, inventory, page); - return new GuiNaturalistInventory(speciesRoot, player, container, inventory, page, 5); - } - - @Override - public Object getContainer(EntityPlayer player, ItemStack heldItem, int page) { - ItemInventoryBackpackPaged inventory = new ItemInventoryBackpackPaged(player, Constants.SLOTS_BACKPACK_APIARIST, heldItem, this); - return new ContainerNaturalistBackpack(player, inventory, page); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.storage.items; + +import forestry.api.genetics.ISpeciesRoot; +import forestry.api.storage.EnumBackpackType; +import forestry.api.storage.IBackpackDefinition; +import forestry.core.config.Constants; +import forestry.core.gui.GuiHandler; +import forestry.core.gui.GuiNaturalistInventory; +import forestry.storage.gui.ContainerNaturalistBackpack; +import forestry.storage.inventory.ItemInventoryBackpackPaged; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +public class ItemBackpackNaturalist extends ItemBackpack { + private final ISpeciesRoot speciesRoot; + + public ItemBackpackNaturalist(ISpeciesRoot speciesRoot, IBackpackDefinition definition, EnumBackpackType type) { + super(definition, type); + this.speciesRoot = speciesRoot; + } + + @Override + protected void openGui(EntityPlayer entityplayer) { + GuiHandler.openGui(entityplayer, this); + } + + @Override + public Object getGui(EntityPlayer player, ItemStack heldItem, int page) { + ItemInventoryBackpackPaged inventory = + new ItemInventoryBackpackPaged(player, Constants.SLOTS_BACKPACK_APIARIST, heldItem, this); + ContainerNaturalistBackpack container = new ContainerNaturalistBackpack(player, inventory, page); + return new GuiNaturalistInventory(speciesRoot, player, container, inventory, page, 5); + } + + @Override + public Object getContainer(EntityPlayer player, ItemStack heldItem, int page) { + ItemInventoryBackpackPaged inventory = + new ItemInventoryBackpackPaged(player, Constants.SLOTS_BACKPACK_APIARIST, heldItem, this); + return new ContainerNaturalistBackpack(player, inventory, page); + } +} diff --git a/src/main/java/forestry/storage/items/ItemRegistryStorage.java b/src/main/java/forestry/storage/items/ItemRegistryStorage.java index 83e80a5f9..7dccf2374 100644 --- a/src/main/java/forestry/storage/items/ItemRegistryStorage.java +++ b/src/main/java/forestry/storage/items/ItemRegistryStorage.java @@ -1,91 +1,103 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.storage.items; - -import net.minecraft.item.Item; - -import forestry.api.apiculture.BeeManager; -import forestry.api.core.Tabs; -import forestry.api.lepidopterology.ButterflyManager; -import forestry.api.storage.BackpackManager; -import forestry.api.storage.EnumBackpackType; -import forestry.api.storage.IBackpackDefinition; -import forestry.core.items.ItemCrated; -import forestry.core.items.ItemRegistry; -import forestry.plugins.PluginManager; - -public class ItemRegistryStorage extends ItemRegistry { - public final ItemCrated crate; - public final ItemBackpackNaturalist apiaristBackpack; - public final ItemBackpackNaturalist lepidopteristBackpack; - public final Item minerBackpack; - public final Item minerBackpackT2; - public final Item diggerBackpack; - public final Item diggerBackpackT2; - public final Item foresterBackpack; - public final Item foresterBackpackT2; - public final Item hunterBackpack; - public final Item hunterBackpackT2; - public final Item adventurerBackpack; - public final Item adventurerBackpackT2; - public final Item builderBackpack; - public final Item builderBackpackT2; - - public ItemRegistryStorage() { - // CRATE - crate = registerItem(new ItemCrated(null, false), "crate"); - - // BACKPACKS - IBackpackDefinition definition; - - if (PluginManager.Module.APICULTURE.isEnabled()) { - definition = BackpackManager.definitions.get("apiarist"); - apiaristBackpack = new ItemBackpackNaturalist(BeeManager.beeRoot, definition, EnumBackpackType.APIARIST); - apiaristBackpack.setCreativeTab(Tabs.tabApiculture); - registerItem(apiaristBackpack, "apiaristBag"); - } else { - apiaristBackpack = null; - } - - if (PluginManager.Module.LEPIDOPTEROLOGY.isEnabled()) { - definition = BackpackManager.definitions.get("lepidopterist"); - lepidopteristBackpack = new ItemBackpackNaturalist(ButterflyManager.butterflyRoot, definition, EnumBackpackType.APIARIST); - lepidopteristBackpack.setCreativeTab(Tabs.tabLepidopterology); - registerItem(lepidopteristBackpack, "lepidopteristBag"); - } else { - lepidopteristBackpack = null; - } - - definition = BackpackManager.definitions.get("miner"); - minerBackpack = registerItem(BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T1), "minerBag"); - minerBackpackT2 = registerItem(BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T2), "minerBagT2"); - - definition = BackpackManager.definitions.get("digger"); - diggerBackpack = registerItem(BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T1), "diggerBag"); - diggerBackpackT2 = registerItem(BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T2), "diggerBagT2"); - - definition = BackpackManager.definitions.get("forester"); - foresterBackpack = registerItem(BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T1), "foresterBag"); - foresterBackpackT2 = registerItem(BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T2), "foresterBagT2"); - - definition = BackpackManager.definitions.get("hunter"); - hunterBackpack = registerItem(BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T1), "hunterBag"); - hunterBackpackT2 = registerItem(BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T2), "hunterBagT2"); - - definition = BackpackManager.definitions.get("adventurer"); - adventurerBackpack = registerItem(BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T1), "adventurerBag"); - adventurerBackpackT2 = registerItem(BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T2), "adventurerBagT2"); - - definition = BackpackManager.definitions.get("builder"); - builderBackpack = registerItem(BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T1), "builderBag"); - builderBackpackT2 = registerItem(BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T2), "builderBagT2"); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.storage.items; + +import forestry.api.apiculture.BeeManager; +import forestry.api.core.Tabs; +import forestry.api.lepidopterology.ButterflyManager; +import forestry.api.storage.BackpackManager; +import forestry.api.storage.EnumBackpackType; +import forestry.api.storage.IBackpackDefinition; +import forestry.core.items.ItemCrated; +import forestry.core.items.ItemRegistry; +import forestry.plugins.PluginManager; +import net.minecraft.item.Item; + +public class ItemRegistryStorage extends ItemRegistry { + public final ItemCrated crate; + public final ItemBackpackNaturalist apiaristBackpack; + public final ItemBackpackNaturalist lepidopteristBackpack; + public final Item minerBackpack; + public final Item minerBackpackT2; + public final Item diggerBackpack; + public final Item diggerBackpackT2; + public final Item foresterBackpack; + public final Item foresterBackpackT2; + public final Item hunterBackpack; + public final Item hunterBackpackT2; + public final Item adventurerBackpack; + public final Item adventurerBackpackT2; + public final Item builderBackpack; + public final Item builderBackpackT2; + + public ItemRegistryStorage() { + // CRATE + crate = registerItem(new ItemCrated(null, false), "crate"); + + // BACKPACKS + IBackpackDefinition definition; + + if (PluginManager.Module.APICULTURE.isEnabled()) { + definition = BackpackManager.definitions.get("apiarist"); + apiaristBackpack = new ItemBackpackNaturalist(BeeManager.beeRoot, definition, EnumBackpackType.APIARIST); + apiaristBackpack.setCreativeTab(Tabs.tabApiculture); + registerItem(apiaristBackpack, "apiaristBag"); + } else { + apiaristBackpack = null; + } + + if (PluginManager.Module.LEPIDOPTEROLOGY.isEnabled()) { + definition = BackpackManager.definitions.get("lepidopterist"); + lepidopteristBackpack = + new ItemBackpackNaturalist(ButterflyManager.butterflyRoot, definition, EnumBackpackType.APIARIST); + lepidopteristBackpack.setCreativeTab(Tabs.tabLepidopterology); + registerItem(lepidopteristBackpack, "lepidopteristBag"); + } else { + lepidopteristBackpack = null; + } + + definition = BackpackManager.definitions.get("miner"); + minerBackpack = registerItem( + BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T1), "minerBag"); + minerBackpackT2 = registerItem( + BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T2), "minerBagT2"); + + definition = BackpackManager.definitions.get("digger"); + diggerBackpack = registerItem( + BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T1), "diggerBag"); + diggerBackpackT2 = registerItem( + BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T2), "diggerBagT2"); + + definition = BackpackManager.definitions.get("forester"); + foresterBackpack = registerItem( + BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T1), "foresterBag"); + foresterBackpackT2 = registerItem( + BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T2), "foresterBagT2"); + + definition = BackpackManager.definitions.get("hunter"); + hunterBackpack = registerItem( + BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T1), "hunterBag"); + hunterBackpackT2 = registerItem( + BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T2), "hunterBagT2"); + + definition = BackpackManager.definitions.get("adventurer"); + adventurerBackpack = registerItem( + BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T1), "adventurerBag"); + adventurerBackpackT2 = registerItem( + BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T2), "adventurerBagT2"); + + definition = BackpackManager.definitions.get("builder"); + builderBackpack = registerItem( + BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T1), "builderBag"); + builderBackpackT2 = registerItem( + BackpackManager.backpackInterface.addBackpack(definition, EnumBackpackType.T2), "builderBagT2"); + } +} diff --git a/src/main/java/forestry/storage/proxy/ProxyStorage.java b/src/main/java/forestry/storage/proxy/ProxyStorage.java index 80d89f497..5bfe7f307 100644 --- a/src/main/java/forestry/storage/proxy/ProxyStorage.java +++ b/src/main/java/forestry/storage/proxy/ProxyStorage.java @@ -1,20 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.storage.proxy; - -import forestry.core.items.ItemCrated; - -public class ProxyStorage { - - public void registerCrateForRendering(ItemCrated crate) { - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.storage.proxy; + +import forestry.core.items.ItemCrated; + +public class ProxyStorage { + + public void registerCrateForRendering(ItemCrated crate) {} +} diff --git a/src/main/java/forestry/storage/proxy/ProxyStorageClient.java b/src/main/java/forestry/storage/proxy/ProxyStorageClient.java index 53c45eeb4..b0e6c5321 100644 --- a/src/main/java/forestry/storage/proxy/ProxyStorageClient.java +++ b/src/main/java/forestry/storage/proxy/ProxyStorageClient.java @@ -1,26 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.storage.proxy; - -import net.minecraftforge.client.MinecraftForgeClient; - -import forestry.core.items.ItemCrated; -import forestry.core.render.RenderCrateItem; - -public class ProxyStorageClient extends ProxyStorage { - - private static final RenderCrateItem crateRenderer = new RenderCrateItem(); - - @Override - public void registerCrateForRendering(ItemCrated crate) { - MinecraftForgeClient.registerItemRenderer(crate, crateRenderer); - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.storage.proxy; + +import forestry.core.items.ItemCrated; +import forestry.core.render.RenderCrateItem; +import net.minecraftforge.client.MinecraftForgeClient; + +public class ProxyStorageClient extends ProxyStorage { + + private static final RenderCrateItem crateRenderer = new RenderCrateItem(); + + @Override + public void registerCrateForRendering(ItemCrated crate) { + MinecraftForgeClient.registerItemRenderer(crate, crateRenderer); + } +} diff --git a/src/main/resources/config/forestry/colour.properties b/src/main/resources/config/forestry/colour.properties index 8bd71abdf..8c264e3ac 100755 --- a/src/main/resources/config/forestry/colour.properties +++ b/src/main/resources/config/forestry/colour.properties @@ -1,47 +1,47 @@ -# Add a file of this format in your texture packs zip as -# /config/forestry/colour.properties to configure font colours. -# A file at that location inside the zip of the active texture pack -# will take precedence over the default. -# -# Hex format without leading 0x - -gui.title=404040 -gui.screen=ffffff -gui.table.header=ababab -gui.table.row=ababab -gui.book=000000 - -gui.beealyzer.binomial=14d50b -gui.beealyzer.recessive=3687ec -gui.beealyzer.dominant=ec3661 - -gui.mail.lettertext=cfa738 -gui.mail.text=6689dc - -ledger.error.background=ff3535 -ledger.error.header=e1c92f -ledger.error.text=000000 - -ledger.hint.background=ea38ff -ledger.hint.header=e1c92f -ledger.hint.text=000000 - -ledger.owner.background=ffffff -ledger.owner.header=e1c92f -ledger.owner.subheader=aaafb8 -ledger.owner.text=000000 - -ledger.climate.background=35a4ff -ledger.climate.header=e1c92f -ledger.climate.subheader=aaafb8 -ledger.climate.text=000000 - -ledger.power.background=d46c1f -ledger.power.header=e1c92f -ledger.power.subheader=aaafb8 -ledger.power.text=000000 - -ledger.farm.background=2ca22c -ledger.farm.header=e1c92f -ledger.farm.subheader=aaafb8 -ledger.farm.text=000000 +# Add a file of this format in your texture packs zip as +# /config/forestry/colour.properties to configure font colours. +# A file at that location inside the zip of the active texture pack +# will take precedence over the default. +# +# Hex format without leading 0x + +gui.title=404040 +gui.screen=ffffff +gui.table.header=ababab +gui.table.row=ababab +gui.book=000000 + +gui.beealyzer.binomial=14d50b +gui.beealyzer.recessive=3687ec +gui.beealyzer.dominant=ec3661 + +gui.mail.lettertext=cfa738 +gui.mail.text=6689dc + +ledger.error.background=ff3535 +ledger.error.header=e1c92f +ledger.error.text=000000 + +ledger.hint.background=ea38ff +ledger.hint.header=e1c92f +ledger.hint.text=000000 + +ledger.owner.background=ffffff +ledger.owner.header=e1c92f +ledger.owner.subheader=aaafb8 +ledger.owner.text=000000 + +ledger.climate.background=35a4ff +ledger.climate.header=e1c92f +ledger.climate.subheader=aaafb8 +ledger.climate.text=000000 + +ledger.power.background=d46c1f +ledger.power.header=e1c92f +ledger.power.subheader=aaafb8 +ledger.power.text=000000 + +ledger.farm.background=2ca22c +ledger.farm.header=e1c92f +ledger.farm.subheader=aaafb8 +ledger.farm.text=000000 diff --git a/src/main/resources/config/forestry/gamemodes/HARD.cfg b/src/main/resources/config/forestry/gamemodes/HARD.cfg index 8e4217858..5b809af6b 100644 --- a/src/main/resources/config/forestry/gamemodes/HARD.cfg +++ b/src/main/resources/config/forestry/gamemodes/HARD.cfg @@ -1,144 +1,144 @@ -# Configuration file - -~CONFIG_VERSION: 1.0.0 - -gamemode { - - energy { - # Modifies the energy required to activate machines, as well as the max amount of energy stored and accepted. [range: 0.0 ~ 10.0, default: 4.0] - S:demand.modifier=4.0 - - # Enable the clockwork engine. [default: true] - B:engine.clockwork=true - } - - farms { - # Modifies the time a piece of fertilizer lasts in a farm. [range: 0 ~ 2000, default: 500] - I:fertilizer.value=500 - } - - fuel { - - ethanol { - # modifies the energy provided by ethanol in Buildcraft Combustion Engines. [range: 0.0 ~ 10.0, default: 0.5] - S:combustion=0.5 - - # modifies the energy provided by ethanol in a Bio Generator. [range: 0.0 ~ 10.0, default: 0.5] - S:generator=0.5 - } - - biomass { - # modifies the energy provided by Biomass in Biogas Engines. [range: 0.0 ~ 10.0, default: 0.5] - S:biogas=0.5 - - # modifies the energy provided by Biomass in a Bio Generator. [range: 0.0 ~ 10.0, default: 0.5] - S:generator=0.5 - } - - } - - recipe { - - output { - # amount yielded by the recipe for tin cans. [range: 0 ~ 64, default: 8] - I:can=8 - - # amount yielded by the recipe for wax capsules. [range: 0 ~ 64, default: 2] - I:capsule=2 - - # amount yielded by the recipe for refractory capsules. [range: 0 ~ 64, default: 2] - I:refractory=2 - - fertilizer { - # amount of fertilizer yielded by the recipe using apatite. [range: 0 ~ 64, default: 5] - I:apatite=5 - - # amount of fertilizer yielded by the recipe using ash. [range: 0 ~ 64, default: 0] - I:ash=0 - } - - compost { - # amount of compost yielded by the recipe using ash. [range: 0 ~ 64, default: 1] - I:ash=1 - - # amount of compost yielded by the recipe using wheat. [range: 0 ~ 64, default: 1] - I:wheat=1 - } - - humus { - # amount of humus yielded by the recipe using compost. [range: 0 ~ 64, default: 8] - I:compost=8 - - # amount of humus yielded by the recipe using fertilizer. [range: 0 ~ 64, default: 8] - I:fertilizer=8 - } - - bogearth { - # amount of bog earth yielded by the recipe using buckets. [range: 0 ~ 64, default: 4] - I:bucket=4 - - # amount of bog earth yielded by the recipes using cans, cells or capsules. [range: 0 ~ 64, default: 5] - I:can=5 - } - - } - - } - - fermenter { - - cycles { - # modifies the amount of cycles compost can keep a fermenter going. [range: 0 ~ 2000, default: 150] - I:compost=150 - - # modifies the amount of cycles fertilizer can keep a fermenter going. [range: 0 ~ 2000, default: 100] - I:fertilizer=100 - } - - value { - # modifies the amount of biomass per cycle a fermenter will produce using compost. [range: 0 ~ 2000, default: 48] - I:compost=48 - - # modifies the amount of biomass per cycle a fermenter will produce using fertilizer. [range: 0 ~ 2000, default: 56] - I:fertilizer=56 - } - - yield { - # modifies the amount of biomass a piece of cactus will yield in a fermenter. [range: 0 ~ 2000, default: 10] - I:cactus=10 - - # modifies the amount of biomass a piece of sugar cane will yield in a fermenter. [range: 0 ~ 2000, default: 10] - I:cane=10 - - # modifies the amount of biomass a mushroom will yield in a fermenter. [range: 0 ~ 2000, default: 10] - I:mushroom=10 - - # modifies the base amount of biomass a sapling will yield in a fermenter, affected by sappiness trait. [range: 0 ~ 2000, default: 50] - I:sapling=50 - - # modifies the amount of biomass a piece of wheat will yield in a fermenter. [range: 0 ~ 2000, default: 10] - I:wheat=10 - } - - } - - squeezer { - - liquid { - # modifies the amount of juice squeezed from a single apple. other sources are based off this. [range: 0 ~ 2000, default: 60] - I:apple=60 - - # modifies the amount of seed oil squeezed from a single seed. other sources are based off this. [range: 0 ~ 2000, default: 3] - I:seed=3 - } - - mulch { - # modifies the chance of mulch per squeezed apple. [range: 0 ~ 2000, default: 8] - I:apple=8 - } - - } - -} - - +# Configuration file + +~CONFIG_VERSION: 1.0.0 + +gamemode { + + energy { + # Modifies the energy required to activate machines, as well as the max amount of energy stored and accepted. [range: 0.0 ~ 10.0, default: 4.0] + S:demand.modifier=4.0 + + # Enable the clockwork engine. [default: true] + B:engine.clockwork=true + } + + farms { + # Modifies the time a piece of fertilizer lasts in a farm. [range: 0 ~ 2000, default: 500] + I:fertilizer.value=500 + } + + fuel { + + ethanol { + # modifies the energy provided by ethanol in Buildcraft Combustion Engines. [range: 0.0 ~ 10.0, default: 0.5] + S:combustion=0.5 + + # modifies the energy provided by ethanol in a Bio Generator. [range: 0.0 ~ 10.0, default: 0.5] + S:generator=0.5 + } + + biomass { + # modifies the energy provided by Biomass in Biogas Engines. [range: 0.0 ~ 10.0, default: 0.5] + S:biogas=0.5 + + # modifies the energy provided by Biomass in a Bio Generator. [range: 0.0 ~ 10.0, default: 0.5] + S:generator=0.5 + } + + } + + recipe { + + output { + # amount yielded by the recipe for tin cans. [range: 0 ~ 64, default: 8] + I:can=8 + + # amount yielded by the recipe for wax capsules. [range: 0 ~ 64, default: 2] + I:capsule=2 + + # amount yielded by the recipe for refractory capsules. [range: 0 ~ 64, default: 2] + I:refractory=2 + + fertilizer { + # amount of fertilizer yielded by the recipe using apatite. [range: 0 ~ 64, default: 5] + I:apatite=5 + + # amount of fertilizer yielded by the recipe using ash. [range: 0 ~ 64, default: 0] + I:ash=0 + } + + compost { + # amount of compost yielded by the recipe using ash. [range: 0 ~ 64, default: 1] + I:ash=1 + + # amount of compost yielded by the recipe using wheat. [range: 0 ~ 64, default: 1] + I:wheat=1 + } + + humus { + # amount of humus yielded by the recipe using compost. [range: 0 ~ 64, default: 8] + I:compost=8 + + # amount of humus yielded by the recipe using fertilizer. [range: 0 ~ 64, default: 8] + I:fertilizer=8 + } + + bogearth { + # amount of bog earth yielded by the recipe using buckets. [range: 0 ~ 64, default: 4] + I:bucket=4 + + # amount of bog earth yielded by the recipes using cans, cells or capsules. [range: 0 ~ 64, default: 5] + I:can=5 + } + + } + + } + + fermenter { + + cycles { + # modifies the amount of cycles compost can keep a fermenter going. [range: 0 ~ 2000, default: 150] + I:compost=150 + + # modifies the amount of cycles fertilizer can keep a fermenter going. [range: 0 ~ 2000, default: 100] + I:fertilizer=100 + } + + value { + # modifies the amount of biomass per cycle a fermenter will produce using compost. [range: 0 ~ 2000, default: 48] + I:compost=48 + + # modifies the amount of biomass per cycle a fermenter will produce using fertilizer. [range: 0 ~ 2000, default: 56] + I:fertilizer=56 + } + + yield { + # modifies the amount of biomass a piece of cactus will yield in a fermenter. [range: 0 ~ 2000, default: 10] + I:cactus=10 + + # modifies the amount of biomass a piece of sugar cane will yield in a fermenter. [range: 0 ~ 2000, default: 10] + I:cane=10 + + # modifies the amount of biomass a mushroom will yield in a fermenter. [range: 0 ~ 2000, default: 10] + I:mushroom=10 + + # modifies the base amount of biomass a sapling will yield in a fermenter, affected by sappiness trait. [range: 0 ~ 2000, default: 50] + I:sapling=50 + + # modifies the amount of biomass a piece of wheat will yield in a fermenter. [range: 0 ~ 2000, default: 10] + I:wheat=10 + } + + } + + squeezer { + + liquid { + # modifies the amount of juice squeezed from a single apple. other sources are based off this. [range: 0 ~ 2000, default: 60] + I:apple=60 + + # modifies the amount of seed oil squeezed from a single seed. other sources are based off this. [range: 0 ~ 2000, default: 3] + I:seed=3 + } + + mulch { + # modifies the chance of mulch per squeezed apple. [range: 0 ~ 2000, default: 8] + I:apple=8 + } + + } + +} + + diff --git a/src/main/resources/config/forestry/gamemodes/NORMAL.cfg b/src/main/resources/config/forestry/gamemodes/NORMAL.cfg index 3a880cbad..d5d7a69f6 100644 --- a/src/main/resources/config/forestry/gamemodes/NORMAL.cfg +++ b/src/main/resources/config/forestry/gamemodes/NORMAL.cfg @@ -1,143 +1,143 @@ -# Configuration file - -~CONFIG_VERSION: 1.0.0 - -gamemode { - - energy { - # Modifies the energy required to activate machines, as well as the max amount of energy stored and accepted. [range: 0.0 ~ 10.0, default: 1.5] - S:demand.modifier=1.5 - - # Enable the clockwork engine. [default: true] - B:engine.clockwork=true - } - - farms { - # Modifies the time a piece of fertilizer lasts in a farm. [range: 0 ~ 2000, default: 1000] - I:fertilizer.value=1000 - } - - fuel { - - ethanol { - # modifies the energy provided by ethanol in Buildcraft Combustion Engines. [range: 0.0 ~ 10.0, default: 0.75] - S:combustion=0.75 - - # modifies the energy provided by ethanol in a Bio Generator. [range: 0.0 ~ 10.0, default: 0.75] - S:generator=0.75 - } - - biomass { - # modifies the energy provided by Biomass in Biogas Engines. [range: 0.0 ~ 10.0, default: 0.75] - S:biogas=0.75 - - # modifies the energy provided by Biomass in a Bio Generator. [range: 0.0 ~ 10.0, default: 0.75] - S:generator=0.75 - } - - } - - recipe { - - output { - # amount yielded by the recipe for tin cans. [range: 0 ~ 64, default: 10] - I:can=10 - - # amount yielded by the recipe for wax capsules. [range: 0 ~ 64, default: 3] - I:capsule=3 - - # amount yielded by the recipe for refractory capsules. [range: 0 ~ 64, default: 3] - I:refractory=3 - - fertilizer { - # amount of fertilizer yielded by the recipe using apatite. [range: 0 ~ 64, default: 6] - I:apatite=6 - - # amount of fertilizer yielded by the recipe using ash. [range: 0 ~ 64, default: 10] - I:ash=10 - } - - compost { - # amount of compost yielded by the recipe using ash. [range: 0 ~ 64, default: 1] - I:ash=1 - - # amount of compost yielded by the recipe using wheat. [range: 0 ~ 64, default: 2] - I:wheat=2 - } - - humus { - # amount of humus yielded by the recipe using compost. [range: 0 ~ 64, default: 8] - I:compost=8 - - # amount of humus yielded by the recipe using fertilizer. [range: 0 ~ 64, default: 8] - I:fertilizer=8 - } - - bogearth { - # amount of bog earth yielded by the recipe using buckets. [range: 0 ~ 64, default: 4] - I:bucket=4 - - # amount of bog earth yielded by the recipes using cans, cells or capsules. [range: 0 ~ 64, default: 6] - I:can=6 - } - - } - - } - - fermenter { - - cycles { - # modifies the amount of cycles compost can keep a fermenter going. [range: 0 ~ 2000, default: 250] - I:compost=250 - - # modifies the amount of cycles fertilizer can keep a fermenter going. [range: 0 ~ 2000, default: 200] - I:fertilizer=200 - } - - value { - # modifies the amount of biomass per cycle a fermenter will produce using compost. [range: 0 ~ 2000, default: 48] - I:compost=48 - - # modifies the amount of biomass per cycle a fermenter will produce using fertilizer. [range: 0 ~ 2000, default: 56] - I:fertilizer=56 - } - - yield { - # modifies the amount of biomass a piece of cactus will yield in a fermenter. [range: 0 ~ 2000, default: 50] - I:cactus=50 - - # modifies the amount of biomass a piece of sugar cane will yield in a fermenter. [range: 0 ~ 2000, default: 50] - I:cane=50 - - # modifies the amount of biomass a mushroom will yield in a fermenter. [range: 0 ~ 2000, default: 50] - I:mushroom=50 - - # modifies the base amount of biomass a sapling will yield in a fermenter, affected by sappiness trait. [range: 0 ~ 2000, default: 250] - I:sapling=250 - - # modifies the amount of biomass a piece of wheat will yield in a fermenter. [range: 0 ~ 2000, default: 50] - I:wheat=50 - } - - } - - squeezer { - - liquid { - # modifies the amount of juice squeezed from a single apple. other sources are based off this. [range: 0 ~ 2000, default: 100] - I:apple=100 - - # modifies the amount of seed oil squeezed from a single seed. other sources are based off this. [range: 0 ~ 2000, default: 5] - I:seed=5 - } - - mulch { - # modifies the chance of mulch per squeezed apple. [range: 0 ~ 2000, default: 10] - I:apple=10 - } - - } - -} - +# Configuration file + +~CONFIG_VERSION: 1.0.0 + +gamemode { + + energy { + # Modifies the energy required to activate machines, as well as the max amount of energy stored and accepted. [range: 0.0 ~ 10.0, default: 1.5] + S:demand.modifier=1.5 + + # Enable the clockwork engine. [default: true] + B:engine.clockwork=true + } + + farms { + # Modifies the time a piece of fertilizer lasts in a farm. [range: 0 ~ 2000, default: 1000] + I:fertilizer.value=1000 + } + + fuel { + + ethanol { + # modifies the energy provided by ethanol in Buildcraft Combustion Engines. [range: 0.0 ~ 10.0, default: 0.75] + S:combustion=0.75 + + # modifies the energy provided by ethanol in a Bio Generator. [range: 0.0 ~ 10.0, default: 0.75] + S:generator=0.75 + } + + biomass { + # modifies the energy provided by Biomass in Biogas Engines. [range: 0.0 ~ 10.0, default: 0.75] + S:biogas=0.75 + + # modifies the energy provided by Biomass in a Bio Generator. [range: 0.0 ~ 10.0, default: 0.75] + S:generator=0.75 + } + + } + + recipe { + + output { + # amount yielded by the recipe for tin cans. [range: 0 ~ 64, default: 10] + I:can=10 + + # amount yielded by the recipe for wax capsules. [range: 0 ~ 64, default: 3] + I:capsule=3 + + # amount yielded by the recipe for refractory capsules. [range: 0 ~ 64, default: 3] + I:refractory=3 + + fertilizer { + # amount of fertilizer yielded by the recipe using apatite. [range: 0 ~ 64, default: 6] + I:apatite=6 + + # amount of fertilizer yielded by the recipe using ash. [range: 0 ~ 64, default: 10] + I:ash=10 + } + + compost { + # amount of compost yielded by the recipe using ash. [range: 0 ~ 64, default: 1] + I:ash=1 + + # amount of compost yielded by the recipe using wheat. [range: 0 ~ 64, default: 2] + I:wheat=2 + } + + humus { + # amount of humus yielded by the recipe using compost. [range: 0 ~ 64, default: 8] + I:compost=8 + + # amount of humus yielded by the recipe using fertilizer. [range: 0 ~ 64, default: 8] + I:fertilizer=8 + } + + bogearth { + # amount of bog earth yielded by the recipe using buckets. [range: 0 ~ 64, default: 4] + I:bucket=4 + + # amount of bog earth yielded by the recipes using cans, cells or capsules. [range: 0 ~ 64, default: 6] + I:can=6 + } + + } + + } + + fermenter { + + cycles { + # modifies the amount of cycles compost can keep a fermenter going. [range: 0 ~ 2000, default: 250] + I:compost=250 + + # modifies the amount of cycles fertilizer can keep a fermenter going. [range: 0 ~ 2000, default: 200] + I:fertilizer=200 + } + + value { + # modifies the amount of biomass per cycle a fermenter will produce using compost. [range: 0 ~ 2000, default: 48] + I:compost=48 + + # modifies the amount of biomass per cycle a fermenter will produce using fertilizer. [range: 0 ~ 2000, default: 56] + I:fertilizer=56 + } + + yield { + # modifies the amount of biomass a piece of cactus will yield in a fermenter. [range: 0 ~ 2000, default: 50] + I:cactus=50 + + # modifies the amount of biomass a piece of sugar cane will yield in a fermenter. [range: 0 ~ 2000, default: 50] + I:cane=50 + + # modifies the amount of biomass a mushroom will yield in a fermenter. [range: 0 ~ 2000, default: 50] + I:mushroom=50 + + # modifies the base amount of biomass a sapling will yield in a fermenter, affected by sappiness trait. [range: 0 ~ 2000, default: 250] + I:sapling=250 + + # modifies the amount of biomass a piece of wheat will yield in a fermenter. [range: 0 ~ 2000, default: 50] + I:wheat=50 + } + + } + + squeezer { + + liquid { + # modifies the amount of juice squeezed from a single apple. other sources are based off this. [range: 0 ~ 2000, default: 100] + I:apple=100 + + # modifies the amount of seed oil squeezed from a single seed. other sources are based off this. [range: 0 ~ 2000, default: 5] + I:seed=5 + } + + mulch { + # modifies the chance of mulch per squeezed apple. [range: 0 ~ 2000, default: 10] + I:apple=10 + } + + } + +} + diff --git a/src/main/resources/config/forestry/gamemodes/OP.cfg b/src/main/resources/config/forestry/gamemodes/OP.cfg index 84417243b..f36e197df 100644 --- a/src/main/resources/config/forestry/gamemodes/OP.cfg +++ b/src/main/resources/config/forestry/gamemodes/OP.cfg @@ -1,143 +1,143 @@ -# Configuration file - -~CONFIG_VERSION: 1.0.0 - -gamemode { - - energy { - # Modifies the energy required to activate machines, as well as the max amount of energy stored and accepted. [range: 0.0 ~ 10.0, default: 1.0] - S:demand.modifier=1.0 - - # Enable the clockwork engine. [default: true] - B:engine.clockwork=true - } - - farms { - # Modifies the time a piece of fertilizer lasts in a farm. [range: 0 ~ 2000, default: 2000] - I:fertilizer.value=2000 - } - - fuel { - - ethanol { - # modifies the energy provided by ethanol in Buildcraft Combustion Engines. [range: 0.0 ~ 10.0, default: 4.0] - S:combustion=4.0 - - # modifies the energy provided by ethanol in a Bio Generator. [range: 0.0 ~ 10.0, default: 4.0] - S:generator=4.0 - } - - biomass { - # modifies the energy provided by Biomass in Biogas Engines. [range: 0.0 ~ 10.0, default: 4.0] - S:biogas=4.0 - - # modifies the energy provided by Biomass in a Bio Generator. [range: 0.0 ~ 10.0, default: 4.0] - S:generator=4.0 - } - - } - - recipe { - - output { - # amount yielded by the recipe for tin cans. [range: 0 ~ 64, default: 24] - I:can=24 - - # amount yielded by the recipe for wax capsules. [range: 0 ~ 64, default: 8] - I:capsule=8 - - # amount yielded by the recipe for refractory capsules. [range: 0 ~ 64, default: 8] - I:refractory=8 - - fertilizer { - # amount of fertilizer yielded by the recipe using apatite. [range: 0 ~ 64, default: 16] - I:apatite=16 - - # amount of fertilizer yielded by the recipe using ash. [range: 0 ~ 64, default: 32] - I:ash=32 - } - - compost { - # amount of compost yielded by the recipe using ash. [range: 0 ~ 64, default: 2] - I:ash=2 - - # amount of compost yielded by the recipe using wheat. [range: 0 ~ 64, default: 8] - I:wheat=8 - } - - humus { - # amount of humus yielded by the recipe using compost. [range: 0 ~ 64, default: 8] - I:compost=8 - - # amount of humus yielded by the recipe using fertilizer. [range: 0 ~ 64, default: 8] - I:fertilizer=8 - } - - bogearth { - # amount of bog earth yielded by the recipe using buckets. [range: 0 ~ 64, default: 6] - I:bucket=6 - - # amount of bog earth yielded by the recipes using cans, cells or capsules. [range: 0 ~ 64, default: 8] - I:can=8 - } - - } - - } - - fermenter { - - cycles { - # modifies the amount of cycles compost can keep a fermenter going. [range: 0 ~ 2000, default: 1000] - I:compost=1000 - - # modifies the amount of cycles fertilizer can keep a fermenter going. [range: 0 ~ 2000, default: 800] - I:fertilizer=800 - } - - value { - # modifies the amount of biomass per cycle a fermenter will produce using compost. [range: 0 ~ 2000, default: 192] - I:compost=192 - - # modifies the amount of biomass per cycle a fermenter will produce using fertilizer. [range: 0 ~ 2000, default: 224] - I:fertilizer=224 - } - - yield { - # modifies the amount of biomass a piece of cactus will yield in a fermenter. [range: 0 ~ 2000, default: 400] - I:cactus=400 - - # modifies the amount of biomass a piece of sugar cane will yield in a fermenter. [range: 0 ~ 2000, default: 400] - I:cane=400 - - # modifies the amount of biomass a mushroom will yield in a fermenter. [range: 0 ~ 2000, default: 400] - I:mushroom=400 - - # modifies the base amount of biomass a sapling will yield in a fermenter, affected by sappiness trait. [range: 0 ~ 2000, default: 2000] - I:sapling=2000 - - # modifies the amount of biomass a piece of wheat will yield in a fermenter. [range: 0 ~ 2000, default: 400] - I:wheat=400 - } - - } - - squeezer { - - liquid { - # modifies the amount of juice squeezed from a single apple. other sources are based off this. [range: 0 ~ 2000, default: 1600] - I:apple=1600 - - # modifies the amount of seed oil squeezed from a single seed. other sources are based off this. [range: 0 ~ 2000, default: 80] - I:seed=80 - } - - mulch { - # modifies the chance of mulch per squeezed apple. [range: 0 ~ 2000, default: 160] - I:apple=160 - } - - } - -} - +# Configuration file + +~CONFIG_VERSION: 1.0.0 + +gamemode { + + energy { + # Modifies the energy required to activate machines, as well as the max amount of energy stored and accepted. [range: 0.0 ~ 10.0, default: 1.0] + S:demand.modifier=1.0 + + # Enable the clockwork engine. [default: true] + B:engine.clockwork=true + } + + farms { + # Modifies the time a piece of fertilizer lasts in a farm. [range: 0 ~ 2000, default: 2000] + I:fertilizer.value=2000 + } + + fuel { + + ethanol { + # modifies the energy provided by ethanol in Buildcraft Combustion Engines. [range: 0.0 ~ 10.0, default: 4.0] + S:combustion=4.0 + + # modifies the energy provided by ethanol in a Bio Generator. [range: 0.0 ~ 10.0, default: 4.0] + S:generator=4.0 + } + + biomass { + # modifies the energy provided by Biomass in Biogas Engines. [range: 0.0 ~ 10.0, default: 4.0] + S:biogas=4.0 + + # modifies the energy provided by Biomass in a Bio Generator. [range: 0.0 ~ 10.0, default: 4.0] + S:generator=4.0 + } + + } + + recipe { + + output { + # amount yielded by the recipe for tin cans. [range: 0 ~ 64, default: 24] + I:can=24 + + # amount yielded by the recipe for wax capsules. [range: 0 ~ 64, default: 8] + I:capsule=8 + + # amount yielded by the recipe for refractory capsules. [range: 0 ~ 64, default: 8] + I:refractory=8 + + fertilizer { + # amount of fertilizer yielded by the recipe using apatite. [range: 0 ~ 64, default: 16] + I:apatite=16 + + # amount of fertilizer yielded by the recipe using ash. [range: 0 ~ 64, default: 32] + I:ash=32 + } + + compost { + # amount of compost yielded by the recipe using ash. [range: 0 ~ 64, default: 2] + I:ash=2 + + # amount of compost yielded by the recipe using wheat. [range: 0 ~ 64, default: 8] + I:wheat=8 + } + + humus { + # amount of humus yielded by the recipe using compost. [range: 0 ~ 64, default: 8] + I:compost=8 + + # amount of humus yielded by the recipe using fertilizer. [range: 0 ~ 64, default: 8] + I:fertilizer=8 + } + + bogearth { + # amount of bog earth yielded by the recipe using buckets. [range: 0 ~ 64, default: 6] + I:bucket=6 + + # amount of bog earth yielded by the recipes using cans, cells or capsules. [range: 0 ~ 64, default: 8] + I:can=8 + } + + } + + } + + fermenter { + + cycles { + # modifies the amount of cycles compost can keep a fermenter going. [range: 0 ~ 2000, default: 1000] + I:compost=1000 + + # modifies the amount of cycles fertilizer can keep a fermenter going. [range: 0 ~ 2000, default: 800] + I:fertilizer=800 + } + + value { + # modifies the amount of biomass per cycle a fermenter will produce using compost. [range: 0 ~ 2000, default: 192] + I:compost=192 + + # modifies the amount of biomass per cycle a fermenter will produce using fertilizer. [range: 0 ~ 2000, default: 224] + I:fertilizer=224 + } + + yield { + # modifies the amount of biomass a piece of cactus will yield in a fermenter. [range: 0 ~ 2000, default: 400] + I:cactus=400 + + # modifies the amount of biomass a piece of sugar cane will yield in a fermenter. [range: 0 ~ 2000, default: 400] + I:cane=400 + + # modifies the amount of biomass a mushroom will yield in a fermenter. [range: 0 ~ 2000, default: 400] + I:mushroom=400 + + # modifies the base amount of biomass a sapling will yield in a fermenter, affected by sappiness trait. [range: 0 ~ 2000, default: 2000] + I:sapling=2000 + + # modifies the amount of biomass a piece of wheat will yield in a fermenter. [range: 0 ~ 2000, default: 400] + I:wheat=400 + } + + } + + squeezer { + + liquid { + # modifies the amount of juice squeezed from a single apple. other sources are based off this. [range: 0 ~ 2000, default: 1600] + I:apple=1600 + + # modifies the amount of seed oil squeezed from a single seed. other sources are based off this. [range: 0 ~ 2000, default: 80] + I:seed=80 + } + + mulch { + # modifies the chance of mulch per squeezed apple. [range: 0 ~ 2000, default: 160] + I:apple=160 + } + + } + +} + diff --git a/src/main/resources/config/forestry/hints.properties b/src/main/resources/config/forestry/hints.properties index deb239b37..142e72f57 100755 --- a/src/main/resources/config/forestry/hints.properties +++ b/src/main/resources/config/forestry/hints.properties @@ -1,34 +1,34 @@ -apiary=accesspipe;nopowerrequired;beebiomes;beebreeding;beejubilance;beeflowers;flowerjungle;flowernether;apiaristsuit;honeyfood; -bee.house=nopowerrequired;beebiomes;beebreeding;beejubilance;beeflowers;flowerjungle;flowernether;apiaristsuit;honeyfood; -beealyzer=beebiomes;beebreeding;beejubilance;beeflowers;flowerjungle;flowernether; -escritoire=beebiomes;beebreeding;beejubilance;beeflowers; -farm=farmland;gearbox;valve;fertilizer;hatch;circuitboard;manualfarms;farmgui; -flutterlyzer= -generator=accesscontrol;accessrules;accesspipe;energyunit;pipette;generatorfuels; -habitat.locator=habitatlocatoruse; -moistener=nopowerrequired;accesscontrol;accessrules;accesspipe;pipette;moistenerproducts; -naturalist.chest=accesscontrol;accessrules;accesspipe; -raintank=powerraintank; -soldering.iron=circuitboard; -treealyzer= -worktable= - -letter=postage; -mailbox=postage; -philatelist=postage; -trade.station=postage; - -powered.machine=powerrequired;accesscontrol;accessrules;accesspipe; -analyzer=pipette;flowerjungle;flowernether;apiaristsuit;honeyfood; -bottler=pipette; -carpenter=pipette;crating; -centrifuge= -fabricator= -fermenter=pipette;shortmead; -squeezer=pipette; -still=pipette; - -engine=accesscontrol;accessrules;accesspipe;energyunit;energybuffer; -engine.bronze=pipette;enginebronzefuels;enginebronzeheatloss;enginebronzeoutput;enginebronzewaste -engine.copper=forcedcooldown;cooldownloss;enginecopperfuels;usesofash;enginecopperwaste;manualpeat;peatharvest -engine.tin=forcedcooldown;cooldownloss;enginetinbatteries;enginetinchoke; +apiary=accesspipe;nopowerrequired;beebiomes;beebreeding;beejubilance;beeflowers;flowerjungle;flowernether;apiaristsuit;honeyfood; +bee.house=nopowerrequired;beebiomes;beebreeding;beejubilance;beeflowers;flowerjungle;flowernether;apiaristsuit;honeyfood; +beealyzer=beebiomes;beebreeding;beejubilance;beeflowers;flowerjungle;flowernether; +escritoire=beebiomes;beebreeding;beejubilance;beeflowers; +farm=farmland;gearbox;valve;fertilizer;hatch;circuitboard;manualfarms;farmgui; +flutterlyzer= +generator=accesscontrol;accessrules;accesspipe;energyunit;pipette;generatorfuels; +habitat.locator=habitatlocatoruse; +moistener=nopowerrequired;accesscontrol;accessrules;accesspipe;pipette;moistenerproducts; +naturalist.chest=accesscontrol;accessrules;accesspipe; +raintank=powerraintank; +soldering.iron=circuitboard; +treealyzer= +worktable= + +letter=postage; +mailbox=postage; +philatelist=postage; +trade.station=postage; + +powered.machine=powerrequired;accesscontrol;accessrules;accesspipe; +analyzer=pipette;flowerjungle;flowernether;apiaristsuit;honeyfood; +bottler=pipette; +carpenter=pipette;crating; +centrifuge= +fabricator= +fermenter=pipette;shortmead; +squeezer=pipette; +still=pipette; + +engine=accesscontrol;accessrules;accesspipe;energyunit;energybuffer; +engine.bronze=pipette;enginebronzefuels;enginebronzeheatloss;enginebronzeoutput;enginebronzewaste +engine.copper=forcedcooldown;cooldownloss;enginecopperfuels;usesofash;enginecopperwaste;manualpeat;peatharvest +engine.tin=forcedcooldown;cooldownloss;enginetinbatteries;enginetinchoke;