diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..fd2792b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,44 @@ +* text eol=lf + +*.[jJ][aA][rR] binary + +*.[pP][nN][gG] binary +*.[jJ][pP][gG] binary +*.[jJ][pP][eE][gG] binary +*.[gG][iI][fF] binary +*.[tT][iI][fF] binary +*.[tT][iI][fF][fF] binary +*.[iI][cC][oO] binary +*.[sS][vV][gG] text +*.[eE][pP][sS] binary +*.[xX][cC][fF] binary + +*.[kK][aA][rR] binary +*.[mM]4[aA] binary +*.[mM][iI][dD] binary +*.[mM][iI][dD][iI] binary +*.[mM][pP]3 binary +*.[oO][gG][gG] binary +*.[rR][aA] binary + +*.7[zZ] binary +*.[gG][zZ] binary +*.[tT][aA][rR] binary +*.[tT][gG][zZ] binary +*.[zZ][iI][pP] binary + +*.[tT][cC][nN] binary +*.[sS][oO] binary +*.[dD][lL][lL] binary +*.[dD][yY][lL][iI][bB] binary +*.[pP][sS][dD] binary +*.[tT][tT][fF] binary +*.[oO][tT][fF] binary + +*.[pP][aA][tT][cC][hH] -text + +*.[bB][aA][tT] text eol=crlf +*.[cC][mM][dD] text eol=crlf +*.[pP][sS]1 text eol=crlf + +*[aA][uU][tT][oO][gG][eE][nN][eE][rR][aA][tT][eE][dD]* binary diff --git a/.github/scripts/update_version b/.github/scripts/update_version new file mode 100644 index 0000000..e30e018 --- /dev/null +++ b/.github/scripts/update_version @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +if ! git diff --name-only HEAD HEAD~1 | grep -qF 'build.gradle'; then + new_version="$(date +%s)" + sed --in-place "s!^//version:.*!//version: $new_version!g" build.gradle + git add build.gradle + git commit -m "[ci skip] update build script version to $new_version" + git push + printf 'Updated buildscript version to %s\n' "$new_version" +else + printf 'Ignored buildscript version update: no changes detected\n' +fi \ No newline at end of file diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml new file mode 100644 index 0000000..5f6fb2a --- /dev/null +++ b/.github/workflows/build-and-test.yml @@ -0,0 +1,13 @@ + +name: Build and test + +on: + pull_request: + branches: [ 1.7.10, 1.7.10-dev ] + push: + branches: [ 1.7.10, 1.7.10-dev ] + +jobs: + build-and-test: + uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/build-and-test.yml@master + secrets: inherit \ No newline at end of file diff --git a/.github/workflows/release-tags.yml b/.github/workflows/release-tags.yml new file mode 100644 index 0000000..dee08b7 --- /dev/null +++ b/.github/workflows/release-tags.yml @@ -0,0 +1,74 @@ + +name: Release tagged build + +on: + push: + tags: [ '*' ] + +permissions: + contents: write + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout mod repo + uses: actions/checkout@v3 + with: + fetch-depth: 32 + + - name: Set release version + run: | + IFS='-' read -r mv pv <<< "${GITHUB_REF#refs/*/}" + echo "MC_VERSION=${mv}" >> $GITHUB_ENV + echo "RELEASE_VERSION=${pv}" >> $GITHUB_ENV + echo "VERSION=${pv}" >> $GITHUB_ENV + + - name: Set up JDK 8 + uses: actions/setup-java@v3 + with: + java-version: '8' + distribution: 'temurin' + cache: gradle + + - name: Grant execute permission for gradlew + run: chmod +x gradlew + + - name: Setup the workspace + run: ./gradlew --info --stacktrace ${{ inputs.workspace }} + + - name: Build the mod + run: ./gradlew --info --stacktrace build + + # Continue on error in the following steps to make sure releases still get made even if one of the methods fails + + - name: Delete old release if it already exists + run: gh release delete --yes "${MC_VERSION}-${RELEASE_VERSION}" + continue-on-error: true + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Release under current tag + run: | + export "CHANGELOG_FILE=$(mktemp --suffix=.md)" + echo "CHANGELOG_FILE=${CHANGELOG_FILE}" >> $GITHUB_ENV + gh api --method POST -H "Accept: application/vnd.github+json" \ + "/repos/${GITHUB_REPOSITORY}/releases/generate-notes" \ + -f tag_name="${MC_VERSION}-${RELEASE_VERSION}" \ + --jq ".body" > "${CHANGELOG_FILE}" + cat "${CHANGELOG_FILE}" + gh release create "${MC_VERSION}-${RELEASE_VERSION}" -F "${CHANGELOG_FILE}" ./build/libs/*.jar + shell: bash + continue-on-error: true + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish to Maven, Modrinth and CurseForge + run: ./gradlew --info --stacktrace build publish + continue-on-error: true + env: + MAVEN_USER: ${{ secrets.MAVEN_USER }} + MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} + MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }} + CURSEFORGE_TOKEN: ${{ secrets.CURSEFORGE_TOKEN }} + if: ${{ env.MAVEN_USER != '' }} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 09ca047..d345562 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ To be consistent with the main branch, it may miss some versions +## 3.8.5 +- Fixed: gtpp transfer crash +- Fixed: gtpp recipe output doubles +- Chore: upgrade gradle build system + ## 3.8.4 - Rebuild of 3.8.3 diff --git a/build.gradle b/build.gradle index 5a794e7..7770647 100644 --- a/build.gradle +++ b/build.gradle @@ -1,32 +1,100 @@ +//version: 1671313514 +/* + 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/master/build.gradle for updates. + */ + + +import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar +import com.matthewprenger.cursegradle.CurseArtifact +import com.matthewprenger.cursegradle.CurseRelation +import com.modrinth.minotaur.dependencies.ModDependency +import com.modrinth.minotaur.dependencies.VersionDependency +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 = "gt" - url = "https://gregtech.overminddl1.com/" + name 'forge' + url 'https://maven.minecraftforge.net' } maven { - name = "forge" - url = "http://files.minecraftforge.net/maven" + // GTNH ForgeGradle and ASM Fork + name = "GTNH Maven" + url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" } maven { - name = "jitpack" - url = "https://jitpack.io" + name 'sonatype' + url 'https://oss.sonatype.org/content/repositories/snapshots/' + } + maven { + name 'Scala CI dependencies' + url 'https://repo1.maven.org/maven2/' } } dependencies { - classpath "com.github.GTNH2:ForgeGradle:FG_1.2-SNAPSHOT" + //Overwrite the current ASM version to fix shading newer than java 8 applicatations. + classpath 'org.ow2.asm:asm-debug-all-custom:5.0.3' + classpath 'net.minecraftforge.gradle:ForgeGradle:1.2.13' } } - plugins { - id("org.ajoberstar.grgit") version("3.1.1") + 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 'com.google.devtools.ksp' version '1.5.30-1.0.0' apply false + id 'org.ajoberstar.grgit' version '4.1.1' + id 'com.github.johnrengelman.shadow' version '4.0.4' + id 'com.palantir.git-version' version '0.13.0' apply false + id 'de.undercouch.download' version '5.0.1' + id 'com.github.gmazzo.buildconfig' version '3.0.3' apply false + id 'com.diffplug.spotless' version '6.7.2' apply false + id 'com.modrinth.minotaur' version '2.+' apply false + id 'com.matthewprenger.cursegradle' version '1.4.0' 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: "java" -apply plugin: "idea" +apply plugin: 'com.diffplug.blowdryer' + +if (project.file('.git/HEAD').isFile()) { + apply plugin: 'com.palantir.git-version' +} + +def out = services.get(StyledTextOutputFactory).create('an-output') + apply plugin: 'forge' +def projectJavaVersion = JavaLanguageVersion.of(8) + +java { + toolchain { + languageVersion.set(projectJavaVersion) + } +} + idea { module { inheritOutputDirs = true @@ -35,83 +103,1014 @@ idea { } } -java { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = 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') } -version = "${mc_version}-${proj_version}" -group = "me.towdium.jecalculation" -archivesBaseName = "JustEnoughCalculation" +if (JavaVersion.current() != JavaVersion.VERSION_1_8) { + throw new GradleException("This project requires Java 8, but it's running on " + JavaVersion.current()) +} + +checkPropertyExists("modName") +checkPropertyExists("modId") +checkPropertyExists("modGroup") +checkPropertyExists("autoUpdateBuildScript") +checkPropertyExists("minecraftVersion") +checkPropertyExists("forgeVersion") +checkPropertyExists("replaceGradleTokenInFile") +checkPropertyExists("gradleTokenModId") +checkPropertyExists("gradleTokenModName") +checkPropertyExists("gradleTokenVersion") +checkPropertyExists("gradleTokenGroupName") +checkPropertyExists("apiPackage") +checkPropertyExists("accessTransformersFile") +checkPropertyExists("usesMixins") +checkPropertyExists("mixinPlugin") +checkPropertyExists("mixinsPackage") +checkPropertyExists("coreModClass") +checkPropertyExists("containsMixinsAndOrCoreModOnly") +checkPropertyExists("usesShadowedDependencies") +checkPropertyExists("developmentEnvironmentUserName") + +propertyDefaultIfUnset("noPublishedSources", false) +propertyDefaultIfUnset("usesMixinDebug", project.usesMixins) +propertyDefaultIfUnset("forceEnableMixins", false) +propertyDefaultIfUnset("channel", "stable") +propertyDefaultIfUnset("mappingsVersion", "12") +propertyDefaultIfUnset("modrinthProjectId", "") +propertyDefaultIfUnset("modrinthRelations", "") +propertyDefaultIfUnset("curseForgeProjectId", "") +propertyDefaultIfUnset("curseForgeRelations", "") + +String javaSourceDir = "src/main/java/" +String scalaSourceDir = "src/main/scala/" +String kotlinSourceDir = "src/main/kotlin/" + + +final String modGroupPath = modGroup.toString().replaceAll("\\.", "/") +final String apiPackagePath = apiPackage.toString().replaceAll("\\.", "/") + +String targetPackageJava = javaSourceDir + modGroupPath +String targetPackageScala = scalaSourceDir + modGroupPath +String targetPackageKotlin = kotlinSourceDir + modGroupPath +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) { + targetPackageJava = javaSourceDir + modGroupPath + "/" + apiPackagePath + targetPackageScala = scalaSourceDir + modGroupPath + "/" + apiPackagePath + targetPackageKotlin = kotlinSourceDir + modGroupPath + "/" + apiPackagePath + 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) { + String targetFile = "src/main/resources/META-INF/" + accessTransformersFile + if (!getFile(targetFile).exists()) { + throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile) + } +} + +if (usesMixins.toBoolean()) { + if (mixinsPackage.isEmpty()) { + throw new GradleException("\"usesMixins\" requires \"mixinsPackage\" to be set!") + } + final String mixinPackagePath = mixinsPackage.toString().replaceAll("\\.", "/") + final String mixinPluginPath = mixinPlugin.toString().replaceAll("\\.", "/") + + targetPackageJava = javaSourceDir + modGroupPath + "/" + mixinPackagePath + targetPackageScala = scalaSourceDir + modGroupPath + "/" + mixinPackagePath + targetPackageKotlin = kotlinSourceDir + modGroupPath + "/" + mixinPackagePath + 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 (!mixinPlugin.isEmpty()) { + String targetFileJava = javaSourceDir + modGroupPath + "/" + mixinPluginPath + ".java" + String targetFileScala = scalaSourceDir + modGroupPath + "/" + mixinPluginPath + ".scala" + String targetFileScalaJava = scalaSourceDir + modGroupPath + "/" + mixinPluginPath + ".java" + String targetFileKotlin = kotlinSourceDir + modGroupPath + "/" + mixinPluginPath + ".kt" + 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) { + final String coreModPath = coreModClass.toString().replaceAll("\\.", "/") + String targetFileJava = javaSourceDir + modGroupPath + "/" + coreModPath + ".java" + String targetFileScala = scalaSourceDir + modGroupPath + "/" + coreModPath + ".scala" + String targetFileScalaJava = scalaSourceDir + modGroupPath + "/" + coreModPath + ".java" + String targetFileKotlin = kotlinSourceDir + modGroupPath + "/" + coreModPath + ".kt" + 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) + } +} + +configurations.all { + resolutionStrategy.cacheChangingModulesFor(0, TimeUnit.SECONDS) + + // Make sure GregTech build won't time out + System.setProperty("org.gradle.internal.http.connectionTimeout", 120000 as String) + System.setProperty("org.gradle.internal.http.socketTimeout", 120000 as String) +} + +// Fix Jenkins' Git: chmod a file should not be detected as a change and append a '.dirty' to the version +try { + 'git config core.fileMode false'.execute() +} +catch (Exception ignored) { + out.style(Style.Failure).println("git isn't installed at all") +} + +// Pulls version first from the VERSION env and then git tag +String identifiedVersion +String versionOverride = System.getenv("VERSION") ?: null +try { + identifiedVersion = versionOverride == null ? gitVersion() : versionOverride +} +catch (Exception ignored) { + out.style(Style.Failure).text( + 'This mod must be version controlled by Git AND the repository must provide at least one tag,\n' + + 'or the VERSION override must be set! ').style(Style.SuccessHeader).text('(Do NOT download from GitHub using the ZIP option, instead\n' + + 'clone the repository, see ').style(Style.Info).text('https://gtnh.miraheze.org/wiki/Development').style(Style.SuccessHeader).println(' for details.)' + ) + versionOverride = 'NO-GIT-TAG-SET' + identifiedVersion = versionOverride +} +version = minecraftVersion + '-' + identifiedVersion +ext { + modVersion = identifiedVersion +} + +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) { + archivesBaseName = customArchiveBaseName +} else { + archivesBaseName = modId +} + +def arguments = [] +def jvmArguments = [] + +if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { + arguments += [ + "--tweakClass org.spongepowered.asm.launch.MixinTweaker" + ] + if (usesMixinDebug.toBoolean()) { + jvmArguments += [ + "-Dmixin.debug.countInjections=true", + "-Dmixin.debug.verbose=true", + "-Dmixin.debug.export=true" + ] + } +} minecraft { - version = '1.7.10-10.13.4.1614-1.7.10' - replace '@VERSION@', project.version + version = minecraftVersion + '-' + forgeVersion + '-' + minecraftVersion + runDir = 'run' + + if (replaceGradleTokenInFile) { + for (f in replaceGradleTokenInFile.split(',')) { + replaceIn f + } + if (gradleTokenModId) { + replace gradleTokenModId, modId + } + if (gradleTokenModName) { + replace gradleTokenModName, modName + } + if (gradleTokenVersion) { + replace gradleTokenVersion, modVersion + } + if (gradleTokenGroupName) { + replace gradleTokenGroupName, modGroup + } + } + + clientIntellijRun { + args(arguments) + jvmArgs(jvmArguments) + + if (developmentEnvironmentUserName) { + args("--username", developmentEnvironmentUserName) + } + } + + serverIntellijRun { + args(arguments) + jvmArgs(jvmArguments) + } } -def commonManifest = { - attributes 'FMLAT': 'nei_at.cfg' +if (file('addon.gradle').exists()) { + apply from: 'addon.gradle' } -jar { - manifest commonManifest +apply from: 'repositories.gradle' + +configurations { + implementation.extendsFrom(shadowImplementation) // TODO: remove after all uses are refactored + implementation.extendsFrom(shadowCompile) + implementation.extendsFrom(shadeCompile) } repositories { - mavenCentral() maven { - name 'CB Repo' - url "http://chickenbones.net/maven/" + name 'Overmind forge repo mirror' + url 'https://gregtech.overminddl1.com/' } - flatDir { - dirs 'libs' + if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { + maven { + name = "GTNH Maven" + url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" + } + if (usesMixinDebug.toBoolean()) { + maven { + name = "Fabric Maven" + url = "https://maven.fabricmc.net/" + } + } } } - dependencies { - // you may put jars on which you depend on in ./libs - // or you may define them like so.. - //compile "some.group:artifact:version:classifier" - //compile "some.group:artifact:version" + 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('com.gtnewhorizon:gtnhmixins:2.1.3:processor') + if (usesMixinDebug.toBoolean()) { + runtimeOnly('org.jetbrains:intellij-fernflower:1.2.1.16') + } + } + if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { + compile('com.gtnewhorizon:gtnhmixins:2.1.3') + } +} - // real examples - //compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env - //compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env +apply from: 'dependencies.gradle' - // for more info... - // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html - // http://www.gradle.org/docs/current/userguide/dependency_management.html - compile "codechicken:NotEnoughItems:${mc_version}-${nei_version}:universal" - compile 'codechicken:CodeChickenLib:1.7.10-1.1.3.138:dev' - compile 'codechicken:CodeChickenCore:1.7.10-1.0.7.+:dev' +def mixingConfigRefMap = 'mixins.' + modId + '.refmap.json' +def refMap = "${tasks.compileJava.temporaryDir}" + File.separator + mixingConfigRefMap +def mixinSrg = "${tasks.reobf.temporaryDir}" + File.separator + "mixins.srg" - compile 'org.reflections:reflections:0.9.12' - testCompile 'org.junit.jupiter:junit-jupiter-api:5.2.0' +task generateAssets { + if (usesMixins.toBoolean()) { + def mixinConfigFile = getFile("/src/main/resources/mixins." + modId + ".json") + if (!mixinConfigFile.exists()) { + def mixinPluginLine = "" + if(!mixinPlugin.isEmpty()) { + // We might not have a mixin plugin if we're using early/late mixins + mixinPluginLine += """\n "plugin": "${modGroup}.${mixinPlugin}", """ + } + + mixinConfigFile.text = """{ + "required": true, + "minVersion": "0.8.5-GTNH", + "package": "${modGroup}.${mixinsPackage}",${mixinPluginLine} + "refmap": "${mixingConfigRefMap}", + "target": "@env(DEFAULT)", + "compatibilityLevel": "JAVA_8", + "mixins": [], + "client": [], + "server": [] +} +""" + } + } +} + +task relocateShadowJar(type: ConfigureShadowRelocation) { + target = tasks.shadowJar + prefix = modGroup + ".shadow" +} + +shadowJar { + project.configurations.shadeCompile.each { dep -> + from(project.zipTree(dep)) { + exclude 'META-INF', 'META-INF/**' + } + } + + manifest { + attributes(getManifestAttributes()) + } + + minimize() // This will only allow shading for actually used classes + configurations = [ + project.configurations.shadowImplementation, + project.configurations.shadowCompile + ] + dependsOn(relocateShadowJar) +} + +jar { + project.configurations.shadeCompile.each { dep -> + from(project.zipTree(dep)) { + exclude 'META-INF', 'META-INF/**' + } + } + + manifest { + attributes(getManifestAttributes()) + } + + if (usesShadowedDependencies.toBoolean()) { + dependsOn(shadowJar) + enabled = false + } +} + +reobf { + if (usesMixins.toBoolean()) { + addExtraSrgFile mixinSrg + } +} + +afterEvaluate { + 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" + ] + } + } +} + +runClient { + if (developmentEnvironmentUserName) { + arguments += [ + "--username", + developmentEnvironmentUserName + ] + } + + args(arguments) + jvmArgs(jvmArguments) +} + +runServer { + args(arguments) + jvmArgs(jvmArguments) +} + +tasks.withType(JavaExec).configureEach { + javaLauncher.set( + javaToolchains.launcherFor { + languageVersion = projectJavaVersion + } + ) } 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) { include 'mcmod.info' - // replace version and mcversion - expand 'version': project.version, 'mcversion': project.minecraft.version + // replace modVersion and minecraftVersion + expand "minecraftVersion": project.minecraft.version, + "modVersion": modVersion, + "modId": modId, + "modName": modName } - // copy everything else, thats not the mcmod.info + 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' } - - // Move access transformer to META-INF - rename '(.+_at.cfg)', 'META-INF/$1' } -tasks.withType(JavaCompile) { - options.encoding = 'UTF-8' +def getManifestAttributes() { + def manifestAttributes = [:] + if (!containsMixinsAndOrCoreModOnly.toBoolean() && (usesMixins.toBoolean() || coreModClass)) { + manifestAttributes += ["FMLCorePluginContainsFMLMod": true] + } + + if (accessTransformersFile) { + manifestAttributes += ["FMLAT": accessTransformersFile.toString()] + } + + if (coreModClass) { + manifestAttributes += ["FMLCorePlugin": modGroup + "." + coreModClass] + } + + if (usesMixins.toBoolean()) { + manifestAttributes += [ + "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")) + getArchiveClassifier().set('sources') +} + +task shadowDevJar(type: ShadowJar) { + project.configurations.shadeCompile.each { dep -> + from(project.zipTree(dep)) { + exclude 'META-INF', 'META-INF/**' + } + } + + from sourceSets.main.output + getArchiveClassifier().set("dev") + + manifest { + attributes(getManifestAttributes()) + } + + minimize() // This will only allow shading for actually used classes + configurations = [ + project.configurations.shadowImplementation, + project.configurations.shadowCompile + ] +} + +task relocateShadowDevJar(type: ConfigureShadowRelocation) { + target = tasks.shadowDevJar + prefix = modGroup + ".shadow" +} + +task circularResolverJar(type: Jar) { + dependsOn(relocateShadowDevJar) + dependsOn(shadowDevJar) + enabled = false +} + +task devJar(type: Jar) { + project.configurations.shadeCompile.each { dep -> + from(project.zipTree(dep)) { + exclude 'META-INF', 'META-INF/**' + } + } + + from sourceSets.main.output + getArchiveClassifier().set("dev") + + manifest { + attributes(getManifestAttributes()) + } + + if (usesShadowedDependencies.toBoolean()) { + dependsOn(circularResolverJar) + enabled = false + } +} + +task apiJar(type: Jar) { + from(sourceSets.main.allSource) { + include modGroupPath + "/" + apiPackagePath + '/**' + } + + from(sourceSets.main.output) { + include modGroupPath + "/" + apiPackagePath + '/**' + } + + from(sourceSets.main.resources.srcDirs) { + include("LICENSE") + } + + getArchiveClassifier().set('api') +} + +artifacts { + if (!noPublishedSources) { + archives sourcesJar + } + archives devJar + if (apiPackage) { + archives apiJar + } +} + +// The gradle metadata includes all of the additional deps that we disabled from POM generation (including forgeBin with no groupID), +// and isn't strictly needed with the POM so just disable it. +tasks.withType(GenerateModuleMetadata) { + enabled = false +} + +// workaround variable hiding in pom processing +def projectConfigs = project.configurations + +publishing { + publications { + maven(MavenPublication) { + from components.java + if (usesShadowedDependencies.toBoolean()) { + artifact source: shadowJar, classifier: "" + } + if (!noPublishedSources) { + artifact source: sourcesJar, classifier: "sources" + } + artifact source: usesShadowedDependencies.toBoolean() ? shadowDevJar : devJar, classifier: "dev" + if (apiPackage) { + artifact source: apiJar, classifier: "api" + } + + groupId = System.getenv("ARTIFACT_GROUP_ID") ?: "com.github.GTNewHorizons" + artifactId = System.getenv("ARTIFACT_ID") ?: project.name + // Using the identified version, not project.version as it has the prepended 1.7.10 + version = System.getenv("RELEASE_VERSION") ?: identifiedVersion + + // remove extra garbage from minecraft and minecraftDeps configuration + pom.withXml { + def badArtifacts = [:].withDefault { [] as Set } + for (configuration in [ + projectConfigs.minecraft, + projectConfigs.minecraftDeps + ]) { + for (dependency in configuration.allDependencies) { + badArtifacts[dependency.group == null ? "" : dependency.group] += dependency.name + } + } + // example for specifying extra stuff to ignore + // badArtifacts["org.example.group"] += "artifactName" + + Node pomNode = asNode() + pomNode.dependencies.'*'.findAll() { + badArtifacts[it.groupId.text()].contains(it.artifactId.text()) + }.each() { + it.parent().remove(it) + } + } + } + } + + repositories { + maven { + url = "http://jenkins.usrv.eu:8081/nexus/content/repositories/releases" + credentials { + username = System.getenv("MAVEN_USER") ?: "NONE" + password = System.getenv("MAVEN_PASSWORD") ?: "NONE" + } + } + } +} + +if (modrinthProjectId.size() != 0 && System.getenv("MODRINTH_TOKEN") != null) { + apply plugin: 'com.modrinth.minotaur' + + File changelogFile = new File(System.getenv("CHANGELOG_FILE") ?: "CHANGELOG.md") + + modrinth { + token = System.getenv("MODRINTH_TOKEN") + projectId = modrinthProjectId + versionNumber = identifiedVersion + versionType = identifiedVersion.endsWith("-pre") ? "beta" : "release" + changelog = changelogFile.exists() ? changelogFile.getText("UTF-8") : "" + uploadFile = jar + additionalFiles = getSecondaryArtifacts() + gameVersions = [minecraftVersion] + loaders = ["forge"] + debugMode = false + } + + if (modrinthRelations.size() != 0) { + String[] deps = modrinthRelations.split(";") + deps.each { dep -> + if (dep.size() == 0) { + return + } + String[] parts = dep.split(":") + String[] qual = parts[0].split("-") + addModrinthDep(qual[0], qual[1], parts[1]) + } + } + if (usesMixins.toBoolean()) { + addModrinthDep("required", "project", "gtnhmixins") + } + tasks.modrinth.dependsOn(build) + tasks.publish.dependsOn(tasks.modrinth) +} + +if (curseForgeProjectId.size() != 0 && System.getenv("CURSEFORGE_TOKEN") != null) { + apply plugin: 'com.matthewprenger.cursegradle' + + File changelogFile = new File(System.getenv("CHANGELOG_FILE") ?: "CHANGELOG.md") + + curseforge { + apiKey = System.getenv("CURSEFORGE_TOKEN") + project { + id = curseForgeProjectId + if (changelogFile.exists()) { + changelogType = "markdown" + changelog = changelogFile + } + releaseType = identifiedVersion.endsWith("-pre") ? "beta" : "release" + addGameVersion minecraftVersion + addGameVersion "Forge" + mainArtifact jar + for (artifact in getSecondaryArtifacts()) addArtifact artifact + } + + options { + javaIntegration = false + forgeGradleIntegration = false + debug = false + } + } + + if (curseForgeRelations.size() != 0) { + String[] deps = curseForgeRelations.split(";") + deps.each { dep -> + if (dep.size() == 0) { + return + } + String[] parts = dep.split(":") + addCurseForgeRelation(parts[0], parts[1]) + } + } + if (usesMixins.toBoolean()) { + addCurseForgeRelation("requiredDependency", "gtnhmixins") + } + tasks.curseforge.dependsOn(build) + tasks.publish.dependsOn(tasks.curseforge) +} + +def addModrinthDep(scope, type, name) { + com.modrinth.minotaur.dependencies.Dependency dep; + if (!(scope in ["required", "optional", "incompatible", "embedded"])) { + throw new Exception("Invalid modrinth dependency scope: " + scope) + } + switch (type) { + case "project": + dep = new ModDependency(name, scope) + break + case "version": + dep = new VersionDependency(name, scope) + break + default: + throw new Exception("Invalid modrinth dependency type: " + type) + } + project.modrinth.dependencies.add(dep) +} + +def addCurseForgeRelation(type, name) { + if (!(type in ["requiredDependency", "embeddedLibrary", "optionalDependency", "tool", "incompatible"])) { + throw new Exception("Invalid CurseForge relation type: " + type) + } + CurseArtifact artifact = project.curseforge.curseProjects[0].mainArtifact + CurseRelation rel = (artifact.curseRelations ?: (artifact.curseRelations = new CurseRelation())) + rel."$type"(name) +} + +// Updating +task updateBuildScript { + doLast { + if (performBuildScriptUpdate(projectDir.toString())) return + + print("Build script already up-to-date!") + } +} + +if (!project.getGradle().startParameter.isOffline() && isNewBuildScriptVersionAvailable(projectDir.toString())) { + if (autoUpdateBuildScript.toBoolean()) { + performBuildScriptUpdate(projectDir.toString()) + } else { + out.style(Style.SuccessHeader).println("Build script update available! Run 'gradle updateBuildScript'") + } +} + +static URL availableBuildScriptUrl() { + 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) { + if (isNewBuildScriptVersionAvailable(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 +} + +boolean isNewBuildScriptVersionAvailable(String projectDir) { + Map parameters = ["connectTimeout": 2000, "readTimeout": 2000] + + String currentBuildScript = getFile("build.gradle").getText() + String currentBuildScriptHash = getVersionHash(currentBuildScript) + String availableBuildScript = availableBuildScriptUrl().newInputStream(parameters).getText() + String availableBuildScriptHash = getVersionHash(availableBuildScript) + + boolean isUpToDate = currentBuildScriptHash.empty || availableBuildScriptHash.empty || currentBuildScriptHash == availableBuildScriptHash + return !isUpToDate +} + +static String getVersionHash(String buildScriptContent) { + String versionLine = buildScriptContent.find("^//version: [a-z0-9]*") + if (versionLine != null) { + return versionLine.split(": ").last() + } + return "" +} + +configure(updateBuildScript) { + group = 'forgegradle' + description = 'Updates the build script to the latest version' +} + +// 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 { + URL url = new URL(sourceURL) + String fileName = url.getFile() + + //get rid of directories: + int lastSlash = fileName.lastIndexOf("/") + if (lastSlash > 0) { + fileName = fileName.substring(lastSlash + 1) + } + //get rid of extension: + if (fileName.endsWith(".jar") || fileName.endsWith(".litemod")) { + fileName = fileName.substring(0, fileName.lastIndexOf(".")) + } + + String hostName = url.getHost() + 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/${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 rawFileName) { + String bon2Version = "2.5.1" + String fileName = URLDecoder.decode(rawFileName, "UTF-8") + String cacheDir = "$project.gradle.gradleUserHomeDir/caches" + String bon2Dir = "$cacheDir/forge_gradle/deobf" + String bon2File = "$bon2Dir/BON2-${bon2Version}.jar" + String obfFile = "$cacheDir/modules-2/files-2.1/${fileName}.jar" + String deobfFile = "$cacheDir/modules-2/files-2.1/${fileName}-deobf.jar" + + if (file(deobfFile).exists()) { + return files(deobfFile) + } + + String mappingsVer + 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 "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 + } + + download.run { + src sourceURL + dest obfFile + quiet true + overwrite false + } + + exec { + commandLine 'java', '-jar', bon2File, '--inputJar', obfFile, '--outputJar', deobfFile, '--mcVer', minecraftVersion, '--mappingsVer', mappingsVer, '--notch' + workingDir bon2Dir + standardOutput = new FileOutputStream("${deobfFile}.log") + } + + return files(deobfFile) +} + +def zipMappings(String zipPath, String url, String bon2Dir) { + File zipFile = new File(zipPath) + if (zipFile.exists()) { + return + } + + String fieldsCache = "$bon2Dir/data/fields.csv" + String methodsCache = "$bon2Dir/data/methods.csv" + + download.run { + src "${url}fields.csv" + dest fieldsCache + quiet true + } + download.run { + src "${url}methods.csv" + dest methodsCache + quiet true + } + + zipFile.getParentFile().mkdirs() + ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)) + + zos.putNextEntry(new ZipEntry("fields.csv")) + Files.copy(Paths.get(fieldsCache), zos) + zos.closeEntry() + + zos.putNextEntry(new ZipEntry("methods.csv")) + Files.copy(Paths.get(methodsCache), zos) + zos.closeEntry() + + zos.close() +} + +// Helper methods + +def checkPropertyExists(String propertyName) { + if (!project.hasProperty(propertyName)) { + throw new GradleException("This project requires a property \"" + propertyName + "\"! Please add it your \"gradle.properties\". You can find all properties and their description here: https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/main/gradle.properties") + } +} + +def propertyDefaultIfUnset(String propertyName, defaultValue) { + if (!project.hasProperty(propertyName) || project.property(propertyName) == "") { + project.ext.setProperty(propertyName, defaultValue) + } +} + +def getFile(String relativePath) { + return new File(projectDir, relativePath) +} + +def getSecondaryArtifacts() { + // Because noPublishedSources from the beginning of the script is somehow not visible here... + boolean noPublishedSources = project.hasProperty("noPublishedSources") ? project.noPublishedSources.toBoolean() : false + def secondaryArtifacts = [devJar] + if (!noPublishedSources) secondaryArtifacts += [sourcesJar] + if (apiPackage) secondaryArtifacts += [apiJar] + return secondaryArtifacts } \ No newline at end of file diff --git a/dependencies.gradle b/dependencies.gradle new file mode 100644 index 0000000..1355f5b --- /dev/null +++ b/dependencies.gradle @@ -0,0 +1,27 @@ +// Add your dependencies here + +dependencies { +// compile("com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-122-GTNH:dev") + compile("com.github.GTNewHorizons:CodeChickenLib:1.1.5.5:dev") + compile("com.github.GTNewHorizons:CodeChickenCore:1.1.6:dev") + compile("com.github.GTNewHorizons:NotEnoughItems:2.3.2-GTNH:dev") +// compile("com.github.GTNewHorizons:Baubles:1.0.1.14:dev") +// compile("com.github.GTNewHorizons:WirelessCraftingTerminal:1.8.9.1:dev") + +// compileOnly("com.github.GTNewHorizons:AE2FluidCraft-Rework:1.0.15-gtnh:dev") { transitive = false } +// compileOnly("com.github.GTNewHorizons:Avaritiaddons:1.5.4-GTNH:dev") { transitive = false } +// compileOnly("com.github.GTNewHorizons:BuildCraftCompat:7.1.12:dev") { transitive = false } + compileOnly('com.github.GTNewHorizons:EnderIO:2.3.1.47:dev') {transitive=false} + compileOnly("com.github.GTNewHorizons:ForestryMC:4.4.14:dev") { transitive = false } + compileOnly("com.github.GTNewHorizons:GT5-Unofficial:5.09.41.37:dev") { transitive = false } + compileOnly("com.github.GTNewHorizons:GTplusplus:1.7.90:dev") { transitive = false } +// compileOnly("com.github.GTNewHorizons:ThaumicEnergistics:1.3.19-GTNH:dev") { transitive = false } + compileOnly("com.github.GTNewHorizons:Botania:1.9.11-GTNH:dev") { transitive = false } + compileOnly("com.gregoriust.gregtech:gregtech_1.7.10:6.14.23:dev") { transitive = false } + compileOnly("curse.maven:thaumcraft-nei-plugin-225095:2241913") { transitive = false } +// compileOnly("curse.maven:thermal-expansion-69163:2388759") { transitive = false } + +// runtime("curse.maven:cofh-core-69162:2388751") + + testCompile 'org.junit.jupiter:junit-jupiter-api:5.2.0' +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 0bae266..a607578 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,7 +1,79 @@ -# Sets default memory used for gradle commands. Can be overridden by user or command line properties. -# This is required to provide enough memory for the Minecraft decompilation process. -org.gradle.jvmargs=-Xmx3G -# suppress inspection "UnusedProperty" for whole file -mc_version=1.7.10 -nei_version=2.1.5-GTNH -proj_version=3.8.4 +modName = Just Enough Calculation + +# This is a case-sensitive string to identify your mod. Convention is to use lower case. +modId = jecalculation + +modGroup = me.towdium.jecalculation + +# WHY is there no version field? +# The build script relies on git to provide a version via tags. It is super easy and will enable you to always know the +# code base or your binary. Check out this tutorial: https://blog.mattclemente.com/2017/10/13/versioning-with-git-tags/ + +# Will update your build.gradle automatically whenever an update is available +autoUpdateBuildScript = false + +minecraftVersion = 1.7.10 +forgeVersion = 10.13.4.1614 + +# Specify a MCP channel and mappings version for dependency deobfuscation and the deobfParams task. +channel = stable +mappingsVersion = 12 + +# Define other MCP mappings for dependency deobfuscation +remoteMappings = https://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/conf/ + +# Select a username for testing your mod with breakpoints. You may leave this empty for a random username each time you +# restart Minecraft in development. Choose this dependent on your mod: +# Do you need consistent player progressing (for example Thaumcraft)? -> Select a name +# Do you need to test how your custom blocks interacts with a player that is not the owner? -> leave name empty +developmentEnvironmentUserName = Developer + +# Define a source file of your project with: +# public static final String VERSION = "GRADLETOKEN_VERSION"; +# The string's content will be replaced with your mod's version when compiled. You should use this to specify your mod's +# version in @Mod([...], version = VERSION, [...]) +# Leave these properties empty to skip individual token replacements +replaceGradleTokenInFile = Tags.java +gradleTokenModId = GRADLETOKEN_MODID +gradleTokenModName = GRADLETOKEN_MODNAME +gradleTokenVersion = GRADLETOKEN_VERSION +gradleTokenGroupName = GRADLETOKEN_GROUPNAME + +# In case your mod provides an API for other mods to implement you may declare its package here. Otherwise, you can +# leave this property empty. +# Example value: apiPackage = api + modGroup = com.myname.mymodid -> com.myname.mymodid.api +apiPackage = + +# Specify the configuration file for Forge's access transformers here. It must be placed into /src/main/resources/META-INF/ +# Example value: mymodid_at.cfg +accessTransformersFile = jeca_at.cfg + +# Provides setup for Mixins if enabled. If you don't know what mixins are: Keep it disabled! +usesMixins = false +# Adds some debug arguments like verbose output and export +usesMixinDebug = false +# Specify the location of your implementation of IMixinConfigPlugin. Leave it empty otherwise. +mixinPlugin = +# Specify the package that contains all of your Mixins. You may only place Mixins in this package or the build will fail! +mixinsPackage = +# Specify the core mod entry class if you use a core mod. This class must implement IFMLLoadingPlugin! +# This parameter is for legacy compatibility only +# Example value: coreModClass = asm.FMLPlugin + modGroup = com.myname.mymodid -> com.myname.mymodid.asm.FMLPlugin +coreModClass = +# If your project is only a consolidation of mixins or a core mod and does NOT contain a 'normal' mod ( = some class +# that is annotated with @Mod) you want this to be true. When in doubt: leave it on false! +containsMixinsAndOrCoreModOnly = false + +# Enables Mixins even if this mod doesn't use them, useful if one of the dependencies uses mixins. +forceEnableMixins = false + +# If enabled, you may use 'shadowCompile' for dependencies. They will be integrated in your jar. It is your +# responsibility check the licence and request permission for distribution, if required. +usesShadowedDependencies = false + +# Optional parameter to customize the produced artifacts. Use this to preserver artifact naming when migrating older +# projects. New projects should not use this parameter. +customArchiveBaseName = JustEnoughCalculation + +# Optional parameter to prevent the source code from being published +# noPublishedSources = diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 3e456d7..3ab0b72 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Wed Jul 02 15:54:47 CDT 2014 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.9.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 0000000..09bbb51 --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,2 @@ +before_install: + - ./gradlew setupCIWorkspace \ No newline at end of file diff --git a/libs/NotEnoughItems-1.7.10-2.1.5-GTNH-universal.jar b/libs/NotEnoughItems-1.7.10-2.1.5-GTNH-universal.jar deleted file mode 100644 index 2fab1a1..0000000 Binary files a/libs/NotEnoughItems-1.7.10-2.1.5-GTNH-universal.jar and /dev/null differ diff --git a/libs/forestry_1.7.10-4.3.1.44.jar b/libs/forestry_1.7.10-4.3.1.44.jar deleted file mode 100644 index 2909524..0000000 Binary files a/libs/forestry_1.7.10-4.3.1.44.jar and /dev/null differ diff --git a/repositories.gradle b/repositories.gradle new file mode 100644 index 0000000..65c3bbc --- /dev/null +++ b/repositories.gradle @@ -0,0 +1,18 @@ +// Add any additional repositories for your dependencies here + +repositories { + maven { + name 'GTNH Maven' + url 'http://jenkins.usrv.eu:8081/nexus/content/groups/public/' + allowInsecureProtocol + } + maven { + url 'https://cursemaven.com' + content { + includeGroup 'curse.maven' + } + } + maven { + url 'https://jitpack.io' + } +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..93c852a --- /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/me/towdium/jecalculation/JecaConfig.java b/src/main/java/me/towdium/jecalculation/JecaConfig.java index 4b476d9..18bbbcf 100644 --- a/src/main/java/me/towdium/jecalculation/JecaConfig.java +++ b/src/main/java/me/towdium/jecalculation/JecaConfig.java @@ -2,11 +2,10 @@ package me.towdium.jecalculation; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.event.FMLPreInitializationEvent; +import java.io.File; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; -import java.io.File; - public class JecaConfig { public static File configDir = new File(Loader.instance().getConfigDir(), "JustEnoughCalculation/"); public static final File configFile = new File(configDir, "main.cfg"); @@ -27,7 +26,10 @@ public class JecaConfig { } public enum EnumItems { - ClientMode, EnableInventoryCheck, ListRecipeBlackList, ListRecipeCategory; + ClientMode, + EnableInventoryCheck, + ListRecipeBlackList, + ListRecipeCategory; public String getComment() { switch (this) { @@ -36,8 +38,8 @@ public class JecaConfig { case EnableInventoryCheck: return "Set to false to disable auto inventory check"; case ListRecipeBlackList: - return "Add string identifier here to disable quick transfer of this type recipe\n" + - "Names can be found in ListRecipeCategory"; + return "Add string identifier here to disable quick transfer of this type recipe\n" + + "Names can be found in ListRecipeCategory"; case ListRecipeCategory: return "List of categories, this is maintained by the mod automatically"; } @@ -89,7 +91,7 @@ public class JecaConfig { case ListRecipeBlackList: return new String[0]; case ListRecipeCategory: - return new String[]{"minecraft.crafting", "minecraft.smelting"}; + return new String[] {"minecraft.crafting", "minecraft.smelting"}; } return JecaConfig.empty; } @@ -99,11 +101,11 @@ public class JecaConfig { if (type != null) { switch (this.getType()) { case Boolean: - return config.get(this.getCategory(), this.getName(), (Boolean) this.getDefault(), - this.getComment()); + return config.get( + this.getCategory(), this.getName(), (Boolean) this.getDefault(), this.getComment()); case ListString: - return config.get(this.getCategory(), this.getName(), (String[]) this.getDefault(), - this.getComment()); + return config.get( + this.getCategory(), this.getName(), (String[]) this.getDefault(), this.getComment()); } config.getCategory(EnumCategory.General.toString()).get(this.getName()); } @@ -128,19 +130,20 @@ public class JecaConfig { } public enum EnumType { - Boolean, ListString, Error + Boolean, + ListString, + Error } public static Object empty; public static void preInit(FMLPreInitializationEvent event) { - config = new Configuration(configFile, JustEnoughCalculation.Reference.VERSION); + config = new Configuration(configFile, Tags.VERSION); config.load(); handleInit(); config.save(); } - public static void handleInit() { for (EnumItems item : EnumItems.values()) { item.init(); diff --git a/src/main/java/me/towdium/jecalculation/JustEnoughCalculation.java b/src/main/java/me/towdium/jecalculation/JustEnoughCalculation.java index 07683c8..05c7a2d 100644 --- a/src/main/java/me/towdium/jecalculation/JustEnoughCalculation.java +++ b/src/main/java/me/towdium/jecalculation/JustEnoughCalculation.java @@ -1,57 +1,73 @@ package me.towdium.jecalculation; import cpw.mods.fml.common.Mod; -import cpw.mods.fml.common.event.FMLInitializationEvent; -import cpw.mods.fml.common.event.FMLPostInitializationEvent; -import cpw.mods.fml.common.event.FMLPreInitializationEvent; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import me.towdium.jecalculation.nei.NEIPlugin; -import me.towdium.jecalculation.network.ClientHandler; +import cpw.mods.fml.common.SidedProxy; +import cpw.mods.fml.common.event.*; +import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.network.CommonProxy; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import javax.annotation.ParametersAreNonnullByDefault; - /** * @author Towdium */ - @ParametersAreNonnullByDefault @SuppressWarnings("unused") -@SideOnly(Side.CLIENT) -@Mod(modid = JustEnoughCalculation.Reference.MODID, - name = JustEnoughCalculation.Reference.MODNAME, - version = JustEnoughCalculation.Reference.VERSION, - dependencies = "required-after:NotEnoughItems") +@Mod( + modid = Tags.MODID, + name = Tags.MODNAME, + version = Tags.VERSION, + dependencies = "required-after:NotEnoughItems", + acceptedMinecraftVersions = "[1.7.10]") public class JustEnoughCalculation { - @Mod.Instance(Reference.MODID) + public static Logger logger = LogManager.getLogger(Tags.MODID); + + @SidedProxy( + clientSide = Tags.GROUPNAME + ".network.ClientProxy", + serverSide = Tags.GROUPNAME + ".network.CommonProxy") + public static CommonProxy proxy; + + @Mod.Instance(Tags.MODID) public static JustEnoughCalculation INSTANCE; - public static ClientHandler handler = new ClientHandler(); - - public static Logger logger = LogManager.getLogger(Reference.MODID); - @Mod.EventHandler - public static void initPre(FMLPreInitializationEvent event) { - JecaConfig.preInit(event); - handler.initPre(); + public static void preInit(FMLPreInitializationEvent event) { + proxy.preInit(event); } @Mod.EventHandler public static void init(FMLInitializationEvent event) { - handler.init(); + proxy.init(event); } @Mod.EventHandler public static void postInit(FMLPostInitializationEvent event) { - handler.initPost(); - NEIPlugin.init(); + proxy.postInit(event); } - public static class Reference { - public static final String MODID = "jecalculation"; - public static final String MODNAME = "Just Enough Calculation"; - public static final String VERSION = "@VERSION@"; + @Mod.EventHandler + public void serverAboutToStart(FMLServerAboutToStartEvent event) { + proxy.serverAboutToStart(event); + } + + @Mod.EventHandler + // register server commands in this event handler + public void serverStarting(FMLServerStartingEvent event) { + proxy.serverStarting(event); + } + + @Mod.EventHandler + public void serverStarted(FMLServerStartedEvent event) { + proxy.serverStarted(event); + } + + @Mod.EventHandler + public void serverStopping(FMLServerStoppingEvent event) { + proxy.serverStopping(event); + } + + @Mod.EventHandler + public void serverStopped(FMLServerStoppedEvent event) { + proxy.serverStopped(event); } } diff --git a/src/main/java/me/towdium/jecalculation/Tags.java b/src/main/java/me/towdium/jecalculation/Tags.java new file mode 100644 index 0000000..1c4882d --- /dev/null +++ b/src/main/java/me/towdium/jecalculation/Tags.java @@ -0,0 +1,9 @@ +package me.towdium.jecalculation; + +public class Tags { + public static final String MODID = "GRADLETOKEN_MODID"; + public static final String MODNAME = "GRADLETOKEN_MODNAME"; + public static final String VERSION = "GRADLETOKEN_VERSION"; + + public static final String GROUPNAME = "GRADLETOKEN_GROUPNAME"; +} diff --git a/src/main/java/me/towdium/jecalculation/command/Commands.java b/src/main/java/me/towdium/jecalculation/command/Commands.java index bc7e525..cc737c0 100644 --- a/src/main/java/me/towdium/jecalculation/command/Commands.java +++ b/src/main/java/me/towdium/jecalculation/command/Commands.java @@ -1,12 +1,11 @@ package me.towdium.jecalculation.command; +import java.util.HashMap; +import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.command.commands.CCraft; import me.towdium.jecalculation.command.commands.CHelp; import me.towdium.jecalculation.command.commands.CMath; import me.towdium.jecalculation.command.commands.CState; -import me.towdium.jecalculation.command.commands.CCraft; - -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.HashMap; /** * Author: towdium diff --git a/src/main/java/me/towdium/jecalculation/command/ISubCommand.java b/src/main/java/me/towdium/jecalculation/command/ISubCommand.java index 2e75ff2..7779ac2 100644 --- a/src/main/java/me/towdium/jecalculation/command/ISubCommand.java +++ b/src/main/java/me/towdium/jecalculation/command/ISubCommand.java @@ -1,11 +1,10 @@ package me.towdium.jecalculation.command; -import net.minecraft.command.CommandException; -import net.minecraft.command.ICommandSender; - -import javax.annotation.ParametersAreNonnullByDefault; import java.util.Collections; import java.util.List; +import javax.annotation.ParametersAreNonnullByDefault; +import net.minecraft.command.CommandException; +import net.minecraft.command.ICommandSender; /** * Author: towdium diff --git a/src/main/java/me/towdium/jecalculation/command/JecaCommand.java b/src/main/java/me/towdium/jecalculation/command/JecaCommand.java index cabc977..0739ae8 100644 --- a/src/main/java/me/towdium/jecalculation/command/JecaCommand.java +++ b/src/main/java/me/towdium/jecalculation/command/JecaCommand.java @@ -1,5 +1,8 @@ package me.towdium.jecalculation.command; +import java.util.Collections; +import java.util.List; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.command.commands.CHelp; import me.towdium.jecalculation.utils.wrappers.Wrapper; import net.minecraft.command.CommandBase; @@ -7,10 +10,6 @@ import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentTranslation; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.Collections; -import java.util.List; - /** * Author: towdium * Date: 8/10/17. @@ -27,7 +26,6 @@ public class JecaCommand extends CommandBase { return "/jeca [options]"; } - @Override public void processCommand(ICommandSender sender, String[] args) throws CommandException { if (args.length == 0 || args[0].equalsIgnoreCase("help")) { @@ -48,8 +46,7 @@ public class JecaCommand extends CommandBase { } private String[] cut(String[] args) { - if (args.length == 0) - return new String[0]; + if (args.length == 0) return new String[0]; String[] ret = new String[args.length - 1]; System.arraycopy(args, 1, ret, 0, args.length - 1); return ret; @@ -66,12 +63,11 @@ public class JecaCommand extends CommandBase { return getListOfStringsFromIterableMatchingLastWord(args, Commands.commands.keySet()); } else { Wrapper sub = new Wrapper<>(null); - Commands.commands.values().stream().filter(c -> c.getName().equals(cmd)) - .findFirst().ifPresent(sub::push); - return sub.value != null ? sub.value.getTabCompletions(sender, cut(args)) - : Collections.emptyList(); + Commands.commands.values().stream() + .filter(c -> c.getName().equals(cmd)) + .findFirst() + .ifPresent(sub::push); + return sub.value != null ? sub.value.getTabCompletions(sender, cut(args)) : Collections.emptyList(); } } - - } diff --git a/src/main/java/me/towdium/jecalculation/command/commands/CCraft.java b/src/main/java/me/towdium/jecalculation/command/commands/CCraft.java index f2ae726..3e1d12f 100644 --- a/src/main/java/me/towdium/jecalculation/command/commands/CCraft.java +++ b/src/main/java/me/towdium/jecalculation/command/commands/CCraft.java @@ -1,14 +1,9 @@ package me.towdium.jecalculation.command.commands; -import me.towdium.jecalculation.command.ISubCommand; -import me.towdium.jecalculation.data.Controller; -import me.towdium.jecalculation.gui.JecaGui; -import net.minecraft.command.CommandException; -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.Entity; -import net.minecraft.util.ChatComponentText; - import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.command.ISubCommand; +import me.towdium.jecalculation.gui.JecaGui; +import net.minecraft.command.ICommandSender; /** * Author: Towdium @@ -26,7 +21,6 @@ public class CCraft implements ISubCommand { return "/jeca craft"; } - @Override public void execute(ICommandSender sender, String[] args) { JecaGui.openGuiCraft(true); diff --git a/src/main/java/me/towdium/jecalculation/command/commands/CHelp.java b/src/main/java/me/towdium/jecalculation/command/commands/CHelp.java index 1f2a424..121c43c 100644 --- a/src/main/java/me/towdium/jecalculation/command/commands/CHelp.java +++ b/src/main/java/me/towdium/jecalculation/command/commands/CHelp.java @@ -1,15 +1,13 @@ package me.towdium.jecalculation.command.commands; +import java.util.Comparator; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.command.Commands; import me.towdium.jecalculation.command.ISubCommand; -import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.Comparator; - /** * Author: towdium * Date: 8/10/17. @@ -17,6 +15,7 @@ import java.util.Comparator; @ParametersAreNonnullByDefault public class CHelp implements ISubCommand { public static final String NAME = "help"; + @Override public String getName() { return NAME; @@ -30,7 +29,8 @@ public class CHelp implements ISubCommand { @Override public void execute(ICommandSender sender, String[] args) { sender.addChatMessage(new ChatComponentTranslation(getKey("list"))); - Commands.commands.values().stream().sorted(Comparator.comparing(ISubCommand::getName)) - .forEachOrdered(c -> sender.addChatMessage(new ChatComponentText(c.getUsage(sender)))); + Commands.commands.values().stream() + .sorted(Comparator.comparing(ISubCommand::getName)) + .forEachOrdered(c -> sender.addChatMessage(new ChatComponentText(c.getUsage(sender)))); } } diff --git a/src/main/java/me/towdium/jecalculation/command/commands/CMath.java b/src/main/java/me/towdium/jecalculation/command/commands/CMath.java index 758eb2f..c1de3b0 100644 --- a/src/main/java/me/towdium/jecalculation/command/commands/CMath.java +++ b/src/main/java/me/towdium/jecalculation/command/commands/CMath.java @@ -1,11 +1,10 @@ package me.towdium.jecalculation.command.commands; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.command.ISubCommand; import me.towdium.jecalculation.gui.JecaGui; import net.minecraft.command.ICommandSender; -import javax.annotation.ParametersAreNonnullByDefault; - /** * Author: Towdium * Date: 19-1-21 diff --git a/src/main/java/me/towdium/jecalculation/command/commands/CState.java b/src/main/java/me/towdium/jecalculation/command/commands/CState.java index d3a4ec2..d899ba4 100644 --- a/src/main/java/me/towdium/jecalculation/command/commands/CState.java +++ b/src/main/java/me/towdium/jecalculation/command/commands/CState.java @@ -1,13 +1,10 @@ package me.towdium.jecalculation.command.commands; -import me.towdium.jecalculation.JustEnoughCalculation; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.command.ISubCommand; -import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentTranslation; -import javax.annotation.ParametersAreNonnullByDefault; - /** * Author: towdium * Date: 8/10/17. diff --git a/src/main/java/me/towdium/jecalculation/data/Controller.java b/src/main/java/me/towdium/jecalculation/data/Controller.java index 230941c..ad0943e 100644 --- a/src/main/java/me/towdium/jecalculation/data/Controller.java +++ b/src/main/java/me/towdium/jecalculation/data/Controller.java @@ -2,6 +2,14 @@ package me.towdium.jecalculation.data; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.io.File; +import java.util.*; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.JecaConfig; import me.towdium.jecalculation.JustEnoughCalculation; import me.towdium.jecalculation.data.label.labels.LPlaceholder; @@ -14,15 +22,6 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChatComponentTranslation; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import java.io.File; -import java.util.*; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - /** * Author: towdium * Date: 17-10-15. @@ -51,8 +50,7 @@ public class Controller { public static List> discover() { File dir = JecaConfig.dataDir; File[] fs = dir.listFiles(); - if (fs == null) - return new ArrayList<>(); + if (fs == null) return new ArrayList<>(); Function read = f -> { NBTTagCompound nbt = Utilities.Json.read(f); if (nbt == null) { @@ -63,22 +61,20 @@ public class Controller { } }; return Arrays.stream(fs) - .map(i -> new Pair<>(i.getName(), read.apply(i))) - .filter(i -> i.two != null) - .collect(Collectors.toList()); + .map(i -> new Pair<>(i.getName(), read.apply(i))) + .filter(i -> i.two != null) + .collect(Collectors.toList()); } public static void inport(Recipes recipes, String group) { ArrayList buffer = new ArrayList<>(); recipes.getGroup(group).stream().filter(i -> !hasDuplicate(i)).forEach(buffer::add); - for (Recipe r : buffer) - addRecipe(group, r); + for (Recipe r : buffer) addRecipe(group, r); } private static void export(String s, Function r) { EntityClientPlayerMP player = Utilities.getPlayer(); - if (player == null) - return; + if (player == null) return; File f = JecaConfig.getDataFile(s); Utilities.Json.write(r.apply(getRecipes()), f); @@ -192,10 +188,8 @@ public class Controller { public static boolean hasDuplicate(Recipe r, String group, int index) { Recipes.RecipeIterator ri = recipeIterator(); return ri.stream().anyMatch(i -> { - if (ri.getIndex() == index && ri.getGroup().equals(group)) - return false; - else - return i.equals(r); + if (ri.getIndex() == index && ri.getGroup().equals(group)) return false; + else return i.equals(r); }); } @@ -203,7 +197,6 @@ public class Controller { return recipeIterator().stream().anyMatch(i -> i.equals(r)); } - public static void loadFromLocal() { //noinspection ResultOfMethodCallIgnored JecaConfig.dataDir.mkdirs(); @@ -214,9 +207,8 @@ public class Controller { if (nbt != null) { rCraftClient = new RecordCraft(nbt.getCompoundTag(KEY_CRAFT)); rMathClient = new RecordMath(nbt.getCompoundTag(KEY_MATH)); - rPlayerClient = nbt.hasKey(KEY_PLAYER) ? - new RecordPlayer(nbt.getCompoundTag(KEY_PLAYER)) : - new RecordPlayer(); + rPlayerClient = + nbt.hasKey(KEY_PLAYER) ? new RecordPlayer(nbt.getCompoundTag(KEY_PLAYER)) : new RecordPlayer(); } else { rPlayerClient = new RecordPlayer(); rCraftClient = new RecordCraft(new NBTTagCompound()); diff --git a/src/main/java/me/towdium/jecalculation/data/label/ILabel.java b/src/main/java/me/towdium/jecalculation/data/label/ILabel.java index b78bc69..b3c9d9f 100644 --- a/src/main/java/me/towdium/jecalculation/data/label/ILabel.java +++ b/src/main/java/me/towdium/jecalculation/data/label/ILabel.java @@ -2,6 +2,13 @@ package me.towdium.jecalculation.data.label; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.*; +import java.util.function.BiPredicate; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.JustEnoughCalculation; import me.towdium.jecalculation.data.label.labels.LFluidStack; import me.towdium.jecalculation.data.label.labels.LItemStack; @@ -24,14 +31,6 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.*; -import java.util.function.BiPredicate; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.stream.Collectors; - /** * Author: towdium * Date: 8/11/17. @@ -68,10 +67,10 @@ public interface ILabel { MERGER.register("itemStack", "itemStack", Impl.form(LItemStack.class, LItemStack.class, LItemStack::merge)); MERGER.register("oreDict", "oreDict", Impl.form(LOreDict.class, LOreDict.class, LOreDict::mergeSame)); MERGER.register("oreDict", "itemStack", Impl.form(LOreDict.class, LItemStack.class, LOreDict::mergeFuzzy)); - MERGER.register("fluidStack", "fluidStack", - Impl.form(LFluidStack.class, LFluidStack.class, LFluidStack::merge)); - MERGER.register("placeholder", "placeholder", - Impl.form(LPlaceholder.class, LPlaceholder.class, LPlaceholder::merge)); + MERGER.register( + "fluidStack", "fluidStack", Impl.form(LFluidStack.class, LFluidStack.class, LFluidStack::merge)); + MERGER.register( + "placeholder", "placeholder", Impl.form(LPlaceholder.class, LPlaceholder.class, LPlaceholder::merge)); } long getAmount(); @@ -114,7 +113,6 @@ public interface ILabel { @SideOnly(Side.CLIENT) void drawLabel(JecaGui gui, int xPos, int yPos, boolean center); - /** * Since {@link ILabel} merging is bidirectional, it is redundant to * implement on both side. So this class is created for merging @@ -126,8 +124,7 @@ public interface ILabel { class Merger { private final Utilities.Relation functions = new Utilities.Relation<>(); - private Merger() { - } + private Merger() {} public void register(String a, String b, MergerFunction func) { functions.put(a, b, func); @@ -144,8 +141,7 @@ public interface ILabel { */ public Optional merge(ILabel a, ILabel b) { MergerFunction mf = functions.get(a.getIdentifier(), b.getIdentifier()); - if (mf == null) - return Optional.empty(); + if (mf == null) return Optional.empty(); return Optional.ofNullable(mf.merge(a, b)); } @@ -175,8 +171,7 @@ public interface ILabel { private final HashMap> idToData = new HashMap<>(); - private Serializer() { - } + private Serializer() {} public void register(String identifier, Function deserializer) { idToData.put(identifier, deserializer); @@ -198,8 +193,7 @@ public interface ILabel { public ILabel deserialize(NBTTagCompound nbt) { String s = nbt.getString(KEY_IDENTIFIER); Function func = idToData.get(s); - if (func == null) - JustEnoughCalculation.logger.warn("Unrecognized identifier \"" + s + "\", abort"); + if (func == null) JustEnoughCalculation.logger.warn("Unrecognized identifier \"" + s + "\", abort"); else try { return func.apply(nbt.getCompoundTag(KEY_CONTENT)); @@ -237,7 +231,10 @@ public interface ILabel { * while input does not contain all entries recorded in tag * Fallback is also used with one input label to guess possible conventions */ - public enum Priority {SUGGEST, FALLBACK} + public enum Priority { + SUGGEST, + FALLBACK + } static { handlers = new EnumMap<>(Priority.class); @@ -246,12 +243,9 @@ public interface ILabel { } public static ILabel from(@Nullable Object o) { - if (o == null) - return ILabel.EMPTY; - else if (o instanceof ItemStack) - return new LItemStack((ItemStack) o); - else if (o instanceof FluidStack) - return new LFluidStack((FluidStack) o); + if (o == null) return ILabel.EMPTY; + else if (o instanceof ItemStack) return new LItemStack((ItemStack) o); + else if (o instanceof FluidStack) return new LFluidStack((FluidStack) o); else if (o instanceof EnchantmentData) { ItemStack itemStack = new ItemStack(Items.enchanted_book); new ItemEnchantedBook().addEnchantment(itemStack, (EnchantmentData) o); @@ -274,17 +268,10 @@ public interface ILabel { // to test if the labels can be converted to other labels (like oreDict) public Pair, List> guess(List labels, @Nullable Class context) { - List suggest = new ReversedIterator<>(handlers.get(Priority.SUGGEST)).stream() - .flatMap(h -> h.convert(labels, - context) - .stream()) - .collect(Collectors.toList()); - List fallback = new ReversedIterator<>(handlers.get(Priority.FALLBACK)).stream() - .flatMap(h -> h.convert( - labels, context) - .stream()) - .collect( - Collectors.toList()); + List suggest = new ReversedIterator<>(handlers.get(Priority.SUGGEST)) + .stream().flatMap(h -> h.convert(labels, context).stream()).collect(Collectors.toList()); + List fallback = new ReversedIterator<>(handlers.get(Priority.FALLBACK)) + .stream().flatMap(h -> h.convert(labels, context).stream()).collect(Collectors.toList()); return new Pair<>(suggest, fallback); } @@ -298,14 +285,12 @@ public interface ILabel { private final ArrayList records = new ArrayList<>(); - private RegistryEditor() { - } + private RegistryEditor() {} public void register(Supplier editor, String unlocalizedName, ILabel representation) { records.add(new Record(editor, "common.label." + unlocalizedName, representation)); } - public List getRecords() { return records; } @@ -332,11 +317,9 @@ public interface ILabel { } @Override - public void drawLabel(JecaGui gui, int xPos, int yPos, boolean center) { - } + public void drawLabel(JecaGui gui, int xPos, int yPos, boolean center) {} - private LEmpty() { - } + private LEmpty() {} @Nullable @Override @@ -395,8 +378,7 @@ public interface ILabel { } @Override - public void getToolTip(List existing, boolean detailed) { - } + public void getToolTip(List existing, boolean detailed) {} @Override public ILabel copy() { @@ -412,7 +394,6 @@ public interface ILabel { public String getIdentifier() { return IDENTIFIER; } - } abstract class Impl implements ILabel { @@ -453,7 +434,7 @@ public interface ILabel { GlStateManager.popMatrix(); } - abstract protected void drawLabel(JecaGui gui); + protected abstract void drawLabel(JecaGui gui); @Override public ILabel increaseAmount() { @@ -466,7 +447,8 @@ public interface ILabel { public ILabel decreaseAmount() { if (getAmount() <= 0) { return ILabel.EMPTY; - } if (getAmount() <= getMultiplier()) { + } + if (getAmount() <= getMultiplier()) { return setAmount(1); } else { return setAmount(getAmount() - getMultiplier()); @@ -490,22 +472,17 @@ public interface ILabel { long amountD = d.isPercent() ? d.getAmount() : Math.multiplyExact(d.getAmount(), 100); long amount = Math.addExact(amountC, amountD); long amountI = (amount > 0 ? Math.addExact(amount, 99) : Math.subtractExact(amount, 99)) / 100; - if (amount == 0) - return EMPTY; - else if (amount > 0) - return d.copy().setAmount(d.isPercent() ? amount : amountI); - else - return c.copy().setAmount(c.isPercent() ? amount : amountI); - } else - return null; + if (amount == 0) return EMPTY; + else if (amount > 0) return d.copy().setAmount(d.isPercent() ? amount : amountI); + else return c.copy().setAmount(c.isPercent() ? amount : amountI); + } else return null; }; } @Override public ILabel multiply(float i) { float amount = i * getAmount(); - if (amount > Long.MAX_VALUE) - throw new ArithmeticException("Multiply overflow"); + if (amount > Long.MAX_VALUE) throw new ArithmeticException("Multiply overflow"); return setAmount((long) amount); } @@ -519,12 +496,9 @@ public interface ILabel { boolean showStack = stack != 0; boolean showReminder = stack < 1000 && remainder != 0; String tip = ""; - if (showStack) - tip += Utilities.cutNumber(stack, 5) + "x64"; - if (showStack && showReminder) - tip += "+"; - if (showReminder) - tip += Long.toString(remainder); + if (showStack) tip += Utilities.cutNumber(stack, 5) + "x64"; + if (showStack && showReminder) tip += "+"; + if (showReminder) tip += Long.toString(remainder); existing.add(FORMAT_GREY + Utilities.I18n.get("label.common.amount", tip)); } } @@ -536,8 +510,7 @@ public interface ILabel { @Override public ILabel setAmount(long amount) { - if (amount == 0) - return ILabel.EMPTY; + if (amount == 0) return ILabel.EMPTY; this.amount = amount; return this; } @@ -546,8 +519,7 @@ public interface ILabel { public NBTTagCompound toNbt() { NBTTagCompound nbt = new NBTTagCompound(); nbt.setLong(KEY_AMOUNT, amount); - if (percent) - nbt.setBoolean(KEY_PERCENT, true); + if (percent) nbt.setBoolean(KEY_PERCENT, true); return nbt; } @@ -557,8 +529,7 @@ public interface ILabel { } public ILabel setPercent(boolean p) { - if (p && !acceptPercent()) - throw new UnsupportedOperationException(); + if (p && !acceptPercent()) throw new UnsupportedOperationException(); if (p && !percent) { amount *= 100; percent = true; @@ -583,18 +554,14 @@ public interface ILabel { @SideOnly(Side.CLIENT) @SuppressWarnings("IntegerDivisionInFloatingPointContext") public String getAmountString(boolean round) { - if (getAmount() == 0) - return ""; - else if (!percent) - return Utilities.cutNumber(getAmount(), 5); - else if (round) - return Utilities.cutNumber((getAmount() + 99) / 100, 5); - else - return Utilities.cutNumber(getAmount(), 4) + "%"; + if (getAmount() == 0) return ""; + else if (!percent) return Utilities.cutNumber(getAmount(), 5); + else if (round) return Utilities.cutNumber((getAmount() + 99) / 100, 5); + else return Utilities.cutNumber(getAmount(), 4) + "%"; } @Override - abstract public Impl copy(); + public abstract Impl copy(); @Override public boolean matches(Object l) { diff --git a/src/main/java/me/towdium/jecalculation/data/label/labels/LFluidStack.java b/src/main/java/me/towdium/jecalculation/data/label/labels/LFluidStack.java index 96ce3a8..597c543 100644 --- a/src/main/java/me/towdium/jecalculation/data/label/labels/LFluidStack.java +++ b/src/main/java/me/towdium/jecalculation/data/label/labels/LFluidStack.java @@ -2,6 +2,11 @@ package me.towdium.jecalculation.data.label.labels; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.gui.Resource; @@ -11,12 +16,6 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - /** * Author: towdium * Date: 17-9-27. @@ -58,8 +57,7 @@ public class LFluidStack extends ILabel.Impl { super(nbt); String id = nbt.getString(KEY_FLUID); Fluid f = FluidRegistry.getFluid(id); - if (f == null) - throw new Serializer.SerializationException("Fluid " + id + " cannot be resolved, ignoring"); + if (f == null) throw new Serializer.SerializationException("Fluid " + id + " cannot be resolved, ignoring"); init(f, nbt.hasKey(KEY_NBT) ? nbt.getCompoundTag(KEY_NBT) : null); } @@ -86,7 +84,6 @@ public class LFluidStack extends ILabel.Impl { return amount >= 1000 ? Utilities.cutNumber(amount / 1000f, 4) + "B" : amount + "mB"; } - @Override @SideOnly(Side.CLIENT) public String getDisplayName() { @@ -103,8 +100,7 @@ public class LFluidStack extends ILabel.Impl { if (l instanceof LFluidStack) { LFluidStack lfs = (LFluidStack) l; return (Objects.equals(nbt, lfs.nbt)) && fluid == lfs.fluid; - } else - return false; + } else return false; } @Override @@ -116,8 +112,7 @@ public class LFluidStack extends ILabel.Impl { public NBTTagCompound toNbt() { NBTTagCompound ret = super.toNbt(); ret.setString(KEY_FLUID, FluidRegistry.getFluidName(fluid)); - if (nbt != null) - ret.setTag(KEY_NBT, nbt); + if (nbt != null) ret.setTag(KEY_NBT, nbt); return ret; } @@ -129,7 +124,6 @@ public class LFluidStack extends ILabel.Impl { existing.add(FORMAT_BLUE + FORMAT_ITALIC + Utilities.getModName(fluid)); } - @Override @SideOnly(Side.CLIENT) public void drawLabel(JecaGui gui) { @@ -147,9 +141,7 @@ public class LFluidStack extends ILabel.Impl { } public static boolean merge(ILabel a, ILabel b) { - if (a instanceof LFluidStack && b instanceof LFluidStack) - return a.matches(b); - else - return false; + if (a instanceof LFluidStack && b instanceof LFluidStack) return a.matches(b); + else return false; } } diff --git a/src/main/java/me/towdium/jecalculation/data/label/labels/LItemStack.java b/src/main/java/me/towdium/jecalculation/data/label/labels/LItemStack.java index 982b012..62164ff 100644 --- a/src/main/java/me/towdium/jecalculation/data/label/labels/LItemStack.java +++ b/src/main/java/me/towdium/jecalculation/data/label/labels/LItemStack.java @@ -1,8 +1,16 @@ package me.towdium.jecalculation.data.label.labels; +import static net.minecraftforge.oredict.OreDictionary.WILDCARD_VALUE; + import cpw.mods.fml.common.registry.GameData; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.utils.ItemStackHelper; @@ -11,15 +19,6 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -import static net.minecraftforge.oredict.OreDictionary.WILDCARD_VALUE; - /** * Author: towdium * Date: 8/11/17. @@ -59,8 +58,12 @@ public class LItemStack extends ILabel.Impl { if (ItemStackHelper.isEmpty(stack)) throw new Serializer.SerializationException("Item " + strId + " cannot be resolved, ignoring"); Item i = stack.getItem(); - init(i, tag.getInteger(KEY_META), tag.hasKey(KEY_NBT) ? stack.stackTagCompound : null, - tag.getBoolean(KEY_F_META), tag.getBoolean(KEY_F_NBT)); + init( + i, + tag.getInteger(KEY_META), + tag.hasKey(KEY_NBT) ? stack.stackTagCompound : null, + tag.getBoolean(KEY_F_META), + tag.getBoolean(KEY_F_NBT)); } private LItemStack(LItemStack lis) { @@ -84,20 +87,19 @@ public class LItemStack extends ILabel.Impl { rep.setTagCompound(this.nbt); } - public static boolean merge(ILabel a, ILabel b) { if (a instanceof LItemStack && b instanceof LItemStack) { LItemStack lisA = (LItemStack) a; LItemStack lisB = (LItemStack) b; - if (lisA.meta != lisB.meta && !lisA.fMeta && lisA.meta != WILDCARD_VALUE && !lisB.fMeta && - lisB.meta != WILDCARD_VALUE) - return false; + if (lisA.meta != lisB.meta + && !lisA.fMeta + && lisA.meta != WILDCARD_VALUE + && !lisB.fMeta + && lisB.meta != WILDCARD_VALUE) return false; if (!lisA.fNbt && !lisB.fNbt) { if (lisA.nbt == null) { - if (lisB.nbt != null) - return false; - } else if (lisB.nbt == null || !lisA.nbt.equals(lisB.nbt)) - return false; + if (lisB.nbt != null) return false; + } else if (lisB.nbt == null || !lisA.nbt.equals(lisB.nbt)) return false; } return lisA.item == lisB.item; } @@ -105,39 +107,29 @@ public class LItemStack extends ILabel.Impl { } public static List suggest(List iss, @Nullable Class context) { - if (iss.size() == 0) - return new ArrayList<>(); - for (ILabel i : iss) - if (!(i instanceof LItemStack)) - return new ArrayList<>(); + if (iss.size() == 0) return new ArrayList<>(); + for (ILabel i : iss) if (!(i instanceof LItemStack)) return new ArrayList<>(); LItemStack lis = (LItemStack) iss.get(0); boolean fMeta = false; boolean fNbt = false; for (ILabel i : iss) { LItemStack ii = (LItemStack) i; - if (ii.item != lis.item) - return new ArrayList<>(); - if (ii.meta != lis.meta || ii.fMeta) - fMeta = true; - if (!Objects.equals(ii.nbt, lis.nbt)) - fNbt = true; + if (ii.item != lis.item) return new ArrayList<>(); + if (ii.meta != lis.meta || ii.fMeta) fMeta = true; + if (!Objects.equals(ii.nbt, lis.nbt)) fNbt = true; } if (fMeta || fNbt) return Collections.singletonList(lis.copy().setFMeta(fMeta).setFNbt(fNbt)); - else - return new ArrayList<>(); + else return new ArrayList<>(); } - public static List fallback(List iss, @Nullable Class context) { List ret = new ArrayList<>(); if (iss.size() == 1) { ILabel label = iss.get(0); - if (!(label instanceof LItemStack)) - return ret; + if (!(label instanceof LItemStack)) return ret; LItemStack lis = (LItemStack) label; - if (lis.fNbt || lis.fMeta) - return new ArrayList<>(); + if (lis.fNbt || lis.fMeta) return new ArrayList<>(); ret.add(lis.copy().setFMeta(true)); ret.add(lis.copy().setFNbt(true)); ret.add(lis.copy().setFMeta(true).setFNbt(true)); @@ -147,8 +139,7 @@ public class LItemStack extends ILabel.Impl { public LItemStack setFMeta(boolean f) { fMeta = f; - if (f) - meta = 0; + if (f) meta = 0; rep = new ItemStack(item, 1, meta); rep.setTagCompound(nbt); return this; @@ -156,8 +147,7 @@ public class LItemStack extends ILabel.Impl { public LItemStack setFNbt(boolean f) { fNbt = f; - if (f) - nbt = null; + if (f) nbt = null; rep = new ItemStack(item, 1, meta); rep.setTagCompound(nbt); return this; @@ -171,10 +161,8 @@ public class LItemStack extends ILabel.Impl { @SideOnly(Side.CLIENT) public void getToolTip(List existing, boolean detailed) { super.getToolTip(existing, detailed); - if (fMeta) - existing.add(FORMAT_GREY + Utilities.I18n.get("label.item_stack.fuzzy_meta")); - if (fNbt) - existing.add(FORMAT_GREY + Utilities.I18n.get("label.item_stack.fuzzy_nbt")); + if (fMeta) existing.add(FORMAT_GREY + Utilities.I18n.get("label.item_stack.fuzzy_meta")); + if (fNbt) existing.add(FORMAT_GREY + Utilities.I18n.get("label.item_stack.fuzzy_nbt")); existing.add(FORMAT_BLUE + FORMAT_ITALIC + Utilities.getModName(item)); } @@ -198,10 +186,13 @@ public class LItemStack extends ILabel.Impl { public boolean matches(Object l) { if (l instanceof LItemStack) { LItemStack lis = (LItemStack) l; - return (Objects.equals(nbt, lis.nbt)) && meta == lis.meta && item == lis.item && fNbt == lis.fNbt && - super.matches(l) && fMeta == lis.fMeta; - } else - return false; + return (Objects.equals(nbt, lis.nbt)) + && meta == lis.meta + && item == lis.item + && fNbt == lis.fNbt + && super.matches(l) + && fMeta == lis.fMeta; + } else return false; } @Override @@ -211,19 +202,14 @@ public class LItemStack extends ILabel.Impl { @Override public NBTTagCompound toNbt() { - if (item == null) - return ILabel.EMPTY.toNbt(); + if (item == null) return ILabel.EMPTY.toNbt(); String strId = Item.itemRegistry.getNameForObject(item); NBTTagCompound ret = super.toNbt(); - if (meta != 0) - ret.setInteger(KEY_META, meta); + if (meta != 0) ret.setInteger(KEY_META, meta); ret.setString(KEY_ITEM, strId); - if (nbt != null) - ret.setTag(KEY_NBT, nbt); - if (fMeta) - ret.setBoolean(KEY_F_META, true); - if (fNbt) - ret.setBoolean(KEY_F_NBT, true); + if (nbt != null) ret.setTag(KEY_NBT, nbt); + if (fMeta) ret.setBoolean(KEY_F_META, true); + if (fNbt) ret.setBoolean(KEY_F_NBT, true); return ret; } @@ -242,6 +228,9 @@ public class LItemStack extends ILabel.Impl { @Override public int hashCode() { // TODO all labels use super hashcode - return (nbt == null ? 0 : nbt.hashCode()) ^ meta ^ item.getUnlocalizedName().hashCode() ^ (int) amount; + return (nbt == null ? 0 : nbt.hashCode()) + ^ meta + ^ item.getUnlocalizedName().hashCode() + ^ (int) amount; } } diff --git a/src/main/java/me/towdium/jecalculation/data/label/labels/LOreDict.java b/src/main/java/me/towdium/jecalculation/data/label/labels/LOreDict.java index b8c8f9d..70ed601 100644 --- a/src/main/java/me/towdium/jecalculation/data/label/labels/LOreDict.java +++ b/src/main/java/me/towdium/jecalculation/data/label/labels/LOreDict.java @@ -2,7 +2,14 @@ package me.towdium.jecalculation.data.label.labels; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import me.towdium.jecalculation.JustEnoughCalculation; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.Tags; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.polyfill.mc.util.NonNullList; @@ -15,14 +22,6 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.oredict.OreDictionary; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.stream.Collectors; - /** * Author: towdium * Date: 17-9-10. @@ -59,8 +58,7 @@ public class LOreDict extends ILabel.Impl { LOreDict lodA = (LOreDict) a; LOreDict lodB = (LOreDict) b; return lodA.getName().equals(lodB.getName()); - } else - return false; + } else return false; } public static boolean mergeFuzzy(ILabel a, ILabel b) { @@ -81,35 +79,32 @@ public class LOreDict extends ILabel.Impl { public static List suggest(List iss, @Nullable Class context) { ILabel l = iss.get(0); - if (!(l instanceof LItemStack)) - return new ArrayList<>(); + if (!(l instanceof LItemStack)) return new ArrayList<>(); LItemStack lis = (LItemStack) l; HashSet ids = new HashSet<>(); long amount = lis.getAmount(); - for (int i : OreDictionary.getOreIDs(lis.getRep())) - if (check(i, iss, true)) - ids.add(i); - return ids.stream().map(i -> new LOreDict(OreDictionary.getOreName(i), amount)).collect(Collectors.toList()); + for (int i : OreDictionary.getOreIDs(lis.getRep())) if (check(i, iss, true)) ids.add(i); + return ids.stream() + .map(i -> new LOreDict(OreDictionary.getOreName(i), amount)) + .collect(Collectors.toList()); } public static List fallback(List iss, @Nullable Class context) { ILabel l = iss.get(0); - if (!(l instanceof LItemStack)) - return new ArrayList<>(); + if (!(l instanceof LItemStack)) return new ArrayList<>(); LItemStack lis = (LItemStack) l; HashSet ids = new HashSet<>(); long amount = lis.getAmount(); - for (int i : OreDictionary.getOreIDs(lis.getRep())) - if (check(i, iss, false)) - ids.add(i); - return ids.stream().map(i -> new LOreDict(OreDictionary.getOreName(i), amount)).collect(Collectors.toList()); + for (int i : OreDictionary.getOreIDs(lis.getRep())) if (check(i, iss, false)) ids.add(i); + return ids.stream() + .map(i -> new LOreDict(OreDictionary.getOreName(i), amount)) + .collect(Collectors.toList()); } // check labels in the list suitable for the ore id private static boolean check(int id, List labels, boolean biDir) { ArrayList ores = OreDictionary.getOres(OreDictionary.getOreName(id)); - if (labels.size() == 1 && ores.size() == 1 && biDir && !MODE_FORCE) - return false; + if (labels.size() == 1 && ores.size() == 1 && biDir && !MODE_FORCE) return false; Wrapper acceptable = new Wrapper<>(true); if (biDir) { @@ -159,8 +154,7 @@ public class LOreDict extends ILabel.Impl { list.add(ore); } } - if (list.isEmpty()) - return ItemStackHelper.EMPTY_ITEM_STACK; + if (list.isEmpty()) return ItemStackHelper.EMPTY_ITEM_STACK; long index = System.currentTimeMillis() / 1500; return list.get((int) (index % list.size())); } @@ -205,7 +199,7 @@ public class LOreDict extends ILabel.Impl { @SideOnly(Side.CLIENT) public void getToolTip(List existing, boolean detailed) { super.getToolTip(existing, detailed); - existing.add(FORMAT_BLUE + FORMAT_ITALIC + JustEnoughCalculation.Reference.MODNAME); + existing.add(FORMAT_BLUE + FORMAT_ITALIC + Tags.MODNAME); } @Override diff --git a/src/main/java/me/towdium/jecalculation/data/label/labels/LPlaceholder.java b/src/main/java/me/towdium/jecalculation/data/label/labels/LPlaceholder.java index c16c4ed..d81b874 100644 --- a/src/main/java/me/towdium/jecalculation/data/label/labels/LPlaceholder.java +++ b/src/main/java/me/towdium/jecalculation/data/label/labels/LPlaceholder.java @@ -2,16 +2,6 @@ package me.towdium.jecalculation.data.label.labels; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import me.towdium.jecalculation.JustEnoughCalculation; -import me.towdium.jecalculation.data.label.ILabel; -import me.towdium.jecalculation.gui.JecaGui; -import me.towdium.jecalculation.gui.Resource; -import me.towdium.jecalculation.utils.Utilities; -import me.towdium.jecalculation.utils.wrappers.Pair; -import net.minecraft.nbt.NBTTagCompound; - -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; import java.util.Arrays; import java.util.List; import java.util.Objects; @@ -19,6 +9,15 @@ import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.Tags; +import me.towdium.jecalculation.data.label.ILabel; +import me.towdium.jecalculation.gui.JecaGui; +import me.towdium.jecalculation.gui.Resource; +import me.towdium.jecalculation.utils.Utilities; +import me.towdium.jecalculation.utils.wrappers.Pair; +import net.minecraft.nbt.NBTTagCompound; /** * Author: towdium @@ -28,7 +27,7 @@ import java.util.stream.Collectors; public class LPlaceholder extends ILabel.Impl { public static final String KEY_NAME = "name"; public static final String IDENTIFIER = "placeholder"; - public static boolean state = true; // true for client, false for server + public static boolean state = true; // true for client, false for server static Utilities.Recent recentClient = new Utilities.Recent<>(100); static Utilities.Recent recentServer = new Utilities.Recent<>(100); @@ -51,8 +50,7 @@ public class LPlaceholder extends ILabel.Impl { public LPlaceholder(String name, long amount, boolean silent) { super(amount, false); this.name = name; - if (!silent) - getActive().push(new LPlaceholder(name, 1, true), false); + if (!silent) getActive().push(new LPlaceholder(name, 1, true), false); } public LPlaceholder(LPlaceholder label) { @@ -119,7 +117,7 @@ public class LPlaceholder extends ILabel.Impl { @SideOnly(Side.CLIENT) public void getToolTip(List existing, boolean detailed) { super.getToolTip(existing, detailed); - existing.add(FORMAT_BLUE + FORMAT_ITALIC + JustEnoughCalculation.Reference.MODNAME); + existing.add(FORMAT_BLUE + FORMAT_ITALIC + Tags.MODNAME); } public static boolean merge(ILabel a, ILabel b) { @@ -127,15 +125,14 @@ public class LPlaceholder extends ILabel.Impl { LPlaceholder lpA = (LPlaceholder) a; LPlaceholder lpB = (LPlaceholder) b; return lpA.name.equals(lpB.name); - } else - return false; + } else return false; } public static class Converter { @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") - static List>> converters = Arrays.asList( - new Pair<>(Pattern.compile("\\[\\[Gas: mekanism:(.+)], (\\d+)]"), - i -> new LPlaceholder("Gas - " + capitalize(i.group(1)), Integer.parseInt(i.group(2))))); + static List>> converters = Arrays.asList(new Pair<>( + Pattern.compile("\\[\\[Gas: mekanism:(.+)], (\\d+)]"), + i -> new LPlaceholder("Gas - " + capitalize(i.group(1)), Integer.parseInt(i.group(2))))); public static String capitalize(String s) { String[] arr = s.replace('_', ' ').split(" "); @@ -150,10 +147,14 @@ public class LPlaceholder extends ILabel.Impl { public static LPlaceholder from(Object o) { String s = o.toString(); - return converters.stream().map(i -> { - Matcher m = i.one.matcher(s); - return m.matches() ? i.two.apply(m) : null; - }).filter(Objects::nonNull).findFirst().orElseGet(() -> new LPlaceholder(s, 1)); + return converters.stream() + .map(i -> { + Matcher m = i.one.matcher(s); + return m.matches() ? i.two.apply(m) : null; + }) + .filter(Objects::nonNull) + .findFirst() + .orElseGet(() -> new LPlaceholder(s, 1)); } } } diff --git a/src/main/java/me/towdium/jecalculation/data/structure/CostList.java b/src/main/java/me/towdium/jecalculation/data/structure/CostList.java index 15aa05e..aa89ed7 100644 --- a/src/main/java/me/towdium/jecalculation/data/structure/CostList.java +++ b/src/main/java/me/towdium/jecalculation/data/structure/CostList.java @@ -1,27 +1,22 @@ package me.towdium.jecalculation.data.structure; +import static me.towdium.jecalculation.utils.Utilities.stream; + +import java.util.*; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.Controller; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.utils.Utilities; import me.towdium.jecalculation.utils.wrappers.Pair; -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityClientPlayerMP; -import net.minecraft.util.ChatComponentTranslation; - -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.*; -import java.util.stream.Collectors; - -import static me.towdium.jecalculation.data.structure.Recipe.IO.INPUT; -import static me.towdium.jecalculation.data.structure.Recipe.IO.OUTPUT; -import static me.towdium.jecalculation.utils.Utilities.stream; // positive => generate; negative => require @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class CostList { + List labels; public CostList() { @@ -30,41 +25,50 @@ public class CostList { public CostList(List labels) { this.labels = labels.stream() - .filter(i -> i != ILabel.EMPTY) - .map(i -> i.copy().multiply(-1)) - .collect(Collectors.toList()); + .filter(i -> i != ILabel.EMPTY) + .map(i -> i.copy().multiply(-1)) + .collect(Collectors.toList()); } public CostList(List positive, List negative) { this(positive); multiply(-1); - merge(new CostList(negative), false, true); + mergeInplace(new CostList(negative), false); } - @SuppressWarnings("UnusedReturnValue") - public CostList merge(CostList costList, boolean strict, boolean inplace) { - CostList ret = inplace ? this : copy(); - costList.labels.forEach(i -> ret.labels.add(i.copy())); - for (int i = 0; i < ret.labels.size(); i++) { - for (int j = i + 1; j < ret.labels.size(); j++) { + public static CostList merge(CostList a, CostList b, boolean strict) { + CostList ret = a.copy(); + ret.mergeInplace(b, strict); + return ret; + } + + /** + * Merge that to this + * + * @param that cost list to merge + * @param strict if true, only merge same label + */ + public void mergeInplace(CostList that, boolean strict) { + that.labels.forEach(i -> this.labels.add(i.copy())); + for (int i = 0; i < this.labels.size(); i++) { + for (int j = i + 1; j < this.labels.size(); j++) { if (strict) { - ILabel a = ret.labels.get(i); - ILabel b = ret.labels.get(j); + ILabel a = this.labels.get(i); + ILabel b = this.labels.get(j); if (a.matches(b)) { - ret.labels.set(i, a.setAmount(Math.addExact(a.getAmount(), b.getAmount()))); - ret.labels.set(j, ILabel.EMPTY); + this.labels.set(i, a.setAmount(Math.addExact(a.getAmount(), b.getAmount()))); + this.labels.set(j, ILabel.EMPTY); } } else { - Optional l = ILabel.MERGER.merge(ret.labels.get(i), ret.labels.get(j)); + Optional l = ILabel.MERGER.merge(this.labels.get(i), this.labels.get(j)); if (l.isPresent()) { - ret.labels.set(i, l.get()); - ret.labels.set(j, ILabel.EMPTY); + this.labels.set(i, l.get()); + this.labels.set(j, ILabel.EMPTY); } } } } - ret.labels = ret.labels.stream().filter(i -> i != ILabel.EMPTY).collect(Collectors.toList()); - return ret; + this.labels = this.labels.stream().filter(i -> i != ILabel.EMPTY).collect(Collectors.toList()); } public CostList multiply(long i) { @@ -77,9 +81,8 @@ public class CostList { if (obj instanceof CostList) { CostList c = (CostList) obj; CostList m = c.copy().multiply(-1); - return merge(m, true, false).labels.isEmpty(); - } else - return false; + return CostList.merge(this, m, true).labels.isEmpty(); + } else return false; } public CostList copy() { @@ -88,7 +91,6 @@ public class CostList { return ret; } - public boolean isEmpty() { return labels.isEmpty(); } @@ -97,7 +99,6 @@ public class CostList { return labels; } - public Calculator calculate() { return new Calculator(); } @@ -105,8 +106,7 @@ public class CostList { @Override public int hashCode() { int hash = 0; - for (ILabel i : labels) - hash ^= i.hashCode(); + for (ILabel i : labels) hash ^= i.hashCode(); return hash; } @@ -117,59 +117,63 @@ public class CostList { private int index; public Calculator() throws ArithmeticException { - EntityClientPlayerMP player = Utilities.getPlayer(); - HashSet set = new HashSet<>(); set.add(CostList.this); - Pair next = find(true); + + // reset index & iterator + reset(); + Pair next = find(); int count = 0; while (next != null) { CostList original = getCurrent(); - List outL = next.one.getLabel(OUTPUT) - .stream() - .filter(i -> i != ILabel.EMPTY) - .collect(Collectors.toList()); + List outL = next.one.getOutput().stream() + .filter(i -> i != ILabel.EMPTY) + .collect(Collectors.toList()); CostList outC = new CostList(outL); outC.multiply(-next.two); - List inL = next.one.getLabel(INPUT) - .stream() - .filter(i -> i != ILabel.EMPTY) - .collect(Collectors.toList()); + List inL = next.one.getInput().stream() + .filter(i -> i != ILabel.EMPTY) + .collect(Collectors.toList()); CostList inC = new CostList(inL); inC.multiply(next.two); - CostList result = original.merge(outC, false, false); - result.merge(inC, false, true); - if (set.contains(result)) - next = find(false); - else { + CostList result = CostList.merge(original, outC, false); + result.mergeInplace(inC, false); + if (!set.contains(result)) { set.add(result); procedure.add(new Pair<>(result, outC)); - addCatalyst(next.one.getLabel(Recipe.IO.CATALYST)); - next = find(true); + addCatalyst(next.one.getCatalyst()); + reset(); } - if (count++ > 1000 && player != null) { - player.addChatMessage( - new ChatComponentTranslation("jecalculation.chat.max_loop")); + next = find(); + if (count++ > 1000) { + Utilities.addChatMessage(Utilities.ChatMessage.MAX_LOOP); break; } } } + private void reset() { + index = 0; + iterator = Controller.recipeIterator(); + } + + /** + * Find next recipe and its amount + * + * @return pair of the next recipe and its amount + */ @Nullable - private Pair find(boolean reset) { - if (reset) { - index = 0; - iterator = Controller.recipeIterator(); - } + private Pair find() { List labels = getCurrent().labels; for (; index < labels.size(); index++) { ILabel label = labels.get(index); - if (label.getAmount() >= 0) - continue; + // Only negative label is required to calculate + if (label.getAmount() >= 0) continue; + // Find the recipe for the label. + // Reset or not reset the iterator is a question while (iterator.hasNext()) { Recipe r = iterator.next(); - if (r.matches(label).isPresent()) - return new Pair<>(r, r.multiplier(label)); + if (r.matches(label).isPresent()) return new Pair<>(r, r.multiplier(label)); } iterator = Controller.recipeIterator(); } @@ -177,13 +181,11 @@ public class CostList { } private void addCatalyst(List labels) { - labels.stream() - .filter(i -> i != ILabel.EMPTY) - .forEach(i -> catalysts.stream() - .filter(j -> j.matches(i)) - .findAny() - .map(j -> j.setAmount(Math.max(i.getAmount(), j.getAmount()))) - .orElseGet(Utilities.fake(() -> catalysts.add(i)))); + labels.stream().filter(i -> i != ILabel.EMPTY).forEach(i -> catalysts.stream() + .filter(j -> j.matches(i)) + .findAny() + .map(j -> j.setAmount(Math.max(i.getAmount(), j.getAmount()))) + .orElseGet(Utilities.fake(() -> catalysts.add(i)))); } private CostList getCurrent() { @@ -196,28 +198,30 @@ public class CostList { public List getInputs() { return getCurrent().labels.stream() - .filter(i -> i.getAmount() < 0) - .map(i -> i.copy().multiply(-1)) - .collect(Collectors.toList()); + .filter(i -> i.getAmount() < 0) + .map(i -> i.copy().multiply(-1)) + .collect(Collectors.toList()); } public List getOutputs(List ignore) { return getCurrent().labels.stream() - .map(i -> i.copy().multiply(-1)) - .map(i -> ignore.stream() - .flatMap(j -> stream(ILabel.MERGER.merge(i, j))) - .findFirst() - .orElse(i)) - .filter(i -> i != ILabel.EMPTY && i.getAmount() < 0) - .map(i -> i.multiply(-1)) - .collect(Collectors.toList()); + .map(i -> i.copy().multiply(-1)) + .map(i -> ignore.stream() + .flatMap(j -> stream(ILabel.MERGER.merge(i, j))) + .findFirst() + .orElse(i)) + .filter(i -> i != ILabel.EMPTY && i.getAmount() < 0) + .map(i -> i.multiply(-1)) + .collect(Collectors.toList()); } public List getSteps() { List ret = procedure.stream().map(i -> i.two.labels.get(0)).collect(Collectors.toList()); Collections.reverse(ret); CostList cl = new CostList(ret).multiply(-1); - return new CostList().merge(cl, false, true).labels; + CostList temp = new CostList(); + temp.mergeInplace(cl, false); + return temp.labels; } } } diff --git a/src/main/java/me/towdium/jecalculation/data/structure/Recipe.java b/src/main/java/me/towdium/jecalculation/data/structure/Recipe.java index 5046533..15a3293 100644 --- a/src/main/java/me/towdium/jecalculation/data/structure/Recipe.java +++ b/src/main/java/me/towdium/jecalculation/data/structure/Recipe.java @@ -1,13 +1,5 @@ package me.towdium.jecalculation.data.structure; -import me.towdium.jecalculation.data.label.ILabel; -import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; -import me.towdium.jecalculation.polyfill.NBTHelper; -import me.towdium.jecalculation.utils.Utilities; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; - -import javax.annotation.ParametersAreNonnullByDefault; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -18,6 +10,13 @@ import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; +import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.data.label.ILabel; +import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; +import me.towdium.jecalculation.polyfill.NBTHelper; +import me.towdium.jecalculation.utils.Utilities; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; /** * Author: towdium @@ -34,35 +33,34 @@ public class Recipe { List output; public Recipe(NBTTagCompound nbt) { - this(readNbtList(nbt.getTagList(KEY_INPUT, 10)), readNbtList(nbt.getTagList(KEY_CATALYST, 10)), - readNbtList(nbt.getTagList(KEY_OUTPUT, 10))); + this( + readNbtList(nbt.getTagList(KEY_INPUT, 10)), + readNbtList(nbt.getTagList(KEY_CATALYST, 10)), + readNbtList(nbt.getTagList(KEY_OUTPUT, 10))); } public Recipe(List input, List catalyst, List output) { - boolean a = Stream.of(input, output, catalyst).anyMatch(i -> - !i.isEmpty() && i.get(i.size() - 1) == ILabel.EMPTY); - boolean b = Stream.of(input, output).anyMatch(i -> - i.stream().allMatch(j -> j == ILabel.EMPTY)); + boolean a = + Stream.of(input, output, catalyst).anyMatch(i -> !i.isEmpty() && i.get(i.size() - 1) == ILabel.EMPTY); + boolean b = Stream.of(input, output).anyMatch(i -> i.stream().allMatch(j -> j == ILabel.EMPTY)); if (a || b) throw new IllegalArgumentException("Invalid recipe"); this.input = input; this.catalyst = catalyst; this.output = output; } - - static private List readNbtList(NBTTagList list) { + private static List readNbtList(NBTTagList list) { return StreamSupport.stream(NBTHelper.spliterator(list), false) - .filter(n -> n instanceof NBTTagCompound) - .map(n -> ILabel.SERIALIZER.deserialize((NBTTagCompound) n)) - .collect(Collectors.toList()); + .filter(n -> n instanceof NBTTagCompound) + .map(n -> ILabel.SERIALIZER.deserialize((NBTTagCompound) n)) + .collect(Collectors.toList()); } @Override public int hashCode() { int[] hash = new int[1]; - Consumer> hasher = (ls) -> ls.stream() - .filter(Objects::nonNull) - .forEach(i -> hash[0] ^= i.hashCode()); + Consumer> hasher = + (ls) -> ls.stream().filter(Objects::nonNull).forEach(i -> hash[0] ^= i.hashCode()); hasher.accept(input); hasher.accept(catalyst); hasher.accept(output); @@ -71,20 +69,28 @@ public class Recipe { @Override public boolean equals(Object obj) { - if (!(obj instanceof Recipe)) - return false; + if (!(obj instanceof Recipe)) return false; Recipe r = (Recipe) obj; BiPredicate, List> p = (i, j) -> { - if (i.size() != j.size()) - return false; - for (int k = 0; k < i.size(); k++) - if (!i.get(k).equals(j.get(k))) - return false; + if (i.size() != j.size()) return false; + for (int k = 0; k < i.size(); k++) if (!i.get(k).equals(j.get(k))) return false; return true; }; return p.test(input, r.input) && p.test(catalyst, r.catalyst) && p.test(output, r.output); } + public List getInput() { + return input; + } + + public List getOutput() { + return output; + } + + public List getCatalyst() { + return catalyst; + } + public List getLabel(IO type) { return get(type, input, output, catalyst); } @@ -103,9 +109,7 @@ public class Recipe { } public ILabel getRep() { - for (int i = 0; i < 8; i++) - if (output.get(i) != ILabel.EMPTY) - return output.get(i); + for (int i = 0; i < 8; i++) if (output.get(i) != ILabel.EMPTY) return output.get(i); return ILabel.EMPTY; } @@ -132,23 +136,29 @@ public class Recipe { } public Optional matches(ILabel label) { - return output.stream().filter(i -> ILabel.MERGER.merge(label, i).isPresent()).findAny(); + return output.stream() + .filter(i -> ILabel.MERGER.merge(label, i).isPresent()) + .findAny(); } public long multiplier(ILabel label) { - return output.stream().filter(i -> ILabel.MERGER.merge(label, i).isPresent()).findAny().map(i -> { - long amountA = label.getAmount(); - if (!label.isPercent()) - amountA = Math.multiplyExact(amountA, 100L); - long amountB = i.getAmount(); - if (!i.isPercent()) - amountB = Math.multiplyExact(amountB, 100L); - return (amountB + Math.abs(amountA) - 1) / amountB; - }).orElse(0L); + return output.stream() + .filter(i -> ILabel.MERGER.merge(label, i).isPresent()) + .findAny() + .map(i -> { + long amountA = label.getAmount(); + if (!label.isPercent()) amountA = Math.multiplyExact(amountA, 100L); + long amountB = i.getAmount(); + if (!i.isPercent()) amountB = Math.multiplyExact(amountB, 100L); + return (amountB + Math.abs(amountA) - 1) / amountB; + }) + .orElse(0L); } public enum IO { - INPUT, OUTPUT, CATALYST; + INPUT, + OUTPUT, + CATALYST; public static IO isInput(boolean b) { return b ? INPUT : OUTPUT; diff --git a/src/main/java/me/towdium/jecalculation/data/structure/Recipes.java b/src/main/java/me/towdium/jecalculation/data/structure/Recipes.java index 4bc06a9..60bdcc3 100644 --- a/src/main/java/me/towdium/jecalculation/data/structure/Recipes.java +++ b/src/main/java/me/towdium/jecalculation/data/structure/Recipes.java @@ -1,5 +1,13 @@ package me.towdium.jecalculation.data.structure; +import java.io.File; +import java.util.*; +import java.util.function.BiConsumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.JecaConfig; import me.towdium.jecalculation.JustEnoughCalculation; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; @@ -10,20 +18,10 @@ import me.towdium.jecalculation.utils.wrappers.Pair; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import java.io.File; -import java.util.*; -import java.util.function.BiConsumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; - /** * Author: towdium * Date: 18-8-28. */ - @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class Recipes { @@ -32,8 +30,7 @@ public class Recipes { public Recipes() { File file = JecaConfig.defaultFile; NBTTagCompound nbt = Utilities.Json.read(file); - if (nbt == null) - JustEnoughCalculation.logger.info("Failed to load default records at " + file + "."); + if (nbt == null) JustEnoughCalculation.logger.info("Failed to load default records at " + file + "."); else { JustEnoughCalculation.logger.info("Loading default records at " + file + "."); deserialize(nbt); @@ -50,14 +47,14 @@ public class Recipes { keySet.stream().sorted().forEach(i -> { NBTTagList group = nbt.getTagList(i, 10); StreamSupport.stream(NBTHelper.spliterator(group), false) - .filter(r -> r instanceof NBTTagCompound) - .forEach(r -> { - try { - add(i, new Recipe((NBTTagCompound) r)); - } catch (IllegalArgumentException e) { - JustEnoughCalculation.logger.warn("Invalid recipe record :" + r); - } - }); + .filter(r -> r instanceof NBTTagCompound) + .forEach(r -> { + try { + add(i, new Recipe((NBTTagCompound) r)); + } catch (IllegalArgumentException e) { + JustEnoughCalculation.logger.warn("Invalid recipe record :" + r); + } + }); }); } @@ -73,19 +70,13 @@ public class Recipes { public void modify(String neu, @Nullable String old, int index, @Nullable Recipe recipe) { if (index == -1) { - if (recipe != null) - add(neu, recipe); - else if (old != null) - renameGroup(old, neu); - else - remove(neu); + if (recipe != null) add(neu, recipe); + else if (old != null) renameGroup(old, neu); + else remove(neu); } else { - if (recipe == null) - remove(neu, index); - else if (old == null || old.equals(neu)) - set(neu, index, recipe); - else - set(neu, old, index, recipe); + if (recipe == null) remove(neu, index); + else if (old == null || old.equals(neu)) set(neu, index, recipe); + else set(neu, old, index, recipe); } } @@ -109,8 +100,7 @@ public class Recipes { public void remove(String group, int index) { List l = records.get(group); l.remove(index); - if (l.isEmpty()) - records.remove(group); + if (l.isEmpty()) records.remove(group); } public void remove(String group) { @@ -191,8 +181,7 @@ public class Recipes { List rs = records.get(group); index = rs.size(); j = new ReversedIterator<>(rs); - } else - return false; + } else return false; } return true; } diff --git a/src/main/java/me/towdium/jecalculation/data/structure/RecordCraft.java b/src/main/java/me/towdium/jecalculation/data/structure/RecordCraft.java index b0ddc8b..4fe7a43 100644 --- a/src/main/java/me/towdium/jecalculation/data/structure/RecordCraft.java +++ b/src/main/java/me/towdium/jecalculation/data/structure/RecordCraft.java @@ -1,15 +1,14 @@ package me.towdium.jecalculation.data.structure; -import me.towdium.jecalculation.data.label.ILabel; -import me.towdium.jecalculation.polyfill.NBTHelper; -import me.towdium.jecalculation.utils.Utilities; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; - import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; +import me.towdium.jecalculation.data.label.ILabel; +import me.towdium.jecalculation.polyfill.NBTHelper; +import me.towdium.jecalculation.utils.Utilities; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; /** * Author: Towdium @@ -28,9 +27,9 @@ public class RecordCraft implements IRecord { public RecordCraft(NBTTagCompound nbt) { List ls = StreamSupport.stream(NBTHelper.spliterator(nbt.getTagList(KEY_RECENTS, 10)), false) - .filter(n -> n instanceof NBTTagCompound) - .map(n -> ILabel.SERIALIZER.deserialize((NBTTagCompound) n)) - .collect(Collectors.toList()); + .filter(n -> n instanceof NBTTagCompound) + .map(n -> ILabel.SERIALIZER.deserialize((NBTTagCompound) n)) + .collect(Collectors.toList()); new Utilities.ReversedIterator<>(ls).forEachRemaining(l -> record.push(l, false)); amount = nbt.getString(KEY_AMOUNT); inventory = nbt.getBoolean(KEY_INVENTORY); @@ -67,6 +66,9 @@ public class RecordCraft implements IRecord { } public enum Mode { - INPUT, OUTPUT, CATALYST, STEPS + INPUT, + OUTPUT, + CATALYST, + STEPS } } diff --git a/src/main/java/me/towdium/jecalculation/data/structure/RecordMath.java b/src/main/java/me/towdium/jecalculation/data/structure/RecordMath.java index 2666ebf..84d4866 100644 --- a/src/main/java/me/towdium/jecalculation/data/structure/RecordMath.java +++ b/src/main/java/me/towdium/jecalculation/data/structure/RecordMath.java @@ -1,12 +1,11 @@ package me.towdium.jecalculation.data.structure; -import net.minecraft.nbt.NBTTagCompound; - import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.util.LinkedList; import java.util.List; +import net.minecraft.nbt.NBTTagCompound; /** * Author: Towdium @@ -25,10 +24,18 @@ public class RecordMath implements IRecord { public Operator operator; String current; - public enum State {INPUT, OUTPUT, ERROR} + public enum State { + INPUT, + OUTPUT, + ERROR + } public enum Operator { - EQUALS, PLUS, MINUS, TIMES, DIVIDE; + EQUALS, + PLUS, + MINUS, + TIMES, + DIVIDE; public BigDecimal operate(BigDecimal a, BigDecimal b) { switch (this) { @@ -48,21 +55,15 @@ public class RecordMath implements IRecord { } } - public RecordMath(State state, - Operator operator, - BigDecimal last, - boolean sign, - int dot, - List numbers) { + public RecordMath( + State state, Operator operator, BigDecimal last, boolean sign, int dot, List numbers) { this.state = state; this.operator = operator; this.last = last; StringBuilder sb = new StringBuilder(); - if (!sign) - sb.append('-'); + if (!sign) sb.append('-'); numbers.forEach(i -> sb.append(i.toString())); - if (dot != DOT_NONE) - sb.insert(sb.length() - dot, '.'); + if (dot != DOT_NONE) sb.insert(sb.length() - dot, '.'); current = sb.toString(); } @@ -89,19 +90,16 @@ public class RecordMath implements IRecord { public LinkedList getNumbers() { LinkedList ret = new LinkedList<>(); - if (current == null) - return ret; + if (current == null) return ret; for (int i = 0; i < current.length(); i++) { char ch = current.charAt(i); - if (ch != '-' && ch != '.') - ret.add(new BigDecimal(ch - '0')); + if (ch != '-' && ch != '.') ret.add(new BigDecimal(ch - '0')); } return ret; } public int getDot() { - if (current == null) - return DOT_NONE; + if (current == null) return DOT_NONE; int index = current.indexOf('.'); return index == -1 ? DOT_NONE : current.length() - index - 1; } diff --git a/src/main/java/me/towdium/jecalculation/data/structure/RecordPlayer.java b/src/main/java/me/towdium/jecalculation/data/structure/RecordPlayer.java index 9c6cf57..eb78264 100644 --- a/src/main/java/me/towdium/jecalculation/data/structure/RecordPlayer.java +++ b/src/main/java/me/towdium/jecalculation/data/structure/RecordPlayer.java @@ -11,7 +11,7 @@ public class RecordPlayer implements IRecord { public static final String KEY_LAST = "last"; public Recipes recipes; - public String last; // last group edited + public String last; // last group edited public RecordPlayer() { recipes = new Recipes(); @@ -25,8 +25,7 @@ public class RecordPlayer implements IRecord { @Override public NBTTagCompound serialize() { NBTTagCompound ret = new NBTTagCompound(); - if (last != null) - ret.setString(KEY_LAST, last); + if (last != null) ret.setString(KEY_LAST, last); ret.setTag(KEY_RECIPES, recipes.serialize()); return ret; } diff --git a/src/main/java/me/towdium/jecalculation/event/Handlers.java b/src/main/java/me/towdium/jecalculation/event/Handlers.java index 62643df..9c58bba 100644 --- a/src/main/java/me/towdium/jecalculation/event/Handlers.java +++ b/src/main/java/me/towdium/jecalculation/event/Handlers.java @@ -2,13 +2,12 @@ package me.towdium.jecalculation.event; import codechicken.nei.guihook.GuiContainerManager; import cpw.mods.fml.common.FMLCommonHandler; +import java.util.ArrayList; import me.towdium.jecalculation.event.handlers.EBusEventHandler; import me.towdium.jecalculation.event.handlers.FMLBusEventHandler; import me.towdium.jecalculation.event.handlers.NEIEventHandler; import net.minecraftforge.common.MinecraftForge; -import java.util.ArrayList; - public class Handlers { public static final ArrayList fmlHandlers; public static final ArrayList ebHandlers; diff --git a/src/main/java/me/towdium/jecalculation/event/handlers/EBusEventHandler.java b/src/main/java/me/towdium/jecalculation/event/handlers/EBusEventHandler.java index 72fa0fa..806bf66 100644 --- a/src/main/java/me/towdium/jecalculation/event/handlers/EBusEventHandler.java +++ b/src/main/java/me/towdium/jecalculation/event/handlers/EBusEventHandler.java @@ -3,7 +3,4 @@ package me.towdium.jecalculation.event.handlers; /** * register to MinecraftForge.EVENT_BUS */ -public class EBusEventHandler { - - -} +public class EBusEventHandler {} diff --git a/src/main/java/me/towdium/jecalculation/event/handlers/FMLBusEventHandler.java b/src/main/java/me/towdium/jecalculation/event/handlers/FMLBusEventHandler.java index 0cc9acc..074a401 100644 --- a/src/main/java/me/towdium/jecalculation/event/handlers/FMLBusEventHandler.java +++ b/src/main/java/me/towdium/jecalculation/event/handlers/FMLBusEventHandler.java @@ -42,6 +42,4 @@ public class FMLBusEventHandler { JecaGui.onGameTick(); } } - } - diff --git a/src/main/java/me/towdium/jecalculation/event/handlers/NEIEventHandler.java b/src/main/java/me/towdium/jecalculation/event/handlers/NEIEventHandler.java index b83499a..a17393c 100644 --- a/src/main/java/me/towdium/jecalculation/event/handlers/NEIEventHandler.java +++ b/src/main/java/me/towdium/jecalculation/event/handlers/NEIEventHandler.java @@ -16,20 +16,18 @@ public class NEIEventHandler implements IContainerInputHandler { } @Override - public void onKeyTyped(GuiContainer guiContainer, char c, int i) { - } + public void onKeyTyped(GuiContainer guiContainer, char c, int i) {} @Override public boolean lastKeyTyped(GuiContainer guiContainer, char keyChar, int keyCode) { if (guiContainer == Minecraft.getMinecraft().currentScreen && guiContainer instanceof JecaGui) { JecaGui gui = (JecaGui) guiContainer; ILabel label = gui.getLabelUnderMouse(); - if (label == null) - return false; + if (label == null) return false; Object stack = label.getRepresentation(); - if (keyCode == NEIClientConfig.getKeyBinding("gui.usage") || - (keyCode == NEIClientConfig.getKeyBinding("gui.recipe") && NEIClientUtils.shiftKey())) { + if (keyCode == NEIClientConfig.getKeyBinding("gui.usage") + || (keyCode == NEIClientConfig.getKeyBinding("gui.recipe") && NEIClientUtils.shiftKey())) { return NEIPlugin.openRecipeGui(stack, true); } if (keyCode == NEIClientConfig.getKeyBinding("gui.recipe")) { @@ -48,9 +46,7 @@ public class NEIEventHandler implements IContainerInputHandler { } @Override - public void onMouseClicked(GuiContainer guiContainer, int i, int i1, int i2) { - - } + public void onMouseClicked(GuiContainer guiContainer, int i, int i1, int i2) {} @Override public void onMouseUp(GuiContainer guiContainer, int i, int i1, int i2) { @@ -63,12 +59,8 @@ public class NEIEventHandler implements IContainerInputHandler { } @Override - public void onMouseScrolled(GuiContainer guiContainer, int i, int i1, int i2) { - - } + public void onMouseScrolled(GuiContainer guiContainer, int i, int i1, int i2) {} @Override - public void onMouseDragged(GuiContainer guiContainer, int i, int i1, int i2, long l) { - - } + public void onMouseDragged(GuiContainer guiContainer, int i, int i1, int i2, long l) {} } diff --git a/src/main/java/me/towdium/jecalculation/gui/JecaGui.java b/src/main/java/me/towdium/jecalculation/gui/JecaGui.java index 22f2727..b23feb7 100644 --- a/src/main/java/me/towdium/jecalculation/gui/JecaGui.java +++ b/src/main/java/me/towdium/jecalculation/gui/JecaGui.java @@ -1,13 +1,20 @@ package me.towdium.jecalculation.gui; +import static org.lwjgl.input.Keyboard.KEY_NONE; + import cpw.mods.fml.client.config.GuiUtils; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.gui.guis.GuiCraft; import me.towdium.jecalculation.gui.guis.GuiMath; import me.towdium.jecalculation.gui.guis.IGui; -import me.towdium.jecalculation.gui.widgets.WLabel; import me.towdium.jecalculation.nei.NEIPlugin; import me.towdium.jecalculation.polyfill.mc.client.renderer.GlStateManager; import me.towdium.jecalculation.utils.ItemStackHelper; @@ -32,15 +39,6 @@ import net.minecraftforge.fluids.Fluid; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import static org.lwjgl.input.Keyboard.KEY_NONE; - /** * Author: towdium * Date: 8/12/17. @@ -48,18 +46,20 @@ import static org.lwjgl.input.Keyboard.KEY_NONE; @ParametersAreNonnullByDefault @SideOnly(Side.CLIENT) public class JecaGui extends GuiContainer { - public static final KeyBinding keyOpenGuiCraft = new KeyBinding("jecalculation.key.gui_craft", KEY_NONE, - "jecalculation.key.category"); - public static final KeyBinding keyOpenGuiMath = new KeyBinding("jecalculation.key.gui_math", KEY_NONE, - "jecalculation.key.category"); + public static final KeyBinding keyOpenGuiCraft = + new KeyBinding("jecalculation.key.gui_craft", KEY_NONE, "jecalculation.key.category"); + public static final KeyBinding keyOpenGuiMath = + new KeyBinding("jecalculation.key.gui_math", KEY_NONE, "jecalculation.key.category"); public static final int COLOR_GUI_GREY = 0xFFA1A1A1; public static final int COLOR_TEXT_RED = 0xFF0000; public static final int COLOR_TEXT_GREY = 0x404040; public static final int COLOR_TEXT_WHITE = 0xFFFFFF; public static final boolean ALWAYS_TOOLTIP = false; + @SuppressWarnings("StringOperationCanBeSimplified") public static final String SEPARATOR = new String(); + public ILabel hand = ILabel.EMPTY; protected static JecaGui last; protected static Runnable scheduled; @@ -75,8 +75,7 @@ public class JecaGui extends GuiContainer { super(acceptsTransfer ? new JecaGui.ContainerTransfer() : new JecaGui.ContainerNonTransfer()); this.parent = parent; this.root = root; - if (inventorySlots instanceof JecaContainer) - ((JecaContainer) inventorySlots).setGui(this); + if (inventorySlots instanceof JecaContainer) ((JecaContainer) inventorySlots).setGui(this); } public static int getMouseX() { @@ -89,22 +88,19 @@ public class JecaGui extends GuiContainer { return gui.height - Mouse.getEventY() * gui.height / gui.mc.displayHeight - 1 - gui.guiTop; } - /** * @return true to terminate further processing of this event. */ public static boolean onMouse() { Optional optionalJecaGui = currentJecaGui(); - if (!optionalJecaGui.isPresent()) - return false; + if (!optionalJecaGui.isPresent()) return false; JecaGui gui = optionalJecaGui.get(); int xMouse = getMouseX(); int yMouse = getMouseY(); int button = Mouse.getEventButton(); if (button == -1) { int diff = Mouse.getEventDWheel() / 120; - if (diff != 0) - gui.root.onMouseScroll(gui, xMouse, yMouse, diff); + if (diff != 0) gui.root.onMouseScroll(gui, xMouse, yMouse, diff); } else if (Mouse.getEventButtonState()) { gui.root.onMouseFocused(gui, xMouse, yMouse, button); if (gui.root.onMouseClicked(gui, xMouse, yMouse, button)) { @@ -125,8 +121,7 @@ public class JecaGui extends GuiContainer { public static void onMouseReleased() { Optional optionalJecaGui = currentJecaGui(); - if (!optionalJecaGui.isPresent()) - return; + if (!optionalJecaGui.isPresent()) return; JecaGui gui = optionalJecaGui.get(); int xMouse = getMouseX(); int yMouse = getMouseY(); @@ -134,15 +129,13 @@ public class JecaGui extends GuiContainer { gui.root.onMouseReleased(gui, xMouse, yMouse, button); } - @Nullable public Slot getSlotUnderMouse() { IInventory i = new InventoryBasic("", false, 1); Slot s = new Slot(i, 0, 0, 0); ILabel l = getLabelUnderMouse(); Object rep = l == null ? null : l.getRepresentation(); - if (rep instanceof ItemStack) - s.putStack((ItemStack) rep); + if (rep instanceof ItemStack) s.putStack((ItemStack) rep); return s; } @@ -161,14 +154,12 @@ public class JecaGui extends GuiContainer { public static void displayGui(boolean updateParent, boolean acceptsTransfer, boolean scheduled, IGui root) { Runnable r = () -> { // isCallingFromMinecraftThread - if (Minecraft.getMinecraft().func_152345_ab()) - displayGuiUnsafe(updateParent, acceptsTransfer, root); + if (Minecraft.getMinecraft().func_152345_ab()) displayGuiUnsafe(updateParent, acceptsTransfer, root); }; if (scheduled) { JecaGui.scheduled = r; JecaGui.timeout = 1; - } else - r.run(); + } else r.run(); } public static Optional currentJecaGui() { @@ -194,14 +185,10 @@ public class JecaGui extends GuiContainer { private static void displayGuiUnsafe(boolean updateParent, boolean acceptsTransfer, IGui root) { Minecraft mc = Minecraft.getMinecraft(); JecaGui parent; - if (mc.currentScreen == null) - parent = null; - else if (!(mc.currentScreen instanceof JecaGui)) - parent = last; - else if (updateParent) - parent = (JecaGui) mc.currentScreen; - else - parent = ((JecaGui) mc.currentScreen).parent; + if (mc.currentScreen == null) parent = null; + else if (!(mc.currentScreen instanceof JecaGui)) parent = last; + else if (updateParent) parent = (JecaGui) mc.currentScreen; + else parent = ((JecaGui) mc.currentScreen).parent; JecaGui toShow = new JecaGui(parent, acceptsTransfer, root); root.onVisible(toShow); last = toShow; @@ -229,10 +216,8 @@ public class JecaGui extends GuiContainer { * I think they won't conflict */ public static void onKey() { - if (keyOpenGuiCraft.isPressed()) - JecaGui.openGuiCraft(false); - if (keyOpenGuiMath.isPressed()) - JecaGui.openGuiMath(false); + if (keyOpenGuiCraft.isPressed()) JecaGui.openGuiCraft(false); + if (keyOpenGuiMath.isPressed()) JecaGui.openGuiMath(false); } public static void onGameTick() { @@ -241,8 +226,7 @@ public class JecaGui extends GuiContainer { Runnable r = scheduled; scheduled = null; r.run(); - } else - timeout--; + } else timeout--; } } @@ -302,22 +286,17 @@ public class JecaGui extends GuiContainer { int separators = 0; for (String s : textLines) { int j = font.getStringWidth(s); - if (j > i) - i = j; + if (j > i) i = j; //noinspection StringEquality - if (s == JecaGui.SEPARATOR) - separators++; + if (s == JecaGui.SEPARATOR) separators++; } //noinspection StringEquality - if (textLines.get(textLines.size() - 1) == SEPARATOR) - separators--; + if (textLines.get(textLines.size() - 1) == SEPARATOR) separators--; int l1 = x + 12; int i2 = y - 12; int k = 8 + (textLines.size() - separators - 1) * 10 + 2 * separators; - if (l1 + i > this.width) - l1 -= 28 + i; - if (i2 + k + 6 > this.height) - i2 = this.height - k - 6; + if (l1 + i > this.width) l1 -= 28 + i; + if (i2 + k + 6 > this.height) i2 = this.height - k - 6; zLevel = 300.0F; itemRender.zLevel = 300.0F; drawGradientRect(l1 - 3, i2 - 4, l1 + i + 3, i2 - 3, -267386864, -267386864); @@ -331,8 +310,7 @@ public class JecaGui extends GuiContainer { drawGradientRect(l1 - 3, i2 + k + 2, l1 + i + 3, i2 + k + 3, 1344798847, 1344798847); for (String s1 : textLines) { //noinspection StringEquality - if (s1 == SEPARATOR) - i2 += 2; + if (s1 == SEPARATOR) i2 += 2; else { font.drawStringWithShadow(s1, l1, i2, -1); i2 += 10; @@ -361,18 +339,31 @@ public class JecaGui extends GuiContainer { drawResourceContinuous(r, xPos, yPos, xSize, ySize, border, border, border, border); } - public void drawResourceContinuous(Resource r, - int xPos, - int yPos, - int xSize, - int ySize, - int borderTop, - int borderBottom, - int borderLeft, - int borderRight) { - GuiUtils.drawContinuousTexturedBox(r.getResourceLocation(), xPos, yPos, r.getXPos(), r.getYPos(), xSize, ySize, - r.getXSize(), r.getYSize(), borderTop, borderBottom, borderLeft, borderRight, - 0); + public void drawResourceContinuous( + Resource r, + int xPos, + int yPos, + int xSize, + int ySize, + int borderTop, + int borderBottom, + int borderLeft, + int borderRight) { + GuiUtils.drawContinuousTexturedBox( + r.getResourceLocation(), + xPos, + yPos, + r.getXPos(), + r.getYPos(), + xSize, + ySize, + r.getXSize(), + r.getYSize(), + borderTop, + borderBottom, + borderLeft, + borderRight, + 0); } private void setColor(int color) { @@ -385,12 +376,10 @@ public class JecaGui extends GuiContainer { public void drawFluid(Fluid f, int xPos, int yPos, int xSize, int ySize) { IIcon fluidIcon = f.getFlowingIcon(); - if (fluidIcon == null) - fluidIcon = f.getStillIcon(); + if (fluidIcon == null) fluidIcon = f.getStillIcon(); mc.renderEngine.bindTexture(TextureMap.locationBlocksTexture); setColor(f.getColor() & 0x00FFFFFF); - if (fluidIcon != null) - drawTexturedModelRectFromIcon(xPos, yPos, fluidIcon, xSize, ySize); + if (fluidIcon != null) drawTexturedModelRectFromIcon(xPos, yPos, fluidIcon, xSize, ySize); } public void drawRectangle(int xPos, int yPos, int xSize, int ySize, int color) { @@ -426,10 +415,8 @@ public class JecaGui extends GuiContainer { drawText(xPos, yPos, f, () -> { int y = 0; for (String i : ss) { - if (f.shadow) - fontRendererObj.drawStringWithShadow(i, 0, y, f.color); - else - fontRendererObj.drawString(i, 0, y, f.color); + if (f.shadow) fontRendererObj.drawStringWithShadow(i, 0, y, f.color); + else fontRendererObj.drawString(i, 0, y, f.color); y += fontRendererObj.FONT_HEIGHT + 1; } }); @@ -446,20 +433,17 @@ public class JecaGui extends GuiContainer { int ellipsisWidth = f.getTextWidth("..."); if (strWidth > width && strWidth > ellipsisWidth) str = f.trimToWidth(str, width - ellipsisWidth).trim() + "..."; - if (f.shadow) - fontRendererObj.drawStringWithShadow(str, 0, 0, f.color); + if (f.shadow) fontRendererObj.drawStringWithShadow(str, 0, 0, f.color); fontRendererObj.drawString(str, 0, 0, f.color); }); } private void drawText(float xPos, float yPos, Font f, Runnable r) { boolean unicode = fontRendererObj.getUnicodeFlag(); - if (f.raw) - fontRendererObj.setUnicodeFlag(false); + if (f.raw) fontRendererObj.setUnicodeFlag(false); GlStateManager.pushMatrix(); GlStateManager.translate(xPos, yPos, 0); - if (f.half) - GlStateManager.scale(0.5, 0.5, 1); + if (f.half) GlStateManager.scale(0.5, 0.5, 1); r.run(); GlStateManager.popMatrix(); fontRendererObj.setUnicodeFlag(unicode); @@ -477,8 +461,7 @@ public class JecaGui extends GuiContainer { GlStateManager.enableDepth(); RenderHelper.enableGUIStandardItemLighting(); FontRenderer font = is.getItem().getFontRenderer(is); - if (font == null) - font = this.fontRendererObj; + if (font == null) font = this.fontRendererObj; itemRender.renderItemAndEffectIntoGUI(font, Minecraft.getMinecraft().renderEngine, is, xPos, yPos); itemRender.renderItemOverlayIntoGUI(font, Minecraft.getMinecraft().renderEngine, is, xPos, yPos); RenderHelper.disableStandardItemLighting(); @@ -494,13 +477,10 @@ public class JecaGui extends GuiContainer { @Override protected void keyTyped(char typedChar, int keyCode) { - if (keyCode == Keyboard.KEY_ESCAPE && hand != ILabel.EMPTY) - hand = ILabel.EMPTY; + if (keyCode == Keyboard.KEY_ESCAPE && hand != ILabel.EMPTY) hand = ILabel.EMPTY; else if (!root.onKeyPressed(this, typedChar, keyCode)) { - if (keyCode == Keyboard.KEY_ESCAPE && parent != null) - displayParent(); - else - super.keyTyped(typedChar, keyCode); + if (keyCode == Keyboard.KEY_ESCAPE && parent != null) displayParent(); + else super.keyTyped(typedChar, keyCode); } } @@ -524,8 +504,7 @@ public class JecaGui extends GuiContainer { public int getTextWidth(String s) { FontRenderer fr = getCurrent().fontRendererObj; boolean flag = fr.getUnicodeFlag(); - if (raw) - fr.setUnicodeFlag(false); + if (raw) fr.setUnicodeFlag(false); int ret = (int) Math.ceil(fr.getStringWidth(s) * (half ? 0.5f : 1)); fr.setUnicodeFlag(flag); return ret; @@ -540,7 +519,6 @@ public class JecaGui extends GuiContainer { } } - @SideOnly(Side.CLIENT) public static class JecaContainer extends Container { JecaGui gui; @@ -560,15 +538,12 @@ public class JecaGui extends GuiContainer { } @SideOnly(Side.CLIENT) - public static class ContainerTransfer extends JecaContainer { - } + public static class ContainerTransfer extends JecaContainer {} @SideOnly(Side.CLIENT) - public static class ContainerNonTransfer extends JecaContainer { - } + public static class ContainerNonTransfer extends JecaContainer {} public void drawHoveringText(List textLines, int x, int y) { this.drawHoveringText(textLines, x, y, fontRendererObj); } - } diff --git a/src/main/java/me/towdium/jecalculation/gui/Resource.java b/src/main/java/me/towdium/jecalculation/gui/Resource.java index 91637d4..41ec111 100644 --- a/src/main/java/me/towdium/jecalculation/gui/Resource.java +++ b/src/main/java/me/towdium/jecalculation/gui/Resource.java @@ -2,10 +2,9 @@ package me.towdium.jecalculation.gui; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import me.towdium.jecalculation.JustEnoughCalculation; -import net.minecraft.util.ResourceLocation; - import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.Tags; +import net.minecraft.util.ResourceLocation; /** * Author: towdium @@ -14,8 +13,7 @@ import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault @SideOnly(Side.CLIENT) public class Resource { - public static final ResourceLocation location = new ResourceLocation( - JustEnoughCalculation.Reference.MODID, "textures/gui/resources.png"); + public static final ResourceLocation location = new ResourceLocation(Tags.MODID, "textures/gui/resources.png"); // letters abbr for button & icon: N - normal, F - focused, D - disabled // letters abbr for fuzzy related: N - normal, F - fuzzy // letters abbr for state related: N - normal, A - active diff --git a/src/main/java/me/towdium/jecalculation/gui/guis/Gui.java b/src/main/java/me/towdium/jecalculation/gui/guis/Gui.java index e2d5964..dae381d 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/Gui.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/Gui.java @@ -1,11 +1,10 @@ package me.towdium.jecalculation.gui.guis; -import me.towdium.jecalculation.gui.widgets.IWidget; -import me.towdium.jecalculation.gui.widgets.WContainer; -import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; - import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.gui.widgets.IWidget; +import me.towdium.jecalculation.gui.widgets.WContainer; +import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault @@ -20,8 +19,7 @@ public class Gui extends WContainer implements IGui { public void setOverlay(@Nullable IWidget overlay) { this.overlay.clear(); - if (overlay != null) - this.overlay.add(overlay); + if (overlay != null) this.overlay.add(overlay); } @Override diff --git a/src/main/java/me/towdium/jecalculation/gui/guis/GuiCraft.java b/src/main/java/me/towdium/jecalculation/gui/guis/GuiCraft.java index b7c056e..3d523eb 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/GuiCraft.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/GuiCraft.java @@ -1,7 +1,14 @@ package me.towdium.jecalculation.gui.guis; +import static me.towdium.jecalculation.data.structure.RecordCraft.Mode.*; + import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.*; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.Controller; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.data.structure.CostList; @@ -18,14 +25,6 @@ import me.towdium.jecalculation.utils.wrappers.Pair; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.*; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static me.towdium.jecalculation.data.structure.RecordCraft.Mode.*; - /** * Author: towdium * Date: 8/14/17. @@ -37,25 +36,28 @@ public class GuiCraft extends Gui { Calculator calculator = null; RecordCraft record; WLabel label = new WLabel(31, 7, 20, 20, true).setLsnrUpdate((i, v) -> refreshLabel(v, false, true)); - WLabelGroup recent = new WLabelGroup(7, 31, 8, 1, false).setLsnrLeftClick( - (i, v) -> { - ILabel l = i.get(v).getLabel(); - if (l != ILabel.EMPTY) { - label.setLabel(i.get(v).getLabel().copy(), true); - } - }); - WLabelScroll result = new WLabelScroll(7, 87, 8, 4, false).setLsnrLeftClick((i, v) -> { - Object rep = i.get(v).getLabel().getRepresentation(); - NEIPlugin.openRecipeGui(rep, false); - }).setLsnrRightClick((widget, value) -> { - Object rep = widget.get(value).getLabel().getRepresentation(); - NEIPlugin.openRecipeGui(rep, true); - }).setFmtAmount(i -> i.getAmountString(true)).setFmtTooltip((i, j) -> i.getToolTip(j, true)); + WLabelGroup recent = new WLabelGroup(7, 31, 8, 1, false).setLsnrLeftClick((i, v) -> { + ILabel l = i.get(v).getLabel(); + if (l != ILabel.EMPTY) { + label.setLabel(i.get(v).getLabel().copy(), true); + } + }); + WLabelScroll result = new WLabelScroll(7, 87, 8, 4, false) + .setLsnrLeftClick((i, v) -> { + Object rep = i.get(v).getLabel().getRepresentation(); + NEIPlugin.openRecipeGui(rep, false); + }) + .setLsnrRightClick((widget, value) -> { + Object rep = widget.get(value).getLabel().getRepresentation(); + NEIPlugin.openRecipeGui(rep, true); + }) + .setFmtAmount(i -> i.getAmountString(true)) + .setFmtTooltip((i, j) -> i.getToolTip(j, true)); WButton steps = new WButtonIcon(64, 62, 20, 20, Resource.BTN_LIST, "craft.step").setListener(i -> setMode(STEPS)); - WButton catalyst = new WButtonIcon(45, 62, 20, 20, Resource.BTN_CAT, "common.catalyst").setListener( - i -> setMode(CATALYST)); - WButton output = new WButtonIcon(26, 62, 20, 20, Resource.BTN_OUT, "craft.output").setListener( - i -> setMode(OUTPUT)); + WButton catalyst = + new WButtonIcon(45, 62, 20, 20, Resource.BTN_CAT, "common.catalyst").setListener(i -> setMode(CATALYST)); + WButton output = + new WButtonIcon(26, 62, 20, 20, Resource.BTN_OUT, "craft.output").setListener(i -> setMode(OUTPUT)); WButton input = new WButtonIcon(7, 62, 20, 20, Resource.BTN_IN, "common.input").setListener(i -> setMode(INPUT)); WButton invE = new WButtonIcon(149, 62, 20, 20, Resource.BTN_INV_E, "craft.inventory_enabled"); WButton invD = new WButtonIcon(149, 62, 20, 20, Resource.BTN_INV_D, "craft.inventory_disabled"); @@ -65,21 +67,20 @@ public class GuiCraft extends Gui { refreshCalculator(); }); - public GuiCraft() { record = Controller.getRCraft(); amount.setText(record.amount); add(new WHelp("craft")); add(new WPanel()); - add(new WButtonIcon(7, 7, 20, 20, Resource.BTN_LABEL, "craft.label").setListener( - i -> JecaGui.displayGui(new GuiLabel(l -> { + add(new WButtonIcon(7, 7, 20, 20, Resource.BTN_LABEL, "craft.label") + .setListener(i -> JecaGui.displayGui(new GuiLabel(l -> { JecaGui.displayParent(); JecaGui.getCurrent().hand = l; })))); - add(new WButtonIcon(130, 7, 20, 20, Resource.BTN_NEW, "craft.recipe").setListener( - i -> JecaGui.displayGui(true, true, new GuiRecipe()))); - add(new WButtonIcon(149, 7, 20, 20, Resource.BTN_SEARCH, "craft.search").setListener( - i -> JecaGui.displayGui(new GuiSearch()))); + add(new WButtonIcon(130, 7, 20, 20, Resource.BTN_NEW, "craft.recipe") + .setListener(i -> JecaGui.displayGui(true, true, new GuiRecipe()))); + add(new WButtonIcon(149, 7, 20, 20, Resource.BTN_SEARCH, "craft.search") + .setListener(i -> JecaGui.displayGui(new GuiSearch()))); add(new WText(53, 13, JecaGui.Font.RAW, "x")); add(new WLine(55)); add(new WIcon(151, 31, 18, 18, Resource.ICN_RECENT, "craft.history")); @@ -137,7 +138,8 @@ public class GuiCraft extends Gui { String s = amount.getText(); long i = s.isEmpty() ? 1 : Long.parseLong(amount.getText()); amount.setColor(JecaGui.COLOR_TEXT_WHITE); - List dest = Collections.singletonList(label.getLabel().copy().setAmount(i)); + List dest = + Collections.singletonList(label.getLabel().copy().setAmount(i)); CostList list = record.inventory ? new CostList(getInventory(), dest) : new CostList(dest); calculator = list.calculate(); } catch (NumberFormatException | ArithmeticException e) { @@ -151,14 +153,13 @@ public class GuiCraft extends Gui { InventoryPlayer inv = Utilities.getPlayer().inventory; ArrayList labels = new ArrayList<>(); Consumer add = i -> Arrays.stream(i) - .filter(j -> !ItemStackHelper.isEmpty(j)) - .forEach(j -> labels.add(ILabel.Converter.from(j))); + .filter(j -> !ItemStackHelper.isEmpty(j)) + .forEach(j -> labels.add(ILabel.Converter.from(j))); add.accept(inv.armorInventory); add.accept(inv.mainInventory); return labels; } - void refreshResult() { if (calculator == null) { result.setLabels(new ArrayList<>()); @@ -192,24 +193,21 @@ public class GuiCraft extends Gui { Stream.of(guess.one, guess.two).flatMap(Collection::stream).forEach(i -> { List list = findRecipe(i); list.forEach(j -> match.add(j.setPercent(false).setAmount(1))); - if (!list.isEmpty()) - fuzzy.add(i); + if (!list.isEmpty()) fuzzy.add(i); }); match.addAll(fuzzy); List list = new ArrayList<>(match); - if (!match.isEmpty()) - setOverlay(new Suggest(list.size() > 3 ? list.subList(0, 3) : list, !dup)); + if (!match.isEmpty()) setOverlay(new Suggest(list.size() > 3 ? list.subList(0, 3) : list, !dup)); } } private static List findRecipe(ILabel l) { - return Controller.recipeIterator() - .stream() - .map(i -> i.matches(l)) - .filter(Optional::isPresent) - .map(Optional::get) - .map(ILabel::copy) - .collect(Collectors.toList()); + return Controller.recipeIterator().stream() + .map(i -> i.matches(l)) + .filter(Optional::isPresent) + .map(Optional::get) + .map(ILabel::copy) + .collect(Collectors.toList()); } class Suggest extends WOverlay { @@ -223,8 +221,9 @@ public class GuiCraft extends Gui { add(new WIcon(5 - width, 7, 18, 20, Resource.ICN_HELP, "craft.suggest")); add(new WLine(26, 7, 20, false)); for (int i = 0; i < labels.size(); i++) { - add(new WLabel(3 - i * 20, 7, 20, 20, false).setLabel(labels.get(i)) - .setLsnrUpdate((j, v) -> refresh(v))); + add(new WLabel(3 - i * 20, 7, 20, 20, false) + .setLabel(labels.get(i)) + .setLsnrUpdate((j, v) -> refresh(v))); } } diff --git a/src/main/java/me/towdium/jecalculation/gui/guis/GuiImport.java b/src/main/java/me/towdium/jecalculation/gui/guis/GuiImport.java index 705875b..59b9ef8 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/GuiImport.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/GuiImport.java @@ -1,5 +1,13 @@ package me.towdium.jecalculation.gui.guis; +import static me.towdium.jecalculation.gui.Resource.BTN_YES; +import static me.towdium.jecalculation.gui.Resource.ICN_TEXT; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.Controller; import me.towdium.jecalculation.data.structure.Recipes; import me.towdium.jecalculation.gui.JecaGui; @@ -9,15 +17,6 @@ import me.towdium.jecalculation.utils.Utilities.I18n; import me.towdium.jecalculation.utils.wrappers.Pair; import me.towdium.jecalculation.utils.wrappers.Quad; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static me.towdium.jecalculation.gui.Resource.BTN_YES; -import static me.towdium.jecalculation.gui.Resource.ICN_TEXT; - /** * Author: Towdium * Date: 18-12-6 @@ -25,14 +24,16 @@ import static me.towdium.jecalculation.gui.Resource.ICN_TEXT; @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class GuiImport extends Gui implements ISearchable { - List> data; // selected, file, group, recipes + List> data; // selected, file, group, recipes List> filtered; WSearch search = new WSearch(26, 25, 90, this); WSwitcher page; - WButton confirm = new WButtonIcon(149, 25, 20, 20, BTN_YES, "import.confirm").setDisabled(true).setListener(i -> { - data.stream().filter(j -> j.one).forEach(j -> Controller.inport(j.four, j.three)); - JecaGui.displayParent(); - }); + WButton confirm = new WButtonIcon(149, 25, 20, 20, BTN_YES, "import.confirm") + .setDisabled(true) + .setListener(i -> { + data.stream().filter(j -> j.one).forEach(j -> Controller.inport(j.four, j.three)); + JecaGui.displayParent(); + }); List> content = new ArrayList<>(); public GuiImport() { @@ -40,10 +41,12 @@ public class GuiImport extends Gui implements ISearchable { add(new WIcon(7, 25, 20, 20, ICN_TEXT, "common.search")); add(search, confirm); IntStream.range(0, 7).forEach(i -> { - WTick tick = new WTick(7, 49 + 16 * i, 13, 13, "import.tick").setDisabled(true).setListener(j -> { - filtered.get(page.getIndex() * 7 + i).one = j.selected(); - confirm.setDisabled(data.stream().noneMatch(k -> k.one)); - }); + WTick tick = new WTick(7, 49 + 16 * i, 13, 13, "import.tick") + .setDisabled(true) + .setListener(j -> { + filtered.get(page.getIndex() * 7 + i).one = j.selected(); + confirm.setDisabled(data.stream().noneMatch(k -> k.one)); + }); WText text = new WTextExpand(49 + 16 * i, ""); add(tick, text); content.add(new Pair<>(tick, text)); @@ -52,10 +55,9 @@ public class GuiImport extends Gui implements ISearchable { @Override public void onVisible(JecaGui gui) { - data = Controller.discover() - .stream() - .flatMap(i -> i.two.stream().map(j -> new Quad<>(false, i.one, j.one, i.two))) - .collect(Collectors.toList()); + data = Controller.discover().stream() + .flatMap(i -> i.two.stream().map(j -> new Quad<>(false, i.one, j.one, i.two))) + .collect(Collectors.toList()); search.refresh(); } @@ -76,12 +78,11 @@ public class GuiImport extends Gui implements ISearchable { @Override public boolean setFilter(String s) { - if (s.isEmpty()) - filtered = new ArrayList<>(data); + if (s.isEmpty()) filtered = new ArrayList<>(data); else filtered = data.stream() - .filter(i -> I18n.contains(i.two, s) || I18n.contains(i.three, s)) - .collect(Collectors.toList()); + .filter(i -> I18n.contains(i.two, s) || I18n.contains(i.three, s)) + .collect(Collectors.toList()); remove(page); page = new WSwitcher(7, 7, 162, (filtered.size() + 6) / 7).setListener(i -> refresh()); add(page); @@ -96,7 +97,7 @@ public class GuiImport extends Gui implements ISearchable { super(25, yPos + 2, 140, JecaGui.Font.SHADOW, key, false); } - //WRectangle rect = new WRectangle(22, 49 + 16 * i, 146, 13, JecaGui.COLOR_GUI_GREY); + // WRectangle rect = new WRectangle(22, 49 + 16 * i, 146, 13, JecaGui.COLOR_GUI_GREY); @Override public boolean onDraw(JecaGui gui, int xMouse, int yMouse) { gui.drawRectangle(22, yPos - 2, 146, 13, JecaGui.COLOR_GUI_GREY); @@ -105,8 +106,7 @@ public class GuiImport extends Gui implements ISearchable { if (JecaGui.mouseIn(22, yPos - 2, gui.getStringWidth(key) + 6, 13, xMouse, yMouse)) { gui.drawRectangle(22, yPos - 2, gui.getStringWidth(key) + 6, 13, JecaGui.COLOR_GUI_GREY); gui.drawText(25, yPos, JecaGui.Font.SHADOW, key); - } else - expand = false; + } else expand = false; } else if (JecaGui.mouseIn(22, yPos - 2, 146, 13, xMouse, yMouse) && gui.getStringWidth(key) > 140) { gui.drawRectangle(22, yPos - 2, gui.getStringWidth(key) + 6, 13, JecaGui.COLOR_GUI_GREY); gui.drawText(25, yPos, JecaGui.Font.SHADOW, key); diff --git a/src/main/java/me/towdium/jecalculation/gui/guis/GuiLabel.java b/src/main/java/me/towdium/jecalculation/gui/guis/GuiLabel.java index ffd4b12..1b3a390 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/GuiLabel.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/GuiLabel.java @@ -5,6 +5,8 @@ import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.function.Consumer; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.gui.guis.pickers.IPicker; import me.towdium.jecalculation.gui.widgets.WContainer; @@ -14,9 +16,6 @@ import me.towdium.jecalculation.gui.widgets.WPanel; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.utils.wrappers.Wrapper; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.function.Consumer; - /** * Author: towdium * Date: 17-9-14. diff --git a/src/main/java/me/towdium/jecalculation/gui/guis/GuiMath.java b/src/main/java/me/towdium/jecalculation/gui/guis/GuiMath.java index b9c2593..eaa887c 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/GuiMath.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/GuiMath.java @@ -1,5 +1,12 @@ package me.towdium.jecalculation.gui.guis; +import static me.towdium.jecalculation.data.structure.RecordMath.DOT_NONE; +import static me.towdium.jecalculation.data.structure.RecordMath.context; + +import java.math.BigDecimal; +import java.util.LinkedList; +import java.util.stream.Collectors; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.Controller; import me.towdium.jecalculation.data.structure.RecordMath; import me.towdium.jecalculation.data.structure.RecordMath.Operator; @@ -10,14 +17,6 @@ import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.utils.Utilities; import org.lwjgl.input.Keyboard; -import javax.annotation.ParametersAreNonnullByDefault; -import java.math.BigDecimal; -import java.util.LinkedList; -import java.util.stream.Collectors; - -import static me.towdium.jecalculation.data.structure.RecordMath.DOT_NONE; -import static me.towdium.jecalculation.data.structure.RecordMath.context; - /** * Author: Towdium * Date: 19-1-3 @@ -36,28 +35,64 @@ public class GuiMath extends Gui { public GuiMath() { add(new WHelp("math")); add(new WPanel(), lcd); - add(new WButtonText(7, 67, 28, 20, "7", null, true).setListener(i -> append(7)).setKeyBind(Keyboard.KEY_7, Keyboard.KEY_NUMPAD7)); - add(new WButtonText(39, 67, 28, 20, "8", null, true).setListener(i -> append(8)).setKeyBind(Keyboard.KEY_8, Keyboard.KEY_NUMPAD8)); - add(new WButtonText(71, 67, 28, 20, "9", null, true).setListener(i -> append(9)).setKeyBind(Keyboard.KEY_9, Keyboard.KEY_NUMPAD9)); - add(new WButtonText(7, 91, 28, 20, "4", null, true).setListener(i -> append(4)).setKeyBind(Keyboard.KEY_4, Keyboard.KEY_NUMPAD4)); - add(new WButtonText(39, 91, 28, 20, "5", null, true).setListener(i -> append(5)).setKeyBind(Keyboard.KEY_5, Keyboard.KEY_NUMPAD5)); - add(new WButtonText(71, 91, 28, 20, "6", null, true).setListener(i -> append(6)).setKeyBind(Keyboard.KEY_6, Keyboard.KEY_NUMPAD6)); - add(new WButtonText(7, 115, 28, 20, "1", null, true).setListener(i -> append(1)).setKeyBind(Keyboard.KEY_1, Keyboard.KEY_NUMPAD1)); - add(new WButtonText(39, 115, 28, 20, "2", null, true).setListener(i -> append(2)).setKeyBind(Keyboard.KEY_2, Keyboard.KEY_NUMPAD2)); - add(new WButtonText(71, 115, 28, 20, "3", null, true).setListener(i -> append(3)).setKeyBind(Keyboard.KEY_3, Keyboard.KEY_NUMPAD3)); - add(new WButtonText(7, 139, 28, 20, "0", null, true).setListener(i -> append(0)).setKeyBind(Keyboard.KEY_0, Keyboard.KEY_NUMPAD0)); + add(new WButtonText(7, 67, 28, 20, "7", null, true) + .setListener(i -> append(7)) + .setKeyBind(Keyboard.KEY_7, Keyboard.KEY_NUMPAD7)); + add(new WButtonText(39, 67, 28, 20, "8", null, true) + .setListener(i -> append(8)) + .setKeyBind(Keyboard.KEY_8, Keyboard.KEY_NUMPAD8)); + add(new WButtonText(71, 67, 28, 20, "9", null, true) + .setListener(i -> append(9)) + .setKeyBind(Keyboard.KEY_9, Keyboard.KEY_NUMPAD9)); + add(new WButtonText(7, 91, 28, 20, "4", null, true) + .setListener(i -> append(4)) + .setKeyBind(Keyboard.KEY_4, Keyboard.KEY_NUMPAD4)); + add(new WButtonText(39, 91, 28, 20, "5", null, true) + .setListener(i -> append(5)) + .setKeyBind(Keyboard.KEY_5, Keyboard.KEY_NUMPAD5)); + add(new WButtonText(71, 91, 28, 20, "6", null, true) + .setListener(i -> append(6)) + .setKeyBind(Keyboard.KEY_6, Keyboard.KEY_NUMPAD6)); + add(new WButtonText(7, 115, 28, 20, "1", null, true) + .setListener(i -> append(1)) + .setKeyBind(Keyboard.KEY_1, Keyboard.KEY_NUMPAD1)); + add(new WButtonText(39, 115, 28, 20, "2", null, true) + .setListener(i -> append(2)) + .setKeyBind(Keyboard.KEY_2, Keyboard.KEY_NUMPAD2)); + add(new WButtonText(71, 115, 28, 20, "3", null, true) + .setListener(i -> append(3)) + .setKeyBind(Keyboard.KEY_3, Keyboard.KEY_NUMPAD3)); + add(new WButtonText(7, 139, 28, 20, "0", null, true) + .setListener(i -> append(0)) + .setKeyBind(Keyboard.KEY_0, Keyboard.KEY_NUMPAD0)); add(new WButtonText(39, 139, 28, 20, "00", null, true).setListener(i -> { append(0); append(0); })); - add(new WButtonText(71, 139, 28, 20, ".", null, true).setListener(i -> dot()).setKeyBind(Keyboard.KEY_PERIOD, Keyboard.KEY_DECIMAL)); - add(new WButtonIcon(109, 67, 28, 20, Resource.WGT_ARR_L).setListener(i -> remove()).setKeyBind(Keyboard.KEY_BACK)); - add(new WButtonText(141, 67, 28, 20, "+", null, true).setListener(i -> operate(Operator.PLUS)).setKeyBind(Keyboard.KEY_EQUALS, Keyboard.KEY_ADD)); - add(new WButtonText(109, 91, 28, 20, "C", null, true).setListener(i -> reset()).setKeyBind(Keyboard.KEY_DELETE)); - add(new WButtonText(141, 91, 28, 20, "-", null, true).setListener(i -> operate(Operator.MINUS)).setKeyBind(Keyboard.KEY_SUBTRACT, Keyboard.KEY_MINUS)); - add(new WButtonText(109, 115, 28, 44, "=", null, true).setListener(i -> operate(Operator.EQUALS)).setKeyBind(Keyboard.KEY_RETURN, Keyboard.KEY_NUMPADENTER, Keyboard.KEY_NUMPADEQUALS)); - add(new WButtonText(141, 115, 28, 20, "x", null, true).setListener(i -> operate(Operator.TIMES)).setKeyBind(Keyboard.KEY_APOSTROPHE, Keyboard.KEY_MULTIPLY)); - add(new WButtonText(141, 139, 28, 20, "/", null, true).setListener(i -> operate(Operator.DIVIDE)).setKeyBind(Keyboard.KEY_SLASH, Keyboard.KEY_DIVIDE)); + add(new WButtonText(71, 139, 28, 20, ".", null, true) + .setListener(i -> dot()) + .setKeyBind(Keyboard.KEY_PERIOD, Keyboard.KEY_DECIMAL)); + add(new WButtonIcon(109, 67, 28, 20, Resource.WGT_ARR_L) + .setListener(i -> remove()) + .setKeyBind(Keyboard.KEY_BACK)); + add(new WButtonText(141, 67, 28, 20, "+", null, true) + .setListener(i -> operate(Operator.PLUS)) + .setKeyBind(Keyboard.KEY_EQUALS, Keyboard.KEY_ADD)); + add(new WButtonText(109, 91, 28, 20, "C", null, true) + .setListener(i -> reset()) + .setKeyBind(Keyboard.KEY_DELETE)); + add(new WButtonText(141, 91, 28, 20, "-", null, true) + .setListener(i -> operate(Operator.MINUS)) + .setKeyBind(Keyboard.KEY_SUBTRACT, Keyboard.KEY_MINUS)); + add(new WButtonText(109, 115, 28, 44, "=", null, true) + .setListener(i -> operate(Operator.EQUALS)) + .setKeyBind(Keyboard.KEY_RETURN, Keyboard.KEY_NUMPADENTER, Keyboard.KEY_NUMPADEQUALS)); + add(new WButtonText(141, 115, 28, 20, "x", null, true) + .setListener(i -> operate(Operator.TIMES)) + .setKeyBind(Keyboard.KEY_APOSTROPHE, Keyboard.KEY_MULTIPLY)); + add(new WButtonText(141, 139, 28, 20, "/", null, true) + .setListener(i -> operate(Operator.DIVIDE)) + .setKeyBind(Keyboard.KEY_SLASH, Keyboard.KEY_DIVIDE)); add(new WLine(61), new WLine(103, 61, 98, false), new WLine.Joint(103, 61, false, true, true, true)); RecordMath recordMath = Controller.getRMath(); state = recordMath.state; @@ -71,9 +106,10 @@ public class GuiMath extends Gui { private void print() { if (state == State.INPUT) { - String s = numbers.isEmpty() ? "0" : numbers.stream().map(Object::toString).collect(Collectors.joining()); - if (!sign) - s = '-' + Utilities.repeat(" ", 6 - s.length()) + s; + String s = numbers.isEmpty() + ? "0" + : numbers.stream().map(Object::toString).collect(Collectors.joining()); + if (!sign) s = '-' + Utilities.repeat(" ", 6 - s.length()) + s; lcd.text = s; lcd.dot = dot; } else if (state == State.ERROR) { @@ -86,12 +122,10 @@ public class GuiMath extends Gui { } private void append(int i) { - if (state != State.INPUT) - state = State.INPUT; + if (state != State.INPUT) state = State.INPUT; if ((i != 0 || !numbers.isEmpty()) && numbers.size() < (sign ? 7 : 6)) { numbers.add(new BigDecimal(i)); - if (dot != DOT_NONE) - dot++; + if (dot != DOT_NONE) dot++; } print(); sync(); @@ -102,8 +136,7 @@ public class GuiMath extends Gui { } private void operate(Operator operator) { - if (state == State.INPUT && numbers.isEmpty() && operator == Operator.MINUS) - sign = !sign; + if (state == State.INPUT && numbers.isEmpty() && operator == Operator.MINUS) sign = !sign; else { if (state == State.INPUT) { try { @@ -128,23 +161,18 @@ public class GuiMath extends Gui { } private void dot() { - if (state != State.INPUT) - state = State.INPUT; - if (numbers.size() == 0) - numbers.add(BigDecimal.ZERO); + if (state != State.INPUT) state = State.INPUT; + if (numbers.size() == 0) numbers.add(BigDecimal.ZERO); dot = 0; print(); sync(); } - private void remove() { - if (state != State.INPUT) - reset(); + if (state != State.INPUT) reset(); if (numbers.size() > 0) { numbers.removeLast(); - if (dot != DOT_NONE) - dot--; + if (dot != DOT_NONE) dot--; } print(); sync(); @@ -163,11 +191,9 @@ public class GuiMath extends Gui { private BigDecimal convert() { BigDecimal f = new BigDecimal(0); - for (BigDecimal i : numbers) - f = f.add(i).multiply(BigDecimal.TEN); + for (BigDecimal i : numbers) f = f.add(i).multiply(BigDecimal.TEN); f = f.divide(BigDecimal.TEN.pow(Math.max(dot, 0) + 1), context); - if (!sign) - f = f.negate(); + if (!sign) f = f.negate(); return f; } } diff --git a/src/main/java/me/towdium/jecalculation/gui/guis/GuiRecipe.java b/src/main/java/me/towdium/jecalculation/gui/guis/GuiRecipe.java index 93cf9c5..193c6e9 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/GuiRecipe.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/GuiRecipe.java @@ -1,7 +1,15 @@ package me.towdium.jecalculation.gui.guis; +import static me.towdium.jecalculation.gui.JecaGui.COLOR_TEXT_RED; +import static me.towdium.jecalculation.gui.JecaGui.COLOR_TEXT_WHITE; +import static me.towdium.jecalculation.gui.JecaGui.Font.PLAIN; +import static me.towdium.jecalculation.gui.Resource.*; + import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.*; +import java.util.stream.Collectors; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.Controller; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.data.structure.CostList; @@ -15,15 +23,6 @@ import me.towdium.jecalculation.utils.wrappers.Pair; import me.towdium.jecalculation.utils.wrappers.Trio; import org.lwjgl.input.Keyboard; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.*; -import java.util.stream.Collectors; - -import static me.towdium.jecalculation.gui.JecaGui.COLOR_TEXT_RED; -import static me.towdium.jecalculation.gui.JecaGui.COLOR_TEXT_WHITE; -import static me.towdium.jecalculation.gui.JecaGui.Font.PLAIN; -import static me.towdium.jecalculation.gui.Resource.*; - /** * Author: towdium * Date: 17-9-8. @@ -44,29 +43,30 @@ public class GuiRecipe extends Gui { Controller.addRecipe(group.getText(), toRecipe()); JecaGui.displayParent(); }); - WButton label = new WButtonIcon(45, 25, 20, 20, BTN_LABEL, "recipe.label").setListener( - i -> JecaGui.displayGui(new GuiLabel((l) -> { + WButton label = new WButtonIcon(45, 25, 20, 20, BTN_LABEL, "recipe.label") + .setListener(i -> JecaGui.displayGui(new GuiLabel((l) -> { JecaGui.displayParent(); JecaGui.getCurrent().hand = l; }))); - WButton save = new WButtonIcon(26, 25, 20, 20, BTN_SAVE, "recipe.save").setDisabled(true).setListener(i -> { - if (dest == null) - Controller.addRecipe(group.getText(), toRecipe()); - else { - String group = this.group.getText(); - if (group.equals(dest.one)) - Controller.setRecipe(dest.one, dest.two, toRecipe()); - else - Controller.setRecipe(group, dest.one, dest.two, toRecipe()); - } - JecaGui.displayParent(); - }); - WButton yes = new WButtonIcon(7, 25, 20, 20, BTN_YES, "recipe.confirm").setDisabled(true).setListener(i -> { - group.setText(text.getText()); - text.setText(""); - setNewGroup(false); - refresh(); - }); + WButton save = new WButtonIcon(26, 25, 20, 20, BTN_SAVE, "recipe.save") + .setDisabled(true) + .setListener(i -> { + if (dest == null) Controller.addRecipe(group.getText(), toRecipe()); + else { + String group = this.group.getText(); + if (group.equals(dest.one)) Controller.setRecipe(dest.one, dest.two, toRecipe()); + else Controller.setRecipe(group, dest.one, dest.two, toRecipe()); + } + JecaGui.displayParent(); + }); + WButton yes = new WButtonIcon(7, 25, 20, 20, BTN_YES, "recipe.confirm") + .setDisabled(true) + .setListener(i -> { + group.setText(text.getText()); + text.setText(""); + setNewGroup(false); + refresh(); + }); WButton no = new WButtonIcon(26, 25, 20, 20, BTN_NO, "common.cancel").setListener(i -> setNewGroup(false)); WButton neu = new WButtonIcon(7, 25, 20, 20, BTN_NEW, "recipe.new").setListener(i -> setNewGroup(true)); EnumMap>> disamb = new EnumMap<>(IO.class); @@ -84,22 +84,21 @@ public class GuiRecipe extends Gui { public GuiRecipe() { for (IO j : IO.values()) { - getWidget(j).setFmtAmount(i -> i.getAmountString(false)) - .setFmtTooltip((i, k) -> i.getToolTip(k, true)) - .setLsnrLeftClick((i, v) -> { - ILabel l = i.get(v).getLabel(); - if (l != ILabel.EMPTY) - setOverlay(new WAmount(j, v)); - }) - .setLsnrRightClick((widget, value) -> { - ILabel l = widget.get(value).getLabel(); - if (l != ILabel.EMPTY) - widget.get(value).setLabel(ILabel.EMPTY, true); - }) - .setLsnrUpdate((i, v) -> { - refresh(); - removeDisamb(j, v); - }); + getWidget(j) + .setFmtAmount(i -> i.getAmountString(false)) + .setFmtTooltip((i, k) -> i.getToolTip(k, true)) + .setLsnrLeftClick((i, v) -> { + ILabel l = i.get(v).getLabel(); + if (l != ILabel.EMPTY) setOverlay(new WAmount(j, v)); + }) + .setLsnrRightClick((widget, value) -> { + ILabel l = widget.get(value).getLabel(); + if (l != ILabel.EMPTY) widget.get(value).setLabel(ILabel.EMPTY, true); + }) + .setLsnrUpdate((i, v) -> { + refresh(); + removeDisamb(j, v); + }); } add(new WHelp("recipe"), new WPanel()); add(new WIcon(7, 61, 18, 36, ICN_OUTPUT, "common.output")); @@ -107,14 +106,11 @@ public class GuiRecipe extends Gui { add(new WIcon(7, 123, 18, 36, ICN_INPUT, "common.input")); add(new WLine(52)); add(catalyst, input, output, group); - if (group.getTexts().isEmpty()) - group.setText(Utilities.I18n.get("gui.common.default")); + if (group.getTexts().isEmpty()) group.setText(Utilities.I18n.get("gui.common.default")); String last = Controller.getLast(); int index = -1; - if (last != null) - index = group.getTexts().indexOf(last); - if (index != -1) - group.setIndex(index); + if (last != null) index = group.getTexts().indexOf(last); + if (index != -1) group.setIndex(index); setNewGroup(false); copy.setDisabled(true); text.setListener(i -> yes.setDisabled(i.getText().isEmpty())); @@ -156,8 +152,7 @@ public class GuiRecipe extends Gui { } public void reset() { - for (IO i : IO.values()) - getWidget(i).setLabels(new ArrayList<>()); + for (IO i : IO.values()) getWidget(i).setLabels(new ArrayList<>()); disamb.clear(); refresh(); } @@ -166,18 +161,15 @@ public class GuiRecipe extends Gui { disamb.clear(); // generate disamb and fill slots - for (IO i : IO.values()) - getWidget(i).setLabels(extract(recipe, i, context)); + for (IO i : IO.values()) getWidget(i).setLabels(extract(recipe, i, context)); refresh(); } - private ArrayList extract(EnumMap>> src, - IO type, - Class context) { + private ArrayList extract( + EnumMap>> src, IO type, Class context) { List> l = src.get(type); ArrayList ret = new ArrayList<>(); - if (l == null) - return ret; + if (l == null) return ret; for (int i = 0; i < l.size(); i++) { Trio p = l.get(i); ret.add(p.one); @@ -194,8 +186,7 @@ public class GuiRecipe extends Gui { private List trim(List ls) { for (int i = ls.size() - 1; i >= 0; i--) { - if (ls.get(i) == ILabel.EMPTY) - ls.remove(i); + if (ls.get(i) == ILabel.EMPTY) ls.remove(i); } return ls; } @@ -209,8 +200,7 @@ public class GuiRecipe extends Gui { Recipe r = toRecipe(); boolean d = dest == null ? Controller.hasDuplicate(r) : Controller.hasDuplicate(r, dest.one, dest.two); save.setDisabled(d); - if (dest != null) - copy.setDisabled(d); + if (dest != null) copy.setDisabled(d); } catch (IllegalArgumentException e) { save.setDisabled(true); copy.setDisabled(true); @@ -219,14 +209,12 @@ public class GuiRecipe extends Gui { private void removeDisamb(IO type, int index) { Map> entry = disamb.get(type); - if (entry != null) - entry.remove(index); + if (entry != null) entry.remove(index); } static boolean handleLabelScroll(WLabel w, int diff) { ILabel l = w.getLabel(); - for (int i = 0; i < Math.abs(diff); i++) - l = diff > 0 ? l.increaseAmount() : l.decreaseAmount(); + for (int i = 0; i < Math.abs(diff); i++) l = diff > 0 ? l.increaseAmount() : l.decreaseAmount(); w.setLabel(l, true); return true; } @@ -263,16 +251,15 @@ public class GuiRecipe extends Gui { JecaGui.getCurrent().hand = temp.getLabel(); set(ILabel.EMPTY, type, idx); }); - yes = new WButtonIcon(x + 59, y - 24, 20, 20, BTN_YES, "recipe.confirm").setListener( - i -> set(temp.getLabel(), type, idx)); - no = new WButtonIcon(x + 78, y - 24, 20, 20, BTN_NO, "recipe.delete").setListener( - i -> set(ILabel.EMPTY, type, idx)); + yes = new WButtonIcon(x + 59, y - 24, 20, 20, BTN_YES, "recipe.confirm") + .setListener(i -> set(temp.getLabel(), type, idx)); + no = new WButtonIcon(x + 78, y - 24, 20, 20, BTN_NO, "recipe.delete") + .setListener(i -> set(ILabel.EMPTY, type, idx)); disamb = new WButtonIcon(x + 40, y - 24, 20, 20, BTN_DISAMB, "recipe.disamb"); Map> entry = GuiRecipe.this.disamb.get(type); if (entry != null && entry.containsKey(idx)) { disamb.setListener(i -> GuiRecipe.this.setOverlay(new WDisamb(type, idx))); - } else - disamb.setDisabled(true); + } else disamb.setDisabled(true); add(temp, text, pick, yes, no, disamb); text.setListener(i -> { boolean acceptable; @@ -280,8 +267,7 @@ public class GuiRecipe extends Gui { try { amount = Long.parseLong(text.getText()); acceptable = amount > 0; - if (!acceptable) - amount = 1; + if (!acceptable) amount = 1; } catch (NumberFormatException e) { acceptable = text.getText().isEmpty(); amount = 1; @@ -291,7 +277,6 @@ public class GuiRecipe extends Gui { temp.setLabel(temp.getLabel().setAmount(amount)); }); update(); - } private void set(ILabel l, IO type, int idx) { @@ -326,13 +311,13 @@ public class GuiRecipe extends Gui { add(new WPanel(x - 7, y - 46, 111, 71)); temp = new WLabel(x - 1, y - 1, 20, 20, false); temp.setLabel(ref.getLabel().copy()); - content = new WLabelScroll(x + 8, y - 40, 4, 2, false).setLabels(disamb.get(type).get(idx)) - .setLsnrLeftClick((i, v) -> { - list.setLabel( - idx, i.get(v).getLabel().copy().multiply(-1)); - GuiRecipe.this.setOverlay(null); - refresh(); - }); + content = new WLabelScroll(x + 8, y - 40, 4, 2, false) + .setLabels(disamb.get(type).get(idx)) + .setLsnrLeftClick((i, v) -> { + list.setLabel(idx, i.get(v).getLabel().copy().multiply(-1)); + GuiRecipe.this.setOverlay(null); + refresh(); + }); add(new WIcon(x + 22, y - 1, 20, 20, ICN_TEXT, "common.search")); search = new WSearch(x + 42, y - 1, 56, content); add(temp, content, search); diff --git a/src/main/java/me/towdium/jecalculation/gui/guis/GuiSearch.java b/src/main/java/me/towdium/jecalculation/gui/guis/GuiSearch.java index 93e2451..fac5192 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/GuiSearch.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/GuiSearch.java @@ -1,5 +1,12 @@ package me.towdium.jecalculation.gui.guis; +import static me.towdium.jecalculation.gui.Resource.*; + +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.function.Consumer; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.Controller; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.data.structure.Recipe; @@ -11,55 +18,43 @@ import me.towdium.jecalculation.utils.Utilities; import me.towdium.jecalculation.utils.wrappers.Trio; import org.lwjgl.input.Keyboard; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.ArrayList; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.function.Consumer; - -import static me.towdium.jecalculation.gui.Resource.*; - @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class GuiSearch extends Gui { IdentityHashMap> recipes; - WLabelScroll labels = new WLabelScroll(7, 51, 8, 6, false) - .setLsnrLeftClick((i, v) -> { - ILabel l = i.get(v).getLabel(); - if (l != ILabel.EMPTY) setOverlay(new Overlay(i.get(v))); - }); + WLabelScroll labels = new WLabelScroll(7, 51, 8, 6, false).setLsnrLeftClick((i, v) -> { + ILabel l = i.get(v).getLabel(); + if (l != ILabel.EMPTY) setOverlay(new Overlay(i.get(v))); + }); WSwitcher group; WTextField text = new WTextField(7, 25, 119); - WButton no = new WButtonIcon(130, 25, 20, 20, BTN_NO, "common.cancel") - .setListener(i -> setRename(false)); + WButton no = new WButtonIcon(130, 25, 20, 20, BTN_NO, "common.cancel").setListener(i -> setRename(false)); WButton yes = new WButtonIcon(149, 25, 20, 20, BTN_YES, "search.confirm") - .setDisabled(true).setListener(i -> { + .setDisabled(true) + .setListener(i -> { Controller.renameGroup(group.getText(), text.getText()); refreshGroups(); group.setText(text.getText()); refreshDisplay(); setRename(false); }); - WButton exportN = new WButtonIcon(111, 25, 20, 20, BTN_EXPORT_N, "search.export_all") - .setListener(i -> Controller.export()); + WButton exportN = + new WButtonIcon(111, 25, 20, 20, BTN_EXPORT_N, "search.export_all").setListener(i -> Controller.export()); WButton export1 = new WButtonIcon(111, 25, 20, 20, BTN_EXPORT_1, "search.export_group") .setListener(i -> Controller.export(group.getText())); - WButton deleteN = new WButtonIcon(130, 25, 20, 20, BTN_DELETE_N, "search.delete_all") - .setListener(i -> { - Controller.getGroups().forEach(Controller::removeGroup); - refreshGroups(); - refreshDisplay(); - }); - WButton delete1 = new WButtonIcon(130, 25, 20, 20, BTN_DELETE_1, "search.delete_group") - .setListener(i -> { - Controller.removeGroup(group.getText()); - refreshGroups(); - refreshDisplay(); - }); + WButton deleteN = new WButtonIcon(130, 25, 20, 20, BTN_DELETE_N, "search.delete_all").setListener(i -> { + Controller.getGroups().forEach(Controller::removeGroup); + refreshGroups(); + refreshDisplay(); + }); + WButton delete1 = new WButtonIcon(130, 25, 20, 20, BTN_DELETE_1, "search.delete_group").setListener(i -> { + Controller.removeGroup(group.getText()); + refreshGroups(); + refreshDisplay(); + }); WButton inport = new WButtonIcon(92, 25, 20, 20, BTN_IMPORT, "search.import") .setListener(i -> JecaGui.displayGui(new GuiImport())); - WButton rename = new WButtonIcon(149, 25, 20, 20, BTN_EDIT, "search.rename") - .setListener(i -> setRename(true)); + WButton rename = new WButtonIcon(149, 25, 20, 20, BTN_EDIT, "search.rename").setListener(i -> setRename(true)); WIcon icon = new WIcon(7, 25, 20, 20, ICN_TEXT, "common.search"); WSearch search = new WSearch(26, 25, 61, labels); List identifiers; @@ -73,7 +68,6 @@ public class GuiSearch extends Gui { add(labels, icon, search, inport, exportN, deleteN, rename); } - private void generate() { identifiers = new ArrayList<>(); recipes = new IdentityHashMap<>(); @@ -83,7 +77,8 @@ public class GuiSearch extends Gui { identifiers.add(id); }; - Recipes.RecipeIterator it = group.getIndex() == 0 ? Controller.recipeIterator() : Controller.recipeIterator(group.getText()); + Recipes.RecipeIterator it = + group.getIndex() == 0 ? Controller.recipeIterator() : Controller.recipeIterator(group.getText()); it.stream().map(j -> new Trio<>(j, it.getGroup(), it.getIndex())).forEach(add); } @@ -113,8 +108,7 @@ public class GuiSearch extends Gui { groups.add(Utilities.I18n.get("gui.search.all")); groups.addAll(Controller.getGroups()); int index = group == null ? 0 : group.getIndex(); - if (index >= groups.size()) - index = groups.size() - 1; + if (index >= groups.size()) index = groups.size() - 1; group = new WSwitcher(7, 7, 162, groups).setListener(i -> refreshDisplay()); group.setIndex(index); add(group); diff --git a/src/main/java/me/towdium/jecalculation/gui/guis/IGui.java b/src/main/java/me/towdium/jecalculation/gui/guis/IGui.java index 8cc5e05..71f8e3c 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/IGui.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/IGui.java @@ -12,8 +12,7 @@ import me.towdium.jecalculation.gui.widgets.IWidget; */ @SideOnly(Side.CLIENT) public interface IGui extends IContainer { - default void onVisible(JecaGui gui) { - } + default void onVisible(JecaGui gui) {} default boolean acceptsTransfer() { return false; diff --git a/src/main/java/me/towdium/jecalculation/gui/guis/pickers/IPicker.java b/src/main/java/me/towdium/jecalculation/gui/guis/pickers/IPicker.java index 11c554b..148c212 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/pickers/IPicker.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/pickers/IPicker.java @@ -2,14 +2,13 @@ package me.towdium.jecalculation.gui.guis.pickers; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.function.Consumer; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.gui.guis.Gui; import me.towdium.jecalculation.gui.guis.IGui; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.function.Consumer; - /** * Author: towdium * Date: 17-9-28. @@ -30,8 +29,7 @@ public interface IPicker extends IGui { } protected void notifyLsnr(ILabel l) { - if (callback != null && l != ILabel.EMPTY) - callback.accept(l); + if (callback != null && l != ILabel.EMPTY) callback.accept(l); } } } diff --git a/src/main/java/me/towdium/jecalculation/gui/guis/pickers/PickerItemStack.java b/src/main/java/me/towdium/jecalculation/gui/guis/pickers/PickerItemStack.java index 54e79f9..35ebe00 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/pickers/PickerItemStack.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/pickers/PickerItemStack.java @@ -1,7 +1,10 @@ package me.towdium.jecalculation.gui.guis.pickers; +import static me.towdium.jecalculation.gui.Resource.*; + import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.data.label.labels.LItemStack; import me.towdium.jecalculation.gui.guis.IGui; @@ -9,10 +12,6 @@ import me.towdium.jecalculation.gui.widgets.WButton; import me.towdium.jecalculation.gui.widgets.WButtonIcon; import me.towdium.jecalculation.gui.widgets.WLabel; -import javax.annotation.ParametersAreNonnullByDefault; - -import static me.towdium.jecalculation.gui.Resource.*; - /** * Author: Towdium * Date: 18-9-18 @@ -21,14 +20,14 @@ import static me.towdium.jecalculation.gui.Resource.*; @SideOnly(Side.CLIENT) public class PickerItemStack extends IPicker.Impl implements IGui { WLabel label = new WLabel(7, 7, 20, 20, true).setLsnrUpdate((i, v) -> update(v)); - WButton bConfirm = new WButtonIcon(149, 7, 20, 20, BTN_YES, "item_stack.confirm").setListener( - i -> callback.accept(label.getLabel())); + WButton bConfirm = new WButtonIcon(149, 7, 20, 20, BTN_YES, "item_stack.confirm") + .setListener(i -> callback.accept(label.getLabel())); WButton bNbtN = new WButtonIcon(49, 7, 20, 20, BTN_NBT_N, "item_stack.nbt_normal").setListener(i -> setFNbt(true)); WButton bNbtF = new WButtonIcon(49, 7, 20, 20, BTN_NBT_F, "item_stack.nbt_fuzzy").setListener(i -> setFNbt(false)); - WButton bMetaN = new WButtonIcon(30, 7, 20, 20, BTN_META_N, "item_stack.meta_normal").setListener( - i -> setFMeta(true)); - WButton bMetaF = new WButtonIcon(30, 7, 20, 20, BTN_META_F, "item_stack.meta_fuzzy").setListener( - i -> setFMeta(false)); + WButton bMetaN = + new WButtonIcon(30, 7, 20, 20, BTN_META_N, "item_stack.meta_normal").setListener(i -> setFMeta(true)); + WButton bMetaF = + new WButtonIcon(30, 7, 20, 20, BTN_META_F, "item_stack.meta_fuzzy").setListener(i -> setFMeta(false)); ILabel raw = ILabel.EMPTY; boolean fMeta, fNbt, fCap = false; @@ -62,10 +61,8 @@ public class PickerItemStack extends IPicker.Impl implements IGui { private void setF(boolean b, WButton be, WButton bd, Runnable r) { remove(be, bd); - if (b) - add(bd); - else - add(be); + if (b) add(bd); + else add(be); r.run(); if (raw instanceof LItemStack) { LItemStack lis = (LItemStack) raw; diff --git a/src/main/java/me/towdium/jecalculation/gui/guis/pickers/PickerPlaceholder.java b/src/main/java/me/towdium/jecalculation/gui/guis/pickers/PickerPlaceholder.java index d16aabb..d37c54a 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/pickers/PickerPlaceholder.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/pickers/PickerPlaceholder.java @@ -1,19 +1,18 @@ package me.towdium.jecalculation.gui.guis.pickers; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import me.towdium.jecalculation.data.label.labels.LPlaceholder; -import me.towdium.jecalculation.gui.guis.IGui; -import me.towdium.jecalculation.gui.widgets.*; -import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; - import static me.towdium.jecalculation.gui.JecaGui.COLOR_TEXT_RED; import static me.towdium.jecalculation.gui.JecaGui.COLOR_TEXT_WHITE; import static me.towdium.jecalculation.gui.Resource.BTN_YES; import static me.towdium.jecalculation.gui.Resource.ICN_TEXT; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.data.label.labels.LPlaceholder; +import me.towdium.jecalculation.gui.guis.IGui; +import me.towdium.jecalculation.gui.widgets.*; +import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; + /** * Author: towdium * Date: 17-9-29. @@ -24,16 +23,16 @@ import static me.towdium.jecalculation.gui.Resource.ICN_TEXT; public class PickerPlaceholder extends IPicker.Impl implements IGui { public PickerPlaceholder() { WLabelScroll scroll = new WLabelScroll(7, 69, 8, 5, false) - .setLabels(LPlaceholder.getRecent()).setLsnrLeftClick((i, v) -> notifyLsnr(i.get(v).getLabel())); - WTextField create = new WTextField(26, 7, 69).setListener( - i -> i.setColor(i.getText().equals("") ? COLOR_TEXT_RED : COLOR_TEXT_WHITE)); + .setLabels(LPlaceholder.getRecent()) + .setLsnrLeftClick((i, v) -> notifyLsnr(i.get(v).getLabel())); + WTextField create = new WTextField(26, 7, 69) + .setListener(i -> i.setColor(i.getText().equals("") ? COLOR_TEXT_RED : COLOR_TEXT_WHITE)); add(new WIcon(7, 45, 20, 20, ICN_TEXT, "common.search")); add(new WIcon(7, 7, 20, 20, ICN_TEXT, "placeholder.create")); add(new WSearch(26, 45, 90, scroll)); add(new WLine(36)); add(new WButtonIcon(95, 7, 20, 20, BTN_YES, "common.confirm").setListener(i -> { - if (!create.getText().equals("")) - callback.accept(new LPlaceholder(create.getText(), 1)); + if (!create.getText().equals("")) callback.accept(new LPlaceholder(create.getText(), 1)); })); add(scroll, create); } diff --git a/src/main/java/me/towdium/jecalculation/gui/guis/pickers/PickerSimple.java b/src/main/java/me/towdium/jecalculation/gui/guis/pickers/PickerSimple.java index 7d7f187..cb00d94 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/pickers/PickerSimple.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/pickers/PickerSimple.java @@ -1,7 +1,13 @@ package me.towdium.jecalculation.gui.guis.pickers; +import static me.towdium.jecalculation.gui.Resource.ICN_TEXT; + import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.data.label.labels.LFluidStack; import me.towdium.jecalculation.data.label.labels.LOreDict; @@ -13,13 +19,6 @@ import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.oredict.OreDictionary; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static me.towdium.jecalculation.gui.Resource.ICN_TEXT; - /** * Author: towdium * Date: 17-9-28. @@ -32,23 +31,21 @@ public class PickerSimple extends IPicker.Impl implements IGui { * @param labels label to be displayed for selection */ public PickerSimple(List labels) { - WLabelScroll ls = new WLabelScroll(7, 33, 8, 7, false).setLabels(labels) + WLabelScroll ls = new WLabelScroll(7, 33, 8, 7, false) + .setLabels(labels) .setLsnrLeftClick((i, v) -> notifyLsnr(i.get(v).getLabel())); add(new WIcon(7, 7, 20, 20, ICN_TEXT, "common.search")); add(new WSearch(26, 7, 90, ls)); add(ls); } - public static class FluidStack extends PickerSimple { public FluidStack() { - super(FluidRegistry.getRegisteredFluids() - .values() - .stream() - // filter the fluid with no icon - .filter(fluid -> fluid.getStillIcon() != null || fluid.getFlowingIcon() != null) - .map(fluid -> new LFluidStack(1000, fluid)) - .collect(Collectors.toList())); + super(FluidRegistry.getRegisteredFluids().values().stream() + // filter the fluid with no icon + .filter(fluid -> fluid.getStillIcon() != null || fluid.getFlowingIcon() != null) + .map(fluid -> new LFluidStack(1000, fluid)) + .collect(Collectors.toList())); } } @@ -59,9 +56,9 @@ public class PickerSimple extends IPicker.Impl implements IGui { static List generate() { return Arrays.stream(OreDictionary.getOreNames()) - .filter(i -> !OreDictionary.getOres(i).isEmpty()) - .map(LOreDict::new) - .collect(Collectors.toList()); + .filter(i -> !OreDictionary.getOres(i).isEmpty()) + .map(LOreDict::new) + .collect(Collectors.toList()); } } } diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/IWidget.java b/src/main/java/me/towdium/jecalculation/gui/widgets/IWidget.java index 4ffb1b5..a3be3ca 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/IWidget.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/IWidget.java @@ -1,12 +1,11 @@ package me.towdium.jecalculation.gui.widgets; +import java.util.List; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.utils.wrappers.Wrapper; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.List; - /** * Author: towdium * Date: 8/14/17. @@ -25,8 +24,7 @@ public interface IWidget { return false; } - default void onMouseFocused(JecaGui gui, int xMouse, int yMouse, int button) { - } + default void onMouseFocused(JecaGui gui, int xMouse, int yMouse, int button) {} default boolean onMouseReleased(JecaGui gui, int xMouse, int yMouse, int button) { return false; diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WButton.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WButton.java index ada27ef..067a07a 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WButton.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WButton.java @@ -1,20 +1,19 @@ package me.towdium.jecalculation.gui.widgets; +import static me.towdium.jecalculation.gui.Resource.*; + import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Arrays; +import java.util.List; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.gui.Resource; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.utils.ClientUtils; import org.lwjgl.input.Keyboard; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.Arrays; -import java.util.List; - -import static me.towdium.jecalculation.gui.Resource.*; - /** * Author: towdium * Date: 17-8-17. @@ -50,8 +49,7 @@ public abstract class WButton extends WTooltip { else if (hovered) res = WGT_BUTTON_F; else res = WGT_BUTTON_N; - gui.drawResourceContinuous(res, xPos, yPos, xSize, - ySize, 5, 5, 5, 5); + gui.drawResourceContinuous(res, xPos, yPos, xSize, ySize, 5, 5, 5, 5); return hovered; } @@ -60,18 +58,14 @@ public abstract class WButton extends WTooltip { if (mouseIn(xMouse, yMouse) && !disabled && button == 0 && listener != null) { trigger(); return true; - } else - return false; + } else return false; } protected boolean hovered(int xMouse, int yMouse) { if (mouseIn(xMouse, yMouse)) { return true; } - if (keys != null) - for (int i : keys) - if (Keyboard.isKeyDown(i)) - return true; + if (keys != null) for (int i : keys) if (Keyboard.isKeyDown(i)) return true; return false; } diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WButtonIcon.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WButtonIcon.java index 5e3c68d..1242a34 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WButtonIcon.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WButtonIcon.java @@ -2,11 +2,10 @@ package me.towdium.jecalculation.gui.widgets; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import me.towdium.jecalculation.gui.JecaGui; -import me.towdium.jecalculation.gui.Resource; - import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.gui.JecaGui; +import me.towdium.jecalculation.gui.Resource; /** * Author: towdium @@ -25,14 +24,15 @@ public class WButtonIcon extends WButton { this(xPos, yPos, xSize, ySize, res.normal, res.focused, res.disabled, null); } - private WButtonIcon(int xPos, - int yPos, - int xSize, - int ySize, - Resource normal, - Resource focused, - @Nullable Resource disabled, - @Nullable String name) { + private WButtonIcon( + int xPos, + int yPos, + int xSize, + int ySize, + Resource normal, + Resource focused, + @Nullable Resource disabled, + @Nullable String name) { super(xPos, yPos, xSize, ySize, name); this.rNormal = normal; this.rFocused = focused; diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WButtonText.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WButtonText.java index a8ad225..556a9cc 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WButtonText.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WButtonText.java @@ -2,10 +2,9 @@ package me.towdium.jecalculation.gui.widgets; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import me.towdium.jecalculation.gui.JecaGui; - import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.gui.JecaGui; /** * Author: towdium diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WContainer.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WContainer.java index a54fe84..5c68c9f 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WContainer.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WContainer.java @@ -2,17 +2,16 @@ package me.towdium.jecalculation.gui.widgets; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.utils.Utilities; import me.towdium.jecalculation.utils.wrappers.Wrapper; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - /** * Author: towdium * Date: 17-9-14. @@ -43,18 +42,16 @@ public class WContainer implements IContainer { public boolean onDraw(JecaGui gui, int mouseX, int mouseY) { Wrapper w = new Wrapper<>(null); widgets.forEach(widget -> { - if (widget.onDraw(gui, mouseX, mouseY)) - w.value = widget; + if (widget.onDraw(gui, mouseX, mouseY)) w.value = widget; }); - if (w.value != null) - w.value.onDraw(gui, mouseX, mouseY); + if (w.value != null) w.value.onDraw(gui, mouseX, mouseY); return false; } @Override public boolean onMouseClicked(JecaGui gui, int xMouse, int yMouse, int button) { - return new Utilities.ReversedIterator<>(widgets).stream() - .anyMatch(i -> i.onMouseClicked(gui, xMouse, yMouse, button)); + return new Utilities.ReversedIterator<>(widgets) + .stream().anyMatch(i -> i.onMouseClicked(gui, xMouse, yMouse, button)); } @Override @@ -69,25 +66,25 @@ public class WContainer implements IContainer { @Override public boolean onMouseReleased(JecaGui gui, int xMouse, int yMouse, int button) { - return new Utilities.ReversedIterator<>(widgets).stream() - .anyMatch(i -> i.onMouseReleased(gui, xMouse, yMouse, button)); + return new Utilities.ReversedIterator<>(widgets) + .stream().anyMatch(i -> i.onMouseReleased(gui, xMouse, yMouse, button)); } @Override public boolean onMouseScroll(JecaGui gui, int xMouse, int yMouse, int diff) { - return new Utilities.ReversedIterator<>(widgets).stream() - .anyMatch(i -> i.onMouseScroll(gui, xMouse, yMouse, diff)); + return new Utilities.ReversedIterator<>(widgets) + .stream().anyMatch(i -> i.onMouseScroll(gui, xMouse, yMouse, diff)); } @Override public boolean onTooltip(JecaGui gui, int xMouse, int yMouse, List tooltip) { - return new Utilities.ReversedIterator<>(widgets).stream() - .anyMatch(i -> i.onTooltip(gui, xMouse, yMouse, tooltip)); + return new Utilities.ReversedIterator<>(widgets) + .stream().anyMatch(i -> i.onTooltip(gui, xMouse, yMouse, tooltip)); } @Override public boolean getLabelUnderMouse(int xMouse, int yMouse, Wrapper label) { - return new Utilities.ReversedIterator<>(widgets).stream() - .anyMatch(i -> i.getLabelUnderMouse(xMouse, yMouse, label)); + return new Utilities.ReversedIterator<>(widgets) + .stream().anyMatch(i -> i.getLabelUnderMouse(xMouse, yMouse, label)); } } diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WHelp.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WHelp.java index 2a72a8a..0264306 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WHelp.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WHelp.java @@ -1,18 +1,17 @@ package me.towdium.jecalculation.gui.widgets; -import me.towdium.jecalculation.gui.JecaGui; -import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; -import me.towdium.jecalculation.utils.Utilities.I18n; -import org.lwjgl.input.Keyboard; - -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.ArrayList; -import java.util.List; - import static me.towdium.jecalculation.gui.JecaGui.Font.PLAIN; import static me.towdium.jecalculation.gui.JecaGui.Font.SHADOW; import static me.towdium.jecalculation.gui.Resource.*; +import java.util.ArrayList; +import java.util.List; +import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.gui.JecaGui; +import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; +import me.towdium.jecalculation.utils.Utilities.I18n; +import org.lwjgl.input.Keyboard; + /** * Author: Towdium * Date: 18-9-23 @@ -24,8 +23,7 @@ public class WHelp extends WContainer { public WHelp(String content) { key = content; - if (I18n.search("gui." + WHelp.this.key + ".title").two - && I18n.search("gui." + WHelp.this.key + ".help").two) { + if (I18n.search("gui." + WHelp.this.key + ".title").two && I18n.search("gui." + WHelp.this.key + ".help").two) { add(new Impl()); } } @@ -51,8 +49,7 @@ public class WHelp extends WContainer { @Override public boolean onMouseClicked(JecaGui gui, int xMouse, int yMouse, int button) { boolean ret = mouseIn(xMouse, yMouse); - if (ret) - gui.root.setOverlay(new Doc()); + if (ret) gui.root.setOverlay(new Doc()); return ret; } } @@ -66,11 +63,9 @@ public class WHelp extends WContainer { add(new WPanel(), new Icon(), title, text, switcher); } - @Override public boolean onMouseClicked(JecaGui gui, int xMouse, int yMouse, int button) { - if (!super.onMouseClicked(gui, xMouse, yMouse, button)) - gui.root.remove(this); + if (!super.onMouseClicked(gui, xMouse, yMouse, button)) gui.root.remove(this); return true; } @@ -145,8 +140,7 @@ public class WHelp extends WContainer { @Override public boolean onMouseClicked(JecaGui gui, int xMouse, int yMouse, int button) { boolean ret = mouseIn(xMouse, yMouse); - if (ret) - gui.root.setOverlay(null); + if (ret) gui.root.setOverlay(null); return ret; } @@ -157,13 +151,11 @@ public class WHelp extends WContainer { @Override public boolean onKeyPressed(JecaGui gui, char ch, int code) { - if (super.onKeyPressed(gui, ch, code)) - return true; + if (super.onKeyPressed(gui, ch, code)) return true; if (code == Keyboard.KEY_ESCAPE) { gui.root.setOverlay(null); return true; - } else - return false; + } else return false; } } } diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WIcon.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WIcon.java index 26fa4bd..5dcb14f 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WIcon.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WIcon.java @@ -1,16 +1,15 @@ package me.towdium.jecalculation.gui.widgets; +import static me.towdium.jecalculation.gui.JecaGui.COLOR_GUI_GREY; + import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.gui.Resource; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import static me.towdium.jecalculation.gui.JecaGui.COLOR_GUI_GREY; - - /** * Author: towdium * Date: 17-8-18. @@ -30,8 +29,7 @@ public class WIcon extends WTooltip { this(xPos, yPos, xSize, ySize, res.normal, res.focused, name); } - private WIcon(int xPos, int yPos, int xSize, int ySize, - Resource normal, Resource focused, @Nullable String name) { + private WIcon(int xPos, int yPos, int xSize, int ySize, Resource normal, Resource focused, @Nullable String name) { super(name); this.xPos = xPos; this.yPos = yPos; @@ -52,7 +50,12 @@ public class WIcon extends WTooltip { @Override public boolean mouseIn(int xMouse, int yMouse) { - return JecaGui.mouseIn(xPos + (xSize - normal.getXSize()) / 2, - yPos + (ySize - normal.getYSize()) / 2, normal.getXSize(), normal.getYSize(), xMouse, yMouse); + return JecaGui.mouseIn( + xPos + (xSize - normal.getXSize()) / 2, + yPos + (ySize - normal.getYSize()) / 2, + normal.getXSize(), + normal.getYSize(), + xMouse, + yMouse); } } diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WLabel.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WLabel.java index c13cf7b..e057289 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WLabel.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WLabel.java @@ -1,23 +1,21 @@ package me.towdium.jecalculation.gui.widgets; +import static me.towdium.jecalculation.gui.JecaGui.Font.HALF; +import static me.towdium.jecalculation.gui.Resource.WGT_SLOT; + import codechicken.lib.gui.GuiDraw; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; +import java.util.function.BiConsumer; +import java.util.function.Function; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.utils.Utilities.Timer; import me.towdium.jecalculation.utils.wrappers.Wrapper; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.List; -import java.util.function.BiConsumer; -import java.util.function.BiFunction; -import java.util.function.Function; - -import static me.towdium.jecalculation.gui.JecaGui.Font.HALF; -import static me.towdium.jecalculation.gui.Resource.WGT_SLOT; - /** * Author: towdium * Date: 17-8-17. @@ -54,8 +52,7 @@ public class WLabel implements IWidget { public WLabel setLabel(ILabel label, boolean notify) { this.label = label; - if (notify) - notifyUpdate(); + if (notify) notifyUpdate(); return this; } @@ -64,22 +61,23 @@ public class WLabel implements IWidget { gui.drawResourceContinuous(WGT_SLOT, xPos, yPos, xSize, ySize, 3, 3, 3, 3); label.drawLabel(gui, xPos + xSize / 2, yPos + ySize / 2, true); String s = fmtAmount.apply(label); - gui.drawText(xPos + xSize / 2.0f + 8 - HALF.getTextWidth(s), yPos + ySize / 2.0f + 8.5f - HALF.getTextHeight(), - HALF, s); + gui.drawText( + xPos + xSize / 2.0f + 8 - HALF.getTextWidth(s), + yPos + ySize / 2.0f + 8.5f - HALF.getTextHeight(), + HALF, + s); if (accept) { timer.setState(gui.hand != ILabel.EMPTY); int color = 0xFFFFFF + (int) ((-Math.cos(timer.getTime() * Math.PI / 1500) + 1) * 0x40) * 0x1000000; GuiDraw.drawRect(xPos + 1, yPos + 1, xSize - 2, ySize - 2, color); } - if (mouseIn(xMouse, yMouse)) - GuiDraw.drawRect(xPos + 1, yPos + 1, xSize - 2, ySize - 2, 0x80FFFFFF); + if (mouseIn(xMouse, yMouse)) GuiDraw.drawRect(xPos + 1, yPos + 1, xSize - 2, ySize - 2, 0x80FFFFFF); return false; } @Override public boolean onTooltip(JecaGui gui, int xMouse, int yMouse, List tooltip) { - if (!mouseIn(xMouse, yMouse)) - return false; + if (!mouseIn(xMouse, yMouse)) return false; if (label != ILabel.EMPTY) { tooltip.add(label.getDisplayName()); tooltip.add(JecaGui.SEPARATOR); @@ -93,37 +91,31 @@ public class WLabel implements IWidget { if (mouseIn(xMouse, yMouse) && this.label != ILabel.EMPTY) { label.value = this.label; return true; - } else - return false; + } else return false; } @Override public boolean onMouseClicked(JecaGui gui, int xMouse, int yMouse, int button) { - if (!mouseIn(xMouse, yMouse)) - return false; + if (!mouseIn(xMouse, yMouse)) return false; if (button == 1) { notifyRightClick(); return true; } if (accept && gui.hand != ILabel.EMPTY) { - label = gui.hand; - gui.hand = label.EMPTY; - notifyUpdate(); - } else - notifyLeftClick(); + label = gui.hand; + gui.hand = label.EMPTY; + notifyUpdate(); + } else notifyLeftClick(); return true; } @Override public boolean onMouseScroll(JecaGui gui, int xMouse, int yMouse, int diff) { - if (scroll == null) - return false; + if (scroll == null) return false; else if (mouseIn(xMouse, yMouse)) { scroll.invoke(this, diff); return true; - } - else - return false; + } else return false; } public WLabel setLsnrUpdate(ListenerValue listener) { @@ -163,17 +155,14 @@ public class WLabel implements IWidget { } private void notifyLeftClick() { - if (leftClick != null) - leftClick.invoke(this); + if (leftClick != null) leftClick.invoke(this); } private void notifyRightClick() { - if (rightClick != null) - rightClick.invoke(this); + if (rightClick != null) rightClick.invoke(this); } private void notifyUpdate() { - if (update != null) - update.invoke(this, label); + if (update != null) update.invoke(this, label); } } diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WLabelGroup.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WLabelGroup.java index 7aa4127..094a57f 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WLabelGroup.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WLabelGroup.java @@ -2,16 +2,15 @@ package me.towdium.jecalculation.gui.widgets; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import me.towdium.jecalculation.data.label.ILabel; -import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; import java.util.ArrayList; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; +import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.data.label.ILabel; +import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; /** * Author: towdium @@ -33,17 +32,16 @@ public class WLabelGroup extends WContainer { for (int j = 0; j < row; j++) { int r = j; IntStream.range(0, column).forEach(c -> { - WLabel l = new WLabel(xPos + c * xSize, yPos + r * ySize, xSize, ySize, accept).setLsnrUpdate( - (i, v) -> { - if (lsnrUpdate != null) - lsnrUpdate.invoke(this, r * column + c); - }).setLsnrLeftClick(i -> { - if (lsnrLeftClick != null) - lsnrLeftClick.invoke(this, r * column + c); - }).setLsnrRightClick(i -> { - if (lsnrRightClick != null) - lsnrRightClick.invoke(this, r * column + c); - }); + WLabel l = new WLabel(xPos + c * xSize, yPos + r * ySize, xSize, ySize, accept) + .setLsnrUpdate((i, v) -> { + if (lsnrUpdate != null) lsnrUpdate.invoke(this, r * column + c); + }) + .setLsnrLeftClick(i -> { + if (lsnrLeftClick != null) lsnrLeftClick.invoke(this, r * column + c); + }) + .setLsnrRightClick(i -> { + if (lsnrRightClick != null) lsnrRightClick.invoke(this, r * column + c); + }); labels.add(l); add(l); }); @@ -63,8 +61,7 @@ public class WLabelGroup extends WContainer { } public void setLabel(List labels, int start) { - for (WLabel label : this.labels) - label.setLabel(start < labels.size() ? labels.get(start++) : ILabel.EMPTY); + for (WLabel label : this.labels) label.setLabel(start < labels.size() ? labels.get(start++) : ILabel.EMPTY); } public WLabelGroup setLsnrUpdate(ListenerValue listener) { @@ -96,4 +93,4 @@ public class WLabelGroup extends WContainer { labels.forEach(i -> i.setFmtTooltip(f)); return this; } -} \ No newline at end of file +} diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WLabelScroll.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WLabelScroll.java index 10708a8..fa5821e 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WLabelScroll.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WLabelScroll.java @@ -2,17 +2,16 @@ package me.towdium.jecalculation.gui.widgets; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import me.towdium.jecalculation.data.label.ILabel; -import me.towdium.jecalculation.gui.JecaGui; -import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; -import me.towdium.jecalculation.utils.Utilities.I18n; - -import javax.annotation.ParametersAreNonnullByDefault; import java.util.ArrayList; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; +import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.data.label.ILabel; +import me.towdium.jecalculation.gui.JecaGui; +import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; +import me.towdium.jecalculation.utils.Utilities.I18n; /** * Author: towdium @@ -38,30 +37,31 @@ public class WLabelScroll extends WContainer implements ISearchable { this.yPos = yPos; this.column = column; this.row = row; - labelGroup = new WLabelGroup(xPos, yPos, column, row, accept).setLsnrUpdate(this::onUpdate) - .setLsnrLeftClick(this::onLeftClick) - .setLsnrRightClick(this::onRightClick); - scroll = new WScroll(xPos + column * 18 + 4, yPos, row * 18).setListener(i -> update(i.getCurrent())) - .setStep(Float.POSITIVE_INFINITY) - .setRatio(1); + labelGroup = new WLabelGroup(xPos, yPos, column, row, accept) + .setLsnrUpdate(this::onUpdate) + .setLsnrLeftClick(this::onLeftClick) + .setLsnrRightClick(this::onRightClick); + scroll = new WScroll(xPos + column * 18 + 4, yPos, row * 18) + .setListener(i -> update(i.getCurrent())) + .setStep(Float.POSITIVE_INFINITY) + .setRatio(1); add(labelGroup); add(scroll); add(new WRectangle(xPos + column * 18, yPos, 4, row * 18, JecaGui.COLOR_GUI_GREY)); } public void update(float f) { - if (f < 0) - f = 0; - if (f > 1) - f = 1; + if (f < 0) f = 0; + if (f > 1) f = 1; int amount = getAmountSteps(); current = (int) (amount * f); - if (current == amount) - current--; + if (current == amount) current--; List ls = accept ? labels : filtered; labelGroup.setLabel(ls, current * column); float step = 1f / (amount - 1); - scroll.setRatio(Math.min(row / (float) getAmountRows(), 1f)).setCurrent(f).setStep(step); + scroll.setRatio(Math.min(row / (float) getAmountRows(), 1f)) + .setCurrent(f) + .setStep(step); } public WLabel get(int index) { @@ -70,10 +70,8 @@ public class WLabelScroll extends WContainer implements ISearchable { public WLabelScroll setLabels(List labels) { this.labels = labels; - if (accept) - update(0); - else - setFilter(filter); + if (accept) update(0); + else setFilter(filter); return this; } @@ -83,11 +81,10 @@ public class WLabelScroll extends WContainer implements ISearchable { } public boolean setFilter(String str) { - if (accept) - throw new RuntimeException("Filtering not allowed when editing"); + if (accept) throw new RuntimeException("Filtering not allowed when editing"); filtered = labels.stream() - .filter(l -> I18n.contains(l.getDisplayName().toLowerCase(), str.toLowerCase())) - .collect(Collectors.toList()); + .filter(l -> I18n.contains(l.getDisplayName().toLowerCase(), str.toLowerCase())) + .collect(Collectors.toList()); update(0); return filtered.size() != 0; } @@ -114,11 +111,9 @@ public class WLabelScroll extends WContainer implements ISearchable { protected void onUpdate(WLabelGroup w, int index) { ILabel l = w.get(index).getLabel(); int i = column * current + index; - while (labels.size() <= i) - labels.add(ILabel.EMPTY); + while (labels.size() <= i) labels.add(ILabel.EMPTY); labels.set(i, l); - if (lsnrUpdate != null) - lsnrUpdate.invoke(this, i); + if (lsnrUpdate != null) lsnrUpdate.invoke(this, i); if (index + 1 == row * column && l != ILabel.EMPTY && (row + current) * column == labels.size()) { labels.add(ILabel.EMPTY); @@ -129,13 +124,11 @@ public class WLabelScroll extends WContainer implements ISearchable { } protected void onLeftClick(WLabelGroup w, int index) { - if (hdlrLeftClick != null) - hdlrLeftClick.invoke(this, column * current + index); + if (hdlrLeftClick != null) hdlrLeftClick.invoke(this, column * current + index); } protected void onRightClick(WLabelGroup w, int index) { - if (hdlrRightClick != null) - hdlrRightClick.invoke(this, column * current + index); + if (hdlrRightClick != null) hdlrRightClick.invoke(this, column * current + index); } public WLabelScroll setLsnrScroll(ListenerValue hdlr) { diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WLcd.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WLcd.java index 234fe67..d7f0757 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WLcd.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WLcd.java @@ -1,19 +1,17 @@ package me.towdium.jecalculation.gui.widgets; -import me.towdium.jecalculation.data.structure.RecordMath.Operator; -import me.towdium.jecalculation.gui.JecaGui; -import me.towdium.jecalculation.gui.Resource; -import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; +import static me.towdium.jecalculation.data.structure.RecordMath.DOT_NONE; -import javax.annotation.ParametersAreNonnullByDefault; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.HashMap; import java.util.Objects; - -import static me.towdium.jecalculation.data.structure.RecordMath.DOT_NONE; - +import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.data.structure.RecordMath.Operator; +import me.towdium.jecalculation.gui.JecaGui; +import me.towdium.jecalculation.gui.Resource; +import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; /** * Author: Towdium @@ -24,7 +22,6 @@ import static me.towdium.jecalculation.data.structure.RecordMath.DOT_NONE; public class WLcd implements IWidget { static HashMap PATTERN = new HashMap<>(); - public int yPos; public String text = ""; public int dot = DOT_NONE; @@ -32,22 +29,22 @@ public class WLcd implements IWidget { public Operator operator = Operator.EQUALS; static { - PATTERN.put('0', new boolean[]{true, true, true, true, true, true, false}); - PATTERN.put('1', new boolean[]{false, true, true, false, false, false, false}); - PATTERN.put('2', new boolean[]{true, true, false, true, true, false, true}); - PATTERN.put('3', new boolean[]{true, true, true, true, false, false, true}); - PATTERN.put('4', new boolean[]{false, true, true, false, false, true, true}); - PATTERN.put('5', new boolean[]{true, false, true, true, false, true, true}); - PATTERN.put('6', new boolean[]{true, false, true, true, true, true, true}); - PATTERN.put('7', new boolean[]{true, true, true, false, false, false, false}); - PATTERN.put('8', new boolean[]{true, true, true, true, true, true, true}); - PATTERN.put('9', new boolean[]{true, true, true, true, false, true, true}); - PATTERN.put('E', new boolean[]{true, false, false, true, true, true, true}); - PATTERN.put('o', new boolean[]{false, false, true, true, true, false, true}); - PATTERN.put('r', new boolean[]{false, false, false, false, true, false, true}); - PATTERN.put('-', new boolean[]{false, false, false, false, false, false, true}); - PATTERN.put(' ', new boolean[]{false, false, false, false, false, false, false}); - //format.setMinimumIntegerDigits(0); + PATTERN.put('0', new boolean[] {true, true, true, true, true, true, false}); + PATTERN.put('1', new boolean[] {false, true, true, false, false, false, false}); + PATTERN.put('2', new boolean[] {true, true, false, true, true, false, true}); + PATTERN.put('3', new boolean[] {true, true, true, true, false, false, true}); + PATTERN.put('4', new boolean[] {false, true, true, false, false, true, true}); + PATTERN.put('5', new boolean[] {true, false, true, true, false, true, true}); + PATTERN.put('6', new boolean[] {true, false, true, true, true, true, true}); + PATTERN.put('7', new boolean[] {true, true, true, false, false, false, false}); + PATTERN.put('8', new boolean[] {true, true, true, true, true, true, true}); + PATTERN.put('9', new boolean[] {true, true, true, true, false, true, true}); + PATTERN.put('E', new boolean[] {true, false, false, true, true, true, true}); + PATTERN.put('o', new boolean[] {false, false, true, true, true, false, true}); + PATTERN.put('r', new boolean[] {false, false, false, false, true, false, true}); + PATTERN.put('-', new boolean[] {false, false, false, false, false, false, true}); + PATTERN.put(' ', new boolean[] {false, false, false, false, false, false, false}); + // format.setMinimumIntegerDigits(0); } public WLcd(int yPos) { @@ -58,8 +55,7 @@ public class WLcd implements IWidget { public boolean onDraw(JecaGui gui, int xMouse, int yMouse) { drawBackground(gui); drawStr(gui, text); - if (dot != DOT_NONE) - drawDot(gui, 6 - dot); + if (dot != DOT_NONE) drawDot(gui, 6 - dot); drawOperator(gui, operator); return false; } @@ -85,26 +81,18 @@ public class WLcd implements IWidget { protected void drawChar(JecaGui gui, char ch, int index) { boolean[] pattern = PATTERN.get(ch); Objects.requireNonNull(pattern, "Unsupported char: " + ch + "."); - if (pattern[0]) - gui.drawResource(Resource.WGT_LCD_H_F, 19 + index * 21, yPos + 14); - if (pattern[1]) - gui.drawResource(Resource.WGT_LCD_UR_F, 30 + index * 21, yPos + 14); - if (pattern[2]) - gui.drawResource(Resource.WGT_LCD_LR_F, 30 + index * 21, yPos + 28); - if (pattern[3]) - gui.drawResource(Resource.WGT_LCD_H_F, 19 + index * 21, yPos + 40); - if (pattern[4]) - gui.drawResource(Resource.WGT_LCD_LL_F, 16 + index * 21, yPos + 28); - if (pattern[5]) - gui.drawResource(Resource.WGT_LCD_UL_F, 16 + index * 21, yPos + 14); - if (pattern[6]) - gui.drawResource(Resource.WGT_LCD_H_F, 19 + index * 21, yPos + 27); + if (pattern[0]) gui.drawResource(Resource.WGT_LCD_H_F, 19 + index * 21, yPos + 14); + if (pattern[1]) gui.drawResource(Resource.WGT_LCD_UR_F, 30 + index * 21, yPos + 14); + if (pattern[2]) gui.drawResource(Resource.WGT_LCD_LR_F, 30 + index * 21, yPos + 28); + if (pattern[3]) gui.drawResource(Resource.WGT_LCD_H_F, 19 + index * 21, yPos + 40); + if (pattern[4]) gui.drawResource(Resource.WGT_LCD_LL_F, 16 + index * 21, yPos + 28); + if (pattern[5]) gui.drawResource(Resource.WGT_LCD_UL_F, 16 + index * 21, yPos + 14); + if (pattern[6]) gui.drawResource(Resource.WGT_LCD_H_F, 19 + index * 21, yPos + 27); } protected void drawStr(JecaGui gui, String str) { int offset = 7 - str.length(); - for (int i = offset; i < 7; i++) - drawChar(gui, str.charAt(i - offset), i); + for (int i = offset; i < 7; i++) drawChar(gui, str.charAt(i - offset), i); } protected void drawDot(JecaGui gui, int index) { diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WLine.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WLine.java index be0c1e8..2315c2b 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WLine.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WLine.java @@ -2,12 +2,11 @@ package me.towdium.jecalculation.gui.widgets; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.gui.Resource; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; -import javax.annotation.ParametersAreNonnullByDefault; - /** * Author: towdium * Date: 17-8-18. diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WOverlay.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WOverlay.java index 5401c7c..a9d4d8e 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WOverlay.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WOverlay.java @@ -1,12 +1,11 @@ package me.towdium.jecalculation.gui.widgets; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.polyfill.mc.client.renderer.GlStateManager; import org.lwjgl.input.Keyboard; -import javax.annotation.ParametersAreNonnullByDefault; - /** * Author: Towdium * Date: 16/02/19 diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WPage.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WPage.java index 79034a2..09bf9dc 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WPage.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WPage.java @@ -1,18 +1,17 @@ package me.towdium.jecalculation.gui.widgets; +import static me.towdium.jecalculation.gui.Resource.WGT_PAGER_F; +import static me.towdium.jecalculation.gui.Resource.WGT_PANEL_N; + import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.label.ILabel.RegistryEditor.Record; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.gui.Resource; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.List; - -import static me.towdium.jecalculation.gui.Resource.WGT_PAGER_F; -import static me.towdium.jecalculation.gui.Resource.WGT_PANEL_N; - /** * Author: towdium * Date: 17-9-16. diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WPanel.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WPanel.java index af41936..0046e5a 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WPanel.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WPanel.java @@ -2,15 +2,14 @@ package me.towdium.jecalculation.gui.widgets; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.gui.Resource; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.utils.wrappers.Wrapper; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.List; - /** * Author: towdium * Date: 17-9-15. @@ -33,7 +32,6 @@ public class WPanel implements IWidget { this(0, 0, 176, 166); } - @Override public boolean onDraw(JecaGui gui, int xMouse, int yMouse) { gui.drawResourceContinuous(Resource.WGT_PANEL_F, xPos, yPos, xSize, ySize, 5, 5, 5, 5); diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WRectangle.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WRectangle.java index aa71e72..3657554 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WRectangle.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WRectangle.java @@ -2,11 +2,10 @@ package me.towdium.jecalculation.gui.widgets; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; -import javax.annotation.ParametersAreNonnullByDefault; - /** * Author: towdium * Date: 17-8-22. diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WScroll.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WScroll.java index 1596737..08468ff 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WScroll.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WScroll.java @@ -1,17 +1,16 @@ package me.towdium.jecalculation.gui.widgets; +import static me.towdium.jecalculation.gui.Resource.*; + import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.gui.Resource; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import org.lwjgl.input.Mouse; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; - -import static me.towdium.jecalculation.gui.Resource.*; - /** * Author: towdium * Date: 17-8-19. @@ -37,10 +36,8 @@ public class WScroll implements IWidget { @Override public boolean onDraw(JecaGui gui, int xMouse, int yMouse) { - if (Mouse.isButtonDown(0) && active) - setCurrent(yMouse - yPos - height / 2, true); - else - active = false; + if (Mouse.isButtonDown(0) && active) setCurrent(yMouse - yPos - height / 2, true); + else active = false; int offset = (int) (current * (ySize - height)); boolean in = mouseIn(xMouse, yMouse); @@ -54,8 +51,7 @@ public class WScroll implements IWidget { @Override public boolean onMouseClicked(JecaGui gui, int xMouse, int yMouse, int button) { active = mouseIn(xMouse, yMouse); - if (active) - setCurrent(yMouse - yPos - height / 2, true); + if (active) setCurrent(yMouse - yPos - height / 2, true); return active; } @@ -91,7 +87,7 @@ public class WScroll implements IWidget { } public WScroll setCurrent(float ratio, boolean notify) { - //setCurrent((int) ((ySize - height) * ratio), false); + // setCurrent((int) ((ySize - height) * ratio), false); current = ratio; if (current < 0) current = 0; if (current > 1) current = 1; diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WSearch.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WSearch.java index 3d30ce3..52e127d 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WSearch.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WSearch.java @@ -1,14 +1,13 @@ package me.towdium.jecalculation.gui.widgets; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; - import static me.towdium.jecalculation.gui.JecaGui.COLOR_TEXT_RED; import static me.towdium.jecalculation.gui.JecaGui.COLOR_TEXT_WHITE; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; + /** * Author: towdium * Date: 17-9-28. @@ -32,9 +31,7 @@ public class WSearch extends WTextField { public void refresh() { boolean b = false; - for (ISearchable i : lss) - if (i.setFilter(textField.getText())) - b = true; + for (ISearchable i : lss) if (i.setFilter(textField.getText())) b = true; setColor(b ? COLOR_TEXT_WHITE : COLOR_TEXT_RED); } } diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WSwitcher.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WSwitcher.java index a889571..a178d24 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WSwitcher.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WSwitcher.java @@ -1,24 +1,20 @@ package me.towdium.jecalculation.gui.widgets; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import me.towdium.jecalculation.gui.JecaGui; -import me.towdium.jecalculation.gui.Resource; -import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; -import me.towdium.jecalculation.utils.Utilities.Circulator; - -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - - import static me.towdium.jecalculation.gui.JecaGui.COLOR_GUI_GREY; import static me.towdium.jecalculation.gui.JecaGui.Font.SHADOW; import static me.towdium.jecalculation.gui.Resource.WGT_ARR_L; import static me.towdium.jecalculation.gui.Resource.WGT_ARR_R; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; +import me.towdium.jecalculation.utils.Utilities.Circulator; + /** * Author: towdium * Date: 17-8-19. @@ -39,8 +35,11 @@ public class WSwitcher extends WContainer { protected String temp; public WSwitcher(int xPos, int yPos, int xSize, int total) { - this(xPos, yPos, xSize, - IntStream.rangeClosed(1, total).mapToObj(i -> i + "/" + total).collect(Collectors.toList())); + this( + xPos, + yPos, + xSize, + IntStream.rangeClosed(1, total).mapToObj(i -> i + "/" + total).collect(Collectors.toList())); } public WSwitcher(int xPos, int yPos, int xSize, List keys) { @@ -100,7 +99,6 @@ public class WSwitcher extends WContainer { return keys; } - public String getText() { return temp == null ? keys.get(index.current()) : temp; } diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WText.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WText.java index 599179a..070d5c1 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WText.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WText.java @@ -2,11 +2,10 @@ package me.towdium.jecalculation.gui.widgets; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; -import javax.annotation.ParametersAreNonnullByDefault; - /** * Author: towdium * Date: 17-8-21. @@ -38,10 +37,8 @@ public class WText implements IWidget { @Override public boolean onDraw(JecaGui gui, int xMouse, int yMouse) { int x = xPos + (centred ? xSize / 2 - font.getTextWidth(key) / 2 : 0); - if (xSize == UNDEFINED) - gui.drawText(x, yPos, font, key); - else - gui.drawText(x, yPos, xSize, font, key); + if (xSize == UNDEFINED) gui.drawText(x, yPos, font, key); + else gui.drawText(x, yPos, xSize, font, key); return false; } } diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WTextField.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WTextField.java index 209c781..7df2f9c 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WTextField.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WTextField.java @@ -2,13 +2,12 @@ package me.towdium.jecalculation.gui.widgets; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiTextField; -import javax.annotation.ParametersAreNonnullByDefault; - /** * Author: towdium * Date: 17-8-18. @@ -41,8 +40,7 @@ public class WTextField implements IWidget { textField.setText(""); notifyLsnr(); return true; - } else - return false; + } else return false; } @Override @@ -54,8 +52,7 @@ public class WTextField implements IWidget { @Override public boolean onKeyPressed(JecaGui gui, char ch, int code) { boolean ret = textField.textboxKeyTyped(ch, code); - if (ret) - notifyLsnr(); + if (ret) notifyLsnr(); return ret; } @@ -80,7 +77,6 @@ public class WTextField implements IWidget { } protected void notifyLsnr() { - if (listener != null) - listener.invoke(this); + if (listener != null) listener.invoke(this); } -} \ No newline at end of file +} diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WTick.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WTick.java index f5eb979..2b8c5ad 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WTick.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WTick.java @@ -1,16 +1,15 @@ package me.towdium.jecalculation.gui.widgets; +import static me.towdium.jecalculation.gui.Resource.*; + +import java.util.Collections; +import java.util.List; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.gui.Resource; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.Collections; -import java.util.List; - -import static me.towdium.jecalculation.gui.Resource.*; - /** * Author: Towdium * Date: 18-12-7 @@ -24,7 +23,6 @@ public class WTick extends WContainer { boolean disabled; ListenerAction listener; - public WTick(int xPos, int yPos, int xSize, int ySize, @Nullable String name) { this.xPos = xPos; this.yPos = yPos; @@ -50,13 +48,10 @@ public class WTick extends WContainer { } public WTick setSelected(boolean selected) { - if (selected == selected()) - return this; + if (selected == selected()) return this; remove(button); - if (selected) - button = new Selected(xPos, yPos, xSize, ySize, name); - else - button = new Normal(xPos, yPos, xSize, ySize, name); + if (selected) button = new Selected(xPos, yPos, xSize, ySize, name); + else button = new Normal(xPos, yPos, xSize, ySize, name); add(button); return this; } diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/WTooltip.java b/src/main/java/me/towdium/jecalculation/gui/widgets/WTooltip.java index c9389ef..f9232e2 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WTooltip.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WTooltip.java @@ -1,21 +1,20 @@ package me.towdium.jecalculation.gui.widgets; +import static java.lang.String.join; + import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.utils.Utilities; import me.towdium.jecalculation.utils.Utilities.I18n; import me.towdium.jecalculation.utils.wrappers.Pair; -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import static java.lang.String.join; - /** * Author: towdium * Date: 17-9-16. @@ -33,8 +32,7 @@ public abstract class WTooltip implements IWidget { @Override public boolean onDraw(JecaGui gui, int xMouse, int yMouse) { - if (name != null) - timer.setState(mouseIn(xMouse, yMouse)); + if (name != null) timer.setState(mouseIn(xMouse, yMouse)); return false; } @@ -42,17 +40,14 @@ public abstract class WTooltip implements IWidget { public boolean onTooltip(JecaGui gui, int xMouse, int yMouse, List tooltip) { if (timer.getTime() > 500) { List> suffix = getSuffix().stream() - .map(s -> I18n.search(s.isEmpty() ? - join(".", "gui", name) : - join(".", "gui", name, s))) - .collect(Collectors.toList()); + .map(s -> I18n.search(s.isEmpty() ? join(".", "gui", name) : join(".", "gui", name, s))) + .collect(Collectors.toList()); String str = suffix.stream() - .filter(p -> p.two) - .findFirst() - .map(p -> p.one) - .orElse(JecaGui.ALWAYS_TOOLTIP ? suffix.get(0).one : null); - if (str != null) - Collections.addAll(tooltip, str.split("\n")); + .filter(p -> p.two) + .findFirst() + .map(p -> p.one) + .orElse(JecaGui.ALWAYS_TOOLTIP ? suffix.get(0).one : null); + if (str != null) Collections.addAll(tooltip, str.split("\n")); } return false; } diff --git a/src/main/java/me/towdium/jecalculation/nei/Adapter.java b/src/main/java/me/towdium/jecalculation/nei/Adapter.java index d036e34..de1befa 100644 --- a/src/main/java/me/towdium/jecalculation/nei/Adapter.java +++ b/src/main/java/me/towdium/jecalculation/nei/Adapter.java @@ -3,14 +3,13 @@ package me.towdium.jecalculation.nei; import codechicken.nei.PositionedStack; import codechicken.nei.recipe.IRecipeHandler; import cpw.mods.fml.common.Loader; +import java.util.ArrayList; +import java.util.List; import me.towdium.jecalculation.JustEnoughCalculation; import me.towdium.jecalculation.nei.adapter.*; import me.towdium.jecalculation.utils.Utilities; import net.minecraft.item.ItemStack; -import java.util.ArrayList; -import java.util.List; - public class Adapter { public static List adapters = new ArrayList<>(); @@ -19,7 +18,7 @@ public class Adapter { String modId = name.substring(0, name.indexOf(":")); String itemId = name.substring(name.indexOf(":") + 1); if (Loader.isModLoaded("gregtech")) { - if(GregTech6.isGT6()) { + if (GregTech6.isGT6()) { return GregTech6.convertFluid(itemStack); } else { return GregTech.convertFluid(itemStack); @@ -31,60 +30,65 @@ public class Adapter { public static void init() { JustEnoughCalculation.logger.info("=====Just Enough Calculation Init Start====="); if (Loader.isModLoaded("Forestry")) { - JustEnoughCalculation.logger.info("Forestry installed"); + JustEnoughCalculation.logger.info("Forestry detected"); adapters.add(new Forestry()); } if (Loader.isModLoaded("appliedenergistics2")) { - JustEnoughCalculation.logger.info("ae2 not supported"); + JustEnoughCalculation.logger.info("ae2 detected"); adapters.add(new AE2()); } if (Loader.isModLoaded("gregtech")) { - if(GregTech6.isGT6()) { - JustEnoughCalculation.logger.info("gregtech6 installed"); + if (GregTech6.isGT6()) { + JustEnoughCalculation.logger.info("gregtech6 detected"); adapters.add(new GregTech6()); } else { - JustEnoughCalculation.logger.info("gregtech5 installed"); + JustEnoughCalculation.logger.info("gregtech5 detected"); adapters.add(new GregTech()); } } try { if (Loader.isModLoaded("miscutils")) { adapters.add(new GTPP()); - JustEnoughCalculation.logger.info("gt++ installed"); + JustEnoughCalculation.logger.info("gt++ detected"); } } catch (Exception e) { - JustEnoughCalculation.logger.info("exception when installing gt++"); + JustEnoughCalculation.logger.error("Init error with gt++"); e.printStackTrace(); } if (Loader.isModLoaded("Avaritia")) { - JustEnoughCalculation.logger.info("Avaritia installed"); + JustEnoughCalculation.logger.info("Avaritia detected"); adapters.add(new Avaritia()); } if (Loader.isModLoaded("EnderIO")) { - JustEnoughCalculation.logger.info("EnderIO installed"); + JustEnoughCalculation.logger.info("EnderIO detected"); adapters.add(new EnderIO()); } if (Loader.isModLoaded("thaumcraftneiplugin")) { adapters.add(new Thaum()); - JustEnoughCalculation.logger.info("Thaumcraft installed"); + JustEnoughCalculation.logger.info("Thaumcraft detected"); } JustEnoughCalculation.logger.info("=====Just Enough Calculation Init Finish====="); } public static void handleRecipe(IRecipeHandler recipe, int index, List inputs, List outputs) { // raw inputs - recipe.getIngredientStacks(index) - .stream() - .map((positionedStack) -> (Object[]) positionedStack.items) - .forEach(inputs::add); + recipe.getIngredientStacks(index).stream() + .map((positionedStack) -> (Object[]) positionedStack.items) + .forEach(inputs::add); // raw outputs PositionedStack resultStack = recipe.getResultStack(index); - if (resultStack != null) - outputs.add(resultStack.items); + if (resultStack != null) outputs.add(resultStack.items); - for (IAdapter adapter : adapters) { - adapter.handleRecipe(recipe, index, inputs, outputs); + try { + for (IAdapter adapter : adapters) { + adapter.handleRecipe(recipe, index, inputs, outputs); + } + } catch (Exception e) { + Utilities.addChatMessage(Utilities.ChatMessage.RECIPE_TRANSFER_ERROR); + JustEnoughCalculation.logger.error( + "Exception when handling recipe: " + recipe.getClass().getName()); + e.printStackTrace(); } } } diff --git a/src/main/java/me/towdium/jecalculation/nei/JecaOverlayHandler.java b/src/main/java/me/towdium/jecalculation/nei/JecaOverlayHandler.java index 72b1faf..fb4912d 100644 --- a/src/main/java/me/towdium/jecalculation/nei/JecaOverlayHandler.java +++ b/src/main/java/me/towdium/jecalculation/nei/JecaOverlayHandler.java @@ -7,6 +7,9 @@ import codechicken.nei.recipe.IRecipeHandler; import codechicken.nei.recipe.TemplateRecipeHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.*; +import java.util.stream.Collectors; +import javax.annotation.Nonnull; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.data.structure.CostList; import me.towdium.jecalculation.data.structure.Recipe; @@ -16,10 +19,6 @@ import me.towdium.jecalculation.utils.wrappers.Trio; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.item.ItemStack; -import javax.annotation.Nonnull; -import java.util.*; -import java.util.stream.Collectors; - @SideOnly(Side.CLIENT) public class JecaOverlayHandler implements IOverlayHandler { @Override @@ -37,11 +36,10 @@ public class JecaOverlayHandler implements IOverlayHandler { } } - private static EnumMap>> convertRecipe(IRecipeHandler recipe, - int recipeIndex, - Class context) { - EnumMap>> merged = new EnumMap<>( - Recipe.IO.class); // item disamb raw + private static EnumMap>> convertRecipe( + IRecipeHandler recipe, int recipeIndex, Class context) { + // item disamb raw + EnumMap>> merged = new EnumMap<>(Recipe.IO.class); // merge recipe input, output and catalysts List recipeInputs = new ArrayList<>(); @@ -61,31 +59,32 @@ public class JecaOverlayHandler implements IOverlayHandler { return merged; } - private static void merge(EnumMap>> dst, - List objs, - Class context, - Recipe.IO type) { + private static void merge( + EnumMap>> dst, + List objs, + Class context, + Recipe.IO type) { List list = objs.stream().map(ILabel.Converter::from).collect(Collectors.toList()); - if (list.isEmpty()) - return; + if (list.isEmpty()) return; ILabel rep = list.get(0).copy(); - if (type == Recipe.IO.INPUT && list.size() != 1) - rep = ILabel.CONVERTER.first(list, context); + if (type == Recipe.IO.INPUT && list.size() != 1) rep = ILabel.CONVERTER.first(list, context); ILabel fin = rep; - dst.computeIfAbsent(type, i -> new ArrayList<>()).stream().filter(p -> { - CostList cl = new CostList(list); - if (p.three.equals(cl)) { - ILabel.MERGER.merge(p.one, fin).ifPresent(i -> p.one = i); - p.two = p.two.merge(cl, true, false); - return true; - } else - return false; - }).findAny().orElseGet(() -> { - Trio ret = new Trio<>(fin, new CostList(list), new CostList(list)); - dst.get(type).add(ret); - return ret; - }); + dst.computeIfAbsent(type, i -> new ArrayList<>()).stream() + .filter(p -> { + CostList cl = new CostList(list); + if (p.three.equals(cl)) { + ILabel.MERGER.merge(p.one, fin).ifPresent(i -> p.one = i); + p.two = CostList.merge(p.two, cl, true); + return true; + } else return false; + }) + .findAny() + .orElseGet(() -> { + Trio ret = new Trio<>(fin, new CostList(list), new CostList(list)); + dst.get(type).add(ret); + return ret; + }); } private static Optional getCatalyst(@Nonnull IRecipeHandler handler) { @@ -107,5 +106,4 @@ public class JecaOverlayHandler implements IOverlayHandler { ItemStack itemStack = info.getItemStack(); return Optional.ofNullable(itemStack); } - } diff --git a/src/main/java/me/towdium/jecalculation/nei/JecaTooltipHandler.java b/src/main/java/me/towdium/jecalculation/nei/JecaTooltipHandler.java index 6d18178..ce6622d 100644 --- a/src/main/java/me/towdium/jecalculation/nei/JecaTooltipHandler.java +++ b/src/main/java/me/towdium/jecalculation/nei/JecaTooltipHandler.java @@ -1,12 +1,11 @@ package me.towdium.jecalculation.nei; import codechicken.nei.guihook.IContainerTooltipHandler; +import java.util.List; import me.towdium.jecalculation.gui.JecaGui; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.item.ItemStack; -import java.util.List; - public class JecaTooltipHandler implements IContainerTooltipHandler { @Override public List handleTooltip(GuiContainer gui, int mousex, int mousey, List currenttip) { @@ -19,11 +18,8 @@ public class JecaTooltipHandler implements IContainerTooltipHandler { } @Override - public List handleItemTooltip(GuiContainer gui, - ItemStack itemstack, - int mousex, - int mousey, - List currenttip) { + public List handleItemTooltip( + GuiContainer gui, ItemStack itemstack, int mousex, int mousey, List currenttip) { if (gui instanceof JecaGui) { NEIPlugin.setLabelUnderMouse(itemstack); } diff --git a/src/main/java/me/towdium/jecalculation/nei/NEICalculatorConfig.java b/src/main/java/me/towdium/jecalculation/nei/NEICalculatorConfig.java index b8ce670..b565f9d 100644 --- a/src/main/java/me/towdium/jecalculation/nei/NEICalculatorConfig.java +++ b/src/main/java/me/towdium/jecalculation/nei/NEICalculatorConfig.java @@ -2,16 +2,15 @@ package me.towdium.jecalculation.nei; import codechicken.nei.api.API; import codechicken.nei.api.IConfigureNEI; -import me.towdium.jecalculation.JustEnoughCalculation; -import me.towdium.jecalculation.gui.JecaGui; -import me.towdium.jecalculation.nei.adapter.IAdapter; - import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +import me.towdium.jecalculation.Tags; +import me.towdium.jecalculation.gui.JecaGui; +import me.towdium.jecalculation.nei.adapter.IAdapter; public class NEICalculatorConfig implements IConfigureNEI { @@ -19,26 +18,27 @@ public class NEICalculatorConfig implements IConfigureNEI { public void loadConfig() { Adapter.init(); /* null For the recipeHandlers which extend `TemplateRecipeHandler` without override the `getOverlayIdentifier` function */ - Set baseOverlayIdentifiers = new HashSet<>( - Arrays.asList("crafting", "crafting2x2", "smelting", "fuel", "brewing", null)); + Set baseOverlayIdentifiers = + new HashSet<>(Arrays.asList("crafting", "crafting2x2", "smelting", "fuel", "brewing", null)); Set adapterIdentifiers = Adapter.adapters.stream() - .map(IAdapter::getAllOverlayIdentifier) - .flatMap(Collection::stream) - .collect(Collectors.toSet()); + .map(IAdapter::getAllOverlayIdentifier) + .flatMap(Collection::stream) + .collect(Collectors.toSet()); - Stream.concat(baseOverlayIdentifiers.stream(), adapterIdentifiers.stream()).forEach(ident -> { - API.registerGuiOverlay(JecaGui.class, ident); - API.registerGuiOverlayHandler(JecaGui.class, new JecaOverlayHandler(), ident); - }); + Stream.concat(baseOverlayIdentifiers.stream(), adapterIdentifiers.stream()) + .forEach(ident -> { + API.registerGuiOverlay(JecaGui.class, ident); + API.registerGuiOverlayHandler(JecaGui.class, new JecaOverlayHandler(), ident); + }); } @Override public String getName() { - return JustEnoughCalculation.Reference.MODNAME; + return Tags.MODNAME; } @Override public String getVersion() { - return JustEnoughCalculation.Reference.VERSION; + return Tags.VERSION; } } diff --git a/src/main/java/me/towdium/jecalculation/nei/NEIPlugin.java b/src/main/java/me/towdium/jecalculation/nei/NEIPlugin.java index 1b3c9f2..6ff9d14 100644 --- a/src/main/java/me/towdium/jecalculation/nei/NEIPlugin.java +++ b/src/main/java/me/towdium/jecalculation/nei/NEIPlugin.java @@ -19,7 +19,8 @@ public class NEIPlugin { public static void init() { GuiContainerManager.addTooltipHandler(new JecaTooltipHandler()); // nei version check - String neiVersion = Loader.instance().getIndexedModList().get("NotEnoughItems").getVersion(); + String neiVersion = + Loader.instance().getIndexedModList().get("NotEnoughItems").getVersion(); JustEnoughCalculation.logger.info("NEI version: " + neiVersion); Version version = new Version(neiVersion); if (version.isSuccess() && version.compareTo(CATALYST_NEI_VERSION) >= 0) { @@ -37,8 +38,7 @@ public class NEIPlugin { } public static ILabel getLabelUnderMouse() { - if (NEIPlugin.currentItemStack == null) - return ILabel.EMPTY; + if (NEIPlugin.currentItemStack == null) return ILabel.EMPTY; Object stack = Adapter.convertFluid(NEIPlugin.currentItemStack); return ILabel.Converter.from(stack); } diff --git a/src/main/java/me/towdium/jecalculation/nei/adapter/AE2.java b/src/main/java/me/towdium/jecalculation/nei/adapter/AE2.java index dd33582..1b85fa5 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/AE2.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/AE2.java @@ -1,22 +1,19 @@ package me.towdium.jecalculation.nei.adapter; import codechicken.nei.recipe.IRecipeHandler; - -import javax.annotation.ParametersAreNonnullByDefault; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; +import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault -public class AE2 implements IAdapter{ +public class AE2 implements IAdapter { @Override public Set getAllOverlayIdentifier() { return new HashSet<>(Arrays.asList("inscriber", "grindstone")); } @Override - public void handleRecipe(IRecipeHandler recipe, int index, List inputs, List outputs) { - - } + public void handleRecipe(IRecipeHandler recipe, int index, List inputs, List outputs) {} } diff --git a/src/main/java/me/towdium/jecalculation/nei/adapter/AdapterUtil.java b/src/main/java/me/towdium/jecalculation/nei/adapter/AdapterUtil.java index 49fb236..637e3a4 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/AdapterUtil.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/AdapterUtil.java @@ -1,7 +1,7 @@ package me.towdium.jecalculation.nei.adapter; -import javax.annotation.ParametersAreNonnullByDefault; import java.util.Optional; +import javax.annotation.ParametersAreNonnullByDefault; @SuppressWarnings("rawtypes") @ParametersAreNonnullByDefault @@ -14,5 +14,4 @@ public class AdapterUtil { return Optional.empty(); } } - } diff --git a/src/main/java/me/towdium/jecalculation/nei/adapter/Avaritia.java b/src/main/java/me/towdium/jecalculation/nei/adapter/Avaritia.java index 2519737..002844e 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/Avaritia.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/Avaritia.java @@ -1,12 +1,11 @@ package me.towdium.jecalculation.nei.adapter; import codechicken.nei.recipe.IRecipeHandler; - -import javax.annotation.ParametersAreNonnullByDefault; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; +import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault public class Avaritia implements IAdapter { @@ -17,7 +16,5 @@ public class Avaritia implements IAdapter { } @Override - public void handleRecipe(IRecipeHandler recipe, int index, List inputs, List outputs) { - - } + public void handleRecipe(IRecipeHandler recipe, int index, List inputs, List outputs) {} } diff --git a/src/main/java/me/towdium/jecalculation/nei/adapter/EnderIO.java b/src/main/java/me/towdium/jecalculation/nei/adapter/EnderIO.java index 0fd0090..9208b5f 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/EnderIO.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/EnderIO.java @@ -2,32 +2,35 @@ package me.towdium.jecalculation.nei.adapter; import codechicken.nei.recipe.IRecipeHandler; import codechicken.nei.recipe.TemplateRecipeHandler; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; - -import javax.annotation.ParametersAreNonnullByDefault; import java.lang.reflect.Field; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; +import javax.annotation.ParametersAreNonnullByDefault; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; @ParametersAreNonnullByDefault public class EnderIO implements IAdapter { @Override public Set getAllOverlayIdentifier() { - return new HashSet<>( - Arrays.asList("EnderIOAlloySmelter", "EIOEnchanter", "EnderIOSagMill", "EnderIOSliceAndSplice", - "EnderIOSoulBinder", "EnderIOVat")); + return new HashSet<>(Arrays.asList( + "EnderIOAlloySmelter", + "EIOEnchanter", + "EnderIOSagMill", + "EnderIOSliceAndSplice", + "EnderIOSoulBinder", + "EnderIOVat")); } - private final static Set> defaultHandlers; - private final static Class vat; + private static final Set> defaultHandlers; + private static final Class vat; static { List handlers = Stream.of("SagMillRecipeHandler") - .map(name -> "crazypants.enderio.nei." + name) - .collect(Collectors.toList()); + .map(name -> "crazypants.enderio.nei." + name) + .collect(Collectors.toList()); defaultHandlers = new HashSet<>(); for (String handler : handlers) { try { @@ -48,10 +51,9 @@ public class EnderIO implements IAdapter { @Override public void handleRecipe(IRecipeHandler recipe, int index, List inputs, List outputs) { if (defaultHandlers.stream().anyMatch(aClass -> aClass.isInstance(recipe))) { - List otherStacks = recipe.getOtherStacks(index) - .stream() - .map(positionedStack -> positionedStack.items) - .collect(Collectors.toList()); + List otherStacks = recipe.getOtherStacks(index).stream() + .map(positionedStack -> positionedStack.items) + .collect(Collectors.toList()); outputs.addAll(otherStacks); } else { try { @@ -60,8 +62,8 @@ public class EnderIO implements IAdapter { Field arecipes = vat.getField("arecipes"); @SuppressWarnings("unchecked") - TemplateRecipeHandler.CachedRecipe cachedRecipe = ((ArrayList) arecipes - .get(recipe)).get(index); + TemplateRecipeHandler.CachedRecipe cachedRecipe = + ((ArrayList) arecipes.get(recipe)).get(index); Field resultField = vatInnerRecipe.getDeclaredField("result"); Field inFluidField = vatInnerRecipe.getDeclaredField("inFluid"); @@ -70,8 +72,8 @@ public class EnderIO implements IAdapter { FluidStack result = (FluidStack) resultField.get(cachedRecipe); FluidStack inFluid = (FluidStack) inFluidField.get(cachedRecipe); - inputs.add(new Object[]{inFluid}); - outputs.add(new Object[]{result}); + inputs.add(new Object[] {inFluid}); + outputs.add(new Object[] {result}); resultField.setAccessible(false); inFluidField.setAccessible(false); } diff --git a/src/main/java/me/towdium/jecalculation/nei/adapter/Forestry.java b/src/main/java/me/towdium/jecalculation/nei/adapter/Forestry.java index 338de5d..eb3a55d 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/Forestry.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/Forestry.java @@ -5,14 +5,13 @@ import codechicken.nei.recipe.IRecipeHandler; import forestry.core.recipes.nei.PositionedFluidTank; import forestry.core.recipes.nei.RecipeHandlerBase; import forestry.factory.recipes.nei.*; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTank; - -import javax.annotation.ParametersAreNonnullByDefault; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +import javax.annotation.ParametersAreNonnullByDefault; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTank; @ParametersAreNonnullByDefault public class Forestry implements IAdapter { @@ -34,16 +33,14 @@ public class Forestry implements IAdapter { private void bottler(RecipeHandlerBase recipe, int recipeIndex, List inputs) { if (recipe instanceof NEIHandlerBottler) { List> fluids = getFluids(recipe, recipeIndex); - if (fluids.size() >= 1) - inputs.add(fluids.get(0).toArray()); + if (fluids.size() >= 1) inputs.add(fluids.get(0).toArray()); } } private void carpenter(RecipeHandlerBase recipe, int recipeIndex, List inputs) { if (recipe instanceof NEIHandlerCarpenter) { List> fluids = getFluids(recipe, recipeIndex); - if (fluids.size() >= 1) - inputs.add(fluids.get(0).toArray()); + if (fluids.size() >= 1) inputs.add(fluids.get(0).toArray()); } } @@ -57,8 +54,7 @@ public class Forestry implements IAdapter { private void fabricator(RecipeHandlerBase recipe, int recipeIndex, List inputs) { if (recipe instanceof NEIHandlerFabricator) { List> fluids = getFluids(recipe, recipeIndex); - if (fluids.size() >= 1) - inputs.add(fluids.get(0).toArray()); + if (fluids.size() >= 1) inputs.add(fluids.get(0).toArray()); } } @@ -66,7 +62,8 @@ public class Forestry implements IAdapter { if (recipe instanceof NEIHandlerFermenter) { List tanks = getTanks(recipe, recipeIndex); tanks.forEach(tank -> { - Object[] fluids = Arrays.stream(tank.tanks).map(FluidTank::getFluid).toArray(); + Object[] fluids = + Arrays.stream(tank.tanks).map(FluidTank::getFluid).toArray(); if (tank.position.x == 30) { // source inputs.add(fluids); @@ -81,8 +78,7 @@ public class Forestry implements IAdapter { private void moistener(RecipeHandlerBase recipe, int recipeIndex, List inputs, List outputs) { if (recipe instanceof NEIHandlerMoistener) { List> fluids = getFluids(recipe, recipeIndex); - if (fluids.size() >= 1) - inputs.add(fluids.get(0).toArray()); + if (fluids.size() >= 1) inputs.add(fluids.get(0).toArray()); List otherStacks = recipe.getOtherStacks(recipeIndex); otherStacks.forEach(positionedStack -> { ItemStack[] items = positionedStack.items; @@ -100,15 +96,15 @@ public class Forestry implements IAdapter { private void squeezer(RecipeHandlerBase recipe, int recipeIndex, List inputs, List outputs) { if (recipe instanceof NEIHandlerSqueezer) { List> fluids = getFluids(recipe, recipeIndex); - if (fluids.size() >= 1) - outputs.add(fluids.get(0).toArray()); + if (fluids.size() >= 1) outputs.add(fluids.get(0).toArray()); } } private void still(RecipeHandlerBase recipe, int recipeIndex, List inputs, List outputs) { if (recipe instanceof NEIHandlerStill) { getTanks(recipe, recipeIndex).forEach(tank -> { - Object[] fluids = Arrays.stream(tank.tanks).map(FluidTank::getFluid).toArray(); + Object[] fluids = + Arrays.stream(tank.tanks).map(FluidTank::getFluid).toArray(); if (tank.position.x == 30) { // input inputs.add(fluids); @@ -128,19 +124,15 @@ public class Forestry implements IAdapter { * @return fluid tanks */ private List> getFluids(RecipeHandlerBase recipe, int recipeIndex) { - return ((RecipeHandlerBase.CachedBaseRecipe) recipe.arecipes.get(recipeIndex)).getFluidTanks() - .stream() - .map(positionedFluidTank -> Arrays - .stream(positionedFluidTank.tanks) - .map(FluidTank::getFluid) - .collect( - Collectors.toList())) - .collect(Collectors.toList()); - + return ((RecipeHandlerBase.CachedBaseRecipe) recipe.arecipes.get(recipeIndex)) + .getFluidTanks().stream() + .map(positionedFluidTank -> Arrays.stream(positionedFluidTank.tanks) + .map(FluidTank::getFluid) + .collect(Collectors.toList())) + .collect(Collectors.toList()); } private List getTanks(RecipeHandlerBase recipe, int recipeIndex) { return ((RecipeHandlerBase.CachedBaseRecipe) recipe.arecipes.get(recipeIndex)).getFluidTanks(); } - } diff --git a/src/main/java/me/towdium/jecalculation/nei/adapter/GTPP.java b/src/main/java/me/towdium/jecalculation/nei/adapter/GTPP.java index 2347c61..b31344b 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/GTPP.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/GTPP.java @@ -1,14 +1,12 @@ package me.towdium.jecalculation.nei.adapter; import codechicken.nei.recipe.IRecipeHandler; - -import javax.annotation.ParametersAreNonnullByDefault; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; - +import javax.annotation.ParametersAreNonnullByDefault; /** * don't work, why? @@ -16,18 +14,27 @@ import java.util.stream.Stream; @ParametersAreNonnullByDefault public class GTPP extends GregTech { - private final static Set> defaultHandlers; + private static final Set> defaultHandlers; static { List handlers = Stream.of( - // gtpp after 2020/5/30 - "GTPP_NEI_DefaultHandler", "GT_NEI_VacFurnace", "GT_NEI_RFPP", "GT_NEI_multiCentriElectroFreezer", - "GT_NEI_MillingMachine", "GT_NEI_FluidReactor", "GT_NEI_FlotationCell", "DecayableRecipeHandler", - // gtpp before 2020/5/30 - "GT_NEI_DefaultHandler", "GT_NEI_Dehydrator", "GT_NEI_MultiBlockHandler", "GTPP_NEI_CustomMapHandler", - "GTPP_NEI_DefaultHandlerEx" - - ).map(name -> "gtPlusPlus.nei." + name).collect(Collectors.toList()); + // gtpp after 2020/5/30 + "GTPP_NEI_DefaultHandler", + "GT_NEI_VacFurnace", + "GT_NEI_RFPP", + "GT_NEI_multiCentriElectroFreezer", + "GT_NEI_MillingMachine", + "GT_NEI_FluidReactor", + "GT_NEI_FlotationCell", + "DecayableRecipeHandler", + // gtpp before 2020/5/30 + "GT_NEI_DefaultHandler", + "GT_NEI_Dehydrator", + "GT_NEI_MultiBlockHandler", + "GTPP_NEI_CustomMapHandler", + "GTPP_NEI_DefaultHandlerEx") + .map(name -> "gtPlusPlus.nei." + name) + .collect(Collectors.toList()); defaultHandlers = new HashSet<>(); for (String handler : handlers) { @@ -44,12 +51,11 @@ public class GTPP extends GregTech { Set recipeNames = new HashSet<>(); try { // add as many recipe as possible - recipeNames.addAll( this.reflectGetRecipeMapNEIName("gregtech.api.util.GTPP_Recipe$GTPP_Recipe_Map", "sMappings")); - recipeNames.addAll(this.reflectGetRecipeMapNEIName("gregtech.api.util.GTPP_Recipe$GTPP_Recipe_Map_Internal", - "sMappingsEx")); + recipeNames.addAll(this.reflectGetRecipeMapNEIName( + "gregtech.api.util.GTPP_Recipe$GTPP_Recipe_Map_Internal", "sMappingsEx")); } catch (Exception e) { e.printStackTrace(); } @@ -62,7 +68,7 @@ public class GTPP extends GregTech { @Override public void handleRecipe(IRecipeHandler recipe, int index, List inputs, List outputs) { if (defaultHandlers.stream().anyMatch(aClass -> aClass.isInstance(recipe))) { - handleDefault(recipe, index, inputs, outputs); + handleDefault(recipe, index, inputs, outputs, true); } } } diff --git a/src/main/java/me/towdium/jecalculation/nei/adapter/GregTech.java b/src/main/java/me/towdium/jecalculation/nei/adapter/GregTech.java index 6656cde..b3ad971 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/GregTech.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/GregTech.java @@ -2,18 +2,17 @@ package me.towdium.jecalculation.nei.adapter; import codechicken.nei.PositionedStack; import codechicken.nei.recipe.IRecipeHandler; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - -import javax.annotation.ParametersAreNonnullByDefault; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors; +import javax.annotation.ParametersAreNonnullByDefault; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; @ParametersAreNonnullByDefault public class GregTech implements IAdapter { @@ -30,13 +29,16 @@ public class GregTech implements IAdapter { Field mNEINameField = gtRecipeMapClz.getField("mNEIName"); Collection sMappings = (Collection) sMappingsField.get(null); - return (Set) sMappings.stream().map(sMapping -> { - try { - return mNEINameField.get(sMapping); - } catch (IllegalAccessException e) { - return null; - } - }).filter(Objects::nonNull).collect(Collectors.toSet()); + return (Set) sMappings.stream() + .map(sMapping -> { + try { + return mNEINameField.get(sMapping); + } catch (IllegalAccessException e) { + return null; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); return new HashSet<>(); @@ -66,15 +68,32 @@ public class GregTech implements IAdapter { } protected void handleDefault(IRecipeHandler recipe, int index, List inputs, List outputs) { - for (int i = 0; i < inputs.size(); i++) { - Object[] objects = Arrays.stream(inputs.get(i)).map(o -> GregTech.convertFluid((ItemStack) o)).toArray(); - inputs.set(i, objects); + handleDefault(recipe, index, inputs, outputs, false); + } + + protected void handleDefault( + IRecipeHandler recipe, int index, List inputs, List outputs, boolean clearOutput) { + inputs.replaceAll(ts -> Arrays.stream(ts) + .map(o -> { + if (o instanceof ItemStack) { + return GregTech.convertFluid((ItemStack) o); + } else if (o instanceof FluidStack) { + return o; + } else { + throw new IllegalArgumentException( + "Shall get ItemStack or FluidStack, but get: " + o.getClass()); + } + }) + .toArray()); + if (clearOutput) { + outputs.clear(); } List otherStacks = recipe.getOtherStacks(index); outputs.addAll(otherStacks.stream() - .map(positionedStack -> positionedStack.items) - .map(itemStacks -> Arrays.stream(itemStacks).map(GregTech::convertFluid).toArray()) - .collect(Collectors.toList())); + .map(positionedStack -> positionedStack.items) + .map(itemStacks -> + Arrays.stream(itemStacks).map(GregTech::convertFluid).toArray()) + .collect(Collectors.toList())); } public static Object convertFluid(ItemStack itemStack) { @@ -93,19 +112,23 @@ public class GregTech implements IAdapter { Enum display_fluid = Enum.valueOf(itemListClz, "Display_Fluid"); Method getItem = itemListClz.getMethod("getItem"); Item displayFluidItem = (Item) getItem.invoke(display_fluid); - if (!isStackValid(aDisplayStack) || aDisplayStack.getItem() != displayFluidItem || - !aDisplayStack.hasTagCompound()) - return null; + if (!isStackValid(aDisplayStack) + || aDisplayStack.getItem() != displayFluidItem + || !aDisplayStack.hasTagCompound()) return null; Fluid tFluid = FluidRegistry.getFluid(displayFluidItem.getDamage(aDisplayStack)); return new FluidStack(tFluid, (int) aDisplayStack.getTagCompound().getLong("mFluidDisplayAmount")); - } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + } catch (ClassNotFoundException + | NoSuchMethodException + | IllegalAccessException + | InvocationTargetException e) { e.printStackTrace(); return null; } } private static boolean isStackValid(Object aStack) { - return (aStack instanceof ItemStack) && ((ItemStack) aStack).getItem() != null && - ((ItemStack) aStack).stackSize >= 0; + return (aStack instanceof ItemStack) + && ((ItemStack) aStack).getItem() != null + && ((ItemStack) aStack).stackSize >= 0; } } diff --git a/src/main/java/me/towdium/jecalculation/nei/adapter/GregTech6.java b/src/main/java/me/towdium/jecalculation/nei/adapter/GregTech6.java index 958b732..d08ced5 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/GregTech6.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/GregTech6.java @@ -1,18 +1,16 @@ package me.towdium.jecalculation.nei.adapter; -import codechicken.nei.PositionedStack; import codechicken.nei.recipe.IRecipeHandler; import codechicken.nei.recipe.TemplateRecipeHandler; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; - -import javax.annotation.ParametersAreNonnullByDefault; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; +import javax.annotation.ParametersAreNonnullByDefault; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; @ParametersAreNonnullByDefault public class GregTech6 implements IAdapter { @@ -71,7 +69,7 @@ public class GregTech6 implements IAdapter { @Override public void handleRecipe(IRecipeHandler recipe, int index, List inputs, List outputs) { if (gtRecipeMap.isInstance(recipe)) { - TemplateRecipeHandler a = (TemplateRecipeHandler)recipe; + TemplateRecipeHandler a = (TemplateRecipeHandler) recipe; TemplateRecipeHandler.CachedRecipe cachedRecipe = a.arecipes.get(index); try { Field mRecipe = gtRecipeMapCachedRecipe.getDeclaredField("mRecipe"); @@ -80,27 +78,32 @@ public class GregTech6 implements IAdapter { Field mOutputs = gtRecipe.getDeclaredField("mOutputs"); Field mFluidInputs = gtRecipe.getDeclaredField("mFluidInputs"); Field mFluidOutputs = gtRecipe.getDeclaredField("mFluidOutputs"); - ItemStack[] input =(ItemStack[]) mInputs.get(re); + ItemStack[] input = (ItemStack[]) mInputs.get(re); ItemStack[] output = (ItemStack[]) mOutputs.get(re); FluidStack[] fluidInputs = (FluidStack[]) mFluidInputs.get(re); FluidStack[] fluidOutputs = (FluidStack[]) mFluidOutputs.get(re); inputs.clear(); - inputs.addAll(Stream.concat(Arrays.stream(input), Arrays.stream(fluidInputs)).map(i -> new Object[] {i}).collect(Collectors.toList())); + inputs.addAll(Stream.concat(Arrays.stream(input), Arrays.stream(fluidInputs)) + .map(i -> new Object[] {i}) + .collect(Collectors.toList())); outputs.clear(); - outputs.addAll(Stream.concat(Arrays.stream(output), Arrays.stream(fluidOutputs)).map(o -> new Object[] {o}).collect(Collectors.toList())); + outputs.addAll(Stream.concat(Arrays.stream(output), Arrays.stream(fluidOutputs)) + .map(o -> new Object[] {o}) + .collect(Collectors.toList())); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } -// for (int i = 0; i < inputs.size(); i++) { -// Object[] objects = Arrays.stream(inputs.get(i)).map(o -> GregTech6.convertFluid((ItemStack) o)).toArray(); -// inputs.set(i, objects); -// } -// List otherStacks = recipe.getOtherStacks(index); -// outputs.addAll(otherStacks -// .stream() -// .map(stack -> stack.items) -// .map(is -> Arrays.stream(is).map(GregTech6::convertFluid).toArray()) -// .collect(Collectors.toList())); + // for (int i = 0; i < inputs.size(); i++) { + // Object[] objects = Arrays.stream(inputs.get(i)).map(o -> + // GregTech6.convertFluid((ItemStack) o)).toArray(); + // inputs.set(i, objects); + // } + // List otherStacks = recipe.getOtherStacks(index); + // outputs.addAll(otherStacks + // .stream() + // .map(stack -> stack.items) + // .map(is -> Arrays.stream(is).map(GregTech6::convertFluid).toArray()) + // .collect(Collectors.toList())); } } @@ -114,7 +117,10 @@ public class GregTech6 implements IAdapter { Class itemListClz = Class.forName("gregapi.data.FL"); Method getFluidMethod = itemListClz.getDeclaredMethod("getFluid", ItemStack.class, boolean.class); return (FluidStack) getFluidMethod.invoke(null, aDisplayStack, true); - } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + } catch (ClassNotFoundException + | NoSuchMethodException + | IllegalAccessException + | InvocationTargetException e) { e.printStackTrace(); return null; } diff --git a/src/main/java/me/towdium/jecalculation/nei/adapter/IAdapter.java b/src/main/java/me/towdium/jecalculation/nei/adapter/IAdapter.java index 2f2a715..dee6b49 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/IAdapter.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/IAdapter.java @@ -1,17 +1,17 @@ package me.towdium.jecalculation.nei.adapter; import codechicken.nei.recipe.IRecipeHandler; - -import javax.annotation.ParametersAreNonnullByDefault; import java.util.Collections; import java.util.List; import java.util.Set; +import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault public interface IAdapter { default Set getAllOverlayIdentifier() { return Collections.emptySet(); - }; + } + ; void handleRecipe(IRecipeHandler recipe, int index, List inputs, List outputs); } diff --git a/src/main/java/me/towdium/jecalculation/nei/adapter/Thaum.java b/src/main/java/me/towdium/jecalculation/nei/adapter/Thaum.java index ac51b55..97d6394 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/Thaum.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/Thaum.java @@ -2,29 +2,35 @@ package me.towdium.jecalculation.nei.adapter; import codechicken.nei.recipe.IRecipeHandler; import cpw.mods.fml.common.registry.GameData; -import net.minecraft.item.ItemStack; - -import javax.annotation.ParametersAreNonnullByDefault; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; +import javax.annotation.ParametersAreNonnullByDefault; +import net.minecraft.item.ItemStack; @ParametersAreNonnullByDefault public class Thaum implements IAdapter { @Override public Set getAllOverlayIdentifier() { - return new HashSet<>( - Arrays.asList("arcaneshapedrecipes", "arcaneshapelessrecipes", "aspectsRecipe", "cruciblerecipe", - "infusionCrafting")); + return new HashSet<>(Arrays.asList( + "arcaneshapedrecipes", + "arcaneshapelessrecipes", + "aspectsRecipe", + "cruciblerecipe", + "infusionCrafting")); } - private final static Set> defaultHandlers; + private static final Set> defaultHandlers; static { - List handlers = Stream.of("ArcaneShapedRecipeHandler", "ArcaneShapelessRecipeHandler", - "AspectRecipeHandler", "CrucibleRecipeHandler", "InfusionRecipeHandler") - .map(name -> "com.djgiannuzz.thaumcraftneiplugin.nei.recipehandler." + name) - .collect(Collectors.toList()); + List handlers = Stream.of( + "ArcaneShapedRecipeHandler", + "ArcaneShapelessRecipeHandler", + "AspectRecipeHandler", + "CrucibleRecipeHandler", + "InfusionRecipeHandler") + .map(name -> "com.djgiannuzz.thaumcraftneiplugin.nei.recipehandler." + name) + .collect(Collectors.toList()); defaultHandlers = new HashSet<>(); for (String handler : handlers) { try { @@ -52,7 +58,6 @@ public class Thaum implements IAdapter { } } } - } } } diff --git a/src/main/java/me/towdium/jecalculation/network/ClientHandler.java b/src/main/java/me/towdium/jecalculation/network/ClientHandler.java deleted file mode 100644 index 7fa53de..0000000 --- a/src/main/java/me/towdium/jecalculation/network/ClientHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -package me.towdium.jecalculation.network; - -import cpw.mods.fml.client.registry.ClientRegistry; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import me.towdium.jecalculation.command.JecaCommand; -import me.towdium.jecalculation.data.Controller; -import me.towdium.jecalculation.data.label.ILabel; -import me.towdium.jecalculation.event.Handlers; -import net.minecraftforge.client.ClientCommandHandler; - -import static me.towdium.jecalculation.gui.JecaGui.keyOpenGuiCraft; -import static me.towdium.jecalculation.gui.JecaGui.keyOpenGuiMath; - -@SideOnly(Side.CLIENT) -public class ClientHandler { - - public void initPre() { - Handlers.register(); - } - - public void initPost() { - ILabel.initServer(); - ClientCommandHandler.instance.registerCommand(new JecaCommand()); - ILabel.initClient(); - Controller.loadFromLocal(); - } - - public void init() { - ClientRegistry.registerKeyBinding(keyOpenGuiCraft); - ClientRegistry.registerKeyBinding(keyOpenGuiMath); - } -} diff --git a/src/main/java/me/towdium/jecalculation/network/ClientProxy.java b/src/main/java/me/towdium/jecalculation/network/ClientProxy.java new file mode 100644 index 0000000..4e17062 --- /dev/null +++ b/src/main/java/me/towdium/jecalculation/network/ClientProxy.java @@ -0,0 +1,58 @@ +package me.towdium.jecalculation.network; + +import static me.towdium.jecalculation.gui.JecaGui.keyOpenGuiCraft; +import static me.towdium.jecalculation.gui.JecaGui.keyOpenGuiMath; + +import cpw.mods.fml.client.registry.ClientRegistry; +import cpw.mods.fml.common.event.*; +import me.towdium.jecalculation.JecaConfig; +import me.towdium.jecalculation.command.JecaCommand; +import me.towdium.jecalculation.data.Controller; +import me.towdium.jecalculation.data.label.ILabel; +import me.towdium.jecalculation.event.Handlers; +import me.towdium.jecalculation.nei.NEIPlugin; +import net.minecraftforge.client.ClientCommandHandler; + +@SuppressWarnings("unused") +public class ClientProxy extends CommonProxy { + + public void preInit(FMLPreInitializationEvent event) { + JecaConfig.preInit(event); + Handlers.register(); + } + + public void init(FMLInitializationEvent event) { + ClientRegistry.registerKeyBinding(keyOpenGuiCraft); + ClientRegistry.registerKeyBinding(keyOpenGuiMath); + } + + public void postInit(FMLPostInitializationEvent event) { + ILabel.initServer(); + ClientCommandHandler.instance.registerCommand(new JecaCommand()); + ILabel.initClient(); + Controller.loadFromLocal(); + + NEIPlugin.init(); + } + + public void serverAboutToStart(FMLServerAboutToStartEvent event) { + super.serverAboutToStart(event); + } + + // register server commands in this event handler + public void serverStarting(FMLServerStartingEvent event) { + super.serverStarting(event); + } + + public void serverStarted(FMLServerStartedEvent event) { + super.serverStarted(event); + } + + public void serverStopping(FMLServerStoppingEvent event) { + super.serverStopping(event); + } + + public void serverStopped(FMLServerStoppedEvent event) { + super.serverStopped(event); + } +} diff --git a/src/main/java/me/towdium/jecalculation/network/CommonProxy.java b/src/main/java/me/towdium/jecalculation/network/CommonProxy.java new file mode 100644 index 0000000..3f551be --- /dev/null +++ b/src/main/java/me/towdium/jecalculation/network/CommonProxy.java @@ -0,0 +1,27 @@ +package me.towdium.jecalculation.network; + +import cpw.mods.fml.common.event.*; + +public class CommonProxy { + + // preInit "Run before anything else. Read your config, create blocks, items, + // etc, and register them with the GameRegistry." + public void preInit(FMLPreInitializationEvent event) {} + + // load "Do your mod setup. Build whatever data structures you care about. Register recipes." + public void init(FMLInitializationEvent event) {} + + // postInit "Handle interaction with other mods, complete your setup based on this." + public void postInit(FMLPostInitializationEvent event) {} + + public void serverAboutToStart(FMLServerAboutToStartEvent event) {} + + // register server commands in this event handler + public void serverStarting(FMLServerStartingEvent event) {} + + public void serverStarted(FMLServerStartedEvent event) {} + + public void serverStopping(FMLServerStoppingEvent event) {} + + public void serverStopped(FMLServerStoppedEvent event) {} +} diff --git a/src/main/java/me/towdium/jecalculation/polyfill/MethodsReturnNonnullByDefault.java b/src/main/java/me/towdium/jecalculation/polyfill/MethodsReturnNonnullByDefault.java index f505969..bd8e391 100644 --- a/src/main/java/me/towdium/jecalculation/polyfill/MethodsReturnNonnullByDefault.java +++ b/src/main/java/me/towdium/jecalculation/polyfill/MethodsReturnNonnullByDefault.java @@ -1,11 +1,11 @@ package me.towdium.jecalculation.polyfill; -import javax.annotation.Nonnull; -import javax.annotation.meta.TypeQualifierDefault; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import javax.annotation.Nonnull; +import javax.annotation.meta.TypeQualifierDefault; /** * This annotation can be applied to a package, class or method to indicate that @@ -23,5 +23,4 @@ import java.lang.annotation.RetentionPolicy; @TypeQualifierDefault(ElementType.METHOD) // Note: This is a copy of javax.annotation.ParametersAreNonnullByDefault with target changed to METHOD @Retention(RetentionPolicy.RUNTIME) -public @interface MethodsReturnNonnullByDefault { -} \ No newline at end of file +public @interface MethodsReturnNonnullByDefault {} diff --git a/src/main/java/me/towdium/jecalculation/polyfill/NBTHelper.java b/src/main/java/me/towdium/jecalculation/polyfill/NBTHelper.java index 6b56181..6812fe4 100644 --- a/src/main/java/me/towdium/jecalculation/polyfill/NBTHelper.java +++ b/src/main/java/me/towdium/jecalculation/polyfill/NBTHelper.java @@ -1,18 +1,14 @@ package me.towdium.jecalculation.polyfill; -import me.towdium.jecalculation.utils.ItemStackHelper; -import me.towdium.jecalculation.utils.ReflectionHelper; -import net.minecraft.item.Item; +import java.util.List; +import java.util.Spliterator; +import java.util.Spliterators; +import javax.annotation.ParametersAreNonnullByDefault; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.List; -import java.util.Spliterator; -import java.util.Spliterators; - @ParametersAreNonnullByDefault public class NBTHelper { /** @@ -55,5 +51,4 @@ public class NBTHelper { stack.writeToNBT(ret); return ret; } - } diff --git a/src/main/java/me/towdium/jecalculation/polyfill/google/common/collect/Streams.java b/src/main/java/me/towdium/jecalculation/polyfill/google/common/collect/Streams.java index 1d7763f..24c3fbb 100644 --- a/src/main/java/me/towdium/jecalculation/polyfill/google/common/collect/Streams.java +++ b/src/main/java/me/towdium/jecalculation/polyfill/google/common/collect/Streams.java @@ -1,14 +1,14 @@ package me.towdium.jecalculation.polyfill.google.common.collect; -import javax.annotation.Nullable; +import static com.google.common.base.Preconditions.checkNotNull; + import java.util.Iterator; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; - -import static com.google.common.base.Preconditions.checkNotNull; +import javax.annotation.Nullable; public class Streams { public interface FunctionWithIndex { @@ -38,8 +38,7 @@ public class Streams { *

The order of the resulting stream is defined if and only if the order of the original stream * was defined. */ - public static Stream mapWithIndex( - Stream stream, FunctionWithIndex function) { + public static Stream mapWithIndex(Stream stream, FunctionWithIndex function) { checkNotNull(stream); checkNotNull(function); boolean isParallel = stream.isParallel(); @@ -98,7 +97,7 @@ public class Streams { } private abstract static class MapWithIndexSpliterator< - F extends Spliterator, R, S extends MapWithIndexSpliterator> + F extends Spliterator, R, S extends MapWithIndexSpliterator> implements Spliterator { final F fromSpliterator; long index; @@ -129,8 +128,7 @@ public class Streams { @Override public int characteristics() { - return fromSpliterator.characteristics() - & (Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED); + return fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED); } } } diff --git a/src/main/java/me/towdium/jecalculation/polyfill/mc/client/renderer/GlStateManager.java b/src/main/java/me/towdium/jecalculation/polyfill/mc/client/renderer/GlStateManager.java index 194daee..62566e2 100644 --- a/src/main/java/me/towdium/jecalculation/polyfill/mc/client/renderer/GlStateManager.java +++ b/src/main/java/me/towdium/jecalculation/polyfill/mc/client/renderer/GlStateManager.java @@ -1,29 +1,27 @@ package me.towdium.jecalculation.polyfill.mc.client.renderer; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import javax.annotation.Nullable; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderHelper; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL15; -import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL14; +import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GLContext; import org.lwjgl.util.vector.Quaternion; @SuppressWarnings("ALL") @SideOnly(Side.CLIENT) -public class GlStateManager -{ +public class GlStateManager { private static final FloatBuffer BUF_FLOAT_16 = BufferUtils.createFloatBuffer(16); private static final FloatBuffer BUF_FLOAT_4 = BufferUtils.createFloatBuffer(4); private static final GlStateManager.AlphaState alphaState = new GlStateManager.AlphaState(); @@ -47,153 +45,129 @@ public class GlStateManager private static final GlStateManager.ColorMask colorMaskState; private static final GlStateManager.Color colorState; - public static void pushAttrib() - { + public static void pushAttrib() { GL11.glPushAttrib(8256); } - public static void popAttrib() - { + public static void popAttrib() { GL11.glPopAttrib(); } - public static void disableAlpha() - { + public static void disableAlpha() { alphaState.alphaTest.setDisabled(); } - public static void enableAlpha() - { + public static void enableAlpha() { alphaState.alphaTest.setEnabled(); } - public static void alphaFunc(int func, float ref) - { - if (func != alphaState.func || ref != alphaState.ref) - { + public static void alphaFunc(int func, float ref) { + if (func != alphaState.func || ref != alphaState.ref) { alphaState.func = func; alphaState.ref = ref; GL11.glAlphaFunc(func, ref); } } - public static void enableLighting() - { + public static void enableLighting() { lightingState.setEnabled(); } - public static void disableLighting() - { + public static void disableLighting() { lightingState.setDisabled(); } - public static void enableLight(int light) - { + public static void enableLight(int light) { lightState[light].setEnabled(); } - public static void disableLight(int light) - { + public static void disableLight(int light) { lightState[light].setDisabled(); } - public static void enableColorMaterial() - { + public static void enableColorMaterial() { colorMaterialState.colorMaterial.setEnabled(); } - public static void disableColorMaterial() - { + public static void disableColorMaterial() { colorMaterialState.colorMaterial.setDisabled(); } - public static void colorMaterial(int face, int mode) - { - if (face != colorMaterialState.face || mode != colorMaterialState.mode) - { + public static void colorMaterial(int face, int mode) { + if (face != colorMaterialState.face || mode != colorMaterialState.mode) { colorMaterialState.face = face; colorMaterialState.mode = mode; GL11.glColorMaterial(face, mode); } } - public static void glLight(int light, int pname, FloatBuffer params) - { + public static void glLight(int light, int pname, FloatBuffer params) { GL11.glLight(light, pname, params); } - public static void glLightModel(int pname, FloatBuffer params) - { + public static void glLightModel(int pname, FloatBuffer params) { GL11.glLightModel(pname, params); } - public static void glNormal3f(float nx, float ny, float nz) - { + public static void glNormal3f(float nx, float ny, float nz) { GL11.glNormal3f(nx, ny, nz); } - public static void disableDepth() - { + public static void disableDepth() { depthState.depthTest.setDisabled(); } - public static void enableDepth() - { + public static void enableDepth() { depthState.depthTest.setEnabled(); } - public static void depthFunc(int depthFunc) - { - if (depthFunc != depthState.depthFunc) - { + public static void depthFunc(int depthFunc) { + if (depthFunc != depthState.depthFunc) { depthState.depthFunc = depthFunc; GL11.glDepthFunc(depthFunc); } } - public static void depthMask(boolean flagIn) - { - if (flagIn != depthState.maskEnabled) - { + public static void depthMask(boolean flagIn) { + if (flagIn != depthState.maskEnabled) { depthState.maskEnabled = flagIn; GL11.glDepthMask(flagIn); } } - public static void disableBlend() - { + public static void disableBlend() { blendState.blend.setDisabled(); } - public static void enableBlend() - { + public static void enableBlend() { blendState.blend.setEnabled(); } - public static void blendFunc(GlStateManager.SourceFactor srcFactor, GlStateManager.DestFactor dstFactor) - { + public static void blendFunc(GlStateManager.SourceFactor srcFactor, GlStateManager.DestFactor dstFactor) { blendFunc(srcFactor.factor, dstFactor.factor); } - public static void blendFunc(int srcFactor, int dstFactor) - { - if (srcFactor != blendState.srcFactor || dstFactor != blendState.dstFactor) - { + public static void blendFunc(int srcFactor, int dstFactor) { + if (srcFactor != blendState.srcFactor || dstFactor != blendState.dstFactor) { blendState.srcFactor = srcFactor; blendState.dstFactor = dstFactor; GL11.glBlendFunc(srcFactor, dstFactor); } } - public static void tryBlendFuncSeparate(GlStateManager.SourceFactor srcFactor, GlStateManager.DestFactor dstFactor, GlStateManager.SourceFactor srcFactorAlpha, GlStateManager.DestFactor dstFactorAlpha) - { + public static void tryBlendFuncSeparate( + GlStateManager.SourceFactor srcFactor, + GlStateManager.DestFactor dstFactor, + GlStateManager.SourceFactor srcFactorAlpha, + GlStateManager.DestFactor dstFactorAlpha) { tryBlendFuncSeparate(srcFactor.factor, dstFactor.factor, srcFactorAlpha.factor, dstFactorAlpha.factor); } - public static void tryBlendFuncSeparate(int srcFactor, int dstFactor, int srcFactorAlpha, int dstFactorAlpha) - { - if (srcFactor != blendState.srcFactor || dstFactor != blendState.dstFactor || srcFactorAlpha != blendState.srcFactorAlpha || dstFactorAlpha != blendState.dstFactorAlpha) - { + public static void tryBlendFuncSeparate(int srcFactor, int dstFactor, int srcFactorAlpha, int dstFactorAlpha) { + if (srcFactor != blendState.srcFactor + || dstFactor != blendState.dstFactor + || srcFactorAlpha != blendState.srcFactorAlpha + || dstFactorAlpha != blendState.dstFactorAlpha) { blendState.srcFactor = srcFactor; blendState.dstFactor = dstFactor; blendState.srcFactorAlpha = srcFactorAlpha; @@ -202,18 +176,16 @@ public class GlStateManager } } - public static void glBlendEquation(int blendEquation) - { + public static void glBlendEquation(int blendEquation) { GL14.glBlendEquation(blendEquation); } @SuppressWarnings("PointlessBitwiseExpression") - public static void enableOutlineMode(int color) - { - BUF_FLOAT_4.put(0, (float)(color >> 16 & 255) / 255.0F); - BUF_FLOAT_4.put(1, (float)(color >> 8 & 255) / 255.0F); - BUF_FLOAT_4.put(2, (float)(color >> 0 & 255) / 255.0F); - BUF_FLOAT_4.put(3, (float)(color >> 24 & 255) / 255.0F); + public static void enableOutlineMode(int color) { + BUF_FLOAT_4.put(0, (float) (color >> 16 & 255) / 255.0F); + BUF_FLOAT_4.put(1, (float) (color >> 8 & 255) / 255.0F); + BUF_FLOAT_4.put(2, (float) (color >> 0 & 255) / 255.0F); + BUF_FLOAT_4.put(3, (float) (color >> 24 & 255) / 255.0F); glTexEnv(8960, 8705, BUF_FLOAT_4); glTexEnvi(8960, 8704, 34160); glTexEnvi(8960, 34161, 7681); @@ -224,8 +196,7 @@ public class GlStateManager glTexEnvi(8960, 34200, 770); } - public static void disableOutlineMode() - { + public static void disableOutlineMode() { glTexEnvi(8960, 8704, 8448); glTexEnvi(8960, 34161, 8448); glTexEnvi(8960, 34162, 8448); @@ -235,170 +206,135 @@ public class GlStateManager glTexEnvi(8960, 34200, 770); } - public static void enableFog() - { + public static void enableFog() { fogState.fog.setEnabled(); } - public static void disableFog() - { + public static void disableFog() { fogState.fog.setDisabled(); } - public static void setFog(GlStateManager.FogMode fogMode) - { + public static void setFog(GlStateManager.FogMode fogMode) { setFog(fogMode.capabilityId); } - private static void setFog(int param) - { - if (param != fogState.mode) - { + private static void setFog(int param) { + if (param != fogState.mode) { fogState.mode = param; GL11.glFogi(GL11.GL_FOG_MODE, param); } } - public static void setFogDensity(float param) - { - if (param != fogState.density) - { + public static void setFogDensity(float param) { + if (param != fogState.density) { fogState.density = param; GL11.glFogf(GL11.GL_FOG_DENSITY, param); } } - public static void setFogStart(float param) - { - if (param != fogState.start) - { + public static void setFogStart(float param) { + if (param != fogState.start) { fogState.start = param; GL11.glFogf(GL11.GL_FOG_START, param); } } - public static void setFogEnd(float param) - { - if (param != fogState.end) - { + public static void setFogEnd(float param) { + if (param != fogState.end) { fogState.end = param; GL11.glFogf(GL11.GL_FOG_END, param); } } - public static void glFog(int pname, FloatBuffer param) - { + public static void glFog(int pname, FloatBuffer param) { GL11.glFog(pname, param); } - public static void glFogi(int pname, int param) - { + public static void glFogi(int pname, int param) { GL11.glFogi(pname, param); } - public static void enableCull() - { + public static void enableCull() { cullState.cullFace.setEnabled(); } - public static void disableCull() - { + public static void disableCull() { cullState.cullFace.setDisabled(); } - public static void cullFace(GlStateManager.CullFace cullFace) - { + public static void cullFace(GlStateManager.CullFace cullFace) { cullFace(cullFace.mode); } - private static void cullFace(int mode) - { - if (mode != cullState.mode) - { + private static void cullFace(int mode) { + if (mode != cullState.mode) { cullState.mode = mode; GL11.glCullFace(mode); } } - public static void glPolygonMode(int face, int mode) - { + public static void glPolygonMode(int face, int mode) { GL11.glPolygonMode(face, mode); } - public static void enablePolygonOffset() - { + public static void enablePolygonOffset() { polygonOffsetState.polygonOffsetFill.setEnabled(); } - public static void disablePolygonOffset() - { + public static void disablePolygonOffset() { polygonOffsetState.polygonOffsetFill.setDisabled(); } - public static void doPolygonOffset(float factor, float units) - { - if (factor != polygonOffsetState.factor || units != polygonOffsetState.units) - { + public static void doPolygonOffset(float factor, float units) { + if (factor != polygonOffsetState.factor || units != polygonOffsetState.units) { polygonOffsetState.factor = factor; polygonOffsetState.units = units; GL11.glPolygonOffset(factor, units); } } - public static void enableColorLogic() - { + public static void enableColorLogic() { colorLogicState.colorLogicOp.setEnabled(); } - public static void disableColorLogic() - { + public static void disableColorLogic() { colorLogicState.colorLogicOp.setDisabled(); } - public static void colorLogicOp(GlStateManager.LogicOp logicOperation) - { + public static void colorLogicOp(GlStateManager.LogicOp logicOperation) { colorLogicOp(logicOperation.opcode); } - public static void colorLogicOp(int opcode) - { - if (opcode != colorLogicState.opcode) - { + public static void colorLogicOp(int opcode) { + if (opcode != colorLogicState.opcode) { colorLogicState.opcode = opcode; GL11.glLogicOp(opcode); } } - public static void enableTexGenCoord(GlStateManager.TexGen texGen) - { + public static void enableTexGenCoord(GlStateManager.TexGen texGen) { texGenCoord(texGen).textureGen.setEnabled(); } - public static void disableTexGenCoord(GlStateManager.TexGen texGen) - { + public static void disableTexGenCoord(GlStateManager.TexGen texGen) { texGenCoord(texGen).textureGen.setDisabled(); } - public static void texGen(GlStateManager.TexGen texGen, int param) - { + public static void texGen(GlStateManager.TexGen texGen, int param) { GlStateManager.TexGenCoord glstatemanager$texgencoord = texGenCoord(texGen); - if (param != glstatemanager$texgencoord.param) - { + if (param != glstatemanager$texgencoord.param) { glstatemanager$texgencoord.param = param; GL11.glTexGeni(glstatemanager$texgencoord.coord, GL11.GL_TEXTURE_GEN_MODE, param); } } - public static void texGen(GlStateManager.TexGen texGen, int pname, FloatBuffer params) - { + public static void texGen(GlStateManager.TexGen texGen, int pname, FloatBuffer params) { GL11.glTexGen(texGenCoord(texGen).coord, pname, params); } - private static GlStateManager.TexGenCoord texGenCoord(GlStateManager.TexGen texGen) - { - switch (texGen) - { + private static GlStateManager.TexGenCoord texGenCoord(GlStateManager.TexGen texGen) { + switch (texGen) { case S: return texGenState.s; case T: @@ -412,140 +348,133 @@ public class GlStateManager } } - public static void setActiveTexture(int texture) - { - if (activeTextureUnit != texture - OpenGlHelper.defaultTexUnit) - { + public static void setActiveTexture(int texture) { + if (activeTextureUnit != texture - OpenGlHelper.defaultTexUnit) { activeTextureUnit = texture - OpenGlHelper.defaultTexUnit; OpenGlHelper.setActiveTexture(texture); } } - public static void enableTexture2D() - { + public static void enableTexture2D() { textureState[activeTextureUnit].texture2DState.setEnabled(); } - public static void disableTexture2D() - { + public static void disableTexture2D() { textureState[activeTextureUnit].texture2DState.setDisabled(); } - public static void glTexEnv(int target, int parameterName, FloatBuffer parameters) - { + public static void glTexEnv(int target, int parameterName, FloatBuffer parameters) { GL11.glTexEnv(target, parameterName, parameters); } - public static void glTexEnvi(int target, int parameterName, int parameter) - { + public static void glTexEnvi(int target, int parameterName, int parameter) { GL11.glTexEnvi(target, parameterName, parameter); } - public static void glTexEnvf(int target, int parameterName, float parameter) - { + public static void glTexEnvf(int target, int parameterName, float parameter) { GL11.glTexEnvf(target, parameterName, parameter); } - public static void glTexParameterf(int target, int parameterName, float parameter) - { + public static void glTexParameterf(int target, int parameterName, float parameter) { GL11.glTexParameterf(target, parameterName, parameter); } - public static void glTexParameteri(int target, int parameterName, int parameter) - { + public static void glTexParameteri(int target, int parameterName, int parameter) { GL11.glTexParameteri(target, parameterName, parameter); } - public static int glGetTexLevelParameteri(int target, int level, int parameterName) - { + public static int glGetTexLevelParameteri(int target, int level, int parameterName) { return GL11.glGetTexLevelParameteri(target, level, parameterName); } - public static int generateTexture() - { + public static int generateTexture() { return GL11.glGenTextures(); } - public static void deleteTexture(int texture) - { + public static void deleteTexture(int texture) { GL11.glDeleteTextures(texture); - for (GlStateManager.TextureState glstatemanager$texturestate : textureState) - { - if (glstatemanager$texturestate.textureName == texture) - { + for (GlStateManager.TextureState glstatemanager$texturestate : textureState) { + if (glstatemanager$texturestate.textureName == texture) { glstatemanager$texturestate.textureName = -1; } } } - public static void bindTexture(int texture) - { - if (texture != textureState[activeTextureUnit].textureName) - { + public static void bindTexture(int texture) { + if (texture != textureState[activeTextureUnit].textureName) { textureState[activeTextureUnit].textureName = texture; GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture); } } - public static void glTexImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, @Nullable IntBuffer pixels) - { + public static void glTexImage2D( + int target, + int level, + int internalFormat, + int width, + int height, + int border, + int format, + int type, + @Nullable IntBuffer pixels) { GL11.glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels); } - public static void glTexSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int type, IntBuffer pixels) - { + public static void glTexSubImage2D( + int target, + int level, + int xOffset, + int yOffset, + int width, + int height, + int format, + int type, + IntBuffer pixels) { GL11.glTexSubImage2D(target, level, xOffset, yOffset, width, height, format, type, pixels); } - public static void glCopyTexSubImage2D(int target, int level, int xOffset, int yOffset, int x, int y, int width, int height) - { + public static void glCopyTexSubImage2D( + int target, int level, int xOffset, int yOffset, int x, int y, int width, int height) { GL11.glCopyTexSubImage2D(target, level, xOffset, yOffset, x, y, width, height); } - public static void glGetTexImage(int target, int level, int format, int type, IntBuffer pixels) - { + public static void glGetTexImage(int target, int level, int format, int type, IntBuffer pixels) { GL11.glGetTexImage(target, level, format, type, pixels); } - public static void enableNormalize() - { + public static void enableNormalize() { normalizeState.setEnabled(); } - public static void disableNormalize() - { + public static void disableNormalize() { normalizeState.setDisabled(); } - public static void shadeModel(int mode) - { - if (mode != activeShadeModel) - { + public static void shadeModel(int mode) { + if (mode != activeShadeModel) { activeShadeModel = mode; GL11.glShadeModel(mode); } } - public static void enableRescaleNormal() - { + public static void enableRescaleNormal() { rescaleNormalState.setEnabled(); } - public static void disableRescaleNormal() - { + public static void disableRescaleNormal() { rescaleNormalState.setDisabled(); } - public static void viewport(int x, int y, int width, int height) - { + public static void viewport(int x, int y, int width, int height) { GL11.glViewport(x, y, width, height); } - public static void colorMask(boolean red, boolean green, boolean blue, boolean alpha) - { - if (red != colorMaskState.red || green != colorMaskState.green || blue != colorMaskState.blue || alpha != colorMaskState.alpha) - { + public static void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { + if (red != colorMaskState.red + || green != colorMaskState.green + || blue != colorMaskState.blue + || alpha != colorMaskState.alpha) { colorMaskState.red = red; colorMaskState.green = green; colorMaskState.blue = blue; @@ -554,19 +483,18 @@ public class GlStateManager } } - public static void clearDepth(double depth) - { - if (depth != clearState.depth) - { + public static void clearDepth(double depth) { + if (depth != clearState.depth) { clearState.depth = depth; GL11.glClearDepth(depth); } } - public static void clearColor(float red, float green, float blue, float alpha) - { - if (red != clearState.color.red || green != clearState.color.green || blue != clearState.color.blue || alpha != clearState.color.alpha) - { + public static void clearColor(float red, float green, float blue, float alpha) { + if (red != clearState.color.red + || green != clearState.color.green + || blue != clearState.color.blue + || alpha != clearState.color.alpha) { clearState.color.red = red; clearState.color.green = green; clearState.color.blue = blue; @@ -575,78 +503,63 @@ public class GlStateManager } } - public static void clear(int mask) - { + public static void clear(int mask) { GL11.glClear(mask); } - public static void matrixMode(int mode) - { + public static void matrixMode(int mode) { GL11.glMatrixMode(mode); } - public static void loadIdentity() - { + public static void loadIdentity() { GL11.glLoadIdentity(); } - public static void pushMatrix() - { + public static void pushMatrix() { GL11.glPushMatrix(); } - public static void popMatrix() - { + public static void popMatrix() { GL11.glPopMatrix(); } - public static void getFloat(int pname, FloatBuffer params) - { + public static void getFloat(int pname, FloatBuffer params) { GL11.glGetFloat(pname, params); } - public static void ortho(double left, double right, double bottom, double top, double zNear, double zFar) - { + public static void ortho(double left, double right, double bottom, double top, double zNear, double zFar) { GL11.glOrtho(left, right, bottom, top, zNear, zFar); } - public static void rotate(float angle, float x, float y, float z) - { + public static void rotate(float angle, float x, float y, float z) { GL11.glRotatef(angle, x, y, z); } - public static void scale(float x, float y, float z) - { + public static void scale(float x, float y, float z) { GL11.glScalef(x, y, z); } - public static void scale(double x, double y, double z) - { + public static void scale(double x, double y, double z) { GL11.glScaled(x, y, z); } - public static void translate(float x, float y, float z) - { + public static void translate(float x, float y, float z) { GL11.glTranslatef(x, y, z); } - public static void translate(double x, double y, double z) - { + public static void translate(double x, double y, double z) { GL11.glTranslated(x, y, z); } - public static void multMatrix(FloatBuffer matrix) - { + public static void multMatrix(FloatBuffer matrix) { GL11.glMultMatrix(matrix); } - public static void rotate(Quaternion quaternionIn) - { + public static void rotate(Quaternion quaternionIn) { multMatrix(quatToGlMatrix(BUF_FLOAT_16, quaternionIn)); } - public static FloatBuffer quatToGlMatrix(FloatBuffer buffer, Quaternion quaternionIn) - { + public static FloatBuffer quatToGlMatrix(FloatBuffer buffer, Quaternion quaternionIn) { buffer.clear(); float f = quaternionIn.x * quaternionIn.x; float f1 = quaternionIn.x * quaternionIn.y; @@ -677,10 +590,11 @@ public class GlStateManager return buffer; } - public static void color(float colorRed, float colorGreen, float colorBlue, float colorAlpha) - { - if (colorRed != colorState.red || colorGreen != colorState.green || colorBlue != colorState.blue || colorAlpha != colorState.alpha) - { + public static void color(float colorRed, float colorGreen, float colorBlue, float colorAlpha) { + if (colorRed != colorState.red + || colorGreen != colorState.green + || colorBlue != colorState.blue + || colorAlpha != colorState.alpha) { colorState.red = colorRed; colorState.green = colorGreen; colorState.blue = colorBlue; @@ -689,163 +603,131 @@ public class GlStateManager } } - public static void color(float colorRed, float colorGreen, float colorBlue) - { + public static void color(float colorRed, float colorGreen, float colorBlue) { color(colorRed, colorGreen, colorBlue, 1.0F); } - public static void glTexCoord2f(float sCoord, float tCoord) - { + public static void glTexCoord2f(float sCoord, float tCoord) { GL11.glTexCoord2f(sCoord, tCoord); } - public static void glVertex3f(float x, float y, float z) - { + public static void glVertex3f(float x, float y, float z) { GL11.glVertex3f(x, y, z); } - public static void resetColor() - { + public static void resetColor() { colorState.red = -1.0F; colorState.green = -1.0F; colorState.blue = -1.0F; colorState.alpha = -1.0F; } - public static void glNormalPointer(int type, int stride, ByteBuffer buffer) - { + public static void glNormalPointer(int type, int stride, ByteBuffer buffer) { GL11.glNormalPointer(type, stride, buffer); } - public static void glTexCoordPointer(int size, int type, int stride, int buffer_offset) - { + public static void glTexCoordPointer(int size, int type, int stride, int buffer_offset) { GL11.glTexCoordPointer(size, type, stride, buffer_offset); } - public static void glTexCoordPointer(int size, int type, int stride, ByteBuffer buffer) - { + public static void glTexCoordPointer(int size, int type, int stride, ByteBuffer buffer) { GL11.glTexCoordPointer(size, type, stride, buffer); } - public static void glVertexPointer(int size, int type, int stride, int buffer_offset) - { + public static void glVertexPointer(int size, int type, int stride, int buffer_offset) { GL11.glVertexPointer(size, type, stride, buffer_offset); } - public static void glVertexPointer(int size, int type, int stride, ByteBuffer buffer) - { + public static void glVertexPointer(int size, int type, int stride, ByteBuffer buffer) { GL11.glVertexPointer(size, type, stride, buffer); } - public static void glColorPointer(int size, int type, int stride, int buffer_offset) - { + public static void glColorPointer(int size, int type, int stride, int buffer_offset) { GL11.glColorPointer(size, type, stride, buffer_offset); } - public static void glColorPointer(int size, int type, int stride, ByteBuffer buffer) - { + public static void glColorPointer(int size, int type, int stride, ByteBuffer buffer) { GL11.glColorPointer(size, type, stride, buffer); } - public static void glDisableClientState(int cap) - { + public static void glDisableClientState(int cap) { GL11.glDisableClientState(cap); } - public static void glEnableClientState(int cap) - { + public static void glEnableClientState(int cap) { GL11.glEnableClientState(cap); } - public static void glBegin(int mode) - { + public static void glBegin(int mode) { GL11.glBegin(mode); } - public static void glEnd() - { + public static void glEnd() { GL11.glEnd(); } - public static void glDrawArrays(int mode, int first, int count) - { + public static void glDrawArrays(int mode, int first, int count) { GL11.glDrawArrays(mode, first, count); } - public static void glLineWidth(float width) - { + public static void glLineWidth(float width) { GL11.glLineWidth(width); } - public static void callList(int list) - { + public static void callList(int list) { GL11.glCallList(list); } - public static void glDeleteLists(int list, int range) - { + public static void glDeleteLists(int list, int range) { GL11.glDeleteLists(list, range); } - public static void glNewList(int list, int mode) - { + public static void glNewList(int list, int mode) { GL11.glNewList(list, mode); } - public static void glEndList() - { + public static void glEndList() { GL11.glEndList(); } - public static int glGenLists(int range) - { + public static int glGenLists(int range) { return GL11.glGenLists(range); } - public static void glPixelStorei(int parameterName, int param) - { + public static void glPixelStorei(int parameterName, int param) { GL11.glPixelStorei(parameterName, param); } - public static void glReadPixels(int x, int y, int width, int height, int format, int type, IntBuffer pixels) - { + public static void glReadPixels(int x, int y, int width, int height, int format, int type, IntBuffer pixels) { GL11.glReadPixels(x, y, width, height, format, type, pixels); } - public static int glGetError() - { + public static int glGetError() { return GL11.glGetError(); } - public static String glGetString(int name) - { + public static String glGetString(int name) { return GL11.glGetString(name); } - public static void glGetInteger(int parameterName, IntBuffer parameters) - { + public static void glGetInteger(int parameterName, IntBuffer parameters) { GL11.glGetInteger(parameterName, parameters); } - public static int glGetInteger(int parameterName) - { + public static int glGetInteger(int parameterName) { return GL11.glGetInteger(parameterName); } - public static void enableBlendProfile(GlStateManager.Profile p_187408_0_) - { + public static void enableBlendProfile(GlStateManager.Profile p_187408_0_) { p_187408_0_.apply(); } - public static void disableBlendProfile(GlStateManager.Profile p_187440_0_) - { + public static void disableBlendProfile(GlStateManager.Profile p_187440_0_) { p_187440_0_.clean(); } - static - { - for (int i = 0; i < 8; ++i) - { + static { + for (int i = 0; i < 8; ++i) { lightState[i] = new GlStateManager.BooleanState(16384 + i); } @@ -862,8 +744,7 @@ public class GlStateManager normalizeState = new GlStateManager.BooleanState(2977); textureState = new GlStateManager.TextureState[8]; - for (int j = 0; j < 8; ++j) - { + for (int j = 0; j < 8; ++j) { textureState[j] = new GlStateManager.TextureState(); } @@ -874,14 +755,12 @@ public class GlStateManager } @SideOnly(Side.CLIENT) - static class AlphaState - { + static class AlphaState { public GlStateManager.BooleanState alphaTest; public int func; public float ref; - private AlphaState() - { + private AlphaState() { this.alphaTest = new GlStateManager.BooleanState(3008); this.func = 519; this.ref = -1.0F; @@ -889,16 +768,14 @@ public class GlStateManager } @SideOnly(Side.CLIENT) - static class BlendState - { + static class BlendState { public GlStateManager.BooleanState blend; public int srcFactor; public int dstFactor; public int srcFactorAlpha; public int dstFactorAlpha; - private BlendState() - { + private BlendState() { this.blend = new GlStateManager.BooleanState(3042); this.srcFactor = 1; this.dstFactor = 0; @@ -908,38 +785,29 @@ public class GlStateManager } @SideOnly(Side.CLIENT) - static class BooleanState - { + static class BooleanState { private final int capability; private boolean currentState; - public BooleanState(int capabilityIn) - { + public BooleanState(int capabilityIn) { this.capability = capabilityIn; } - public void setDisabled() - { + public void setDisabled() { this.setState(false); } - public void setEnabled() - { + public void setEnabled() { this.setState(true); } - public void setState(boolean state) - { - if (state != this.currentState) - { + public void setState(boolean state) { + if (state != this.currentState) { this.currentState = state; - if (state) - { + if (state) { GL11.glEnable(this.capability); - } - else - { + } else { GL11.glDisable(this.capability); } } @@ -947,33 +815,28 @@ public class GlStateManager } @SideOnly(Side.CLIENT) - static class ClearState - { + static class ClearState { public double depth; public GlStateManager.Color color; - private ClearState() - { + private ClearState() { this.depth = 1.0D; this.color = new GlStateManager.Color(0.0F, 0.0F, 0.0F, 0.0F); } } @SideOnly(Side.CLIENT) - static class Color - { + static class Color { public float red; public float green; public float blue; public float alpha; - public Color() - { + public Color() { this(1.0F, 1.0F, 1.0F, 1.0F); } - public Color(float redIn, float greenIn, float blueIn, float alphaIn) - { + public Color(float redIn, float greenIn, float blueIn, float alphaIn) { this.red = 1.0F; this.green = 1.0F; this.blue = 1.0F; @@ -986,28 +849,24 @@ public class GlStateManager } @SideOnly(Side.CLIENT) - static class ColorLogicState - { + static class ColorLogicState { public GlStateManager.BooleanState colorLogicOp; public int opcode; - private ColorLogicState() - { + private ColorLogicState() { this.colorLogicOp = new GlStateManager.BooleanState(3058); this.opcode = 5379; } } @SideOnly(Side.CLIENT) - static class ColorMask - { + static class ColorMask { public boolean red; public boolean green; public boolean blue; public boolean alpha; - private ColorMask() - { + private ColorMask() { this.red = true; this.green = true; this.blue = true; @@ -1016,14 +875,12 @@ public class GlStateManager } @SideOnly(Side.CLIENT) - static class ColorMaterialState - { + static class ColorMaterialState { public GlStateManager.BooleanState colorMaterial; public int face; public int mode; - private ColorMaterialState() - { + private ColorMaterialState() { this.colorMaterial = new GlStateManager.BooleanState(2903); this.face = 1032; this.mode = 5634; @@ -1031,42 +888,36 @@ public class GlStateManager } @SideOnly(Side.CLIENT) - public static enum CullFace - { + public static enum CullFace { FRONT(1028), BACK(1029), FRONT_AND_BACK(1032); public final int mode; - private CullFace(int modeIn) - { + private CullFace(int modeIn) { this.mode = modeIn; } } @SideOnly(Side.CLIENT) - static class CullState - { + static class CullState { public GlStateManager.BooleanState cullFace; public int mode; - private CullState() - { + private CullState() { this.cullFace = new GlStateManager.BooleanState(2884); this.mode = 1029; } } @SideOnly(Side.CLIENT) - static class DepthState - { + static class DepthState { public GlStateManager.BooleanState depthTest; public boolean maskEnabled; public int depthFunc; - private DepthState() - { + private DepthState() { this.depthTest = new GlStateManager.BooleanState(2929); this.maskEnabled = true; this.depthFunc = 513; @@ -1074,8 +925,7 @@ public class GlStateManager } @SideOnly(Side.CLIENT) - public static enum DestFactor - { + public static enum DestFactor { CONSTANT_ALPHA(32771), CONSTANT_COLOR(32769), DST_ALPHA(772), @@ -1093,38 +943,33 @@ public class GlStateManager public final int factor; - private DestFactor(int factorIn) - { + private DestFactor(int factorIn) { this.factor = factorIn; } } @SideOnly(Side.CLIENT) - public static enum FogMode - { + public static enum FogMode { LINEAR(9729), EXP(2048), EXP2(2049); public final int capabilityId; - private FogMode(int capabilityIn) - { + private FogMode(int capabilityIn) { this.capabilityId = capabilityIn; } } @SideOnly(Side.CLIENT) - static class FogState - { + static class FogState { public GlStateManager.BooleanState fog; public int mode; public float density; public float start; public float end; - private FogState() - { + private FogState() { this.fog = new GlStateManager.BooleanState(2912); this.mode = 2048; this.density = 1.0F; @@ -1133,8 +978,7 @@ public class GlStateManager } @SideOnly(Side.CLIENT) - public static enum LogicOp - { + public static enum LogicOp { AND(5377), AND_INVERTED(5380), AND_REVERSE(5378), @@ -1154,53 +998,48 @@ public class GlStateManager public final int opcode; - private LogicOp(int opcodeIn) - { + private LogicOp(int opcodeIn) { this.opcode = opcodeIn; } } @SideOnly(Side.CLIENT) - static class PolygonOffsetState - { + static class PolygonOffsetState { public GlStateManager.BooleanState polygonOffsetFill; public GlStateManager.BooleanState polygonOffsetLine; public float factor; public float units; - private PolygonOffsetState() - { + private PolygonOffsetState() { this.polygonOffsetFill = new GlStateManager.BooleanState(32823); this.polygonOffsetLine = new GlStateManager.BooleanState(10754); } } @SideOnly(Side.CLIENT) - public static enum Profile - { + public static enum Profile { DEFAULT { - public void apply() - { + public void apply() { GlStateManager.disableAlpha(); GlStateManager.alphaFunc(519, 0.0F); GlStateManager.disableLighting(); GL11.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, reflectSetColorBuffer(0.2F, 0.2F, 0.2F, 1.0F)); - for (int i = 0; i < 8; ++i) - { + for (int i = 0; i < 8; ++i) { GlStateManager.disableLight(i); GL11.glLight(GL11.GL_LIGHT0 + i, GL11.GL_AMBIENT, reflectSetColorBuffer(0.0F, 0.0F, 0.0F, 1.0F)); GL11.glLight(GL11.GL_LIGHT0 + i, GL11.GL_POSITION, reflectSetColorBuffer(0.0F, 0.0F, 1.0F, 0.0F)); - if (i == 0) - { - GL11.glLight(GL11.GL_LIGHT0 + i, GL11.GL_DIFFUSE, reflectSetColorBuffer(1.0F, 1.0F, 1.0F, 1.0F)); - GL11.glLight(GL11.GL_LIGHT0 + i, GL11.GL_SPECULAR, reflectSetColorBuffer(1.0F, 1.0F, 1.0F, 1.0F)); - } - else - { - GL11.glLight(GL11.GL_LIGHT0 + i, GL11.GL_DIFFUSE, reflectSetColorBuffer(0.0F, 0.0F, 0.0F, 1.0F)); - GL11.glLight(GL11.GL_LIGHT0 + i, GL11.GL_SPECULAR, reflectSetColorBuffer(0.0F, 0.0F, 0.0F, 1.0F)); + if (i == 0) { + GL11.glLight( + GL11.GL_LIGHT0 + i, GL11.GL_DIFFUSE, reflectSetColorBuffer(1.0F, 1.0F, 1.0F, 1.0F)); + GL11.glLight( + GL11.GL_LIGHT0 + i, GL11.GL_SPECULAR, reflectSetColorBuffer(1.0F, 1.0F, 1.0F, 1.0F)); + } else { + GL11.glLight( + GL11.GL_LIGHT0 + i, GL11.GL_DIFFUSE, reflectSetColorBuffer(0.0F, 0.0F, 0.0F, 1.0F)); + GL11.glLight( + GL11.GL_LIGHT0 + i, GL11.GL_SPECULAR, reflectSetColorBuffer(0.0F, 0.0F, 0.0F, 1.0F)); } } @@ -1211,7 +1050,11 @@ public class GlStateManager GlStateManager.depthMask(true); GlStateManager.disableBlend(); GlStateManager.blendFunc(GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); - GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); + GlStateManager.tryBlendFuncSeparate( + GlStateManager.SourceFactor.ONE, + GlStateManager.DestFactor.ZERO, + GlStateManager.SourceFactor.ONE, + GlStateManager.DestFactor.ZERO); GL14.glBlendEquation(GL14.GL_FUNC_ADD); GlStateManager.disableFog(); GL11.glFogi(GL11.GL_FOG_MODE, GL11.GL_EXP); @@ -1220,8 +1063,7 @@ public class GlStateManager GlStateManager.setFogEnd(1.0F); GL11.glFog(GL11.GL_FOG_COLOR, reflectSetColorBuffer(0.0F, 0.0F, 0.0F, 0.0F)); - if (GLContext.getCapabilities().GL_NV_fog_distance) - { + if (GLContext.getCapabilities().GL_NV_fog_distance) { GL11.glFogi(GL11.GL_FOG_MODE, 34140); } @@ -1254,7 +1096,8 @@ public class GlStateManager GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MIN_LOD, -1000); GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, 0.0F); GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_MODULATE); - GL11.glTexEnv(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_COLOR, reflectSetColorBuffer(0.0F, 0.0F, 0.0F, 0.0F)); + GL11.glTexEnv( + GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_COLOR, reflectSetColorBuffer(0.0F, 0.0F, 0.0F, 0.0F)); GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_RGB, GL11.GL_MODULATE); GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_ALPHA, GL11.GL_MODULATE); GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL15.GL_SRC0_RGB, GL11.GL_TEXTURE); @@ -1282,43 +1125,36 @@ public class GlStateManager GL11.glPolygonMode(GL11.GL_BACK, GL11.GL_FILL); } - public void clean() - { - } + public void clean() {} }, PLAYER_SKIN { - public void apply() - { + public void apply() { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); } - public void clean() - { + public void clean() { GlStateManager.disableBlend(); } }, TRANSPARENT_MODEL { - public void apply() - { + public void apply() { GlStateManager.color(1.0F, 1.0F, 1.0F, 0.15F); GlStateManager.depthMask(false); GlStateManager.enableBlend(); - GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); + GlStateManager.blendFunc( + GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); GlStateManager.alphaFunc(516, 0.003921569F); } - public void clean() - { + public void clean() { GlStateManager.disableBlend(); GlStateManager.alphaFunc(516, 0.1F); GlStateManager.depthMask(true); } }; - private Profile() - { - } + private Profile() {} public abstract void apply(); @@ -1326,8 +1162,7 @@ public class GlStateManager } @SideOnly(Side.CLIENT) - public static enum SourceFactor - { + public static enum SourceFactor { CONSTANT_ALPHA(32771), CONSTANT_COLOR(32769), DST_ALPHA(772), @@ -1346,36 +1181,31 @@ public class GlStateManager public final int factor; - private SourceFactor(int factorIn) - { + private SourceFactor(int factorIn) { this.factor = factorIn; } } @SideOnly(Side.CLIENT) - static class StencilFunc - { + static class StencilFunc { public int func; public int mask; - private StencilFunc() - { + private StencilFunc() { this.func = 519; this.mask = -1; } } @SideOnly(Side.CLIENT) - static class StencilState - { + static class StencilState { public GlStateManager.StencilFunc func; public int mask; public int fail; public int zfail; public int zpass; - private StencilState() - { + private StencilState() { this.func = new GlStateManager.StencilFunc(); this.mask = -1; this.fail = 7680; @@ -1385,8 +1215,7 @@ public class GlStateManager } @SideOnly(Side.CLIENT) - public static enum TexGen - { + public static enum TexGen { S, T, R, @@ -1394,29 +1223,25 @@ public class GlStateManager } @SideOnly(Side.CLIENT) - static class TexGenCoord - { + static class TexGenCoord { public GlStateManager.BooleanState textureGen; public int coord; public int param = -1; - public TexGenCoord(int coordIn, int capabilityIn) - { + public TexGenCoord(int coordIn, int capabilityIn) { this.coord = coordIn; this.textureGen = new GlStateManager.BooleanState(capabilityIn); } } @SideOnly(Side.CLIENT) - static class TexGenState - { + static class TexGenState { public GlStateManager.TexGenCoord s; public GlStateManager.TexGenCoord t; public GlStateManager.TexGenCoord r; public GlStateManager.TexGenCoord q; - private TexGenState() - { + private TexGenState() { this.s = new GlStateManager.TexGenCoord(8192, 3168); this.t = new GlStateManager.TexGenCoord(8193, 3169); this.r = new GlStateManager.TexGenCoord(8194, 3170); @@ -1425,20 +1250,21 @@ public class GlStateManager } @SideOnly(Side.CLIENT) - static class TextureState - { + static class TextureState { public GlStateManager.BooleanState texture2DState; public int textureName; - private TextureState() - { + private TextureState() { this.texture2DState = new GlStateManager.BooleanState(3553); } } - private static FloatBuffer reflectSetColorBuffer(float p_74521_0_, float p_74521_1_, float p_74521_2_, float p_74521_3_) { + + private static FloatBuffer reflectSetColorBuffer( + float p_74521_0_, float p_74521_1_, float p_74521_2_, float p_74521_3_) { FloatBuffer res = null; try { - Method m = RenderHelper.class.getDeclaredMethod("setColorBuffer", float.class, float.class, float.class, float.class); + Method m = RenderHelper.class.getDeclaredMethod( + "setColorBuffer", float.class, float.class, float.class, float.class); m.setAccessible(true); res = (FloatBuffer) m.invoke(null, p_74521_0_, p_74521_1_, p_74521_2_, p_74521_3_); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { diff --git a/src/main/java/me/towdium/jecalculation/polyfill/mc/util/NonNullList.java b/src/main/java/me/towdium/jecalculation/polyfill/mc/util/NonNullList.java index 9d8687c..4f24590 100644 --- a/src/main/java/me/towdium/jecalculation/polyfill/mc/util/NonNullList.java +++ b/src/main/java/me/towdium/jecalculation/polyfill/mc/util/NonNullList.java @@ -1,6 +1,5 @@ package me.towdium.jecalculation.polyfill.mc.util; - import java.util.AbstractList; import java.util.ArrayList; import java.util.Arrays; @@ -9,81 +8,64 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.Validate; -public class NonNullList extends AbstractList -{ +public class NonNullList extends AbstractList { private final List delegate; private final E defaultElement; - public static NonNullList create() - { + public static NonNullList create() { return new NonNullList(); } - public static NonNullList withSize(int size, E fill) - { + public static NonNullList withSize(int size, E fill) { Validate.notNull(fill); Object[] aobject = new Object[size]; Arrays.fill(aobject, fill); - return new NonNullList(Arrays.asList((E[])aobject), fill); + return new NonNullList(Arrays.asList((E[]) aobject), fill); } - public static NonNullList from(E defaultElementIn, E... elements) - { + public static NonNullList from(E defaultElementIn, E... elements) { return new NonNullList(Arrays.asList(elements), defaultElementIn); } - protected NonNullList() - { + protected NonNullList() { this(new ArrayList(), null); } - protected NonNullList(List delegateIn, @Nullable E listType) - { + protected NonNullList(List delegateIn, @Nullable E listType) { this.delegate = delegateIn; this.defaultElement = listType; } @Nonnull - public E get(int p_get_1_) - { + public E get(int p_get_1_) { return this.delegate.get(p_get_1_); } - public E set(int p_set_1_, E p_set_2_) - { + public E set(int p_set_1_, E p_set_2_) { Validate.notNull(p_set_2_); return this.delegate.set(p_set_1_, p_set_2_); } - public void add(int p_add_1_, E p_add_2_) - { + public void add(int p_add_1_, E p_add_2_) { Validate.notNull(p_add_2_); this.delegate.add(p_add_1_, p_add_2_); } - public E remove(int p_remove_1_) - { + public E remove(int p_remove_1_) { return this.delegate.remove(p_remove_1_); } - public int size() - { + public int size() { return this.delegate.size(); } - public void clear() - { - if (this.defaultElement == null) - { + public void clear() { + if (this.defaultElement == null) { super.clear(); - } - else - { - for (int i = 0; i < this.size(); ++i) - { + } else { + for (int i = 0; i < this.size(); ++i) { this.set(i, this.defaultElement); } } } } - diff --git a/src/main/java/me/towdium/jecalculation/polyfill/mc/util/math/MathHelper.java b/src/main/java/me/towdium/jecalculation/polyfill/mc/util/math/MathHelper.java index 9c989e7..80c3bf9 100644 --- a/src/main/java/me/towdium/jecalculation/polyfill/mc/util/math/MathHelper.java +++ b/src/main/java/me/towdium/jecalculation/polyfill/mc/util/math/MathHelper.java @@ -1,14 +1,11 @@ package me.towdium.jecalculation.polyfill.mc.util.math; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; - import java.util.Random; import java.util.UUID; -public class MathHelper -{ +public class MathHelper { public static final float SQRT_2 = sqrt(2.0F); private static final float[] SIN_TABLE = new float[65536]; private static final Random RANDOM = new Random(); @@ -17,135 +14,103 @@ public class MathHelper private static final double[] ASINE_TAB; private static final double[] COS_TAB; - public static float sin(float value) - { - return SIN_TABLE[(int)(value * 10430.378F) & 65535]; + public static float sin(float value) { + return SIN_TABLE[(int) (value * 10430.378F) & 65535]; } - public static float cos(float value) - { - return SIN_TABLE[(int)(value * 10430.378F + 16384.0F) & 65535]; + public static float cos(float value) { + return SIN_TABLE[(int) (value * 10430.378F + 16384.0F) & 65535]; } - public static float sqrt(float value) - { - return (float)Math.sqrt((double)value); + public static float sqrt(float value) { + return (float) Math.sqrt((double) value); } - public static float sqrt(double value) - { - return (float)Math.sqrt(value); + public static float sqrt(double value) { + return (float) Math.sqrt(value); } - public static int floor(float value) - { - int i = (int)value; - return value < (float)i ? i - 1 : i; + public static int floor(float value) { + int i = (int) value; + return value < (float) i ? i - 1 : i; } @SideOnly(Side.CLIENT) - public static int fastFloor(double value) - { - return (int)(value + 1024.0D) - 1024; + public static int fastFloor(double value) { + return (int) (value + 1024.0D) - 1024; } - public static int floor(double value) - { - int i = (int)value; - return value < (double)i ? i - 1 : i; + public static int floor(double value) { + int i = (int) value; + return value < (double) i ? i - 1 : i; } - public static long lfloor(double value) - { - long i = (long)value; - return value < (double)i ? i - 1L : i; + public static long lfloor(double value) { + long i = (long) value; + return value < (double) i ? i - 1L : i; } @SideOnly(Side.CLIENT) - public static int absFloor(double value) - { - return (int)(value >= 0.0D ? value : -value + 1.0D); + public static int absFloor(double value) { + return (int) (value >= 0.0D ? value : -value + 1.0D); } - public static float abs(float value) - { + public static float abs(float value) { return value >= 0.0F ? value : -value; } - public static int abs(int value) - { + public static int abs(int value) { return value >= 0 ? value : -value; } - public static int ceil(float value) - { - int i = (int)value; - return value > (float)i ? i + 1 : i; + public static int ceil(float value) { + int i = (int) value; + return value > (float) i ? i + 1 : i; } - public static int ceil(double value) - { - int i = (int)value; - return value > (double)i ? i + 1 : i; + public static int ceil(double value) { + int i = (int) value; + return value > (double) i ? i + 1 : i; } - public static int clamp(int num, int min, int max) - { - if (num < min) - { + public static int clamp(int num, int min, int max) { + if (num < min) { return min; - } - else - { + } else { return num > max ? max : num; } } - public static float clamp(float num, float min, float max) - { - if (num < min) - { + public static float clamp(float num, float min, float max) { + if (num < min) { return min; - } - else - { + } else { return num > max ? max : num; } } - public static double clamp(double num, double min, double max) - { - if (num < min) - { + public static double clamp(double num, double min, double max) { + if (num < min) { return min; - } - else - { + } else { return num > max ? max : num; } } - public static double clampedLerp(double lowerBnd, double upperBnd, double slide) - { - if (slide < 0.0D) - { + public static double clampedLerp(double lowerBnd, double upperBnd, double slide) { + if (slide < 0.0D) { return lowerBnd; - } - else - { + } else { return slide > 1.0D ? upperBnd : lowerBnd + (upperBnd - lowerBnd) * slide; } } - public static double absMax(double p_76132_0_, double p_76132_2_) - { - if (p_76132_0_ < 0.0D) - { + public static double absMax(double p_76132_0_, double p_76132_2_) { + if (p_76132_0_ < 0.0D) { p_76132_0_ = -p_76132_0_; } - if (p_76132_2_ < 0.0D) - { + if (p_76132_2_ < 0.0D) { p_76132_2_ = -p_76132_2_; } @@ -153,149 +118,119 @@ public class MathHelper } @SideOnly(Side.CLIENT) - public static int intFloorDiv(int p_76137_0_, int p_76137_1_) - { + public static int intFloorDiv(int p_76137_0_, int p_76137_1_) { return p_76137_0_ < 0 ? -((-p_76137_0_ - 1) / p_76137_1_) - 1 : p_76137_0_ / p_76137_1_; } - public static int getInt(Random random, int minimum, int maximum) - { + public static int getInt(Random random, int minimum, int maximum) { return minimum >= maximum ? minimum : random.nextInt(maximum - minimum + 1) + minimum; } - public static float nextFloat(Random random, float minimum, float maximum) - { + public static float nextFloat(Random random, float minimum, float maximum) { return minimum >= maximum ? minimum : random.nextFloat() * (maximum - minimum) + minimum; } - public static double nextDouble(Random random, double minimum, double maximum) - { + public static double nextDouble(Random random, double minimum, double maximum) { return minimum >= maximum ? minimum : random.nextDouble() * (maximum - minimum) + minimum; } - public static double average(long[] values) - { + public static double average(long[] values) { long i = 0L; - for (long j : values) - { + for (long j : values) { i += j; } - return (double)i / (double)values.length; + return (double) i / (double) values.length; } @SideOnly(Side.CLIENT) - public static boolean epsilonEquals(float p_180185_0_, float p_180185_1_) - { + public static boolean epsilonEquals(float p_180185_0_, float p_180185_1_) { return abs(p_180185_1_ - p_180185_0_) < 1.0E-5F; } @SideOnly(Side.CLIENT) - public static int normalizeAngle(int p_180184_0_, int p_180184_1_) - { + public static int normalizeAngle(int p_180184_0_, int p_180184_1_) { return (p_180184_0_ % p_180184_1_ + p_180184_1_) % p_180184_1_; } @SideOnly(Side.CLIENT) - public static float positiveModulo(float numerator, float denominator) - { + public static float positiveModulo(float numerator, float denominator) { return (numerator % denominator + denominator) % denominator; } @SideOnly(Side.CLIENT) - public static double positiveModulo(double numerator, double denominator) - { + public static double positiveModulo(double numerator, double denominator) { return (numerator % denominator + denominator) % denominator; } - public static float wrapDegrees(float value) - { + public static float wrapDegrees(float value) { value = value % 360.0F; - if (value >= 180.0F) - { + if (value >= 180.0F) { value -= 360.0F; } - if (value < -180.0F) - { + if (value < -180.0F) { value += 360.0F; } return value; } - public static double wrapDegrees(double value) - { + public static double wrapDegrees(double value) { value = value % 360.0D; - if (value >= 180.0D) - { + if (value >= 180.0D) { value -= 360.0D; } - if (value < -180.0D) - { + if (value < -180.0D) { value += 360.0D; } return value; } - public static int wrapDegrees(int angle) - { + public static int wrapDegrees(int angle) { angle = angle % 360; - if (angle >= 180) - { + if (angle >= 180) { angle -= 360; } - if (angle < -180) - { + if (angle < -180) { angle += 360; } return angle; } - public static int getInt(String value, int defaultValue) - { - try - { + public static int getInt(String value, int defaultValue) { + try { return Integer.parseInt(value); - } - catch (Throwable var3) - { + } catch (Throwable var3) { return defaultValue; } } - public static int getInt(String value, int defaultValue, int max) - { + public static int getInt(String value, int defaultValue, int max) { return Math.max(max, getInt(value, defaultValue)); } - public static double getDouble(String value, double defaultValue) - { - try - { + public static double getDouble(String value, double defaultValue) { + try { return Double.parseDouble(value); - } - catch (Throwable var4) - { + } catch (Throwable var4) { return defaultValue; } } - public static double getDouble(String value, double defaultValue, double max) - { + public static double getDouble(String value, double defaultValue, double max) { return Math.max(max, getDouble(value, defaultValue)); } - public static int smallestEncompassingPowerOfTwo(int value) - { + public static int smallestEncompassingPowerOfTwo(int value) { int i = value - 1; i = i | i >> 1; i = i | i >> 2; @@ -305,36 +240,26 @@ public class MathHelper return i + 1; } - private static boolean isPowerOfTwo(int value) - { + private static boolean isPowerOfTwo(int value) { return value != 0 && (value & value - 1) == 0; } - public static int log2DeBruijn(int value) - { + public static int log2DeBruijn(int value) { value = isPowerOfTwo(value) ? value : smallestEncompassingPowerOfTwo(value); - return MULTIPLY_DE_BRUIJN_BIT_POSITION[(int)((long)value * 125613361L >> 27) & 31]; + return MULTIPLY_DE_BRUIJN_BIT_POSITION[(int) ((long) value * 125613361L >> 27) & 31]; } - public static int log2(int value) - { + public static int log2(int value) { return log2DeBruijn(value) - (isPowerOfTwo(value) ? 0 : 1); } - public static int roundUp(int number, int interval) - { - if (interval == 0) - { + public static int roundUp(int number, int interval) { + if (interval == 0) { return 0; - } - else if (number == 0) - { + } else if (number == 0) { return interval; - } - else - { - if (number < 0) - { + } else { + if (number < 0) { interval *= -1; } @@ -343,99 +268,83 @@ public class MathHelper } } - public static long getCoordinateRandom(int x, int y, int z) - { - long i = (long)(x * 3129871) ^ (long)z * 116129781L ^ (long)y; + public static long getCoordinateRandom(int x, int y, int z) { + long i = (long) (x * 3129871) ^ (long) z * 116129781L ^ (long) y; i = i * i * 42317861L + i * 11L; return i; } @SideOnly(Side.CLIENT) - public static int rgb(float rIn, float gIn, float bIn) - { + public static int rgb(float rIn, float gIn, float bIn) { return rgb(floor(rIn * 255.0F), floor(gIn * 255.0F), floor(bIn * 255.0F)); } @SideOnly(Side.CLIENT) - public static int rgb(int rIn, int gIn, int bIn) - { + public static int rgb(int rIn, int gIn, int bIn) { int lvt_3_1_ = (rIn << 8) + gIn; lvt_3_1_ = (lvt_3_1_ << 8) + bIn; return lvt_3_1_; } @SideOnly(Side.CLIENT) - public static int multiplyColor(int p_180188_0_, int p_180188_1_) - { + public static int multiplyColor(int p_180188_0_, int p_180188_1_) { int i = (p_180188_0_ & 16711680) >> 16; int j = (p_180188_1_ & 16711680) >> 16; int k = (p_180188_0_ & 65280) >> 8; int l = (p_180188_1_ & 65280) >> 8; int i1 = (p_180188_0_ & 255) >> 0; int j1 = (p_180188_1_ & 255) >> 0; - int k1 = (int)((float)i * (float)j / 255.0F); - int l1 = (int)((float)k * (float)l / 255.0F); - int i2 = (int)((float)i1 * (float)j1 / 255.0F); + int k1 = (int) ((float) i * (float) j / 255.0F); + int l1 = (int) ((float) k * (float) l / 255.0F); + int i2 = (int) ((float) i1 * (float) j1 / 255.0F); return p_180188_0_ & -16777216 | k1 << 16 | l1 << 8 | i2; } @SideOnly(Side.CLIENT) - public static double frac(double number) - { + public static double frac(double number) { return number - Math.floor(number); } @SideOnly(Side.CLIENT) - public static long getPositionRandom(Vec3i pos) - { + public static long getPositionRandom(Vec3i pos) { return getCoordinateRandom(pos.getX(), pos.getY(), pos.getZ()); } - public static UUID getRandomUUID(Random rand) - { + public static UUID getRandomUUID(Random rand) { long i = rand.nextLong() & -61441L | 16384L; long j = rand.nextLong() & 4611686018427387903L | Long.MIN_VALUE; return new UUID(i, j); } - public static UUID getRandomUUID() - { + public static UUID getRandomUUID() { return getRandomUUID(RANDOM); } - public static double pct(double p_181160_0_, double p_181160_2_, double p_181160_4_) - { + public static double pct(double p_181160_0_, double p_181160_2_, double p_181160_4_) { return (p_181160_0_ - p_181160_2_) / (p_181160_4_ - p_181160_2_); } - public static double atan2(double p_181159_0_, double p_181159_2_) - { + public static double atan2(double p_181159_0_, double p_181159_2_) { double d0 = p_181159_2_ * p_181159_2_ + p_181159_0_ * p_181159_0_; - if (Double.isNaN(d0)) - { + if (Double.isNaN(d0)) { return Double.NaN; - } - else - { + } else { boolean flag = p_181159_0_ < 0.0D; - if (flag) - { + if (flag) { p_181159_0_ = -p_181159_0_; } boolean flag1 = p_181159_2_ < 0.0D; - if (flag1) - { + if (flag1) { p_181159_2_ = -p_181159_2_; } boolean flag2 = p_181159_0_ > p_181159_2_; - if (flag2) - { + if (flag2) { double d1 = p_181159_2_; p_181159_2_ = p_181159_0_; p_181159_0_ = d1; @@ -445,7 +354,7 @@ public class MathHelper p_181159_2_ = p_181159_2_ * d9; p_181159_0_ = p_181159_0_ * d9; double d2 = FRAC_BIAS + p_181159_0_; - int i = (int)Double.doubleToRawLongBits(d2); + int i = (int) Double.doubleToRawLongBits(d2); double d3 = ASINE_TAB[i]; double d4 = COS_TAB[i]; double d5 = d2 - FRAC_BIAS; @@ -453,18 +362,15 @@ public class MathHelper double d7 = (6.0D + d6 * d6) * d6 * 0.16666666666666666D; double d8 = d3 + d7; - if (flag2) - { + if (flag2) { d8 = (Math.PI / 2D) - d8; } - if (flag1) - { + if (flag1) { d8 = Math.PI - d8; } - if (flag) - { + if (flag) { d8 = -d8; } @@ -472,8 +378,7 @@ public class MathHelper } } - public static double fastInvSqrt(double p_181161_0_) - { + public static double fastInvSqrt(double p_181161_0_) { double d0 = 0.5D * p_181161_0_; long i = Double.doubleToRawLongBits(p_181161_0_); i = 6910469410427058090L - (i >> 1); @@ -483,10 +388,9 @@ public class MathHelper } @SideOnly(Side.CLIENT) - public static int hsvToRGB(float hue, float saturation, float value) - { - int i = (int)(hue * 6.0F) % 6; - float f = hue * 6.0F - (float)i; + public static int hsvToRGB(float hue, float saturation, float value) { + int i = (int) (hue * 6.0F) % 6; + float f = hue * 6.0F - (float) i; float f1 = value * (1.0F - saturation); float f2 = value * (1.0F - f * saturation); float f3 = value * (1.0F - (1.0F - f) * saturation); @@ -494,8 +398,7 @@ public class MathHelper float f5; float f6; - switch (i) - { + switch (i) { case 0: f4 = value; f5 = f3; @@ -527,17 +430,17 @@ public class MathHelper f6 = f2; break; default: - throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + hue + ", " + saturation + ", " + value); + throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + hue + + ", " + saturation + ", " + value); } - int j = clamp((int)(f4 * 255.0F), 0, 255); - int k = clamp((int)(f5 * 255.0F), 0, 255); - int l = clamp((int)(f6 * 255.0F), 0, 255); + int j = clamp((int) (f4 * 255.0F), 0, 255); + int k = clamp((int) (f5 * 255.0F), 0, 255); + int l = clamp((int) (f6 * 255.0F), 0, 255); return j << 16 | k << 8 | l; } - public static int hash(int p_188208_0_) - { + public static int hash(int p_188208_0_) { p_188208_0_ = p_188208_0_ ^ p_188208_0_ >>> 16; p_188208_0_ = p_188208_0_ * -2048144789; p_188208_0_ = p_188208_0_ ^ p_188208_0_ >>> 13; @@ -546,21 +449,21 @@ public class MathHelper return p_188208_0_; } - static - { - for (int i = 0; i < 65536; ++i) - { - SIN_TABLE[i] = (float)Math.sin((double)i * Math.PI * 2.0D / 65536.0D); + static { + for (int i = 0; i < 65536; ++i) { + SIN_TABLE[i] = (float) Math.sin((double) i * Math.PI * 2.0D / 65536.0D); } - MULTIPLY_DE_BRUIJN_BIT_POSITION = new int[] {0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; + MULTIPLY_DE_BRUIJN_BIT_POSITION = new int[] { + 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, + 5, 10, 9 + }; FRAC_BIAS = Double.longBitsToDouble(4805340802404319232L); ASINE_TAB = new double[257]; COS_TAB = new double[257]; - for (int j = 0; j < 257; ++j) - { - double d0 = (double)j / 256.0D; + for (int j = 0; j < 257; ++j) { + double d0 = (double) j / 256.0D; double d1 = Math.asin(d0); COS_TAB[j] = Math.cos(d1); ASINE_TAB[j] = d1; diff --git a/src/main/java/me/towdium/jecalculation/polyfill/mc/util/math/Vec3i.java b/src/main/java/me/towdium/jecalculation/polyfill/mc/util/math/Vec3i.java index 22d5463..2597834 100644 --- a/src/main/java/me/towdium/jecalculation/polyfill/mc/util/math/Vec3i.java +++ b/src/main/java/me/towdium/jecalculation/polyfill/mc/util/math/Vec3i.java @@ -1,126 +1,106 @@ package me.towdium.jecalculation.polyfill.mc.util.math; - import com.google.common.base.Objects; import javax.annotation.concurrent.Immutable; @Immutable -public class Vec3i implements Comparable -{ +public class Vec3i implements Comparable { public static final Vec3i NULL_VECTOR = new Vec3i(0, 0, 0); private final int x; private final int y; private final int z; - public Vec3i(int xIn, int yIn, int zIn) - { + public Vec3i(int xIn, int yIn, int zIn) { this.x = xIn; this.y = yIn; this.z = zIn; } - public Vec3i(double xIn, double yIn, double zIn) - { + public Vec3i(double xIn, double yIn, double zIn) { this(MathHelper.floor(xIn), MathHelper.floor(yIn), MathHelper.floor(zIn)); } - public boolean equals(Object p_equals_1_) - { - if (this == p_equals_1_) - { + public boolean equals(Object p_equals_1_) { + if (this == p_equals_1_) { return true; - } - else if (!(p_equals_1_ instanceof Vec3i)) - { + } else if (!(p_equals_1_ instanceof Vec3i)) { return false; - } - else - { - Vec3i vec3i = (Vec3i)p_equals_1_; + } else { + Vec3i vec3i = (Vec3i) p_equals_1_; - if (this.getX() != vec3i.getX()) - { + if (this.getX() != vec3i.getX()) { return false; - } - else if (this.getY() != vec3i.getY()) - { + } else if (this.getY() != vec3i.getY()) { return false; - } - else - { + } else { return this.getZ() == vec3i.getZ(); } } } - public int hashCode() - { + public int hashCode() { return (this.getY() + this.getZ() * 31) * 31 + this.getX(); } - public int compareTo(Vec3i p_compareTo_1_) - { - if (this.getY() == p_compareTo_1_.getY()) - { - return this.getZ() == p_compareTo_1_.getZ() ? this.getX() - p_compareTo_1_.getX() : this.getZ() - p_compareTo_1_.getZ(); - } - else - { + public int compareTo(Vec3i p_compareTo_1_) { + if (this.getY() == p_compareTo_1_.getY()) { + return this.getZ() == p_compareTo_1_.getZ() + ? this.getX() - p_compareTo_1_.getX() + : this.getZ() - p_compareTo_1_.getZ(); + } else { return this.getY() - p_compareTo_1_.getY(); } } - public int getX() - { + public int getX() { return this.x; } - public int getY() - { + public int getY() { return this.y; } - public int getZ() - { + public int getZ() { return this.z; } - public Vec3i crossProduct(Vec3i vec) - { - return new Vec3i(this.getY() * vec.getZ() - this.getZ() * vec.getY(), this.getZ() * vec.getX() - this.getX() * vec.getZ(), this.getX() * vec.getY() - this.getY() * vec.getX()); + public Vec3i crossProduct(Vec3i vec) { + return new Vec3i( + this.getY() * vec.getZ() - this.getZ() * vec.getY(), + this.getZ() * vec.getX() - this.getX() * vec.getZ(), + this.getX() * vec.getY() - this.getY() * vec.getX()); } - public double getDistance(int xIn, int yIn, int zIn) - { - double d0 = (double)(this.getX() - xIn); - double d1 = (double)(this.getY() - yIn); - double d2 = (double)(this.getZ() - zIn); + public double getDistance(int xIn, int yIn, int zIn) { + double d0 = (double) (this.getX() - xIn); + double d1 = (double) (this.getY() - yIn); + double d2 = (double) (this.getZ() - zIn); return Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2); } - public double distanceSq(double toX, double toY, double toZ) - { - double d0 = (double)this.getX() - toX; - double d1 = (double)this.getY() - toY; - double d2 = (double)this.getZ() - toZ; + public double distanceSq(double toX, double toY, double toZ) { + double d0 = (double) this.getX() - toX; + double d1 = (double) this.getY() - toY; + double d2 = (double) this.getZ() - toZ; return d0 * d0 + d1 * d1 + d2 * d2; } - public double distanceSqToCenter(double xIn, double yIn, double zIn) - { - double d0 = (double)this.getX() + 0.5D - xIn; - double d1 = (double)this.getY() + 0.5D - yIn; - double d2 = (double)this.getZ() + 0.5D - zIn; + public double distanceSqToCenter(double xIn, double yIn, double zIn) { + double d0 = (double) this.getX() + 0.5D - xIn; + double d1 = (double) this.getY() + 0.5D - yIn; + double d2 = (double) this.getZ() + 0.5D - zIn; return d0 * d0 + d1 * d1 + d2 * d2; } - public double distanceSq(Vec3i to) - { - return this.distanceSq((double)to.getX(), (double)to.getY(), (double)to.getZ()); + public double distanceSq(Vec3i to) { + return this.distanceSq((double) to.getX(), (double) to.getY(), (double) to.getZ()); } - public String toString() - { - return Objects.toStringHelper(this).add("x", this.getX()).add("y", this.getY()).add("z", this.getZ()).toString(); + public String toString() { + return Objects.toStringHelper(this) + .add("x", this.getX()) + .add("y", this.getY()) + .add("z", this.getZ()) + .toString(); } } diff --git a/src/main/java/me/towdium/jecalculation/utils/ClientUtils.java b/src/main/java/me/towdium/jecalculation/utils/ClientUtils.java index c25ef03..17857c3 100644 --- a/src/main/java/me/towdium/jecalculation/utils/ClientUtils.java +++ b/src/main/java/me/towdium/jecalculation/utils/ClientUtils.java @@ -11,7 +11,8 @@ public class ClientUtils { public static void playClickSound(float pitchIn) { try { - mc().getSoundHandler().playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), pitchIn)); + mc().getSoundHandler() + .playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), pitchIn)); } catch (Exception e) { // why may crash ?? e.printStackTrace(); diff --git a/src/main/java/me/towdium/jecalculation/utils/ItemStackHelper.java b/src/main/java/me/towdium/jecalculation/utils/ItemStackHelper.java index f7d82a4..3bfbb16 100644 --- a/src/main/java/me/towdium/jecalculation/utils/ItemStackHelper.java +++ b/src/main/java/me/towdium/jecalculation/utils/ItemStackHelper.java @@ -1,22 +1,13 @@ package me.towdium.jecalculation.utils; -import me.towdium.jecalculation.JustEnoughCalculation; -import me.towdium.jecalculation.polyfill.NBTHelper; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.function.Consumer; -import java.util.function.Function; public class ItemStackHelper { public static final Item EMPTY_ITEM = null; - public static final ItemStack EMPTY_ITEM_STACK = new ItemStack((Item)null); + public static final ItemStack EMPTY_ITEM_STACK = new ItemStack((Item) null); public static boolean isEmpty(ItemStack stack) { return stack == null || stack == EMPTY_ITEM_STACK || stack.getItem() == EMPTY_ITEM; } - } diff --git a/src/main/java/me/towdium/jecalculation/utils/NBTJson.java b/src/main/java/me/towdium/jecalculation/utils/NBTJson.java index baff815..6b5d955 100644 --- a/src/main/java/me/towdium/jecalculation/utils/NBTJson.java +++ b/src/main/java/me/towdium/jecalculation/utils/NBTJson.java @@ -1,8 +1,6 @@ package me.towdium.jecalculation.utils; import com.google.gson.*; -import net.minecraft.nbt.*; - import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; @@ -10,6 +8,7 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.IntStream; +import net.minecraft.nbt.*; public class NBTJson { private static final Pattern numberPattern = Pattern.compile("^([-+]?[\\d]+\\.?[0-9]*)([bBsSlLfFdD]?)$"); @@ -20,16 +19,16 @@ public class NBTJson { final String jsonString = toJsonObject(tag).toString(); return gson.toJson(parser.parse(jsonString)); } - + @SuppressWarnings("unchecked") public static JsonElement toJsonObject(NBTBase nbt) { if (nbt instanceof NBTTagCompound) { // NBTTagCompound final NBTTagCompound nbtTagCompound = (NBTTagCompound) nbt; - final Map tagMap = (Map)nbtTagCompound.tagMap; - + final Map tagMap = (Map) nbtTagCompound.tagMap; + JsonObject root = new JsonObject(); - for (Map.Entry nbtEntry : tagMap.entrySet() ) { + for (Map.Entry nbtEntry : tagMap.entrySet()) { root.add(nbtEntry.getKey(), toJsonObject(nbtEntry.getValue())); } return root; @@ -38,7 +37,7 @@ public class NBTJson { return new JsonPrimitive(((NBTBase.NBTPrimitive) nbt).func_150286_g()); } else if (nbt instanceof NBTTagString) { // String - return new JsonPrimitive(((NBTTagString) nbt).func_150285_a_()); + return new JsonPrimitive(((NBTTagString) nbt).func_150285_a_()); } else if (nbt instanceof NBTTagList) { // Tag List JsonArray arr = new JsonArray(); @@ -47,14 +46,14 @@ public class NBTJson { } else if (nbt instanceof NBTTagIntArray) { // Int Array JsonArray arr = new JsonArray(); - for(int i : ((NBTTagIntArray) nbt).func_150302_c()) { + for (int i : ((NBTTagIntArray) nbt).func_150302_c()) { arr.add(new JsonPrimitive(i)); } return arr; } else if (nbt instanceof NBTTagByteArray) { // Byte Array JsonArray arr = new JsonArray(); - for(int i : ((NBTTagByteArray) nbt).func_150292_c()) { + for (int i : ((NBTTagByteArray) nbt).func_150292_c()) { arr.add(new JsonPrimitive(i)); } return arr; @@ -62,19 +61,19 @@ public class NBTJson { throw new IllegalArgumentException("Unsupported NBT Tag: " + NBTBase.NBTTypes[nbt.getId()] + " - " + nbt); } } - + public static NBTBase toNbt(JsonElement jsonElement) { if (jsonElement instanceof JsonPrimitive) { // Number or String final JsonPrimitive jsonPrimitive = (JsonPrimitive) jsonElement; final String jsonString = jsonPrimitive.getAsString(); final Matcher m = numberPattern.matcher(jsonString); - if(m.find()) { + if (m.find()) { // Number final String numberString = m.group(1); if (m.groupCount() == 2 && m.group(2).length() > 0) { final char numberType = m.group(2).charAt(0); - switch(numberType) { + switch (numberType) { case 'b': case 'B': return new NBTTagByte(Byte.parseByte(numberString)); @@ -92,34 +91,34 @@ public class NBTJson { return new NBTTagDouble(Double.parseDouble(numberString)); } } else { - if (numberString.contains(".")) - return new NBTTagDouble(Double.parseDouble(numberString)); - else - return new NBTTagInt(Integer.parseInt(numberString)); + if (numberString.contains(".")) return new NBTTagDouble(Double.parseDouble(numberString)); + else return new NBTTagInt(Integer.parseInt(numberString)); } } else { // String return new NBTTagString(jsonString); } - } else if (jsonElement instanceof JsonArray) { + } else if (jsonElement instanceof JsonArray) { // NBTTagIntArray or NBTTagList final JsonArray jsonArray = (JsonArray) jsonElement; final List nbtList = new ArrayList<>(); - + for (JsonElement element : jsonArray) { nbtList.add(toNbt(element)); } - + if (nbtList.stream().allMatch(n -> n instanceof NBTTagInt)) { - return new NBTTagIntArray(nbtList.stream().mapToInt(i -> ((NBTTagInt)i).func_150287_d() ).toArray()); + return new NBTTagIntArray(nbtList.stream() + .mapToInt(i -> ((NBTTagInt) i).func_150287_d()) + .toArray()); } else if (nbtList.stream().allMatch(n -> n instanceof NBTTagByte)) { - return new NBTTagByteArray(toByteArray(nbtList.stream().mapToInt(i -> ((NBTTagInt)i).func_150287_d() ))); + return new NBTTagByteArray( + toByteArray(nbtList.stream().mapToInt(i -> ((NBTTagInt) i).func_150287_d()))); } else { NBTTagList nbtTagList = new NBTTagList(); nbtList.forEach(nbtTagList::appendTag); return nbtTagList; - } } else if (jsonElement instanceof JsonObject) { // NBTTagCompound @@ -130,12 +129,15 @@ public class NBTJson { } return nbtTagCompound; } - + throw new IllegalArgumentException("Unhandled element " + jsonElement); } + public static byte[] toByteArray(IntStream stream) { - return stream.collect(ByteArrayOutputStream::new, (baos, i) -> baos.write((byte) i), (baos1, baos2) -> baos1.write(baos2.toByteArray(), 0, baos2.size())) - .toByteArray(); + return stream.collect( + ByteArrayOutputStream::new, + (baos, i) -> baos.write((byte) i), + (baos1, baos2) -> baos1.write(baos2.toByteArray(), 0, baos2.size())) + .toByteArray(); } - } diff --git a/src/main/java/me/towdium/jecalculation/utils/ReflectionHelper.java b/src/main/java/me/towdium/jecalculation/utils/ReflectionHelper.java index ba0bc87..78cf7b9 100644 --- a/src/main/java/me/towdium/jecalculation/utils/ReflectionHelper.java +++ b/src/main/java/me/towdium/jecalculation/utils/ReflectionHelper.java @@ -8,10 +8,10 @@ import java.lang.reflect.Field; */ public class ReflectionHelper { @SuppressWarnings("unchecked") - public static T getField(C o, String... names){ + public static T getField(C o, String... names) { Field field = null; boolean flag = false; - for(String name : names){ + for (String name : names) { try { field = o.getClass().getDeclaredField(name); } catch (NoSuchFieldException e) { @@ -20,10 +20,10 @@ public class ReflectionHelper { flag = true; break; } - if(!flag){ - StringBuilder buffer = new StringBuilder( - "Field not found in class " + o.getClass().getCanonicalName() + ":"); - for(String s : names){ + if (!flag) { + StringBuilder buffer = + new StringBuilder("Field not found in class " + o.getClass().getCanonicalName() + ":"); + for (String s : names) { buffer.append(" "); buffer.append(s); } @@ -37,7 +37,6 @@ public class ReflectionHelper { return null; } } - } public static T get(C o, String name) { diff --git a/src/main/java/me/towdium/jecalculation/utils/Utilities.java b/src/main/java/me/towdium/jecalculation/utils/Utilities.java index ab418f6..923d008 100644 --- a/src/main/java/me/towdium/jecalculation/utils/Utilities.java +++ b/src/main/java/me/towdium/jecalculation/utils/Utilities.java @@ -1,5 +1,7 @@ package me.towdium.jecalculation.utils; +import static net.minecraft.client.resources.I18n.format; + import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; @@ -8,24 +10,6 @@ import cpw.mods.fml.common.ModContainer; import cpw.mods.fml.common.registry.GameData; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import me.towdium.jecalculation.JustEnoughCalculation; -import me.towdium.jecalculation.polyfill.NBTHelper; -import me.towdium.jecalculation.utils.wrappers.Pair; -import net.minecraft.client.entity.EntityClientPlayerMP; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.util.IIcon; -import net.minecraftforge.fluids.Fluid; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.StringEscapeUtils; -import org.apache.commons.lang3.text.WordUtils; - -import javax.annotation.Nullable; -import javax.annotation.ParametersAreNonnullByDefault; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -39,8 +23,23 @@ import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import java.util.stream.StreamSupport; - -import static net.minecraft.client.resources.I18n.format; +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.JustEnoughCalculation; +import me.towdium.jecalculation.Tags; +import me.towdium.jecalculation.polyfill.NBTHelper; +import me.towdium.jecalculation.utils.wrappers.Pair; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChatComponentTranslation; +import net.minecraft.util.IIcon; +import net.minecraftforge.fluids.Fluid; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.text.WordUtils; /** * Author: Towdium @@ -50,20 +49,20 @@ import static net.minecraft.client.resources.I18n.format; @ParametersAreNonnullByDefault public class Utilities { // FLOAT FORMATTING - public static char[] suffix = new char[]{'K', 'M', 'B', 'G', 'T', 'P'}; - public static DecimalFormat[] format = new DecimalFormat[]{new DecimalFormat("#."), - new DecimalFormat("#.#"), - new DecimalFormat("#.##"), - new DecimalFormat("#.###"), - new DecimalFormat("#.####")}; + public static char[] suffix = new char[] {'K', 'M', 'B', 'G', 'T', 'P'}; + public static DecimalFormat[] format = new DecimalFormat[] { + new DecimalFormat("#."), + new DecimalFormat("#.#"), + new DecimalFormat("#.##"), + new DecimalFormat("#.###"), + new DecimalFormat("#.####") + }; public static String cutNumber(float f, int size) { BiFunction form = (fl, len) -> format[len - 1 - (int) Math.log10(fl)].format(fl); int scale = (int) Math.log10(f) / 3; - if (scale == 0) - return form.apply(f, size); - else - return form.apply(f / (float) Math.pow(1000, scale), size - 1) + suffix[scale - 1]; + if (scale == 0) return form.apply(f, size); + else return form.apply(f / (float) Math.pow(1000, scale), size - 1) + suffix[scale - 1]; } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @@ -80,8 +79,7 @@ public class Utilities { public static String repeat(String s, int n) { StringBuilder sb = new StringBuilder(); - for (int i = 0; i < n; i++) - sb.append(s); + for (int i = 0; i < n; i++) sb.append(s); return sb.toString(); } @@ -90,7 +88,9 @@ public class Utilities { public static String getModName(Item item) { String name = getName(item); String id = name.substring(0, name.indexOf(":")); - return id.equals("minecraft") ? "Minecraft" : Loader.instance().getIndexedModList().get(id).getName(); + return id.equals("minecraft") + ? "Minecraft" + : Loader.instance().getIndexedModList().get(id).getName(); } public static String getName(Item item) { @@ -113,8 +113,7 @@ public class Utilities { */ public static String getModName(Fluid fluid) { String name = fluid.getName(); - if (name.equals("lava") || name.equals("water")) - return "Minecraft"; + if (name.equals("lava") || name.equals("water")) return "Minecraft"; else { IIcon icon = getFluidIcon(fluid); if (icon == null) { @@ -136,7 +135,6 @@ public class Utilities { } } - private static IIcon getFluidIcon(Fluid fluid) { IIcon icon = fluid.getFlowingIcon(); if (icon == null) { @@ -146,13 +144,33 @@ public class Utilities { } public static NBTTagCompound getTag(ItemStack is) { - return NBTHelper.getOrCreateSubCompound(is, JustEnoughCalculation.Reference.MODID); + return NBTHelper.getOrCreateSubCompound(is, Tags.MODID); } public static EntityClientPlayerMP getPlayer() { return Objects.requireNonNull(ClientUtils.mc().thePlayer); } + public static void addChatMessage(ChatMessage cm) { + EntityClientPlayerMP player = Utilities.getPlayer(); + if (player != null) player.addChatMessage(new ChatComponentTranslation(cm.get())); + } + + public enum ChatMessage { + MAX_LOOP, + RECIPE_TRANSFER_ERROR; + + private String get() { + switch (this) { + case MAX_LOOP: + return "jecalculation.chat.max_loop"; + case RECIPE_TRANSFER_ERROR: + return "jecalculation.chat.recipe_transfer_error"; + default: + return ""; + } + } + } public static class Relation { public HashMap, V> data = new HashMap<>(); @@ -166,8 +184,7 @@ public class Utilities { @Nullable public V get(K a, K b) { V ret = data.get(new Pair<>(a, b)); - if (ret == null) - ret = data.get(new Pair<>(b, a)); + if (ret == null) ret = data.get(new Pair<>(b, a)); return ret; } } @@ -177,8 +194,7 @@ public class Utilities { boolean running = false; public void setState(boolean b) { - if (!b && running) - running = false; + if (!b && running) running = false; if (b && !running) { running = true; time = System.currentTimeMillis(); @@ -213,10 +229,8 @@ public class Utilities { public Circulator move(int steps) { current += steps; - if (current < 0) - current += (total - current - 1) / total * total; - else - current = current % total; + if (current < 0) current += (total - current - 1) / total * total; + else current = current % total; return this; } @@ -225,10 +239,8 @@ public class Utilities { } public Circulator set(int index) { - if (index >= 0 && index < total) - current = index; - else - throw new RuntimeException(String.format("Expected: [0, %d), given: %d.", total, index)); + if (index >= 0 && index < total) current = index; + else throw new RuntimeException(String.format("Expected: [0, %d), given: %d.", total, index)); return this; } @@ -245,8 +257,7 @@ public class Utilities { } public ReversedIterator(ListIterator i) { - while (i.hasNext()) - i.next(); + while (i.hasNext()) i.next(); this.i = i; } @@ -286,9 +297,15 @@ public class Utilities { } public static List wrap(String s, int width) { - return new TextWrapper().wrap(s, - ClientUtils.mc().getLanguageManager().getCurrentLanguage().getLanguageCode(), - i -> TextWrapper.renderer.getCharWidth(i), width); + return new TextWrapper() + .wrap( + s, + ClientUtils.mc() + .getLanguageManager() + .getCurrentLanguage() + .getLanguageCode(), + i -> TextWrapper.renderer.getCharWidth(i), + width); } static class TextWrapper { @@ -302,11 +319,9 @@ public class Utilities { private void cut() { char c = str.charAt(cursor); - if (c == '\f') - cursor++; + if (c == '\f') cursor++; temp.add(str.substring(start, cursor)); - if (c == ' ' || c == ' ' || c == '\n') - cursor++; + if (c == ' ' || c == ' ' || c == '\n') cursor++; start = cursor; end = cursor; space = width; @@ -335,13 +350,10 @@ public class Utilities { for (cursor = end; cursor < i; cursor++) { char ch = str.charAt(cursor); section += func.apply(str.charAt(cursor)); - if (ch == '\n' || ch == '\f') - cut(); + if (ch == '\n' || ch == '\f') cut(); else if (section > space) { - if (start == end) - cut(); - else - move(); + if (start == end) cut(); + else move(); } } space -= section; @@ -369,12 +381,10 @@ public class Utilities { } public boolean push(T obj, boolean replace) { - if (replace) - data.pop(); + if (replace) data.pop(); boolean ret = data.removeIf(t -> tester != null ? tester.test(t, obj) : t.equals(obj)); data.addFirst(obj); - if (data.size() > limit) - data.removeLast(); + if (data.size() > limit) data.removeLast(); return ret; } @@ -441,12 +451,10 @@ public class Utilities { public static Locale getLocaleFromString(String languageCode) { String[] parts = languageCode.split("_", -1); - if (parts.length == 1) - return new Locale(parts[0]); + if (parts.length == 1) return new Locale(parts[0]); else if (parts.length == 2 || (parts.length == 3 && parts[2].startsWith("#"))) return new Locale(parts[0], parts[1]); - else - return new Locale(parts[0], parts[1], parts[2]); + else return new Locale(parts[0], parts[1], parts[2]); } public static String[] mergeStringArrays(String[]... arrays) { diff --git a/src/main/java/me/towdium/jecalculation/utils/Version.java b/src/main/java/me/towdium/jecalculation/utils/Version.java index f24a89b..d3342cc 100644 --- a/src/main/java/me/towdium/jecalculation/utils/Version.java +++ b/src/main/java/me/towdium/jecalculation/utils/Version.java @@ -1,9 +1,7 @@ package me.towdium.jecalculation.utils; - -import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; - import javax.annotation.ParametersAreNonnullByDefault; +import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @@ -29,8 +27,7 @@ public class Version implements Comparable { success1 = false; } else { String[] versions = split[0].split("\\."); - if (versions.length != 3) - success1 = false; + if (versions.length != 3) success1 = false; else { try { major = Integer.parseInt(versions[0]); @@ -53,12 +50,9 @@ public class Version implements Comparable { public int compareTo(Version o) { assert this.isSuccess(); assert o.isSuccess(); - if (this.getMajor() != o.getMajor()) - return this.getMajor() < o.getMajor() ? -1 : 1; - if (this.getMinor() != o.getMinor()) - return this.getMinor() < o.getMinor() ? -1 : 1; - if (this.getPatch() != o.getPatch()) - return this.getPatch() < o.getPatch() ? -1 : 1; + if (this.getMajor() != o.getMajor()) return this.getMajor() < o.getMajor() ? -1 : 1; + if (this.getMinor() != o.getMinor()) return this.getMinor() < o.getMinor() ? -1 : 1; + if (this.getPatch() != o.getPatch()) return this.getPatch() < o.getPatch() ? -1 : 1; return 0; } diff --git a/src/main/java/me/towdium/jecalculation/utils/wrappers/Wrapper.java b/src/main/java/me/towdium/jecalculation/utils/wrappers/Wrapper.java index 1e84be2..f4f4f41 100644 --- a/src/main/java/me/towdium/jecalculation/utils/wrappers/Wrapper.java +++ b/src/main/java/me/towdium/jecalculation/utils/wrappers/Wrapper.java @@ -1,10 +1,10 @@ package me.towdium.jecalculation.utils.wrappers; -import javax.annotation.Nullable; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; +import javax.annotation.Nullable; /** * Author: Towdium @@ -19,8 +19,7 @@ public class Wrapper { } public Wrapper push(@Nullable T value) { - if (value != null && predicate.test(value)) - this.value = value; + if (value != null && predicate.test(value)) this.value = value; return this; } @@ -34,14 +33,12 @@ public class Wrapper { } public Wrapper ifPresent(Consumer c) { - if (value != null) - c.accept(value); + if (value != null) c.accept(value); return this; } public Wrapper ifPresentNot(Runnable r) { - if (value == null) - r.run(); + if (value == null) r.run(); return this; } } diff --git a/src/main/resources/nei_at.cfg b/src/main/resources/META-INF/jeca_at.cfg similarity index 100% rename from src/main/resources/nei_at.cfg rename to src/main/resources/META-INF/jeca_at.cfg diff --git a/src/main/resources/assets/jecalculation/lang/en_US.lang b/src/main/resources/assets/jecalculation/lang/en_US.lang index 93854f1..2a06879 100644 --- a/src/main/resources/assets/jecalculation/lang/en_US.lang +++ b/src/main/resources/assets/jecalculation/lang/en_US.lang @@ -11,6 +11,7 @@ jecalculation.chat.max_loop=Sorry, it seems the calculation does not converge in jecalculation.chat.server_mode=The mod is not working in client mode, so you cannot open the interface without an calculator item jecalculation.chat.export=Selected recipes has been exported to "%s". jecalculation.chat.help=/jeca craft - open crafting calculator\n/jeca math - open math calculator +jecalculation.chat.recipe_transfer_error=Calculator: Sorry, the recipe cannot be transferred to the calculator. It would be great if you could provide log files to help us fix it jecalculation.gui.craft.inventory_enabled=Inventory detection enabled jecalculation.gui.craft.inventory_disabled=Inventory detection disabled jecalculation.gui.craft.recipe=New recipe @@ -35,7 +36,7 @@ jecalculation.gui.recipe.label=Add label jecalculation.gui.recipe.confirm.enabled=Confirm jecalculation.gui.recipe.confirm.disabled=Cannot use empty string as group name jecalculation.gui.recipe.disamb.enabled=Open disambiguate settings -jecalculation.gui.recipe.disamb.disabled=Disambiguation settings are only\navailable when transferring recipes\nwith multiple options from JEI +jecalculation.gui.recipe.disamb.disabled=Disambiguation settings are only\navailable when transferring recipes\nwith multiple options from NEI jecalculation.gui.recipe.new=New group jecalculation.gui.recipe.pick=Pick label @@ -45,7 +46,7 @@ jecalculation.gui.recipe.to_percent=Change to percentage jecalculation.gui.recipe.to_amount=Change to amount jecalculation.gui.recipe.title=Recipe Editing -jecalculation.gui.recipe.help=This interface allows you to create or edit recipes. To create one recipe, you can pick items from the JEI item list, then put it into the slots. When finished, simply click the save button. You can also fast transer recipes from JEI by clicking "+" when openning recipe view.\fTo edit one label, you can simply click it, then a toolbar will pop up to help you, where you can switch between amount and percentage mode, type the amount, or remove the label. In addition, you can use mouse scroll to quickly change the amount. Clicking the "Clear" button will remove all of the labels.\fUsing recipe fast transfer, some labels will automatically setup for you, like oreDict labels. If you do not want this behavoir, simply use "Disambiguous" button to select manually. You can also add labels by ckicking the "Add label" button. By the way, normally you shouldn't put fuzzy labels as output.\fYou can easily manage recipes using groups. Click the "New group" button, type the group name and hit the tick, you are done. The new group name will show in the top bar. If you already have groups set up and you want to use an existing one, you can use the arrows to select between them.\fWhen you are editing an existing recipe, you will have two extra buttons, "Save as" and "Delete". "Save as" allows you to save the current recipe as a new recipe, without changing the existing one. "Delete" simply allows you to delete the recipe. +jecalculation.gui.recipe.help=This interface allows you to create or edit recipes. To create one recipe, you can pick items from the NEI item list, then put it into the slots. When finished, simply click the save button. You can also fast transer recipes from NEI by clicking "+" when openning recipe view.\fTo edit one label, you can simply click it, then a toolbar will pop up to help you, where you can switch between amount and percentage mode, type the amount, or remove the label. In addition, you can use mouse scroll to quickly change the amount. Clicking the "Clear" button will remove all of the labels.\fUsing recipe fast transfer, some labels will automatically setup for you, like oreDict labels. If you do not want this behavoir, simply use "Disambiguous" button to select manually. You can also add labels by ckicking the "Add label" button. By the way, normally you shouldn't put fuzzy labels as output.\fYou can easily manage recipes using groups. Click the "New group" button, type the group name and hit the tick, you are done. The new group name will show in the top bar. If you already have groups set up and you want to use an existing one, you can use the arrows to select between them.\fWhen you are editing an existing recipe, you will have two extra buttons, "Save as" and "Delete". "Save as" allows you to save the current recipe as a new recipe, without changing the existing one. "Delete" simply allows you to delete the recipe. jecalculation.gui.label.title=Label Editing jecalculation.gui.label.help=This interface allows you to create labels. This mod provides 4 types of labels: fluid, oreDict, placeholder and item. To create fluid and oreDict label, you can just search and pick. Item labels represent an item stack, but with fuzzy options for meta, nbt and capalibity.\fAs is indicated by the name, Placeholder labels do not hold any content. It is just a string to connect recipes. You can use it for anything, like structure or event energy. To create one, simply type in the name, then hit the tick. You can also search and pick from existing ones. diff --git a/src/main/resources/assets/jecalculation/lang/ru_RU.lang b/src/main/resources/assets/jecalculation/lang/ru_RU.lang index dbfb9d4..9c30bd4 100644 --- a/src/main/resources/assets/jecalculation/lang/ru_RU.lang +++ b/src/main/resources/assets/jecalculation/lang/ru_RU.lang @@ -15,7 +15,7 @@ jecalculation.gui.craft.inventory_enabled=Обнаружение инвента jecalculation.gui.craft.inventory_disabled=Обнаружение инвентаря выключено jecalculation.gui.craft.recipe=Новый рецепт jecalculation.gui.craft.history=История -jecalculation.gui.craft.help=Добро пожаловать в основной интерфейс мода. Первое, что предлагается сделать, это использовать две кнопки в правом верхнем углу для ввода рецептов, что позволяет создавать и редактировать рецепты. Все расчеты требуют записи рецептов.\fДля расчета стоимости предмета просто выберите предмет из списка предметов JEI, затем поместите его в слот в левом верхнем углу интерфейса со всеми рецептами для использования записи. Результат будет отображаться в нижних слотах интерфейса. Четыре кнопки предоставляют опции для отображения этапов ввода, вывода, катализатора и создания.\fКнопка в левом верхнем углу позволяет редактировать и получать метку. Ярлыки являются очень важной частью мода. В основном это вещи, которые могут быть помещены в слот, включая ItemStack, FluidStack, запись словаря руды или просто заполнитель. Метки используются в процессе расчета. В большинстве случаев они достаточно умны, если вы правильно их настроите. +jecalculation.gui.craft.help=Добро пожаловать в основной интерфейс мода. Первое, что предлагается сделать, это использовать две кнопки в правом верхнем углу для ввода рецептов, что позволяет создавать и редактировать рецепты. Все расчеты требуют записи рецептов.\fДля расчета стоимости предмета просто выберите предмет из списка предметов NEI, затем поместите его в слот в левом верхнем углу интерфейса со всеми рецептами для использования записи. Результат будет отображаться в нижних слотах интерфейса. Четыре кнопки предоставляют опции для отображения этапов ввода, вывода, катализатора и создания.\fКнопка в левом верхнем углу позволяет редактировать и получать метку. Ярлыки являются очень важной частью мода. В основном это вещи, которые могут быть помещены в слот, включая ItemStack, FluidStack, запись словаря руды или просто заполнитель. Метки используются в процессе расчета. В большинстве случаев они достаточно умны, если вы правильно их настроите. jecalculation.gui.craft.title=Калькулятор создания jecalculation.gui.craft.label=Добавить метку jecalculation.gui.craft.step=Этапы @@ -35,7 +35,7 @@ jecalculation.gui.recipe.label=Добавить метку jecalculation.gui.recipe.confirm.enabled=Подтвердить jecalculation.gui.recipe.confirm.disabled=Нельзя использовать пустую строку в качестве имени группы jecalculation.gui.recipe.disamb.enabled=Открыть настройки устранения неоднозначности -jecalculation.gui.recipe.disamb.disabled=Настройки неоднозначности доступны только\nпри переносе рецептов\nс несколькими вариантами из JEI +jecalculation.gui.recipe.disamb.disabled=Настройки неоднозначности доступны только\nпри переносе рецептов\nс несколькими вариантами из NEI jecalculation.gui.recipe.new=Новая группа #jecalculation.gui.recipe.pick=Pick label @@ -45,7 +45,7 @@ jecalculation.gui.recipe.new=Новая группа #jecalculation.gui.recipe.to_amount=Change to amount jecalculation.gui.recipe.title=Редактирование рецепта -jecalculation.gui.recipe.help=Этот интерфейс позволяет создавать или редактировать рецепты. Чтобы создать один рецепт, вы можете выбрать предметы из списка предметов JEI, а затем поместить их в слоты. Когда закончите, просто нажмите кнопку Сохранить. Вы также можете быстро пересылать рецепты из JEI, нажимая "+" при открытии представления рецептов.\fДля редактирования одной метки вы можете просто щелкнуть его, после чего появится всплывающая панель инструментов, где вы можете переключаться между режимом количества и процента, введите сумму или удалите метку. Кроме того, вы можете использовать прокрутку мыши, чтобы быстро изменить сумму. Нажатие кнопки "Очистить" удалит все метки.\fПри использовании быстрого переноса рецепта некоторые метки будут автоматически настроены для вас, например, метки словаря руды. Если вы не хотите этого поведения, просто используйте кнопку "Однозначный", чтобы выбрать вручную. Вы также можете добавить метки, нажав кнопку "Добавить метку". Кстати, обычно вы не должны помещать нечеткие метки в качестве вывода.\fВы можете легко управлять рецептами, используя группы. Нажмите кнопку "Новая группа", введите имя группы и нажмите галочку, все готово. Имя новой группы будет отображаться в верхней панели. Если у вас уже настроены группы и вы хотите использовать существующую, вы можете использовать стрелки для выбора между ними.\fПри редактировании существующего рецепта у вас будут две дополнительные кнопки: "Сохранить как" и "Удалить". "Сохранить как" позволяет сохранить текущий рецепт как новый рецепт, не меняя существующий. "Удалить" просто позволяет удалить рецепт. +jecalculation.gui.recipe.help=Этот интерфейс позволяет создавать или редактировать рецепты. Чтобы создать один рецепт, вы можете выбрать предметы из списка предметов NEI, а затем поместить их в слоты. Когда закончите, просто нажмите кнопку Сохранить. Вы также можете быстро пересылать рецепты из NEI, нажимая "+" при открытии представления рецептов.\fДля редактирования одной метки вы можете просто щелкнуть его, после чего появится всплывающая панель инструментов, где вы можете переключаться между режимом количества и процента, введите сумму или удалите метку. Кроме того, вы можете использовать прокрутку мыши, чтобы быстро изменить сумму. Нажатие кнопки "Очистить" удалит все метки.\fПри использовании быстрого переноса рецепта некоторые метки будут автоматически настроены для вас, например, метки словаря руды. Если вы не хотите этого поведения, просто используйте кнопку "Однозначный", чтобы выбрать вручную. Вы также можете добавить метки, нажав кнопку "Добавить метку". Кстати, обычно вы не должны помещать нечеткие метки в качестве вывода.\fВы можете легко управлять рецептами, используя группы. Нажмите кнопку "Новая группа", введите имя группы и нажмите галочку, все готово. Имя новой группы будет отображаться в верхней панели. Если у вас уже настроены группы и вы хотите использовать существующую, вы можете использовать стрелки для выбора между ними.\fПри редактировании существующего рецепта у вас будут две дополнительные кнопки: "Сохранить как" и "Удалить". "Сохранить как" позволяет сохранить текущий рецепт как новый рецепт, не меняя существующий. "Удалить" просто позволяет удалить рецепт. jecalculation.gui.label.title=Редактирование метки jecalculation.gui.label.help=Этот интерфейс позволяет создавать метки. Этот мод предоставляет 4 типа меток: жидкость, словарь руды, заполнитель и предмет. Чтобы создать жидкостную и словарь руды метки, вы можете просто искать и выбирать. Метки предметво представляют стак предметов, но с нечеткими опциями для мета, nbt и возможность.\fКак указано именем, метки заполнитель не содержат никакого содержимого. Это просто строка для подключения рецептов. Вы можете использовать его для чего угодно, например, для структуры или энергии события. Чтобы создать его, просто введите имя, а затем нажмите галочку. Вы также можете искать и выбирать из существующих. diff --git a/src/main/resources/assets/jecalculation/lang/zh_CN.lang b/src/main/resources/assets/jecalculation/lang/zh_CN.lang index c5ca8b2..b892324 100644 --- a/src/main/resources/assets/jecalculation/lang/zh_CN.lang +++ b/src/main/resources/assets/jecalculation/lang/zh_CN.lang @@ -11,11 +11,12 @@ jecalculation.chat.max_loop=抱歉,由于计算过程已经超过1000次迭代 jecalculation.chat.server_mode=抱歉,本模组目前不在客户端模式下运行,所以你无法使用右击计算器以外的方式打开界面。 jecalculation.chat.export=选中的配方已经导出到“%s”。 jecalculation.chat.help=/jeca craft - 打开合成计算器\n/jeca math - 打开数学计算器 +jecalculation.chat.recipe_transfer_error=计算器: 抱歉,无法将该配方导出到计算器。你可以提供日志文件帮助我们修复这个问题。 jecalculation.gui.craft.inventory_enabled=启用物品栏检测 jecalculation.gui.craft.inventory_disabled=禁用物品栏检测 jecalculation.gui.craft.recipe=新建配方 jecalculation.gui.craft.history=历史记录 -jecalculation.gui.craft.help=欢迎来到本模组的主界面!首先,我建议你使用右上角的两个按钮来添加/编辑配方。配方是本模组的核心,而且,抱歉,只能手动载入。当你添加了计算所需的所有配方,你只需要从JEI物品列表中抓取所需计算的物品,放入左上角的槽位,结果就会自动显示在下方的列表中。通过下方的四个按钮,你可以在输入,额外输出,催化剂和合成步骤中切换。\f你可以使用左上角的按钮来插入标签。“标签”是本模组运算的的核心,本质上任何可以放入物品槽的东西都是一种标签。最简单的是物品栈,但是你还可以创建更高级的标签,诸如流体栈,矿物词典或者仅仅是一个占位符。在运算过程中,相同的标签会自动关联。除此之外,矿物词典标签或者带有模糊设定的物品栈标签还会智能地与其他匹配的标签相关联。 +jecalculation.gui.craft.help=欢迎来到本模组的主界面!首先,我建议你使用右上角的两个按钮来添加/编辑配方。配方是本模组的核心,而且,抱歉,只能手动载入。当你添加了计算所需的所有配方,你只需要从NEI物品列表中抓取所需计算的物品,放入左上角的槽位,结果就会自动显示在下方的列表中。通过下方的四个按钮,你可以在输入,额外输出,催化剂和合成步骤中切换。\f你可以使用左上角的按钮来插入标签。“标签”是本模组运算的的核心,本质上任何可以放入物品槽的东西都是一种标签。最简单的是物品栈,但是你还可以创建更高级的标签,诸如流体栈,矿物词典或者仅仅是一个占位符。在运算过程中,相同的标签会自动关联。除此之外,矿物词典标签或者带有模糊设定的物品栈标签还会智能地与其他匹配的标签相关联。 jecalculation.gui.craft.title=合成计算器 jecalculation.gui.craft.label=添加算子 jecalculation.gui.craft.step=步骤 @@ -35,7 +36,7 @@ jecalculation.gui.recipe.label=添加算子 jecalculation.gui.recipe.confirm.enabled=确认 jecalculation.gui.recipe.confirm.disabled=组名不能为空 jecalculation.gui.recipe.disamb.enabled=打开消歧义设定 -jecalculation.gui.recipe.disamb.disabled=消歧义设定只在从JEI转移配方\n并且含有歧义项时生效 +jecalculation.gui.recipe.disamb.disabled=消歧义设定只在从NEI转移配方\n并且含有歧义项时生效 jecalculation.gui.recipe.new=新建编组 jecalculation.gui.recipe.pick=抓取算子 @@ -45,7 +46,7 @@ jecalculation.gui.recipe.to_percent=切换至百分比 jecalculation.gui.recipe.to_amount=切换至数量 jecalculation.gui.recipe.title=编辑配方 -jecalculation.gui.recipe.help=你可以使用本界面编辑或者创建配方。你可以手动从JEI物品列表抓取物品,然后放入槽位中。除此之外,你也可以使用JEI查询,然后点击“+”来快速转移配方。完成编辑后,点击“保存配方”就可以将该配方添加至你个人的配方库中。\n当你点击一个算子,一个工具栏会弹出来帮助你编辑。你可以使用这个工具栏来输入数量,切换百分比设定,或是删除算子。除此之外,你也可以直接使用鼠标滚轮来编辑算子的数量。\f在你从JEI快速转移配方的时候,系统会帮你自动配置好一些算子,诸如矿辞或是流体之类。如果你不想系统自动匹配,你可以使用消歧义选项来手动选取你需要的算子类型。与此同时,你也可以通过“添加算子”按钮手动选取并添加算子。值得一提的是,虽然本模组不会阻止你在输出列表中使用模糊算子,但是这通常是不必要的。\f你可以使用编组来轻松地管理你的配方。要添加一个新组,你只需要点击“新建编组”,键入名称,再点击确认即可。如果你想要使用已有的编组,可以使用两侧的箭头按钮进行切换。\n在你编辑已有的合成表时,会有两个额外的按钮。使用“另存为”,你可以将当前的合成表保存为新的合成表,而不改动原有合成表。使用“删除”将从合成表库中删除当前合成表。 +jecalculation.gui.recipe.help=你可以使用本界面编辑或者创建配方。你可以手动从NEI物品列表抓取物品,然后放入槽位中。除此之外,你也可以使用NEI查询,然后点击“+”来快速转移配方。完成编辑后,点击“保存配方”就可以将该配方添加至你个人的配方库中。\n当你点击一个算子,一个工具栏会弹出来帮助你编辑。你可以使用这个工具栏来输入数量,切换百分比设定,或是删除算子。除此之外,你也可以直接使用鼠标滚轮来编辑算子的数量。\f在你从NEI快速转移配方的时候,系统会帮你自动配置好一些算子,诸如矿辞或是流体之类。如果你不想系统自动匹配,你可以使用消歧义选项来手动选取你需要的算子类型。与此同时,你也可以通过“添加算子”按钮手动选取并添加算子。值得一提的是,虽然本模组不会阻止你在输出列表中使用模糊算子,但是这通常是不必要的。\f你可以使用编组来轻松地管理你的配方。要添加一个新组,你只需要点击“新建编组”,键入名称,再点击确认即可。如果你想要使用已有的编组,可以使用两侧的箭头按钮进行切换。\n在你编辑已有的合成表时,会有两个额外的按钮。使用“另存为”,你可以将当前的合成表保存为新的合成表,而不改动原有合成表。使用“删除”将从合成表库中删除当前合成表。 jecalculation.gui.label.title=编辑算子 jecalculation.gui.label.help=你可以使用该界面创建算子。本模组目前有四类算子:流体栈,矿物词典,占位符和物品栈。要创建流体或矿辞算子,你只需要搜索并抓取即可。物品栈算子可以表示游戏中的物品栈,但是可以对Metadata,NBT和Capability使用额外的模糊选项。\n占位符并不表示任何实际内容,但可以用来链接配方,代表多方块结构,能量,或者任何你能想到的东西。只需要键入名字,就可以创建占位符算子。另外地,你也可以在已有的占位符中直接搜索并抓取。 diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info index 152442f..86a674b 100644 --- a/src/main/resources/mcmod.info +++ b/src/main/resources/mcmod.info @@ -1,16 +1,17 @@ -[ { - "modid": "jecalculation", - "name": "Just Enough Calculation", - "description": "A simple mod to help you with recipe calculation.", - "version": "${version}", - "mcversion": "${mcversion}", - "url": "https://github.com/Towdium/JustEnoughCalculation", - "updateUrl": "http://minecratft.curseforge.com/projects/just-enough-calculation", - "authorList": ["Towdium", "Discreater"], - "logoFile": "", - "screenshots": [], - "dependencies": ["NotEnoughItems"], - "credits": "Thanks to the MCP, Forge and FML guys; along with sesess, Pahimar, MrCrayfish and BedrockMiner for their tutorial." -} -] \ No newline at end of file + "modListVersion": 2, + "modList": [{ + "modid": "${modId}", + "name": "${modName}", + "description": "A simple mod to help you with recipe calculation.", + "version": "${modVersion}", + "mcversion": "${minecraftVersion}", + "url": "https://github.com/Towdium/JustEnoughCalculation", + "updateUrl": "http://minecratft.curseforge.com/projects/just-enough-calculation", + "authorList": ["Towdium", "Discreater"], + "logoFile": "", + "screenshots": [], + "dependencies": ["NotEnoughItems"], + "credits": "Thanks to the MCP, Forge and FML guys; along with sesess, Pahimar, MrCrayfish and BedrockMiner for their tutorial." + }] +} \ No newline at end of file diff --git a/src/main/resources/spotless.gradle b/src/main/resources/spotless.gradle new file mode 100644 index 0000000..eab4d99 --- /dev/null +++ b/src/main/resources/spotless.gradle @@ -0,0 +1,30 @@ +printf("Configuring spotless\n") + +// Spotless autoformatter +// See https://github.com/diffplug/spotless/tree/main/plugin-gradle +// Can be locally toggled via spotless:off/spotless:on comments +spotless { + encoding 'UTF-8' + + format 'misc', { + target '.gitignore' + + trimTrailingWhitespace() + indentWithSpaces(4) + endWithNewline() + } + java { + toggleOffOn() + importOrder() + removeUnusedImports() + palantirJavaFormat('1.1.0') // last version supporting jvm 8 + } + kotlin { + toggleOffOn() + ktfmt('0.39') + + trimTrailingWhitespace() + indentWithSpaces(4) + endWithNewline() + } +} \ No newline at end of file diff --git a/src/test/java/me/towdium/jecalculation/utils/VersionTest.java b/src/test/java/me/towdium/jecalculation/utils/VersionTest.java index 85882bf..3e7564e 100644 --- a/src/test/java/me/towdium/jecalculation/utils/VersionTest.java +++ b/src/test/java/me/towdium/jecalculation/utils/VersionTest.java @@ -1,10 +1,9 @@ package me.towdium.jecalculation.utils; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; /** * Please use IDEA test instead Gradle. (In settings 'Gradle -> Run Tests Using') @@ -35,7 +34,6 @@ class VersionTest { assertEquals(new Version("2.0.0").compareTo(new Version("1.0.0")), 1); } - @Test void compareTo_withSameVersion_isEqual() { assertEquals(new Version("2.0.0").compareTo(new Version("2.0.0")), 0); @@ -56,4 +54,4 @@ class VersionTest { Version version = new Version("1.0.6c"); assert !version.isSuccess(); } -} \ No newline at end of file +}