diff --git a/.github/workflows/release-tags.yml b/.github/workflows/release-tags.yml index dee08b70f..6953b9298 100644 --- a/.github/workflows/release-tags.yml +++ b/.github/workflows/release-tags.yml @@ -19,26 +19,31 @@ jobs: - name: Set release version run: | - IFS='-' read -r mv pv <<< "${GITHUB_REF#refs/*/}" + IFS='-' read -r mv pv <<< "${{ github.ref_name }}" echo "MC_VERSION=${mv}" >> $GITHUB_ENV echo "RELEASE_VERSION=${pv}" >> $GITHUB_ENV echo "VERSION=${pv}" >> $GITHUB_ENV - - name: Set up JDK 8 + - name: Validate gradle wrapper checksum + uses: gradle/wrapper-validation-action@v1 + + - name: Set up JDK 8 and 17 uses: actions/setup-java@v3 with: - java-version: '8' - distribution: 'temurin' + java-version: | + 8 + 17 + distribution: 'zulu' cache: gradle - name: Grant execute permission for gradlew run: chmod +x gradlew - name: Setup the workspace - run: ./gradlew --info --stacktrace ${{ inputs.workspace }} + run: ./gradlew --build-cache --info --stacktrace ${{ inputs.workspace }} - name: Build the mod - run: ./gradlew --info --stacktrace build + run: ./gradlew --build-cache --info --stacktrace build # Continue on error in the following steps to make sure releases still get made even if one of the methods fails @@ -50,6 +55,7 @@ jobs: - name: Release under current tag run: | + PRERELEASE="--prerelease" export "CHANGELOG_FILE=$(mktemp --suffix=.md)" echo "CHANGELOG_FILE=${CHANGELOG_FILE}" >> $GITHUB_ENV gh api --method POST -H "Accept: application/vnd.github+json" \ @@ -57,18 +63,8 @@ jobs: -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 + gh release create "${MC_VERSION}-${RELEASE_VERSION}" -F "${CHANGELOG_FILE}" $PRERELEASE ./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/build.gradle b/build.gradle index 777064727..50c3291c8 100644 --- a/build.gradle +++ b/build.gradle @@ -1,4 +1,4 @@ -//version: 1671313514 +//version: 1702141377 /* DO NOT CHANGE THIS FILE! Also, you may replace this file at any time if there is an update available. @@ -6,113 +6,91 @@ */ -import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar +import com.gtnewhorizons.retrofuturagradle.ObfuscationAttribute +import com.gtnewhorizons.retrofuturagradle.mcp.ReobfuscatedJar +import com.gtnewhorizons.retrofuturagradle.minecraft.RunMinecraftTask +import com.gtnewhorizons.retrofuturagradle.util.Distribution 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 org.gradle.internal.xml.XmlTransformer +import org.jetbrains.gradle.ext.Application +import org.jetbrains.gradle.ext.Gradle +import javax.inject.Inject import java.nio.file.Files import java.nio.file.Paths import java.util.concurrent.TimeUnit -import java.util.zip.ZipEntry -import java.util.zip.ZipInputStream -import java.util.zip.ZipOutputStream buildscript { repositories { - mavenCentral() - - maven { - name 'forge' - url 'https://maven.minecraftforge.net' - } - maven { - // GTNH ForgeGradle and ASM Fork - name = "GTNH Maven" - url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" - } - maven { - name 'sonatype' - url 'https://oss.sonatype.org/content/repositories/snapshots/' - } maven { - name 'Scala CI dependencies' - url 'https://repo1.maven.org/maven2/' + // GTNH RetroFuturaGradle and ASM Fork + name "GTNH Maven" + url "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" + allowInsecureProtocol = true } - } - dependencies { - //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' + mavenLocal() } } plugins { id 'java-library' - id 'idea' + id "org.jetbrains.gradle.plugin.idea-ext" version "1.1.7" 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 'org.jetbrains.kotlin.jvm' version '1.8.0' apply false + id 'org.jetbrains.kotlin.kapt' version '1.8.0' apply false + id 'com.google.devtools.ksp' version '1.8.0-1.0.9' apply false + id 'org.ajoberstar.grgit' version '4.1.1' // 4.1.1 is the last jvm8 supporting version, unused, available for addon.gradle + id 'com.github.johnrengelman.shadow' version '8.1.1' apply false + id 'com.palantir.git-version' version '3.0.0' apply false + id 'de.undercouch.download' version '5.4.0' + id 'com.github.gmazzo.buildconfig' version '3.1.0' apply false // Unused, available for addon.gradle + id 'com.diffplug.spotless' version '6.13.0' apply false // 6.13.0 is the last jvm8 supporting version id 'com.modrinth.minotaur' version '2.+' apply false id 'com.matthewprenger.cursegradle' version '1.4.0' apply false + id 'com.gtnewhorizons.retrofuturagradle' version '1.3.26' } + +print("You might want to check out './gradlew :faq' if your build fails.\n") + boolean settingsupdated = verifySettingsGradle() settingsupdated = verifyGitAttributes() || settingsupdated if (settingsupdated) throw new GradleException("Settings has been updated, please re-run task.") -dependencies { - implementation 'com.diffplug:blowdryer:1.6.0' -} - -apply plugin: 'com.diffplug.blowdryer' - -if (project.file('.git/HEAD').isFile()) { +// In submodules, .git is a file pointing to the real git dir +if (project.file('.git/HEAD').isFile() || project.file('.git').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 - downloadJavadoc = true - downloadSources = true - } -} - boolean disableSpotless = project.hasProperty("disableSpotless") ? project.disableSpotless.toBoolean() : false - -if (!disableSpotless) { - apply plugin: 'com.diffplug.spotless' - apply from: Blowdryer.file('spotless.gradle') -} - -if (JavaVersion.current() != JavaVersion.VERSION_1_8) { - throw new GradleException("This project requires Java 8, but it's running on " + JavaVersion.current()) -} +boolean disableCheckstyle = project.hasProperty("disableCheckstyle") ? project.disableCheckstyle.toBoolean() : false + +final String CHECKSTYLE_CONFIG = """ + + + + + + + + + + + +""" checkPropertyExists("modName") checkPropertyExists("modId") @@ -121,10 +99,7 @@ checkPropertyExists("autoUpdateBuildScript") checkPropertyExists("minecraftVersion") checkPropertyExists("forgeVersion") checkPropertyExists("replaceGradleTokenInFile") -checkPropertyExists("gradleTokenModId") -checkPropertyExists("gradleTokenModName") checkPropertyExists("gradleTokenVersion") -checkPropertyExists("gradleTokenGroupName") checkPropertyExists("apiPackage") checkPropertyExists("accessTransformersFile") checkPropertyExists("usesMixins") @@ -135,23 +110,165 @@ checkPropertyExists("containsMixinsAndOrCoreModOnly") checkPropertyExists("usesShadowedDependencies") checkPropertyExists("developmentEnvironmentUserName") +propertyDefaultIfUnset("generateGradleTokenClass", "") +propertyDefaultIfUnset("includeWellKnownRepositories", true) propertyDefaultIfUnset("noPublishedSources", false) propertyDefaultIfUnset("usesMixinDebug", project.usesMixins) propertyDefaultIfUnset("forceEnableMixins", false) propertyDefaultIfUnset("channel", "stable") propertyDefaultIfUnset("mappingsVersion", "12") +propertyDefaultIfUnset("usesMavenPublishing", true) +propertyDefaultIfUnset("mavenPublishUrl", "http://jenkins.usrv.eu:8081/nexus/content/repositories/releases") propertyDefaultIfUnset("modrinthProjectId", "") propertyDefaultIfUnset("modrinthRelations", "") propertyDefaultIfUnset("curseForgeProjectId", "") propertyDefaultIfUnset("curseForgeRelations", "") +propertyDefaultIfUnset("minimizeShadowedDependencies", true) +propertyDefaultIfUnset("relocateShadowedDependencies", true) +// Deprecated properties (kept for backwards compat) +propertyDefaultIfUnset("gradleTokenModId", "") +propertyDefaultIfUnset("gradleTokenModName", "") +propertyDefaultIfUnset("gradleTokenGroupName", "") + +propertyDefaultIfUnset("enableModernJavaSyntax", false) // On by default for new projects only +propertyDefaultIfUnset("enableGenericInjection", false) // On by default for new projects only + +// this is meant to be set using the user wide property file. by default we do nothing. +propertyDefaultIfUnset("ideaOverrideBuildType", "") // Can be nothing, "gradle" or "idea" + +project.extensions.add(com.diffplug.blowdryer.Blowdryer, "Blowdryer", com.diffplug.blowdryer.Blowdryer) // Make blowdryer available in "apply from:" scripts +if (!disableSpotless) { + apply plugin: 'com.diffplug.spotless' + apply from: Blowdryer.file('spotless.gradle') +} + +if (!disableCheckstyle) { + apply plugin: 'checkstyle' + tasks.named("checkstylePatchedMc") { enabled = false } + tasks.named("checkstyleMcLauncher") { enabled = false } + tasks.named("checkstyleIdeVirtualMain") { enabled = false } + tasks.named("checkstyleInjectedTags") { enabled = false } + checkstyle { + config = resources.text.fromString(CHECKSTYLE_CONFIG) + } +} String javaSourceDir = "src/main/java/" String scalaSourceDir = "src/main/scala/" String kotlinSourceDir = "src/main/kotlin/" +if (usesShadowedDependencies.toBoolean()) { + apply plugin: "com.github.johnrengelman.shadow" +} + +java { + toolchain { + if (enableModernJavaSyntax.toBoolean()) { + languageVersion.set(JavaLanguageVersion.of(17)) + } else { + languageVersion.set(projectJavaVersion) + } + vendor.set(JvmVendorSpec.AZUL) + } + if (!noPublishedSources) { + withSourcesJar() + } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = "UTF-8" +} + +tasks.withType(ScalaCompile).configureEach { + options.encoding = "UTF-8" +} + +pluginManager.withPlugin('org.jetbrains.kotlin.jvm') { + // If Kotlin is enabled in the project + kotlin { + jvmToolchain(8) + } + // Kotlin hacks our source sets, so we hack Kotlin's tasks + def disabledKotlinTaskList = [ + "kaptGenerateStubsMcLauncherKotlin", + "kaptGenerateStubsPatchedMcKotlin", + "kaptGenerateStubsInjectedTagsKotlin", + "compileMcLauncherKotlin", + "compilePatchedMcKotlin", + "compileInjectedTagsKotlin", + "kaptMcLauncherKotlin", + "kaptPatchedMcKotlin", + "kaptInjectedTagsKotlin", + "kspMcLauncherKotlin", + "kspPatchedMcKotlin", + "kspInjectedTagsKotlin", + ] + tasks.configureEach { task -> + if (task.name in disabledKotlinTaskList) { + task.enabled = false + } + } +} + +configurations { + create("runtimeOnlyNonPublishable") { + description = "Runtime only dependencies that are not published alongside the jar" + canBeConsumed = false + canBeResolved = false + } + + create("devOnlyNonPublishable") { + description = "Runtime and compiletime dependencies that are not published alongside the jar (compileOnly + runtimeOnlyNonPublishable)" + canBeConsumed = false + canBeResolved = false + } + compileOnly.extendsFrom(devOnlyNonPublishable) + runtimeOnlyNonPublishable.extendsFrom(devOnlyNonPublishable) +} + +if (enableModernJavaSyntax.toBoolean()) { + repositories { + mavenCentral { + mavenContent { + includeGroup("me.eigenraven.java8unsupported") + } + } + } + + dependencies { + annotationProcessor 'com.github.bsideup.jabel:jabel-javac-plugin:1.0.0' + // workaround for https://github.com/bsideup/jabel/issues/174 + annotationProcessor 'net.java.dev.jna:jna-platform:5.13.0' + compileOnly('com.github.bsideup.jabel:jabel-javac-plugin:1.0.0') { + transitive = false // We only care about the 1 annotation class + } + // Allow using jdk.unsupported classes like sun.misc.Unsafe in the compiled code, working around JDK-8206937. + patchedMinecraft('me.eigenraven.java8unsupported:java-8-unsupported-shim:1.0.0') + } + + tasks.withType(JavaCompile).configureEach { + if (it.name in ["compileMcLauncherJava", "compilePatchedMcJava"]) { + return + } + sourceCompatibility = 17 // for the IDE support + options.release.set(8) + + javaCompiler.set(javaToolchains.compilerFor { + languageVersion.set(JavaLanguageVersion.of(17)) + vendor.set(JvmVendorSpec.AZUL) + }) + } +} + +eclipse { + classpath { + downloadSources = true + downloadJavadoc = true + } +} -final String modGroupPath = modGroup.toString().replaceAll("\\.", "/") -final String apiPackagePath = apiPackage.toString().replaceAll("\\.", "/") +final String modGroupPath = modGroup.toString().replace('.' as char, '/' as char) +final String apiPackagePath = apiPackage.toString().replace('.' as char, '/' as char) String targetPackageJava = javaSourceDir + modGroupPath String targetPackageScala = scalaSourceDir + modGroupPath @@ -170,9 +287,32 @@ if (apiPackage) { } 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) + for (atFile in accessTransformersFile.split(" ")) { + String targetFile = "src/main/resources/META-INF/" + atFile.trim() + if (!getFile(targetFile).exists()) { + throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile) + } + tasks.deobfuscateMergedJarToSrg.accessTransformerFiles.from(targetFile) + tasks.srgifyBinpatchedJar.accessTransformerFiles.from(targetFile) + } +} else { + boolean atsFound = false + for (File at : sourceSets.getByName("main").resources.files) { + if (at.name.toLowerCase().endsWith("_at.cfg")) { + atsFound = true + tasks.deobfuscateMergedJarToSrg.accessTransformerFiles.from(at) + tasks.srgifyBinpatchedJar.accessTransformerFiles.from(at) + } + } + for (File at : sourceSets.getByName("api").resources.files) { + if (at.name.toLowerCase().endsWith("_at.cfg")) { + atsFound = true + tasks.deobfuscateMergedJarToSrg.accessTransformerFiles.from(at) + tasks.srgifyBinpatchedJar.accessTransformerFiles.from(at) + } + } + if (atsFound) { + logger.warn("Found and added access transformers in the resources folder, please configure gradle.properties to explicitly mention them by name") } } @@ -212,7 +352,7 @@ if (coreModClass) { } } -configurations.all { +configurations.configureEach { resolutionStrategy.cacheChangingModulesFor(0, TimeUnit.SECONDS) // Make sure GregTech build won't time out @@ -232,18 +372,38 @@ catch (Exception ignored) { String identifiedVersion String versionOverride = System.getenv("VERSION") ?: null try { - identifiedVersion = versionOverride == null ? gitVersion() : versionOverride + // Produce a version based on the tag, or for branches something like 0.2.2-configurable-maven-and-extras.38+43090270b6-dirty + if (versionOverride == null) { + def gitDetails = versionDetails() + def isDirty = gitVersion().endsWith(".dirty") // No public API for this, isCleanTag has a different meaning + String branchName = gitDetails.branchName ?: (System.getenv('GIT_BRANCH') ?: 'git') + if (branchName.startsWith('origin/')) { + branchName = branchName.minus('origin/') + } + branchName = branchName.replaceAll("[^a-zA-Z0-9-]+", "-") // sanitize branch names for semver + identifiedVersion = gitDetails.lastTag ?: '${gitDetails.gitHash}' + if (gitDetails.commitDistance > 0) { + identifiedVersion += "-${branchName}.${gitDetails.commitDistance}+${gitDetails.gitHash}" + if (isDirty) { + identifiedVersion += "-dirty" + } + } else if (isDirty) { + identifiedVersion += "-${branchName}+${gitDetails.gitHash}-dirty" + } + } else { + identifiedVersion = 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.)' + '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 +version = identifiedVersion ext { modVersion = identifiedVersion } @@ -252,76 +412,163 @@ if (identifiedVersion == versionOverride) { out.style(Style.Failure).text('Override version to ').style(Style.Identifier).text(modVersion).style(Style.Failure).println('!\7') } -group = modGroup +group = "com.github.GTNewHorizons" if (project.hasProperty("customArchiveBaseName") && customArchiveBaseName) { - archivesBaseName = customArchiveBaseName + base { + archivesName = customArchiveBaseName + } } else { - archivesBaseName = modId + base { + archivesName = modId + } } -def arguments = [] -def jvmArguments = [] -if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { - arguments += [ - "--tweakClass org.spongepowered.asm.launch.MixinTweaker" - ] - if (usesMixinDebug.toBoolean()) { - jvmArguments += [ +minecraft { + if (replaceGradleTokenInFile) { + for (f in replaceGradleTokenInFile.split(',')) { + tagReplacementFiles.add f + } + } + if (gradleTokenModId) { + injectedTags.put gradleTokenModId, modId + } + if (gradleTokenModName) { + injectedTags.put gradleTokenModName, modName + } + if (gradleTokenVersion) { + injectedTags.put gradleTokenVersion, modVersion + } + if (gradleTokenGroupName) { + injectedTags.put gradleTokenGroupName, modGroup + } + if (enableGenericInjection.toBoolean()) { + injectMissingGenerics.set(true) + } + + username = developmentEnvironmentUserName.toString() + + lwjgl3Version = "3.3.2" + + // Enable assertions in the current mod + extraRunJvmArguments.add("-ea:${modGroup}") + + if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { + if (usesMixinDebug.toBoolean()) { + extraRunJvmArguments.addAll([ "-Dmixin.debug.countInjections=true", "-Dmixin.debug.verbose=true", "-Dmixin.debug.export=true" - ] + ]) + } } + + // Blowdryer is present in some old mod builds, do not propagate it further as a dependency + // IC2 has no reobf jars in its Maven + groupsToExcludeFromAutoReobfMapping.addAll(["com.diffplug", "com.diffplug.durian", "net.industrial-craft"]) } -minecraft { - version = minecraftVersion + '-' + forgeVersion + '-' + minecraftVersion - runDir = 'run' +if (generateGradleTokenClass) { + tasks.injectTags.outputClassName.set(generateGradleTokenClass) +} - 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 +// Custom reobf auto-mappings +configurations.configureEach { + dependencies.configureEach { dep -> + if (dep instanceof org.gradle.api.artifacts.ExternalModuleDependency) { + if (dep.group == "net.industrial-craft" && dep.name == "industrialcraft-2") { + // https://www.curseforge.com/minecraft/mc-mods/industrial-craft/files/2353971 + project.dependencies.reobfJarConfiguration("curse.maven:ic2-242638:2353971") + } } } - - clientIntellijRun { - args(arguments) - jvmArgs(jvmArguments) - - if (developmentEnvironmentUserName) { - args("--username", developmentEnvironmentUserName) + def obfuscationAttr = it.attributes.getAttribute(ObfuscationAttribute.OBFUSCATION_ATTRIBUTE) + if (obfuscationAttr != null && obfuscationAttr.name == ObfuscationAttribute.SRG) { + resolutionStrategy.eachDependency { DependencyResolveDetails details -> + // Remap CoFH core cursemaven dev jar to the obfuscated version for runObfClient/Server + if (details.requested.group == 'curse.maven' && details.requested.name.endsWith('-69162') && details.requested.version == '2388751') { + details.useVersion '2388750' + details.because 'Pick obfuscated jar' + } } } +} - serverIntellijRun { - args(arguments) - jvmArgs(jvmArguments) +// Ensure tests have access to minecraft classes +sourceSets { + test { + java { + compileClasspath += sourceSets.patchedMc.output + sourceSets.mcLauncher.output + runtimeClasspath += sourceSets.patchedMc.output + sourceSets.mcLauncher.output + } } } -if (file('addon.gradle').exists()) { +if (file('addon.gradle.kts').exists()) { + apply from: 'addon.gradle.kts' +} else if (file('addon.gradle').exists()) { apply from: 'addon.gradle' } -apply from: 'repositories.gradle' +// File for local tweaks not commited to Git +if (file('addon.local.gradle.kts').exists()) { + apply from: 'addon.local.gradle.kts' +} else if (file('addon.local.gradle').exists()) { + apply from: 'addon.local.gradle' +} + +// Allow unsafe repos but warn +repositories.configureEach { repo -> + if (repo instanceof org.gradle.api.artifacts.repositories.UrlArtifactRepository) { + if (repo.getUrl() != null && repo.getUrl().getScheme() == "http" && !repo.allowInsecureProtocol) { + logger.warn("Deprecated: Allowing insecure connections for repo '${repo.name}' - add 'allowInsecureProtocol = true'") + repo.allowInsecureProtocol = true + } + } +} + +if (file('repositories.gradle.kts').exists()) { + apply from: 'repositories.gradle.kts' +} else if (file('repositories.gradle').exists()) { + apply from: 'repositories.gradle' +} else { + logger.error("Neither repositories.gradle.kts nor repositories.gradle was found, make sure you extracted the full ExampleMod template.") + throw new RuntimeException("Missing repositories.gradle[.kts]") +} configurations { - implementation.extendsFrom(shadowImplementation) // TODO: remove after all uses are refactored - implementation.extendsFrom(shadowCompile) - implementation.extendsFrom(shadeCompile) + runtimeClasspath.extendsFrom(runtimeOnlyNonPublishable) + testRuntimeClasspath.extendsFrom(runtimeOnlyNonPublishable) + for (config in [compileClasspath, runtimeClasspath, testCompileClasspath, testRuntimeClasspath]) { + if (usesShadowedDependencies.toBoolean()) { + config.extendsFrom(shadowImplementation) + // TODO: remove Compile after all uses are refactored to Implementation + config.extendsFrom(shadeCompile) + config.extendsFrom(shadowCompile) + } + } + // A "bag-of-dependencies"-style configuration for backwards compatibility, gets put in "api" + create("compile") { + description = "Deprecated: use api or implementation instead, gets put in api" + canBeConsumed = false + canBeResolved = false + visible = false + } + create("testCompile") { + description = "Deprecated: use testImplementation instead" + canBeConsumed = false + canBeResolved = false + visible = false + } + api.extendsFrom(compile) + testImplementation.extendsFrom(testCompile) +} + +afterEvaluate { + if (!configurations.compile.allDependencies.empty || !configurations.testCompile.allDependencies.empty) { + logger.warn("This project uses deprecated `compile` dependencies, please migrate to using `api` and `implementation`") + logger.warn("For more details, see https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/master/dependencies.gradle") + } } repositories { @@ -329,49 +576,145 @@ repositories { name 'Overmind forge repo mirror' url 'https://gregtech.overminddl1.com/' } - if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { - maven { - name = "GTNH Maven" - url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" + maven { + name = "GTNH Maven" + url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" + allowInsecureProtocol = true + } + maven { + name 'sonatype' + url 'https://oss.sonatype.org/content/repositories/snapshots/' + content { + includeGroup "org.lwjgl" } - if (usesMixinDebug.toBoolean()) { - maven { - name = "Fabric Maven" - url = "https://maven.fabricmc.net/" + } + if (includeWellKnownRepositories.toBoolean()) { + exclusiveContent { + forRepository { + maven { + name "CurseMaven" + url "https://cursemaven.com" + } + } + filter { + includeGroup "curse.maven" + } + } + exclusiveContent { + forRepository { + maven { + name = "Modrinth" + url = "https://api.modrinth.com/maven" + } + } + filter { + includeGroup "maven.modrinth" } } + maven { + name = "ic2" + url = getURL("https://maven2.ic2.player.to/", "https://maven.ic2.player.to/") + content { + includeGroup "net.industrial-craft" + } + metadataSources { + mavenPom() + artifact() + } + } + maven { + name "MMD Maven" + url "https://maven.mcmoddev.com/" + } } } +def mixinProviderGroup = "io.github.legacymoddingmc" +def mixinProviderModule = "unimixins" +def mixinProviderVersion = "0.1.13" +def mixinProviderSpecNoClassifer = "${mixinProviderGroup}:${mixinProviderModule}:${mixinProviderVersion}" +def mixinProviderSpec = "${mixinProviderSpecNoClassifer}:dev" +ext.mixinProviderSpec = mixinProviderSpec + +def mixingConfigRefMap = 'mixins.' + modId + '.refmap.json' + dependencies { if (usesMixins.toBoolean()) { annotationProcessor('org.ow2.asm:asm-debug-all:5.0.3') annotationProcessor('com.google.guava:guava:24.1.1-jre') annotationProcessor('com.google.code.gson:gson:2.8.6') - annotationProcessor('com.gtnewhorizon:gtnhmixins:2.1.3:processor') + annotationProcessor(mixinProviderSpec) if (usesMixinDebug.toBoolean()) { - runtimeOnly('org.jetbrains:intellij-fernflower:1.2.1.16') + runtimeOnlyNonPublishable('org.jetbrains:intellij-fernflower:1.2.1.16') } } - if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { - compile('com.gtnewhorizon:gtnhmixins:2.1.3') + if (usesMixins.toBoolean()) { + implementation(modUtils.enableMixins(mixinProviderSpec, mixingConfigRefMap)) + } else if (forceEnableMixins.toBoolean()) { + runtimeOnlyNonPublishable(mixinProviderSpec) } } -apply from: 'dependencies.gradle' +pluginManager.withPlugin('org.jetbrains.kotlin.kapt') { + if (usesMixins.toBoolean()) { + dependencies { + kapt(mixinProviderSpec) + } + } +} -def mixingConfigRefMap = 'mixins.' + modId + '.refmap.json' -def refMap = "${tasks.compileJava.temporaryDir}" + File.separator + mixingConfigRefMap -def mixinSrg = "${tasks.reobf.temporaryDir}" + File.separator + "mixins.srg" +// Replace old mixin mods with unimixins +// https://docs.gradle.org/8.0.2/userguide/resolution_rules.html#sec:substitution_with_classifier +configurations.all { + resolutionStrategy.dependencySubstitution { + substitute module('com.gtnewhorizon:gtnhmixins') using module(mixinProviderSpecNoClassifer) withClassifier("dev") because("Unimixins replaces other mixin mods") + substitute module('com.github.GTNewHorizons:Mixingasm') using module(mixinProviderSpecNoClassifer) withClassifier("dev") because("Unimixins replaces other mixin mods") + substitute module('com.github.GTNewHorizons:SpongePoweredMixin') using module(mixinProviderSpecNoClassifer) withClassifier("dev") because("Unimixins replaces other mixin mods") + substitute module('com.github.GTNewHorizons:SpongeMixins') using module(mixinProviderSpecNoClassifer) withClassifier("dev") because("Unimixins replaces other mixin mods") + substitute module('io.github.legacymoddingmc:unimixins') using module(mixinProviderSpecNoClassifer) withClassifier("dev") because("Our previous unimixins upload was missing the dev classifier") -task generateAssets { - if (usesMixins.toBoolean()) { + substitute module('org.scala-lang:scala-library:2.11.1') using module('org.scala-lang:scala-library:2.11.5') because('To allow mixing with Java 8 targets') + } +} + +dependencies { + constraints { + def minGtnhLibVersion = "0.0.13" + implementation("com.github.GTNewHorizons:GTNHLib:${minGtnhLibVersion}") { + because("fixes duplicate mod errors in java 17 configurations using old gtnhlib") + } + runtimeOnly("com.github.GTNewHorizons:GTNHLib:${minGtnhLibVersion}") { + because("fixes duplicate mod errors in java 17 configurations using old gtnhlib") + } + devOnlyNonPublishable("com.github.GTNewHorizons:GTNHLib:${minGtnhLibVersion}") { + because("fixes duplicate mod errors in java 17 configurations using old gtnhlib") + } + runtimeOnlyNonPublishable("com.github.GTNewHorizons:GTNHLib:${minGtnhLibVersion}") { + because("fixes duplicate mod errors in java 17 configurations using old gtnhlib") + } + } +} + +if (file('dependencies.gradle.kts').exists()) { + apply from: 'dependencies.gradle.kts' +} else if (file('dependencies.gradle').exists()) { + apply from: 'dependencies.gradle' +} else { + logger.error("Neither dependencies.gradle.kts nor dependencies.gradle was found, make sure you extracted the full ExampleMod template.") + throw new RuntimeException("Missing dependencies.gradle[.kts]") +} + +tasks.register('generateAssets') { + group = "GTNH Buildscript" + description = "Generates a mixin config file at /src/main/resources/mixins.modid.json if needed" + onlyIf { usesMixins.toBoolean() } + doLast { def mixinConfigFile = getFile("/src/main/resources/mixins." + modId + ".json") if (!mixinConfigFile.exists()) { def mixinPluginLine = "" - if(!mixinPlugin.isEmpty()) { + if (!mixinPlugin.isEmpty()) { // We might not have a mixin plugin if we're using early/late mixins - mixinPluginLine += """\n "plugin": "${modGroup}.${mixinPlugin}", """ + mixinPluginLine += """\n "plugin": "${modGroup}.${mixinPlugin}", """ } mixinConfigFile.text = """{ @@ -390,119 +733,176 @@ task generateAssets { } } -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/**' - } +if (usesMixins.toBoolean()) { + tasks.named("processResources").configure { + dependsOn("generateAssets") } - manifest { - attributes(getManifestAttributes()) + tasks.named("compileJava", JavaCompile).configure { + options.compilerArgs += [ + // 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" + ] } - - 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/**' - } - } +tasks.named("processResources", ProcessResources).configure { + // this will ensure that this task is redone when the versions change. + inputs.property "version", project.version + inputs.property "mcversion", project.minecraft.mcVersion + exclude("spotless.gradle") - manifest { - attributes(getManifestAttributes()) + // replace stuff in mcmod.info, nothing else. replaces ${key} with value in text + filesMatching("mcmod.info") { + expand "minecraftVersion": project.minecraft.mcVersion, + "modVersion": modVersion, + "modId": modId, + "modName": modName } - if (usesShadowedDependencies.toBoolean()) { - dependsOn(shadowJar) - enabled = false + if (usesMixins.toBoolean()) { + dependsOn("compileJava", "compileScala") } } -reobf { - if (usesMixins.toBoolean()) { - addExtraSrgFile mixinSrg - } +ext.java17Toolchain = (JavaToolchainSpec spec) -> { + spec.languageVersion.set(JavaLanguageVersion.of(17)) + spec.vendor.set(JvmVendorSpec.matching("jetbrains")) } -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" - ] - } - } +ext.java17DependenciesCfg = configurations.create("java17Dependencies") { + extendsFrom(configurations.getByName("runtimeClasspath")) // Ensure consistent transitive dependency resolution + canBeConsumed = false +} +ext.java17PatchDependenciesCfg = configurations.create("java17PatchDependencies") { + canBeConsumed = false } -runClient { - if (developmentEnvironmentUserName) { - arguments += [ - "--username", - developmentEnvironmentUserName - ] +dependencies { + def lwjgl3ifyVersion = '1.5.7' + if (modId != 'lwjgl3ify') { + java17Dependencies("com.github.GTNewHorizons:lwjgl3ify:${lwjgl3ifyVersion}") + } + if (modId != 'hodgepodge') { + java17Dependencies('com.github.GTNewHorizons:Hodgepodge:2.3.35') + } + + java17PatchDependencies("com.github.GTNewHorizons:lwjgl3ify:${lwjgl3ifyVersion}:forgePatches") {transitive = false} +} + +ext.java17JvmArgs = [ + // Java 9+ support + "--illegal-access=warn", + "-Djava.security.manager=allow", + "-Dfile.encoding=UTF-8", + "--add-opens", "java.base/jdk.internal.loader=ALL-UNNAMED", + "--add-opens", "java.base/java.net=ALL-UNNAMED", + "--add-opens", "java.base/java.nio=ALL-UNNAMED", + "--add-opens", "java.base/java.io=ALL-UNNAMED", + "--add-opens", "java.base/java.lang=ALL-UNNAMED", + "--add-opens", "java.base/java.lang.reflect=ALL-UNNAMED", + "--add-opens", "java.base/java.text=ALL-UNNAMED", + "--add-opens", "java.base/java.util=ALL-UNNAMED", + "--add-opens", "java.base/jdk.internal.reflect=ALL-UNNAMED", + "--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED", + "--add-opens", "jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming", + "--add-opens", "java.desktop/sun.awt.image=ALL-UNNAMED", + "--add-modules", "jdk.dynalink", + "--add-opens", "jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED", + "--add-modules", "java.sql.rowset", + "--add-opens", "java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED" +] + +ext.hotswapJvmArgs = [ + // DCEVM advanced hot reload + "-XX:+AllowEnhancedClassRedefinition", + "-XX:HotswapAgent=fatjar" +] + +ext.setupHotswapAgentTask = tasks.register("setupHotswapAgent") { + group = "GTNH Buildscript" + description = "Installs a recent version of HotSwapAgent into the Java 17 JetBrains runtime directory" + def hsaUrl = 'https://github.com/HotswapProjects/HotswapAgent/releases/download/1.4.2-SNAPSHOT/hotswap-agent-1.4.2-SNAPSHOT.jar' + def targetFolderProvider = javaToolchains.launcherFor(java17Toolchain).map {it.metadata.installationPath.dir("lib/hotswap")} + def targetFilename = "hotswap-agent.jar" + onlyIf { + !targetFolderProvider.get().file(targetFilename).asFile.exists() + } + doLast { + def targetFolder = targetFolderProvider.get() + targetFolder.asFile.mkdirs() + download.run { + src hsaUrl + dest targetFolder.file(targetFilename).asFile + overwrite false + tempAndMove true + } } - - args(arguments) - jvmArgs(jvmArguments) } -runServer { - args(arguments) - jvmArgs(jvmArguments) -} +public abstract class RunHotswappableMinecraftTask extends RunMinecraftTask { + // IntelliJ doesn't seem to allow commandline arguments so we also support an env variable + private boolean enableHotswap = Boolean.valueOf(System.getenv("HOTSWAP")); -tasks.withType(JavaExec).configureEach { - javaLauncher.set( - javaToolchains.launcherFor { - languageVersion = projectJavaVersion - } - ) -} + @Input + public boolean getEnableHotswap() { return enableHotswap } + @Option(option = "hotswap", description = "Enables HotSwapAgent for enhanced class reloading under a debugger") + public boolean setEnableHotswap(boolean enable) { enableHotswap = enable } -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") + @Inject + public RunHotswappableMinecraftTask(Distribution side, String superTask, org.gradle.api.invocation.Gradle gradle) { + super(side, gradle) - // replace stuff in mcmod.info, nothing else - from(sourceSets.main.resources.srcDirs) { - include 'mcmod.info' + this.lwjglVersion = 3 + this.javaLauncher = project.javaToolchains.launcherFor(project.java17Toolchain) + this.extraJvmArgs.addAll(project.java17JvmArgs) + this.extraJvmArgs.addAll(project.provider(() -> enableHotswap ? project.hotswapJvmArgs : [])) - // replace modVersion and minecraftVersion - expand "minecraftVersion": project.minecraft.version, - "modVersion": modVersion, - "modId": modId, - "modName": modName + this.classpath(project.java17PatchDependenciesCfg) + if (side == Distribution.CLIENT) { + this.classpath(project.minecraftTasks.lwjgl3Configuration) + } + // Use a raw provider instead of map to not create a dependency on the task + this.classpath(project.provider(() -> project.tasks.named(superTask, RunMinecraftTask).get().classpath)) + this.classpath.filter { file -> + !file.path.contains("2.9.4-nightly-20150209") // Remove lwjgl2 + } + this.classpath(project.java17DependenciesCfg) + } + + public void setup(Project project) { + super.setup(project) + if (project.usesMixins.toBoolean()) { + this.extraJvmArgs.addAll(project.provider(() -> { + def mixinCfg = project.configurations.detachedConfiguration(project.dependencies.create(project.mixinProviderSpec)) + mixinCfg.canBeConsumed = false + mixinCfg.transitive = false + enableHotswap ? ["-javaagent:" + mixinCfg.singleFile.absolutePath] : [] + })) + } } +} - if (usesMixins.toBoolean()) { - from refMap - } +def runClient17Task = tasks.register("runClient17", RunHotswappableMinecraftTask, Distribution.CLIENT, "runClient") +runClient17Task.configure { + setup(project) + group = "Modded Minecraft" + description = "Runs the modded client using Java 17, lwjgl3ify and Hodgepodge" + dependsOn(setupHotswapAgentTask, mcpTasks.launcherSources.classesTaskName, minecraftTasks.taskDownloadVanillaAssets, mcpTasks.taskPackagePatchedMc, 'jar') + mainClass = "GradleStart" + username = minecraft.username + userUUID = minecraft.userUUID +} - // copy everything else that's not the mcmod.info - from(sourceSets.main.resources.srcDirs) { - exclude 'mcmod.info' - exclude 'spotless.gradle' - } +def runServer17Task = tasks.register("runServer17", RunHotswappableMinecraftTask, Distribution.DEDICATED_SERVER, "runServer") +runServer17Task.configure { + setup(project) + group = "Modded Minecraft" + description = "Runs the modded server using Java 17, lwjgl3ify and Hodgepodge" + dependsOn(setupHotswapAgentTask, mcpTasks.launcherSources.classesTaskName, minecraftTasks.taskDownloadVanillaAssets, mcpTasks.taskPackagePatchedMc, 'jar') + mainClass = "GradleStartServer" + extraArgs.add("nogui") } def getManifestAttributes() { @@ -521,73 +921,65 @@ def getManifestAttributes() { if (usesMixins.toBoolean()) { manifestAttributes += [ - "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", - "MixinConfigs" : "mixins." + modId + ".json", - "ForceLoadAsMod": !containsMixinsAndOrCoreModOnly.toBoolean() + "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", + "MixinConfigs" : "mixins." + modId + ".json", + "ForceLoadAsMod": !containsMixinsAndOrCoreModOnly.toBoolean() ] } return manifestAttributes } -task sourcesJar(type: Jar) { - from(sourceSets.main.allSource) - from(file("$projectDir/LICENSE")) - 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") - +tasks.named("jar", Jar).configure { 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/**' +if (usesShadowedDependencies.toBoolean()) { + tasks.named("shadowJar", ShadowJar).configure { + manifest { + attributes(getManifestAttributes()) } - } - from sourceSets.main.output - getArchiveClassifier().set("dev") - - manifest { - attributes(getManifestAttributes()) + if (minimizeShadowedDependencies.toBoolean()) { + minimize() // This will only allow shading for actually used classes + } + configurations = [ + project.configurations.shadowImplementation, + project.configurations.shadowCompile, + project.configurations.shadeCompile + ] + archiveClassifier.set('dev') + if (relocateShadowedDependencies.toBoolean()) { + relocationPrefix = modGroup + ".shadow" + enableRelocation = true + } } - - if (usesShadowedDependencies.toBoolean()) { - dependsOn(circularResolverJar) + configurations.runtimeElements.outgoing.artifacts.clear() + configurations.apiElements.outgoing.artifacts.clear() + configurations.runtimeElements.outgoing.artifact(tasks.named("shadowJar", ShadowJar)) + configurations.apiElements.outgoing.artifact(tasks.named("shadowJar", ShadowJar)) + tasks.named("jar", Jar) { enabled = false + finalizedBy(tasks.shadowJar) + } + tasks.named("reobfJar", ReobfuscatedJar) { + inputJar.set(tasks.named("shadowJar", ShadowJar).flatMap({it.archiveFile})) + } + AdhocComponentWithVariants javaComponent = (AdhocComponentWithVariants) project.components.findByName("java") + javaComponent.withVariantsFromConfiguration(configurations.shadowRuntimeElements) { + skip() + } + for (runTask in ["runClient", "runServer", "runClient17", "runServer17"]) { + tasks.named(runTask).configure { + dependsOn("shadowJar") + } } } +ext.publishableDevJar = usesShadowedDependencies.toBoolean() ? tasks.shadowJar : tasks.jar +ext.publishableObfJar = tasks.reobfJar -task apiJar(type: Jar) { +tasks.register('apiJar', Jar) { from(sourceSets.main.allSource) { include modGroupPath + "/" + apiPackagePath + '/**' } @@ -605,18 +997,163 @@ task apiJar(type: Jar) { artifacts { if (!noPublishedSources) { - archives sourcesJar + archives tasks.named("sourcesJar") } - archives devJar if (apiPackage) { - archives apiJar + archives tasks.named("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 +idea { + module { + downloadJavadoc = true + downloadSources = true + inheritOutputDirs = true + } + project { + settings { + if (ideaOverrideBuildType != "") { + delegateActions { + if ("gradle".equalsIgnoreCase(ideaOverrideBuildType)) { + delegateBuildRunToGradle = true + testRunner = org.jetbrains.gradle.ext.ActionDelegationConfig.TestRunner.GRADLE + } else if ("idea".equalsIgnoreCase(ideaOverrideBuildType)) { + delegateBuildRunToGradle = false + testRunner = org.jetbrains.gradle.ext.ActionDelegationConfig.TestRunner.PLATFORM + } else { + throw GradleScriptException('Accepted value for ideaOverrideBuildType is one of gradle or idea.') + } + } + } + runConfigurations { + "0. Build and Test"(Gradle) { + taskNames = ["build"] + } + "1. Run Client"(Gradle) { + taskNames = ["runClient"] + } + "2. Run Server"(Gradle) { + taskNames = ["runServer"] + } + "1a. Run Client (Java 17)"(Gradle) { + taskNames = ["runClient17"] + } + "2a. Run Server (Java 17)"(Gradle) { + taskNames = ["runServer17"] + } + "1b. Run Client (Java 17, Hotswap)"(Gradle) { + taskNames = ["runClient17"] + envs = ["HOTSWAP": "true"] + } + "2b. Run Server (Java 17, Hotswap)"(Gradle) { + taskNames = ["runServer17"] + envs = ["HOTSWAP": "true"] + } + "3. Run Obfuscated Client"(Gradle) { + taskNames = ["runObfClient"] + } + "4. Run Obfuscated Server"(Gradle) { + taskNames = ["runObfServer"] + } + if (!disableSpotless) { + "5. Apply spotless"(Gradle) { + taskNames = ["spotlessApply"] + } + } + def coreModArgs = "" + if (coreModClass) { + coreModArgs = ' "-Dfml.coreMods.load=' + modGroup + '.' + coreModClass + '"' + } + "Run Client (IJ Native)"(Application) { + mainClass = "GradleStart" + moduleName = project.name + ".ideVirtualMain" + afterEvaluate { + workingDirectory = tasks.runClient.workingDir.absolutePath + programParameters = tasks.runClient.calculateArgs(project).collect { '"' + it + '"' }.join(' ') + jvmArgs = tasks.runClient.calculateJvmArgs(project).collect { '"' + it + '"' }.join(' ') + + ' ' + tasks.runClient.systemProperties.collect { '"-D' + it.key + '=' + it.value.toString() + '"' }.join(' ') + + coreModArgs + } + } + "Run Server (IJ Native)"(Application) { + mainClass = "GradleStartServer" + moduleName = project.name + ".ideVirtualMain" + afterEvaluate { + workingDirectory = tasks.runServer.workingDir.absolutePath + programParameters = tasks.runServer.calculateArgs(project).collect { '"' + it + '"' }.join(' ') + jvmArgs = tasks.runServer.calculateJvmArgs(project).collect { '"' + it + '"' }.join(' ') + + ' ' + tasks.runServer.systemProperties.collect { '"-D' + it.key + '=' + it.value.toString() + '"' }.join(' ') + + coreModArgs + } + } + } + compiler.javac { + afterEvaluate { + javacAdditionalOptions = "-encoding utf8" + moduleJavacAdditionalOptions = [ + (project.name + ".main"): tasks.compileJava.options.compilerArgs.collect { '"' + it + '"' }.join(' ') + ] + } + } + withIDEADir { File ideaDir -> + if (!ideaDir.path.contains(".idea")) { + // If an .ipr file exists, the project root directory is passed here instead of the .idea subdirectory + ideaDir = new File(ideaDir, ".idea") + } + if (ideaDir.isDirectory()) { + def miscFile = new File(ideaDir, "misc.xml") + if (miscFile.isFile()) { + boolean dirty = false + def miscTransformer = new XmlTransformer() + miscTransformer.addAction { root -> + Node rootNode = root.asNode() + def rootManager = rootNode + .component.find { it.@name == 'ProjectRootManager' } + if (!rootManager) { + rootManager = rootNode.appendNode('component', ['name': 'ProjectRootManager', 'version': '2']) + dirty = true + } + def output = rootManager.output + if (!output) { + output = rootManager.appendNode('output') + dirty = true + } + if (!output.@url) { + // Only modify the output url if it doesn't yet have one, or if the existing one is blank somehow. + // This is a sensible default for most setups + output.@url = 'file://$PROJECT_DIR$/build/ideaBuild' + dirty = true + } + } + def result = miscTransformer.transform(miscFile.text) + if (dirty) { + miscFile.write(result) + } + } else { + miscFile.text = """ + + + + + +""" + } + } + } + } + } +} + +tasks.named("processIdeaSettings").configure { + dependsOn("injectTags") +} + +tasks.named("ideVirtualMainClasses").configure { + // Make IntelliJ "Build project" build the mod jars + dependsOn("jar", "reobfJar") + if (!disableSpotless) { + dependsOn("spotlessCheck") + } } // workaround variable hiding in pom processing @@ -624,54 +1161,28 @@ def projectConfigs = project.configurations publishing { publications { - maven(MavenPublication) { + create("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" + artifact apiJar } - groupId = System.getenv("ARTIFACT_GROUP_ID") ?: "com.github.GTNewHorizons" + groupId = System.getenv("ARTIFACT_GROUP_ID") ?: project.group 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 (usesMavenPublishing.toBoolean() && System.getenv("MAVEN_USER") != null) { + maven { + url = mavenPublishUrl + allowInsecureProtocol = mavenPublishUrl.startsWith("http://") // Mostly for the GTNH maven + credentials { + username = System.getenv("MAVEN_USER") ?: "NONE" + password = System.getenv("MAVEN_PASSWORD") ?: "NONE" + } } } } @@ -688,7 +1199,7 @@ if (modrinthProjectId.size() != 0 && System.getenv("MODRINTH_TOKEN") != null) { versionNumber = identifiedVersion versionType = identifiedVersion.endsWith("-pre") ? "beta" : "release" changelog = changelogFile.exists() ? changelogFile.getText("UTF-8") : "" - uploadFile = jar + uploadFile = publishableObfJar additionalFiles = getSecondaryArtifacts() gameVersions = [minecraftVersion] loaders = ["forge"] @@ -707,7 +1218,7 @@ if (modrinthProjectId.size() != 0 && System.getenv("MODRINTH_TOKEN") != null) { } } if (usesMixins.toBoolean()) { - addModrinthDep("required", "project", "gtnhmixins") + addModrinthDep("required", "project", "unimixins") } tasks.modrinth.dependsOn(build) tasks.publish.dependsOn(tasks.modrinth) @@ -729,7 +1240,7 @@ if (curseForgeProjectId.size() != 0 && System.getenv("CURSEFORGE_TOKEN") != null releaseType = identifiedVersion.endsWith("-pre") ? "beta" : "release" addGameVersion minecraftVersion addGameVersion "Forge" - mainArtifact jar + mainArtifact publishableObfJar for (artifact in getSecondaryArtifacts()) addArtifact artifact } @@ -751,13 +1262,13 @@ if (curseForgeProjectId.size() != 0 && System.getenv("CURSEFORGE_TOKEN") != null } } if (usesMixins.toBoolean()) { - addCurseForgeRelation("requiredDependency", "gtnhmixins") + addCurseForgeRelation("requiredDependency", "unimixins") } tasks.curseforge.dependsOn(build) tasks.publish.dependsOn(tasks.curseforge) } -def addModrinthDep(scope, type, name) { +def addModrinthDep(String scope, String type, String name) { com.modrinth.minotaur.dependencies.Dependency dep; if (!(scope in ["required", "optional", "incompatible", "embedded"])) { throw new Exception("Invalid modrinth dependency scope: " + scope) @@ -775,7 +1286,7 @@ def addModrinthDep(scope, type, name) { project.modrinth.dependencies.add(dep) } -def addCurseForgeRelation(type, name) { +def addCurseForgeRelation(String type, String name) { if (!(type in ["requiredDependency", "embeddedLibrary", "optionalDependency", "tool", "incompatible"])) { throw new Exception("Invalid CurseForge relation type: " + type) } @@ -785,19 +1296,53 @@ def addCurseForgeRelation(type, name) { } // Updating -task updateBuildScript { + +def buildscriptGradleVersion = "8.5" + +tasks.named('wrapper', Wrapper).configure { + gradleVersion = buildscriptGradleVersion +} + +tasks.register('updateBuildScript') { + group = 'GTNH Buildscript' + description = 'Updates the build script to the latest version' + + if (gradle.gradleVersion != buildscriptGradleVersion && !Boolean.getBoolean('DISABLE_BUILDSCRIPT_GRADLE_UPDATE')) { + dependsOn('wrapper') + } + doLast { - if (performBuildScriptUpdate(projectDir.toString())) return + if (performBuildScriptUpdate()) return print("Build script already up-to-date!") } } -if (!project.getGradle().startParameter.isOffline() && isNewBuildScriptVersionAvailable(projectDir.toString())) { +if (!project.getGradle().startParameter.isOffline() && !Boolean.getBoolean('DISABLE_BUILDSCRIPT_UPDATE_CHECK') && isNewBuildScriptVersionAvailable()) { if (autoUpdateBuildScript.toBoolean()) { - performBuildScriptUpdate(projectDir.toString()) + performBuildScriptUpdate() } else { out.style(Style.SuccessHeader).println("Build script update available! Run 'gradle updateBuildScript'") + if (gradle.gradleVersion != buildscriptGradleVersion) { + out.style(Style.SuccessHeader).println("updateBuildScript can update gradle from ${gradle.gradleVersion} to ${buildscriptGradleVersion}\n") + } + } +} + +// If you want to add more cases to this task, implement them as arguments if total amount to print gets too large +tasks.register('faq') { + group = 'GTNH Buildscript' + description = 'Prints frequently asked questions about building a project' + + doLast { + print("If your build fails to fetch dependencies, run './gradlew updateDependencies'. " + + "Or you can manually check if the versions are still on the distributing sites - " + + "the links can be found in repositories.gradle and build.gradle:repositories, " + + "but not build.gradle:buildscript.repositories - those ones are for gradle plugin metadata.\n\n" + + "If your build fails to recognize the syntax of new Java versions, enable Jabel in your " + + "gradle.properties. See how it's done in GTNH ExampleMod/gradle.properties. " + + "However, keep in mind that Jabel enables only syntax features, but not APIs that were introduced in " + + "Java 9 or later.") } } @@ -838,10 +1383,11 @@ boolean verifySettingsGradle() { return false } -boolean performBuildScriptUpdate(String projectDir) { - if (isNewBuildScriptVersionAvailable(projectDir)) { +boolean performBuildScriptUpdate() { + if (isNewBuildScriptVersionAvailable()) { def buildscriptFile = getFile("build.gradle") availableBuildScriptUrl().withInputStream { i -> buildscriptFile.withOutputStream { it << i } } + def out = services.get(StyledTextOutputFactory).create('buildscript-update-output') out.style(Style.Success).print("Build script updated. Please REIMPORT the project or RESTART your IDE!") boolean settingsupdated = verifySettingsGradle() settingsupdated = verifyGitAttributes() || settingsupdated @@ -852,13 +1398,19 @@ boolean performBuildScriptUpdate(String projectDir) { return false } -boolean isNewBuildScriptVersionAvailable(String projectDir) { +boolean isNewBuildScriptVersionAvailable() { 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) + String availableBuildScriptHash + try { + String availableBuildScript = availableBuildScriptUrl().newInputStream(parameters).getText() + availableBuildScriptHash = getVersionHash(availableBuildScript) + } catch (IOException e) { + logger.warn("Could not check for buildscript update availability: {}", e.message) + return false + } boolean isUpToDate = currentBuildScriptHash.empty || availableBuildScriptHash.empty || currentBuildScriptHash == availableBuildScriptHash return !isUpToDate @@ -872,15 +1424,12 @@ static String getVersionHash(String buildScriptContent) { return "" } -configure(updateBuildScript) { - group = 'forgegradle' - description = 'Updates the build script to the latest version' -} - // Parameter Deobfuscation -task deobfParams { - doLast { +tasks.register('deobfParams') { + group = 'GTNH Buildscript' + description = 'Rename all obfuscated parameter names inherited from Minecraft classes' + doLast { // TODO String mcpDir = "$project.gradle.gradleUserHomeDir/caches/minecraft/de/oceanlabs/mcp/mcp_$channel/$mappingsVersion" String mcpZIP = "$mcpDir/mcp_$channel-$mappingsVersion-${minecraftVersion}.zip" @@ -894,7 +1443,10 @@ task deobfParams { if (!file(paramsCSV).exists()) { println("Extracting MCP archive ...") - unzip(mcpZIP, mcpDir) + copy { + from(zipTree(mcpZIP)) + into(mcpDir) + } } println("Parsing params.csv ...") @@ -937,43 +1489,7 @@ static int replaceParams(File file, Map params) { 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 +// Dependency Deobfuscation (Deprecated, use the new RFG API documented in dependencies.gradle) def deobf(String sourceURL) { try { @@ -999,44 +1515,31 @@ def deobf(String sourceURL) { hostName = String.join(".", parts) return deobf(sourceURL, "$hostName/$fileName") - } catch (Exception e) { + } catch (Exception ignored) { return deobf(sourceURL, "deobf/${sourceURL.hashCode()}") } } +def deobfMaven(String repoURL, String mavenDep) { + if (!repoURL.endsWith("/")) { + repoURL += "/" + } + String[] parts = mavenDep.split(":") + parts[0] = parts[0].replace('.', '/') + def jarURL = repoURL + parts[0] + "/" + parts[1] + "/" + parts[2] + "/" + parts[1] + "-" + parts[2] + ".jar" + return deobf(jarURL) +} + +def deobfCurse(String curseDep) { + return dependencies.rfg.deobf("curse.maven:$curseDep") +} + // 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 @@ -1044,50 +1547,8 @@ def deobf(String sourceURL, String rawFileName) { 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) + return dependencies.rfg.deobf(files(obfFile)) } - -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) { @@ -1109,8 +1570,41 @@ def getFile(String 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] + def secondaryArtifacts = [publishableDevJar] if (!noPublishedSources) secondaryArtifacts += [sourcesJar] if (apiPackage) secondaryArtifacts += [apiJar] return secondaryArtifacts -} \ No newline at end of file +} + +def getURL(String main, String fallback) { + return pingURL(main, 10000) ? main : fallback +} + +// credit: https://stackoverflow.com/a/3584332 +def pingURL(String url, int timeout) { + url = url.replaceFirst("^https", "http") // Otherwise an exception may be thrown on invalid SSL certificates. + try { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection() + connection.setConnectTimeout(timeout) + connection.setReadTimeout(timeout) + connection.setRequestMethod("HEAD") + int responseCode = connection.getResponseCode() + return 200 <= responseCode && responseCode <= 399 + } catch (IOException ignored) { + return false + } +} + +// For easier scripting of things that require variables defined earlier in the buildscript +if (file('addon.late.gradle.kts').exists()) { + apply from: 'addon.late.gradle.kts' +} else if (file('addon.late.gradle').exists()) { + apply from: 'addon.late.gradle' +} + +// File for local tweaks not commited to Git +if (file('addon.late.local.gradle.kts').exists()) { + apply from: 'addon.late.local.gradle.kts' +} else if (file('addon.late.local.gradle').exists()) { + apply from: 'addon.late.local.gradle' +} diff --git a/dependencies.gradle b/dependencies.gradle index 1355f5b6a..8b720ae90 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -2,26 +2,22 @@ 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") + api("com.github.GTNewHorizons:CodeChickenLib:1.1.5.5:dev") + api("com.github.GTNewHorizons:CodeChickenCore:1.1.6:dev") + api("com.github.GTNewHorizons:NotEnoughItems:2.4.13-GTNH: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.github.GTNewHorizons:AE2FluidCraft-Rework:1.1.71-gtnh:dev") { transitive = false } +// compileOnly("com.github.GTNewHorizons:Avaritiaddons:1.6.0-GTNH:dev") { transitive = false } +// compileOnly("com.github.GTNewHorizons:BuildCraftCompat:7.1.16:dev") { transitive = false } + compileOnly('com.github.GTNewHorizons:EnderIO:2.5.6:dev') { transitive=false } + compileOnly("com.github.GTNewHorizons:ForestryMC:4.7.0:dev") { transitive = false } + compileOnly("com.github.GTNewHorizons:GT5-Unofficial:5.09.44.98:dev") { transitive = false } + compileOnly("com.github.GTNewHorizons:GTplusplus:1.10.39:dev") { transitive = false } +// compileOnly("com.github.GTNewHorizons:ThaumicEnergistics:1.5.3-GTNH:dev") { transitive = false } + compileOnly("com.github.GTNewHorizons:Botania:1.10.3-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' + testImplementation('org.junit.jupiter:junit-jupiter-api:5.2.0') } \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index a60757859..08aa64057 100644 --- a/gradle.properties +++ b/gradle.properties @@ -28,16 +28,28 @@ remoteMappings = https://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/con # 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: +# Enables using modern java syntax (up to version 17) via Jabel, while still targeting JVM 8. +# See https://github.com/bsideup/jabel for details on how this works. +enableModernJavaSyntax = false + +# Enables injecting missing generics into the decompiled source code for a better coding experience +# Turns most publicly visible List, Map, etc. into proper List, Map types +enableGenericInjection = false + + +# Generate a class with String fields for the mod id, name, version and group name named with the fields below +generateGradleTokenClass = me.towdium.jecalculation.Tags +gradleTokenModId = MODID +gradleTokenModName = MODNAME +gradleTokenVersion = VERSION +gradleTokenGroupName = GROUPNAME +# [DEPRECATED] +# Multiple source files can be defined here by providing a comma-seperated list: Class1.java,Class2.java,Class3.java # 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 +replaceGradleTokenInFile = # 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. @@ -70,10 +82,65 @@ 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 +# If disabled, won't remove unused classes from shaded dependencies. Some libraries use reflection to access +# their own classes, making the minimization unreliable. +minimizeShadowedDependencies = true +# If disabled, won't rename the shadowed classes. +relocateShadowedDependencies = true + +# Adds the GTNH maven, CurseMaven, IC2/Player maven, and some more well-known 1.7.10 repositories +includeWellKnownRepositories = true # 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 +# Change these to your Maven coordinates if you want to publish to a custom Maven repository instead of the default GTNH Maven. +# Authenticate with the MAVEN_USERNAME and MAVEN_PASSWORD environment variables. +# If you need a more complex setup disable maven publishing here and add a publishing repository to addon.gradle. +usesMavenPublishing = false +# mavenPublishUrl = http://jenkins.usrv.eu:8081/nexus/content/repositories/releases + +# Publishing to modrinth requires you to set the MODRINTH_TOKEN environment variable to your current modrinth API token. + +# The project's ID on Modrinth. Can be either the slug or the ID. +# Leave this empty if you don't want to publish on Modrinth. +modrinthProjectId = + +# The project's relations on Modrinth. You can use this to refer to other projects on Modrinth. +# Syntax: scope1-type1:name1;scope2-type2:name2;... +# Where scope can be one of [required, optional, incompatible, embedded], +# type can be one of [project, version], +# and the name is the Modrinth project or version slug/id of the other mod. +# Example: required-project:fplib;optional-project:gasstation;incompatible-project:gregtech +# Note: GTNH Mixins is automatically set as a required dependency if usesMixins = true +modrinthRelations = + +# Publishing to CurseForge requires you to set the CURSEFORGE_TOKEN environment variable to one of your CurseForge API tokens. + +# The project's numeric ID on CurseForge. You can find this in the About Project box. +# Leave this empty if you don't want to publish on CurseForge. +curseForgeProjectId = + +# 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 = + # Optional parameter to prevent the source code from being published # noPublishedSources = + +# Uncomment this to disable spotless checks +# This should only be uncommented to keep it easier to sync with upstream/other forks. +# That is, if there is no other active fork/upstream, NEVER change this. + disableSpotless = true + +# Uncomment this to disable checkstyle checks (currently wildcard import check). + disableCheckstyle = true + +# Override the IDEA build type. Valid value is "" (leave blank, do not override), "idea" (force use native IDEA build), "gradle" +# (force use delegated build). +# This is meant to be set in $HOME/.gradle/gradle.properties. +# e.g. add "systemProp.org.gradle.project.ideaOverrideBuildType=idea" will override the build type to be always native build. +# WARNING: If you do use this option, it will overwrite whatever you have in your existing projects. This might not be what you want! +# Usually there is no need to uncomment this here as other developers do not necessarily use the same build type as you. +# ideaOverrideBuildType = idea diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 5c2d1cf01..d64cd4917 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 3ab0b725e..7cf08140d 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.9.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists +zipStorePath=wrapper/dists \ No newline at end of file diff --git a/gradlew b/gradlew index 83f2acfdc..31042a677 100644 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,78 +17,111 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -97,92 +130,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=$((i+1)) + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" fi -exec "$JAVACMD" "$@" +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" \ No newline at end of file diff --git a/gradlew.bat b/gradlew.bat index 9618d8d96..2578005b5 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -14,7 +14,7 @@ @rem limitations under the License. @rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,10 +25,14 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @@ -37,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -51,7 +55,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -61,40 +65,28 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal -:omega +:omega \ No newline at end of file diff --git a/repositories.gradle b/repositories.gradle index 65c3bbcb6..033d07fda 100644 --- a/repositories.gradle +++ b/repositories.gradle @@ -1,18 +1,5 @@ // 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' - } + mavenLocal() } diff --git a/settings.gradle b/settings.gradle index 93c852a12..301a04a95 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,10 +1,28 @@ + +pluginManagement { + repositories { + maven { + // RetroFuturaGradle + name "GTNH Maven" + url "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" + allowInsecureProtocol = true + mavenContent { + includeGroup("com.gtnewhorizons.retrofuturagradle") + } + } + gradlePluginPortal() + mavenCentral() + mavenLocal() + } +} + plugins { id 'com.diffplug.blowdryerSetup' version '1.6.0' + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.4.0' // Provides java toolchains } -apply plugin: 'com.diffplug.blowdryerSetup' - blowdryerSetup { - github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.1.5') + repoSubfolder 'gtnhShared' + github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.2.2') //devLocal '.' // Use this when testing config updates locally -} +} \ No newline at end of file diff --git a/src/main/java/me/towdium/jecalculation/JecaConfig.java b/src/main/java/me/towdium/jecalculation/JecaConfig.java index 18bbbcf54..d43184dca 100644 --- a/src/main/java/me/towdium/jecalculation/JecaConfig.java +++ b/src/main/java/me/towdium/jecalculation/JecaConfig.java @@ -1,13 +1,19 @@ 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 cpw.mods.fml.common.Loader; +import cpw.mods.fml.common.event.FMLPreInitializationEvent; + public class JecaConfig { - public static File configDir = new File(Loader.instance().getConfigDir(), "JustEnoughCalculation/"); + + public static File configDir = new File( + Loader.instance() + .getConfigDir(), + "JustEnoughCalculation/"); public static final File configFile = new File(configDir, "main.cfg"); public static final File recordFile = new File(configDir, "record.json"); public static final File defaultFile = new File(configDir, "default.json"); @@ -22,10 +28,12 @@ public static File getDataFile(String group) { public static Configuration config; public static boolean isClintMode() { - return EnumItems.ClientMode.getProperty().getBoolean(); + return EnumItems.ClientMode.getProperty() + .getBoolean(); } public enum EnumItems { + ClientMode, EnableInventoryCheck, ListRecipeBlackList, @@ -39,7 +47,7 @@ public String getComment() { 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"; + + "Names can be found in ListRecipeCategory"; case ListRecipeCategory: return "List of categories, this is maintained by the mod automatically"; } @@ -91,7 +99,7 @@ public Object getDefault() { 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; } @@ -101,23 +109,26 @@ public Property init() { 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()); + config.getCategory(EnumCategory.General.toString()) + .get(this.getName()); } return config.get(this.getCategory(), this.getName(), false, this.getComment()); } public Property getProperty() { - return config.getCategory(EnumCategory.General.toString()).get(this.getName()); + return config.getCategory(EnumCategory.General.toString()) + .get(this.getName()); } } public enum EnumCategory { + General; @Override diff --git a/src/main/java/me/towdium/jecalculation/JustEnoughCalculation.java b/src/main/java/me/towdium/jecalculation/JustEnoughCalculation.java index 05c7a2d60..30e071491 100644 --- a/src/main/java/me/towdium/jecalculation/JustEnoughCalculation.java +++ b/src/main/java/me/towdium/jecalculation/JustEnoughCalculation.java @@ -1,12 +1,14 @@ package me.towdium.jecalculation; +import javax.annotation.ParametersAreNonnullByDefault; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + import cpw.mods.fml.common.Mod; 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; /** * @author Towdium @@ -14,17 +16,18 @@ @ParametersAreNonnullByDefault @SuppressWarnings("unused") @Mod( - modid = Tags.MODID, - name = Tags.MODNAME, - version = Tags.VERSION, - dependencies = "required-after:NotEnoughItems", - acceptedMinecraftVersions = "[1.7.10]") + modid = Tags.MODID, + name = Tags.MODNAME, + version = Tags.VERSION, + dependencies = "required-after:NotEnoughItems", + acceptedMinecraftVersions = "[1.7.10]") public class JustEnoughCalculation { + public static Logger logger = LogManager.getLogger(Tags.MODID); @SidedProxy( - clientSide = Tags.GROUPNAME + ".network.ClientProxy", - serverSide = Tags.GROUPNAME + ".network.CommonProxy") + clientSide = Tags.GROUPNAME + ".network.ClientProxy", + serverSide = Tags.GROUPNAME + ".network.CommonProxy") public static CommonProxy proxy; @Mod.Instance(Tags.MODID) diff --git a/src/main/java/me/towdium/jecalculation/Tags.java b/src/main/java/me/towdium/jecalculation/Tags.java deleted file mode 100644 index 1c4882d0a..000000000 --- a/src/main/java/me/towdium/jecalculation/Tags.java +++ /dev/null @@ -1,9 +0,0 @@ -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 cc737c0c4..3f5833164 100644 --- a/src/main/java/me/towdium/jecalculation/command/Commands.java +++ b/src/main/java/me/towdium/jecalculation/command/Commands.java @@ -1,7 +1,9 @@ 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; @@ -9,10 +11,11 @@ /** * Author: towdium - * Date: 8/10/17. + * Date: 8/10/17. */ @ParametersAreNonnullByDefault public class Commands { + public static final HashMap commands = new HashMap<>(); static { diff --git a/src/main/java/me/towdium/jecalculation/command/ISubCommand.java b/src/main/java/me/towdium/jecalculation/command/ISubCommand.java index 7779ac2f2..788ff14a2 100644 --- a/src/main/java/me/towdium/jecalculation/command/ISubCommand.java +++ b/src/main/java/me/towdium/jecalculation/command/ISubCommand.java @@ -2,16 +2,19 @@ import java.util.Collections; import java.util.List; + import javax.annotation.ParametersAreNonnullByDefault; + import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; /** * Author: towdium - * Date: 8/10/17. + * Date: 8/10/17. */ @ParametersAreNonnullByDefault public interface ISubCommand { + String getName(); String getUsage(ICommandSender sender); diff --git a/src/main/java/me/towdium/jecalculation/command/JecaCommand.java b/src/main/java/me/towdium/jecalculation/command/JecaCommand.java index 0739ae878..35e324031 100644 --- a/src/main/java/me/towdium/jecalculation/command/JecaCommand.java +++ b/src/main/java/me/towdium/jecalculation/command/JecaCommand.java @@ -2,20 +2,24 @@ 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; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentTranslation; +import me.towdium.jecalculation.command.commands.CHelp; +import me.towdium.jecalculation.utils.wrappers.Wrapper; + /** * Author: towdium - * Date: 8/10/17. + * Date: 8/10/17. */ @ParametersAreNonnullByDefault public class JecaCommand extends CommandBase { + @Override public String getCommandName() { return "jeca"; @@ -29,7 +33,8 @@ public String getCommandUsage(ICommandSender sender) { @Override public void processCommand(ICommandSender sender, String[] args) throws CommandException { if (args.length == 0 || args[0].equalsIgnoreCase("help")) { - Commands.commands.get(CHelp.NAME).execute(sender, cut(args)); + Commands.commands.get(CHelp.NAME) + .execute(sender, cut(args)); } else { ISubCommand cmd = Commands.commands.get(args[0].toLowerCase()); if (cmd != null) { @@ -63,10 +68,13 @@ public List addTabCompletionOptions(ICommandSender sender, String[] args 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); + 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 3e1d12f03..393f0c544 100644 --- a/src/main/java/me/towdium/jecalculation/command/commands/CCraft.java +++ b/src/main/java/me/towdium/jecalculation/command/commands/CCraft.java @@ -1,9 +1,11 @@ package me.towdium.jecalculation.command.commands; import javax.annotation.ParametersAreNonnullByDefault; + +import net.minecraft.command.ICommandSender; + import me.towdium.jecalculation.command.ISubCommand; import me.towdium.jecalculation.gui.JecaGui; -import net.minecraft.command.ICommandSender; /** * Author: Towdium @@ -11,6 +13,7 @@ */ @ParametersAreNonnullByDefault public class CCraft implements ISubCommand { + @Override public String getName() { return "craft"; 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 121c43c75..e4f71a8ce 100644 --- a/src/main/java/me/towdium/jecalculation/command/commands/CHelp.java +++ b/src/main/java/me/towdium/jecalculation/command/commands/CHelp.java @@ -1,19 +1,23 @@ 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.ICommandSender; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; +import me.towdium.jecalculation.command.Commands; +import me.towdium.jecalculation.command.ISubCommand; + /** * Author: towdium - * Date: 8/10/17. + * Date: 8/10/17. */ @ParametersAreNonnullByDefault public class CHelp implements ISubCommand { + public static final String NAME = "help"; @Override @@ -29,8 +33,9 @@ public String getUsage(ICommandSender sender) { @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 c1de3b08b..a7ec0f35e 100644 --- a/src/main/java/me/towdium/jecalculation/command/commands/CMath.java +++ b/src/main/java/me/towdium/jecalculation/command/commands/CMath.java @@ -1,9 +1,11 @@ package me.towdium.jecalculation.command.commands; import javax.annotation.ParametersAreNonnullByDefault; + +import net.minecraft.command.ICommandSender; + import me.towdium.jecalculation.command.ISubCommand; import me.towdium.jecalculation.gui.JecaGui; -import net.minecraft.command.ICommandSender; /** * Author: Towdium @@ -11,6 +13,7 @@ */ @ParametersAreNonnullByDefault public class CMath implements ISubCommand { + @Override public String getName() { return "math"; 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 d899ba47d..03ac90e84 100644 --- a/src/main/java/me/towdium/jecalculation/command/commands/CState.java +++ b/src/main/java/me/towdium/jecalculation/command/commands/CState.java @@ -1,16 +1,19 @@ package me.towdium.jecalculation.command.commands; import javax.annotation.ParametersAreNonnullByDefault; -import me.towdium.jecalculation.command.ISubCommand; + import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentTranslation; +import me.towdium.jecalculation.command.ISubCommand; + /** * Author: towdium - * Date: 8/10/17. + * Date: 8/10/17. */ @ParametersAreNonnullByDefault public class CState implements ISubCommand { + @Override public String getName() { return "state"; diff --git a/src/main/java/me/towdium/jecalculation/data/Controller.java b/src/main/java/me/towdium/jecalculation/data/Controller.java index ad0943e19..6189e3f3c 100644 --- a/src/main/java/me/towdium/jecalculation/data/Controller.java +++ b/src/main/java/me/towdium/jecalculation/data/Controller.java @@ -1,15 +1,22 @@ 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 net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChatComponentTranslation; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import me.towdium.jecalculation.JecaConfig; import me.towdium.jecalculation.JustEnoughCalculation; import me.towdium.jecalculation.data.label.labels.LPlaceholder; @@ -17,19 +24,16 @@ import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.utils.Utilities; import me.towdium.jecalculation.utils.wrappers.Pair; -import net.minecraft.client.entity.EntityClientPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ChatComponentTranslation; /** * Author: towdium - * Date: 17-10-15. + * Date: 17-10-15. */ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault @SideOnly(Side.CLIENT) public class Controller { + public static final String KEY_MATH = "math"; public static final String KEY_CRAFT = "craft"; public static final String KEY_PLAYER = "player"; @@ -61,14 +65,17 @@ public static List> discover() { } }; 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); + recipes.getGroup(group) + .stream() + .filter(i -> !hasDuplicate(i)) + .forEach(buffer::add); for (Recipe r : buffer) addRecipe(group, r); } @@ -187,18 +194,21 @@ public static T getR(T t, String s, Function f) { */ 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); - }); + return ri.stream() + .anyMatch(i -> { + if (ri.getIndex() == index && ri.getGroup() + .equals(group)) return false; + else return i.equals(r); + }); } public static boolean hasDuplicate(Recipe r) { - return recipeIterator().stream().anyMatch(i -> i.equals(r)); + return recipeIterator().stream() + .anyMatch(i -> i.equals(r)); } public static void loadFromLocal() { - //noinspection ResultOfMethodCallIgnored + // noinspection ResultOfMethodCallIgnored JecaConfig.dataDir.mkdirs(); File file = JecaConfig.recordFile; NBTTagCompound nbt = Utilities.Json.read(file); @@ -207,8 +217,8 @@ public static void loadFromLocal() { 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 b3c9d9fb4..bd0988dab 100644 --- a/src/main/java/me/towdium/jecalculation/data/label/ILabel.java +++ b/src/main/java/me/towdium/jecalculation/data/label/ILabel.java @@ -1,14 +1,24 @@ 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 net.minecraft.enchantment.EnchantmentData; +import net.minecraft.init.Items; +import net.minecraft.item.ItemEnchantedBook; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import me.towdium.jecalculation.JustEnoughCalculation; import me.towdium.jecalculation.data.label.labels.LFluidStack; import me.towdium.jecalculation.data.label.labels.LItemStack; @@ -23,20 +33,14 @@ import me.towdium.jecalculation.utils.Utilities; import me.towdium.jecalculation.utils.Utilities.ReversedIterator; import me.towdium.jecalculation.utils.wrappers.Pair; -import net.minecraft.enchantment.EnchantmentData; -import net.minecraft.init.Items; -import net.minecraft.item.ItemEnchantedBook; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; /** * Author: towdium - * Date: 8/11/17. + * Date: 8/11/17. */ @ParametersAreNonnullByDefault public interface ILabel { + Merger MERGER = new Merger(); Serializer SERIALIZER = new Serializer(); Converter CONVERTER = new Converter(); @@ -67,10 +71,12 @@ static void initClient() { 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( - "fluidStack", "fluidStack", Impl.form(LFluidStack.class, LFluidStack.class, LFluidStack::merge)); - MERGER.register( - "placeholder", "placeholder", Impl.form(LPlaceholder.class, LPlaceholder.class, LPlaceholder::merge)); + "placeholder", + "placeholder", + Impl.form(LPlaceholder.class, LPlaceholder.class, LPlaceholder::merge)); } long getAmount(); @@ -122,6 +128,7 @@ static void initServer() { * For registering, see {@link Serializer}. */ class Merger { + private final Utilities.Relation functions = new Utilities.Relation<>(); private Merger() {} @@ -134,10 +141,10 @@ public void register(String a, String b, MergerFunction func) { * @param a one label * @param b another label * @return merge result or empty - * This function will try to merge two labels. - * If both label has same type, just sum up amount - * For different type, the framework will try reversing the order for MergeFunctions to work - * So generally speaking, a and b has no priority in this function + * This function will try to merge two labels. + * If both label has same type, just sum up amount + * For different type, the framework will try reversing the order for MergeFunctions to work + * So generally speaking, a and b has no priority in this function */ public Optional merge(ILabel a, ILabel b) { MergerFunction mf = functions.get(a.getIdentifier(), b.getIdentifier()); @@ -147,13 +154,14 @@ public Optional merge(ILabel a, ILabel b) { @FunctionalInterface public interface MergerFunction { + /** * @param a requested label * @param b supplied label * @return merge result or empty - * This function ensures to generate same type if a and b are from same type - * If a is fuzzy, b is explicit, generates a is amount is negative, else generates b - * Normally, explicit type cannot request fuzzy type + * This function ensures to generate same type if a and b are from same type + * If a is fuzzy, b is explicit, generates a is amount is negative, else generates b + * Normally, explicit type cannot request fuzzy type */ @Nullable ILabel merge(ILabel a, ILabel b); @@ -166,6 +174,7 @@ public interface MergerFunction { * For {@link ILabel} operations, see {@link Merger} */ class Serializer { + public static final String KEY_IDENTIFIER = "type"; public static final String KEY_CONTENT = "content"; @@ -180,25 +189,26 @@ public void register(String identifier, Function deseria /** * @param nbt NBT to deserialize * @return the recovered label - * A typical NBT structure of an {@link ILabel} is as follows: - *
{@code
+         *         A typical NBT structure of an {@link ILabel} is as follows:
+         * 
+         *         
+         * {@code
          * {
          *     KEY_IDENTIFIER: entry_id
          *     KEY_CONTENT: {
          *         entry_content
          *     }
          * }
-         * }
+ * } + *
*/ 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"); - else - try { - return func.apply(nbt.getCompoundTag(KEY_CONTENT)); - } catch (SerializationException ignored) { - } + else try { + return func.apply(nbt.getCompoundTag(KEY_CONTENT)); + } catch (SerializationException ignored) {} return EMPTY; } @@ -210,6 +220,7 @@ public NBTTagCompound serialize(ILabel label) { } public static class SerializationException extends RuntimeException { + public SerializationException(String s) { super(s); JustEnoughCalculation.logger.warn(s); @@ -223,6 +234,7 @@ public SerializationException(String s) { * It can also convert ItemStack or FluidStack to ILabel */ class Converter { + static EnumMap> handlers; /** @@ -257,7 +269,8 @@ else if (o instanceof EnchantmentData) { } public void register(ConverterFunction handler, Priority priority) { - handlers.get(priority).add(handler); + handlers.get(priority) + .add(handler); } // get most possible guess from labels @@ -268,15 +281,22 @@ public ILabel first(List labels, @Nullable Class context) { // 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); } @FunctionalInterface public interface ConverterFunction { + List convert(List a, @Nullable Class context); } } @@ -296,6 +316,7 @@ public List getRecords() { } public static class Record { + public Supplier editor; public String localizeKey; public ILabel representation; @@ -309,6 +330,7 @@ public Record(Supplier editor, String localizeKey, ILabel representatio } class LEmpty implements ILabel { + public static final String IDENTIFIER = "empty"; @Override @@ -397,6 +419,7 @@ public String getIdentifier() { } abstract class Impl implements ILabel { + public static final String KEY_AMOUNT = "amount"; public static final String KEY_PERCENT = "percent"; protected long amount; @@ -473,8 +496,10 @@ protected static Merger.MergerFunction form(Class a, Class b, BiPredicate< 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 if (amount > 0) return d.copy() + .setAmount(d.isPercent() ? amount : amountI); + else return c.copy() + .setAmount(c.isPercent() ? amount : amountI); } else return null; }; } 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 597c543ef..185e92dd0 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 @@ -1,27 +1,31 @@ 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; -import me.towdium.jecalculation.utils.Utilities; + import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; +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.gui.Resource; +import me.towdium.jecalculation.utils.Utilities; + /** * Author: towdium - * Date: 17-9-27. + * Date: 17-9-27. */ @ParametersAreNonnullByDefault public class LFluidStack extends ILabel.Impl { + public static final String IDENTIFIER = "fluidStack"; public static final String KEY_FLUID = "fluid"; public static final String KEY_NBT = "nbt"; @@ -133,7 +137,8 @@ public void drawLabel(JecaGui gui) { @Override public int hashCode() { - return super.hashCode() ^ fluid.getUnlocalizedName().hashCode() ^ (nbt == null ? 0 : nbt.hashCode()); + return super.hashCode() ^ fluid.getUnlocalizedName() + .hashCode() ^ (nbt == null ? 0 : nbt.hashCode()); } public static List suggest(List iss, @Nullable Class context) { 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 62164ff37..d0115668d 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 @@ -2,29 +2,33 @@ 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 net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +import cpw.mods.fml.common.registry.GameData; +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.utils.ItemStackHelper; import me.towdium.jecalculation.utils.Utilities; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; /** * Author: towdium - * Date: 8/11/17. + * Date: 8/11/17. */ @ParametersAreNonnullByDefault public class LItemStack extends ILabel.Impl { + public static final String IDENTIFIER = "itemStack"; private static final String KEY_ITEM = "item"; @@ -49,8 +53,10 @@ public LItemStack(ItemStack is) { public LItemStack(NBTTagCompound tag) { super(tag); final String strId = tag.getString(KEY_ITEM); - if (!tag.hasKey("id")) - tag.setShort("id", (short) GameData.getItemRegistry().getId(strId)); + if (!tag.hasKey("id")) tag.setShort( + "id", + (short) GameData.getItemRegistry() + .getId(strId)); tag.setByte("Count", (byte) 1); tag.setShort("Damage", tag.hasKey(KEY_META) ? (short) tag.getInteger(KEY_META) : 0); ItemStack stack = ItemStack.loadItemStackFromNBT(tag); @@ -59,11 +65,11 @@ public LItemStack(NBTTagCompound tag) { 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)); + 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) { @@ -91,11 +97,10 @@ 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; @@ -118,8 +123,10 @@ public static List suggest(List iss, @Nullable Class context) 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)); + if (fMeta || fNbt) return Collections.singletonList( + lis.copy() + .setFMeta(fMeta) + .setFNbt(fNbt)); else return new ArrayList<>(); } @@ -130,9 +137,16 @@ public static List fallback(List iss, @Nullable Class context if (!(label instanceof LItemStack)) return ret; LItemStack lis = (LItemStack) label; 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)); + ret.add( + lis.copy() + .setFMeta(true)); + ret.add( + lis.copy() + .setFNbt(true)); + ret.add( + lis.copy() + .setFMeta(true) + .setFNbt(true)); } return ret; } @@ -186,12 +200,11 @@ public String getIdentifier() { 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; + return (Objects.equals(nbt, lis.nbt)) && meta == lis.meta + && item == lis.item + && fNbt == lis.fNbt + && super.matches(l) + && fMeta == lis.fMeta; } else return false; } @@ -218,19 +231,19 @@ public NBTTagCompound toNbt() { public void drawLabel(JecaGui gui) { gui.drawItemStack(0, 0, rep, false); // TODO some item won't render correctly with overlay - // if (fNbt || fMeta) - // gui.drawResource(Resource.LBL_FRAME, 0, 0); - // if (fNbt) - // gui.drawResource(Resource.LBL_FR_UL, 0, 0); - // if (fMeta) - // gui.drawResource(Resource.LBL_FR_UR, 0, 0); + // if (fNbt || fMeta) + // gui.drawResource(Resource.LBL_FRAME, 0, 0); + // if (fNbt) + // gui.drawResource(Resource.LBL_FR_UL, 0, 0); + // if (fMeta) + // gui.drawResource(Resource.LBL_FR_UR, 0, 0); } @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 70ed601a1..31429bdfd 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 @@ -1,14 +1,22 @@ 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.HashSet; import java.util.List; import java.util.stream.Collectors; + import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; + +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.oredict.OreDictionary; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import me.towdium.jecalculation.Tags; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.gui.JecaGui; @@ -16,18 +24,14 @@ import me.towdium.jecalculation.utils.ItemStackHelper; import me.towdium.jecalculation.utils.Utilities; import me.towdium.jecalculation.utils.wrappers.Wrapper; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.oredict.OreDictionary; /** * Author: towdium - * Date: 17-9-10. + * Date: 17-9-10. */ @ParametersAreNonnullByDefault public class LOreDict extends ILabel.Impl { + public static final String IDENTIFIER = "oreDict"; public static final String KEY_NAME = "name"; public static final boolean MODE_FORCE = false; @@ -57,7 +61,8 @@ public static boolean mergeSame(ILabel a, ILabel b) { if (a instanceof LOreDict && b instanceof LOreDict) { LOreDict lodA = (LOreDict) a; LOreDict lodB = (LOreDict) b; - return lodA.getName().equals(lodB.getName()); + return lodA.getName() + .equals(lodB.getName()); } else return false; } @@ -85,8 +90,8 @@ public static List suggest(List iss, @Nullable Class context) 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()); + .map(i -> new LOreDict(OreDictionary.getOreName(i), amount)) + .collect(Collectors.toList()); } public static List fallback(List iss, @Nullable Class context) { @@ -97,8 +102,8 @@ public static List fallback(List iss, @Nullable Class context 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()); + .map(i -> new LOreDict(OreDictionary.getOreName(i), amount)) + .collect(Collectors.toList()); } // check labels in the list suitable for the ore id 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 d81b8740a..b3a0739c0 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 @@ -1,7 +1,5 @@ package me.towdium.jecalculation.data.label.labels; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import java.util.Arrays; import java.util.List; import java.util.Objects; @@ -9,22 +7,28 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; + import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; + +import net.minecraft.nbt.NBTTagCompound; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; 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 - * Date: 17-9-28. + * Date: 17-9-28. */ @ParametersAreNonnullByDefault 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 @@ -69,7 +73,10 @@ public String getIdentifier() { } public static List getRecent() { - return getActive().toList().stream().map(LPlaceholder::copy).collect(Collectors.toList()); + return getActive().toList() + .stream() + .map(LPlaceholder::copy) + .collect(Collectors.toList()); } @Override @@ -129,32 +136,37 @@ public static boolean merge(ILabel a, ILabel b) { } public static class Converter { + @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") - static List>> converters = Arrays.asList(new Pair<>( + 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(" "); + String[] arr = s.replace('_', ' ') + .split(" "); StringBuilder sb = new StringBuilder(); for (String value : arr) { sb.append(Character.toUpperCase(value.charAt(0))); - sb.append(value.substring(1)).append(" "); + sb.append(value.substring(1)) + .append(" "); } - return sb.toString().trim(); + return sb.toString() + .trim(); } 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)); + .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 aa89ed70e..99f577153 100644 --- a/src/main/java/me/towdium/jecalculation/data/structure/CostList.java +++ b/src/main/java/me/towdium/jecalculation/data/structure/CostList.java @@ -4,8 +4,10 @@ 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; @@ -25,9 +27,11 @@ public 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) { @@ -68,11 +72,15 @@ public void mergeInplace(CostList that, boolean strict) { } } } - this.labels = this.labels.stream().filter(i -> i != ILabel.EMPTY).collect(Collectors.toList()); + this.labels = this.labels.stream() + .filter(i -> i != ILabel.EMPTY) + .collect(Collectors.toList()); } public CostList multiply(long i) { - labels = labels.stream().map(j -> j.multiply(i)).collect(Collectors.toList()); + labels = labels.stream() + .map(j -> j.multiply(i)) + .collect(Collectors.toList()); return this; } @@ -80,14 +88,17 @@ public CostList multiply(long i) { public boolean equals(Object obj) { if (obj instanceof CostList) { CostList c = (CostList) obj; - CostList m = c.copy().multiply(-1); + CostList m = c.copy() + .multiply(-1); return CostList.merge(this, m, true).labels.isEmpty(); } else return false; } public CostList copy() { CostList ret = new CostList(); - ret.labels = labels.stream().map(ILabel::copy).collect(Collectors.toList()); + ret.labels = labels.stream() + .map(ILabel::copy) + .collect(Collectors.toList()); return ret; } @@ -111,6 +122,7 @@ public int hashCode() { } public class Calculator { + ArrayList> procedure = new ArrayList<>(); ArrayList catalysts = new ArrayList<>(); Recipes.RecipeIterator iterator = Controller.recipeIterator(); @@ -126,14 +138,16 @@ public Calculator() throws ArithmeticException { int count = 0; while (next != null) { CostList original = getCurrent(); - List outL = next.one.getOutput().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.getInput().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 = CostList.merge(original, outC, false); @@ -173,7 +187,8 @@ private Pair find() { // 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(); } @@ -181,11 +196,14 @@ private Pair find() { } 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() { @@ -198,25 +216,32 @@ public List getCatalysts() { 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()); + List ret = procedure.stream() + .map(i -> i.two.labels.get(0)) + .collect(Collectors.toList()); Collections.reverse(ret); CostList cl = new CostList(ret).multiply(-1); CostList temp = new CostList(); diff --git a/src/main/java/me/towdium/jecalculation/data/structure/IRecord.java b/src/main/java/me/towdium/jecalculation/data/structure/IRecord.java index adc9627b5..c6bfbf866 100644 --- a/src/main/java/me/towdium/jecalculation/data/structure/IRecord.java +++ b/src/main/java/me/towdium/jecalculation/data/structure/IRecord.java @@ -7,5 +7,6 @@ * Date: 05/02/19 */ public interface IRecord { + NBTTagCompound serialize(); } 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 15a329304..8c323d819 100644 --- a/src/main/java/me/towdium/jecalculation/data/structure/Recipe.java +++ b/src/main/java/me/towdium/jecalculation/data/structure/Recipe.java @@ -10,21 +10,25 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; + import javax.annotation.ParametersAreNonnullByDefault; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + 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 - * Date: 17-10-6. + * Date: 17-10-6. */ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class Recipe { + public static final String KEY_INPUT = "input"; public static final String KEY_CATALYST = "catalyst"; public static final String KEY_OUTPUT = "output"; @@ -34,15 +38,18 @@ public class Recipe { public Recipe(NBTTagCompound nbt) { this( - readNbtList(nbt.getTagList(KEY_INPUT, 10)), - readNbtList(nbt.getTagList(KEY_CATALYST, 10)), - readNbtList(nbt.getTagList(KEY_OUTPUT, 10))); + 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; @@ -51,16 +58,17 @@ public Recipe(List input, List catalyst, List output) { 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); @@ -73,7 +81,8 @@ public boolean equals(Object obj) { 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; + 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); @@ -126,7 +135,8 @@ public NBTTagCompound serialize() { } NBTTagList r = new NBTTagList(); - new Utilities.ReversedIterator<>(labels).stream().forEach(l -> r.appendTag(ILabel.SERIALIZER.serialize(l))); + new Utilities.ReversedIterator<>(labels).stream() + .forEach(l -> r.appendTag(ILabel.SERIALIZER.serialize(l))); return r; }; ret.setTag(KEY_INPUT, convert.apply(input)); @@ -137,25 +147,30 @@ public NBTTagCompound serialize() { public Optional matches(ILabel label) { return output.stream() - .filter(i -> ILabel.MERGER.merge(label, i).isPresent()) - .findAny(); + .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); + .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; 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 60bdcc329..1a1ffaaaa 100644 --- a/src/main/java/me/towdium/jecalculation/data/structure/Recipes.java +++ b/src/main/java/me/towdium/jecalculation/data/structure/Recipes.java @@ -6,8 +6,13 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; + import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + import me.towdium.jecalculation.JecaConfig; import me.towdium.jecalculation.JustEnoughCalculation; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; @@ -15,16 +20,15 @@ import me.towdium.jecalculation.utils.Utilities; import me.towdium.jecalculation.utils.Utilities.ReversedIterator; import me.towdium.jecalculation.utils.wrappers.Pair; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; /** * Author: towdium - * Date: 18-8-28. + * Date: 18-8-28. */ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class Recipes { + HashMap> records = new HashMap<>(); public Recipes() { @@ -42,11 +46,13 @@ public Recipes(NBTTagCompound nbt) { } protected void deserialize(NBTTagCompound nbt) { - //noinspection unchecked + // noinspection unchecked Set keySet = (Set) nbt.func_150296_c(); - keySet.stream().sorted().forEach(i -> { - NBTTagList group = nbt.getTagList(i, 10); - StreamSupport.stream(NBTHelper.spliterator(group), false) + 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 { @@ -55,11 +61,12 @@ protected void deserialize(NBTTagCompound nbt) { JustEnoughCalculation.logger.warn("Invalid recipe record :" + r); } }); - }); + }); } public void add(String group, Recipe recipe) { - records.computeIfAbsent(group, k -> new ArrayList<>()).add(recipe); + records.computeIfAbsent(group, k -> new ArrayList<>()) + .add(recipe); } public void renameGroup(String old, String neu) { @@ -81,7 +88,8 @@ public void modify(String neu, @Nullable String old, int index, @Nullable Recipe } public void set(String group, int index, Recipe recipe) { - records.get(group).set(index, recipe); + records.get(group) + .set(index, recipe); } public void set(String neu, String old, int index, Recipe recipe) { @@ -94,7 +102,9 @@ public int size() { } public Stream>> stream() { - return records.entrySet().stream().map(i -> new Pair<>(i.getKey(), i.getValue())); + return records.entrySet() + .stream() + .map(i -> new Pair<>(i.getKey(), i.getValue())); } public void remove(String group, int index) { @@ -112,7 +122,10 @@ public Recipe getRecipe(String group, int index) { } public List getRecipes() { - return records.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); + return records.values() + .stream() + .flatMap(Collection::stream) + .collect(Collectors.toList()); } public List getRecipes(String group) { @@ -144,7 +157,10 @@ public NBTTagCompound serialize(Collection groups) { } public List getGroups() { - return records.keySet().stream().sorted().collect(Collectors.toList()); + return records.keySet() + .stream() + .sorted() + .collect(Collectors.toList()); } public NBTTagCompound serialize() { @@ -160,6 +176,7 @@ public RecipeIterator recipeIterator(String group) { } public class RecipeIterator implements Iterator { + String group; int index; Iterator i; @@ -170,7 +187,8 @@ public RecipeIterator() { } public RecipeIterator(String group) { - i = Collections.singleton(group).iterator(); + i = Collections.singleton(group) + .iterator(); } @Override @@ -188,7 +206,7 @@ public boolean hasNext() { @Override public Recipe next() { - //noinspection ResultOfMethodCallIgnored + // noinspection ResultOfMethodCallIgnored hasNext(); index--; return j.next(); 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 4fe7a435a..e03f52a30 100644 --- a/src/main/java/me/towdium/jecalculation/data/structure/RecordCraft.java +++ b/src/main/java/me/towdium/jecalculation/data/structure/RecordCraft.java @@ -4,17 +4,20 @@ import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; + 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 * Date: 19-1-20 */ public class RecordCraft implements IRecord { + public static final String KEY_RECENTS = "recents"; public static final String KEY_AMOUNT = "amount"; public static final String KEY_INVENTORY = "inventory"; @@ -27,16 +30,19 @@ 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); String s = nbt.getString(KEY_MODE); mode = Mode.INPUT; for (Mode m : Mode.values()) { - if (s.equals(m.toString().toLowerCase())) mode = m; + if (s.equals( + m.toString() + .toLowerCase())) + mode = m; } } @@ -46,11 +52,14 @@ public boolean push(ILabel label, boolean replace) { } public ILabel getLatest() { - return record.size() == 0 ? ILabel.EMPTY : record.toList().get(0); + return record.size() == 0 ? ILabel.EMPTY + : record.toList() + .get(0); } public List getHistory() { - return record.size() > 1 ? record.toList().subList(1, record.size()) : new ArrayList<>(); + return record.size() > 1 ? record.toList() + .subList(1, record.size()) : new ArrayList<>(); } @Override @@ -59,9 +68,13 @@ public NBTTagCompound serialize() { ret.setBoolean(KEY_INVENTORY, inventory); ret.setString(KEY_AMOUNT, amount); NBTTagList recent = new NBTTagList(); - record.toList().forEach(l -> recent.appendTag(ILabel.SERIALIZER.serialize(l))); + record.toList() + .forEach(l -> recent.appendTag(ILabel.SERIALIZER.serialize(l))); ret.setTag(KEY_RECENTS, recent); - ret.setString(KEY_MODE, mode.toString().toLowerCase()); + ret.setString( + KEY_MODE, + mode.toString() + .toLowerCase()); return ret; } 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 84d486682..27c2889af 100644 --- a/src/main/java/me/towdium/jecalculation/data/structure/RecordMath.java +++ b/src/main/java/me/towdium/jecalculation/data/structure/RecordMath.java @@ -5,6 +5,7 @@ import java.math.RoundingMode; import java.util.LinkedList; import java.util.List; + import net.minecraft.nbt.NBTTagCompound; /** @@ -12,6 +13,7 @@ * Date: 19-1-20 */ public class RecordMath implements IRecord { + public static MathContext context = new MathContext(7, RoundingMode.HALF_UP); public static final int DOT_NONE = -1; static final String KEY_CURRENT = "current"; @@ -31,6 +33,7 @@ public enum State { } public enum Operator { + EQUALS, PLUS, MINUS, @@ -55,8 +58,8 @@ public BigDecimal operate(BigDecimal a, BigDecimal b) { } } - 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; 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 eb782642b..6322ef85e 100644 --- a/src/main/java/me/towdium/jecalculation/data/structure/RecordPlayer.java +++ b/src/main/java/me/towdium/jecalculation/data/structure/RecordPlayer.java @@ -7,6 +7,7 @@ * Date: 19-1-21 */ public class RecordPlayer implements IRecord { + public static final String KEY_RECIPES = "recipes"; public static final String KEY_LAST = "last"; diff --git a/src/main/java/me/towdium/jecalculation/event/Handlers.java b/src/main/java/me/towdium/jecalculation/event/Handlers.java index 9c58bbaf8..17353858c 100644 --- a/src/main/java/me/towdium/jecalculation/event/Handlers.java +++ b/src/main/java/me/towdium/jecalculation/event/Handlers.java @@ -1,14 +1,17 @@ package me.towdium.jecalculation.event; +import java.util.ArrayList; + +import net.minecraftforge.common.MinecraftForge; + 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; public class Handlers { + public static final ArrayList fmlHandlers; public static final ArrayList ebHandlers; @@ -21,7 +24,9 @@ public class Handlers { } public static void register() { - Handlers.fmlHandlers.forEach(FMLCommonHandler.instance().bus()::register); + Handlers.fmlHandlers.forEach( + FMLCommonHandler.instance() + .bus()::register); Handlers.ebHandlers.forEach(MinecraftForge.EVENT_BUS::register); GuiContainerManager.addInputHandler(new NEIEventHandler()); } 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 806bf6683..c57f315d5 100644 --- a/src/main/java/me/towdium/jecalculation/event/handlers/EBusEventHandler.java +++ b/src/main/java/me/towdium/jecalculation/event/handlers/EBusEventHandler.java @@ -3,4 +3,5 @@ /** * 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 074a401d5..a0b676b31 100644 --- a/src/main/java/me/towdium/jecalculation/event/handlers/FMLBusEventHandler.java +++ b/src/main/java/me/towdium/jecalculation/event/handlers/FMLBusEventHandler.java @@ -13,10 +13,11 @@ /** * Author: towdium - * Date: 8/13/17. + * Date: 8/13/17. */ @SuppressWarnings("unused") public class FMLBusEventHandler { + @SideOnly(Side.CLIENT) @SubscribeEvent(receiveCanceled = true) public void onKey(InputEvent.KeyInputEvent event) { 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 a17393c07..5230da5f7 100644 --- a/src/main/java/me/towdium/jecalculation/event/handlers/NEIEventHandler.java +++ b/src/main/java/me/towdium/jecalculation/event/handlers/NEIEventHandler.java @@ -1,15 +1,17 @@ package me.towdium.jecalculation.event.handlers; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.inventory.GuiContainer; + import codechicken.nei.NEIClientConfig; import codechicken.nei.NEIClientUtils; import codechicken.nei.guihook.IContainerInputHandler; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.nei.NEIPlugin; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.inventory.GuiContainer; public class NEIEventHandler implements IContainerInputHandler { + @Override public boolean keyTyped(GuiContainer guiContainer, char c, int i) { return false; @@ -27,7 +29,7 @@ public boolean lastKeyTyped(GuiContainer guiContainer, char keyChar, int keyCode Object stack = label.getRepresentation(); if (keyCode == NEIClientConfig.getKeyBinding("gui.usage") - || (keyCode == NEIClientConfig.getKeyBinding("gui.recipe") && NEIClientUtils.shiftKey())) { + || (keyCode == NEIClientConfig.getKeyBinding("gui.recipe") && NEIClientUtils.shiftKey())) { return NEIPlugin.openRecipeGui(stack, true); } if (keyCode == NEIClientConfig.getKeyBinding("gui.recipe")) { diff --git a/src/main/java/me/towdium/jecalculation/gui/JecaGui.java b/src/main/java/me/towdium/jecalculation/gui/JecaGui.java index b23feb708..83f47ff1a 100644 --- a/src/main/java/me/towdium/jecalculation/gui/JecaGui.java +++ b/src/main/java/me/towdium/jecalculation/gui/JecaGui.java @@ -2,24 +2,14 @@ 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.nei.NEIPlugin; -import me.towdium.jecalculation.polyfill.mc.client.renderer.GlStateManager; -import me.towdium.jecalculation.utils.ItemStackHelper; -import me.towdium.jecalculation.utils.Utilities; -import me.towdium.jecalculation.utils.wrappers.Wrapper; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiScreen; @@ -36,20 +26,39 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.fluids.Fluid; + import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; +import cpw.mods.fml.client.config.GuiUtils; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +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.nei.NEIPlugin; +import me.towdium.jecalculation.polyfill.mc.client.renderer.GlStateManager; +import me.towdium.jecalculation.utils.ItemStackHelper; +import me.towdium.jecalculation.utils.Utilities; +import me.towdium.jecalculation.utils.wrappers.Wrapper; + /** * Author: towdium - * Date: 8/12/17. + * Date: 8/12/17. */ @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; @@ -154,7 +163,8 @@ public static void displayGui(boolean updateParent, boolean acceptsTransfer, IGu 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; @@ -173,8 +183,8 @@ public static Optional currentJecaGui() { /** * @return The currently displayed {@link JecaGui} - * Make sure the method is called when a {@link JecaGui} is displayed! - * Otherwise it will throw a {@link NullPointerException} + * Make sure the method is called when a {@link JecaGui} is displayed! + * Otherwise it will throw a {@link NullPointerException} */ public static JecaGui getCurrent() { GuiScreen gui = Minecraft.getMinecraft().currentScreen; @@ -199,7 +209,8 @@ public static void displayParent() { JecaGui gui = getCurrent().parent; gui.root.onVisible(gui); last = gui; - Minecraft.getMinecraft().displayGuiScreen(gui); + Minecraft.getMinecraft() + .displayGuiScreen(gui); } @Nullable @@ -212,7 +223,8 @@ public ILabel getLabelUnderMouse() { /** * Called by {@link me.towdium.jecalculation.event.handlers.FMLBusEventHandler}. * This event happened only when not in gui. - * For nei keybinding event, see {@link me.towdium.jecalculation.event.handlers.NEIEventHandler#lastKeyTyped(GuiContainer, char, int)} + * For nei keybinding event, see + * {@link me.towdium.jecalculation.event.handlers.NEIEventHandler#lastKeyTyped(GuiContainer, char, int)} * I think they won't conflict */ public static void onKey() { @@ -275,7 +287,7 @@ public void drawScreen(int mouseX, int mouseY, float partialTicks) { @Override // modified from vanilla public void drawHoveringText(List lines, int x, int y, FontRenderer font) { - //noinspection unchecked + // noinspection unchecked List textLines = (List) lines; if (!textLines.isEmpty()) { GlStateManager.disableRescaleNormal(); @@ -287,10 +299,10 @@ public void drawHoveringText(List lines, int x, int y, FontRenderer font) { for (String s : textLines) { int j = font.getStringWidth(s); if (j > i) i = j; - //noinspection StringEquality + // noinspection StringEquality if (s == JecaGui.SEPARATOR) separators++; } - //noinspection StringEquality + // noinspection StringEquality if (textLines.get(textLines.size() - 1) == SEPARATOR) separators--; int l1 = x + 12; int i2 = y - 12; @@ -309,7 +321,7 @@ public void drawHoveringText(List lines, int x, int y, FontRenderer font) { drawGradientRect(l1 - 3, i2 - 3, l1 + i + 3, i2 - 3 + 1, 1347420415, 1347420415); drawGradientRect(l1 - 3, i2 + k + 2, l1 + i + 3, i2 + k + 3, 1344798847, 1344798847); for (String s1 : textLines) { - //noinspection StringEquality + // noinspection StringEquality if (s1 == SEPARATOR) i2 += 2; else { font.drawStringWithShadow(s1, l1, i2, -1); @@ -331,7 +343,8 @@ public void drawResource(Resource r, int xPos, int yPos) { public void drawResource(Resource r, int xPos, int yPos, int color) { setColor(color); - mc.getTextureManager().bindTexture(r.getResourceLocation()); + mc.getTextureManager() + .bindTexture(r.getResourceLocation()); drawTexturedModalRect(xPos, yPos, r.getXPos(), r.getYPos(), r.getXSize(), r.getYSize()); } @@ -339,31 +352,23 @@ public void drawResourceContinuous(Resource r, int xPos, int yPos, int xSize, in 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) { + 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); + r.getResourceLocation(), + xPos, + yPos, + r.getXPos(), + r.getYPos(), + xSize, + ySize, + r.getXSize(), + r.getYSize(), + borderTop, + borderBottom, + borderLeft, + borderRight, + 0); } private void setColor(int color) { @@ -431,8 +436,8 @@ public void drawText(float xPos, float yPos, int width, Font f, String s) { String str = s; int strWidth = f.getTextWidth(str); int ellipsisWidth = f.getTextWidth("..."); - if (strWidth > width && strWidth > ellipsisWidth) - str = f.trimToWidth(str, width - ellipsisWidth).trim() + "..."; + if (strWidth > width && strWidth > ellipsisWidth) str = f.trimToWidth(str, width - ellipsisWidth) + .trim() + "..."; if (f.shadow) fontRendererObj.drawStringWithShadow(str, 0, 0, f.color); fontRendererObj.drawString(str, 0, 0, f.color); }); @@ -460,7 +465,8 @@ public void drawItemStack(int xPos, int yPos, ItemStack is, boolean centred) { float zLevel = itemRender.zLevel += 100F; GlStateManager.enableDepth(); RenderHelper.enableGUIStandardItemLighting(); - FontRenderer font = is.getItem().getFontRenderer(is); + FontRenderer font = is.getItem() + .getFontRenderer(is); if (font == null) font = this.fontRendererObj; itemRender.renderItemAndEffectIntoGUI(font, Minecraft.getMinecraft().renderEngine, is, xPos, yPos); itemRender.renderItemOverlayIntoGUI(font, Minecraft.getMinecraft().renderEngine, is, xPos, yPos); @@ -486,6 +492,7 @@ else if (!root.onKeyPressed(this, typedChar, keyCode)) { @SideOnly(Side.CLIENT) public static class Font { + public static final Font SHADOW = new Font(JecaGui.COLOR_TEXT_WHITE, true, false, false); public static final Font PLAIN = new Font(JecaGui.COLOR_TEXT_GREY, false, false, false); public static final Font RAW = new Font(JecaGui.COLOR_TEXT_GREY, false, false, true); @@ -521,6 +528,7 @@ public String trimToWidth(String s, int i) { @SideOnly(Side.CLIENT) public static class JecaContainer extends Container { + JecaGui gui; public JecaGui getGui() { @@ -538,10 +546,12 @@ public boolean canInteractWith(EntityPlayer playerIn) { } @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 41ec11129..ea151e1b1 100644 --- a/src/main/java/me/towdium/jecalculation/gui/Resource.java +++ b/src/main/java/me/towdium/jecalculation/gui/Resource.java @@ -1,18 +1,21 @@ package me.towdium.jecalculation.gui; +import javax.annotation.ParametersAreNonnullByDefault; + +import net.minecraft.util.ResourceLocation; + import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import javax.annotation.ParametersAreNonnullByDefault; import me.towdium.jecalculation.Tags; -import net.minecraft.util.ResourceLocation; /** * Author: towdium - * Date: 17-8-17. + * Date: 17-8-17. */ @ParametersAreNonnullByDefault @SideOnly(Side.CLIENT) public class Resource { + 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 @@ -265,6 +268,7 @@ private static Resource getLabel(int x) { } public static class ResourceGroup { + public Resource normal; public Resource focused; public Resource disabled; 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 dae381d90..ee410c4d7 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/Gui.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/Gui.java @@ -2,6 +2,7 @@ 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; @@ -9,6 +10,7 @@ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class Gui extends WContainer implements IGui { + protected WContainer overlay = new WContainer(); protected WContainer widgets = new WContainer(); 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 3d523ebec..63fb459c4 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/GuiCraft.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/GuiCraft.java @@ -2,13 +2,18 @@ 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 net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import me.towdium.jecalculation.data.Controller; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.data.structure.CostList; @@ -22,42 +27,49 @@ import me.towdium.jecalculation.utils.ItemStackHelper; import me.towdium.jecalculation.utils.Utilities; import me.towdium.jecalculation.utils.wrappers.Pair; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; /** * Author: towdium - * Date: 8/14/17. + * Date: 8/14/17. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) 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(); + ILabel l = i.get(v) + .getLabel(); if (l != ILabel.EMPTY) { - label.setLabel(i.get(v).getLabel().copy(), true); + 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)); + 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"); @@ -72,14 +84,17 @@ 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") + 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") + 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") + 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)); @@ -138,8 +153,10 @@ void refreshCalculator() { 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) { @@ -153,8 +170,8 @@ List getInventory() { 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; @@ -190,11 +207,16 @@ private void refreshLabel(ILabel l, boolean replace, boolean suggest) { Pair, List> guess = ILabel.CONVERTER.guess(Collections.singletonList(l), null); LinkedHashSet match = new LinkedHashSet<>(); List fuzzy = new ArrayList<>(); - 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); - }); + 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); + }); match.addAll(fuzzy); List list = new ArrayList<>(match); if (!match.isEmpty()) setOverlay(new Suggest(list.size() > 3 ? list.subList(0, 3) : list, !dup)); @@ -202,27 +224,31 @@ private void refreshLabel(ILabel l, boolean replace, boolean suggest) { } 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 { + boolean replace; public Suggest(List labels, boolean replace) { this.replace = replace; int width = labels.size() * 20; add(new WPanel(-width, 2, 56 + width, 30)); - add(new WLabel(31, 7, 20, 20, false).setLabel(label.getLabel()).setLsnrUpdate((i, v) -> refresh(v))); + add( + new WLabel(31, 7, 20, 20, false).setLabel(label.getLabel()) + .setLsnrUpdate((i, v) -> refresh(v))); 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)) + 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 59b9ef82e..710138120 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/GuiImport.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/GuiImport.java @@ -7,7 +7,9 @@ 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; @@ -24,40 +26,47 @@ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class GuiImport extends Gui implements ISearchable { + 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() { add(new WHelp("import"), new WPanel()); 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) + 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)); + confirm.setDisabled( + data.stream() + .noneMatch(k -> k.one)); }); - WText text = new WTextExpand(49 + 16 * i, ""); - add(tick, text); - content.add(new Pair<>(tick, text)); - }); + WText text = new WTextExpand(49 + 16 * i, ""); + add(tick, text); + content.add(new Pair<>(tick, text)); + }); } @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(); } @@ -66,11 +75,13 @@ public void refresh() { Pair pair = content.get(i); int index = i + 7 * page.getIndex(); if (index >= filtered.size()) { - pair.one.setSelected(false).setDisabled(true); + pair.one.setSelected(false) + .setDisabled(true); pair.two.key = ""; } else { Quad quad = filtered.get(index); - pair.one.setSelected(quad.one).setDisabled(false); + pair.one.setSelected(quad.one) + .setDisabled(false); pair.two.key = quad.two + " -> " + quad.three; } } @@ -79,10 +90,9 @@ public void refresh() { @Override public boolean setFilter(String s) { 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()); + else filtered = data.stream() + .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); @@ -91,6 +101,7 @@ public boolean setFilter(String s) { } private static class WTextExpand extends WText { + boolean expand = false; public WTextExpand(int yPos, String 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 1b3a390dc..28d7e9629 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/GuiLabel.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/GuiLabel.java @@ -1,12 +1,15 @@ package me.towdium.jecalculation.gui.guis; +import java.util.function.Consumer; + +import javax.annotation.ParametersAreNonnullByDefault; + import com.google.common.cache.CacheBuilder; 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; @@ -18,32 +21,38 @@ /** * Author: towdium - * Date: 17-9-14. + * Date: 17-9-14. */ @SuppressWarnings("UnstableApiUsage") @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class GuiLabel extends Gui { + WContainer container = new WContainer(); IPicker current; Consumer callback; - LoadingCache cache = CacheBuilder.newBuilder().build(new CacheLoader() { - @Override - public IPicker load(Integer i) { - ILabel.RegistryEditor.Record record = ILabel.EDITOR.getRecords().get(i); - return record.editor.get().setCallback(callback); - } - }); + LoadingCache cache = CacheBuilder.newBuilder() + .build(new CacheLoader() { + + @Override + public IPicker load(Integer i) { + ILabel.RegistryEditor.Record record = ILabel.EDITOR.getRecords() + .get(i); + return record.editor.get() + .setCallback(callback); + } + }); public GuiLabel(Consumer callback) { this.callback = callback; Wrapper index = new Wrapper<>(0); - ILabel.EDITOR.getRecords().forEach(r -> { - int i = index.value; - add(new WPage(i, r, false).setListener(j -> refresh(i))); - index.value += 1; - }); + ILabel.EDITOR.getRecords() + .forEach(r -> { + int i = index.value; + add(new WPage(i, r, false).setListener(j -> refresh(i))); + index.value += 1; + }); add(new WHelp("label"), new WPanel()); add(container); refresh(0); @@ -58,6 +67,11 @@ protected void refresh(int index) { container.clear(); current = cache.getUnchecked(index); container.add(current); - container.add(new WPage(index, ILabel.EDITOR.getRecords().get(index), true)); + container.add( + new WPage( + index, + ILabel.EDITOR.getRecords() + .get(index), + true)); } } 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 eaa887c7a..bb0c80a54 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/GuiMath.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/GuiMath.java @@ -6,7 +6,11 @@ import java.math.BigDecimal; import java.util.LinkedList; import java.util.stream.Collectors; + import javax.annotation.ParametersAreNonnullByDefault; + +import org.lwjgl.input.Keyboard; + import me.towdium.jecalculation.data.Controller; import me.towdium.jecalculation.data.structure.RecordMath; import me.towdium.jecalculation.data.structure.RecordMath.Operator; @@ -15,7 +19,6 @@ import me.towdium.jecalculation.gui.widgets.*; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.utils.Utilities; -import org.lwjgl.input.Keyboard; /** * Author: Towdium @@ -24,6 +27,7 @@ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class GuiMath extends Gui { + WLcd lcd = new WLcd(7); LinkedList numbers; BigDecimal last; @@ -35,63 +39,63 @@ 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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()) + 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()) + 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)) + 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()) + 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)) + 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)) + 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)) + 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)) + 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(); @@ -106,9 +110,10 @@ public GuiMath() { private void print() { if (state == State.INPUT) { - String s = numbers.isEmpty() - ? "0" - : numbers.stream().map(Object::toString).collect(Collectors.joining()); + 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; @@ -191,7 +196,8 @@ private void reset() { 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(); 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 193c6e970..d8eddd8ff 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/GuiRecipe.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/GuiRecipe.java @@ -5,11 +5,15 @@ 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 org.lwjgl.input.Keyboard; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import me.towdium.jecalculation.data.Controller; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.data.structure.CostList; @@ -21,16 +25,16 @@ import me.towdium.jecalculation.utils.Utilities; import me.towdium.jecalculation.utils.wrappers.Pair; import me.towdium.jecalculation.utils.wrappers.Trio; -import org.lwjgl.input.Keyboard; /** * Author: towdium - * Date: 17-9-8. + * Date: 17-9-8. */ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault @SideOnly(Side.CLIENT) public class GuiRecipe extends Gui { + Pair dest; WSwitcher group = new WSwitcher(7, 7, 162, Controller.getGroups()).setListener(i -> refresh()); WTextField text = new WTextField(49, 25, 119); @@ -44,29 +48,27 @@ public class GuiRecipe extends Gui { JecaGui.displayParent(); }); 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(); - }); + .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 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); @@ -76,29 +78,37 @@ public GuiRecipe(String group, int index) { dest = new Pair<>(group, index); Recipe r = Controller.getRecipe(group, index); for (IO i : IO.values()) { - getWidget(i).setLabels(r.getLabel(i).stream().map(ILabel::copy).collect(Collectors.toList())); + getWidget(i).setLabels( + r.getLabel(i) + .stream() + .map(ILabel::copy) + .collect(Collectors.toList())); } - this.group.setIndex(Controller.getGroups().indexOf(group)); + this.group.setIndex( + Controller.getGroups() + .indexOf(group)); refresh(); } 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")); @@ -106,14 +116,19 @@ public GuiRecipe() { 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 (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())); + text.setListener( + i -> yes.setDisabled( + i.getText() + .isEmpty())); } public WLabelScroll getWidget(IO type) { @@ -165,20 +180,22 @@ public void transfer(EnumMap>> recipe, 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; for (int i = 0; i < l.size(); i++) { Trio p = l.get(i); ret.add(p.one); - if (p.two.getLabels().size() > 1) { + if (p.two.getLabels() + .size() > 1) { List raw = p.two.getLabels(); List suggest = new ArrayList<>(); suggest.addAll(ILabel.CONVERTER.guess(raw, context).one); suggest.addAll(raw); - disamb.computeIfAbsent(type, j -> new HashMap<>()).put(i, suggest); + disamb.computeIfAbsent(type, j -> new HashMap<>()) + .put(i, suggest); } } return ret; @@ -220,6 +237,7 @@ static boolean handleLabelScroll(WLabel w, int diff) { } class WAmount extends WOverlay { + WLabel temp; WButton number; WTextField text; @@ -235,15 +253,19 @@ public WAmount(IO type, int idx) { int x = ref.xPos; int y = ref.yPos; number = new WButtonText(x + 78, y - 1, 20, 20, "#", "recipe.to_percent").setListener(i -> { - temp.getLabel().setPercent(true); + temp.getLabel() + .setPercent(true); update(); }); percent = new WButtonText(x + 78, y - 1, 20, 20, "%", "recipe.to_amount").setListener(i -> { - temp.getLabel().setPercent(false); + temp.getLabel() + .setPercent(false); update(); }); temp = new WLabel(x - 1, y - 1, 20, 20, true).setLsnrUpdate((i, v) -> update()); - temp.setLabel(ref.getLabel().copy()); + temp.setLabel( + ref.getLabel() + .copy()); add(new WPanel(x - 7, y - 30, 111, 55)); add(new WText(x + 21, y + 5, PLAIN, "x")); text = new WTextField(x + 28, y + 9 - WTextField.HEIGHT / 2, 50); @@ -252,9 +274,9 @@ public WAmount(IO type, int idx) { 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)); + .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)); + .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)) { @@ -269,12 +291,15 @@ public WAmount(IO type, int idx) { acceptable = amount > 0; if (!acceptable) amount = 1; } catch (NumberFormatException e) { - acceptable = text.getText().isEmpty(); + acceptable = text.getText() + .isEmpty(); amount = 1; } text.setColor(acceptable ? COLOR_TEXT_WHITE : COLOR_TEXT_RED); yes.setDisabled(!acceptable); - temp.setLabel(temp.getLabel().setAmount(amount)); + temp.setLabel( + temp.getLabel() + .setAmount(amount)); }); update(); } @@ -286,19 +311,26 @@ private void set(ILabel l, IO type, int idx) { } private void update() { - number.setDisabled(!temp.getLabel().acceptPercent()); - if (temp.getLabel().isPercent()) { + number.setDisabled( + !temp.getLabel() + .acceptPercent()); + if (temp.getLabel() + .isPercent()) { remove(number); add(percent); } else { remove(percent); add(number); } - text.setText(Long.toString(temp.getLabel().getAmount())); + text.setText( + Long.toString( + temp.getLabel() + .getAmount())); } } class WDisamb extends WOverlay { + WLabel temp; WLabelScroll content; WTextField search; @@ -310,14 +342,22 @@ public WDisamb(IO type, int idx) { int y = ref.yPos; 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(); - }); + 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(); + }); 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 fac519217..8fd3d4647 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/GuiSearch.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/GuiSearch.java @@ -6,7 +6,11 @@ import java.util.IdentityHashMap; import java.util.List; import java.util.function.Consumer; + import javax.annotation.ParametersAreNonnullByDefault; + +import org.lwjgl.input.Keyboard; + import me.towdium.jecalculation.data.Controller; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.data.structure.Recipe; @@ -16,34 +20,35 @@ import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.utils.Utilities; import me.towdium.jecalculation.utils.wrappers.Trio; -import org.lwjgl.input.Keyboard; @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(); + 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 yes = new WButtonIcon(149, 25, 20, 20, BTN_YES, "search.confirm") - .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 yes = new WButtonIcon(149, 25, 20, 20, BTN_YES, "search.confirm").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 export1 = new WButtonIcon(111, 25, 20, 20, BTN_EXPORT_1, "search.export_group") - .setListener(i -> Controller.export(group.getText())); + .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); + Controller.getGroups() + .forEach(Controller::removeGroup); refreshGroups(); refreshDisplay(); }); @@ -53,7 +58,7 @@ public class GuiSearch extends Gui { refreshDisplay(); }); WButton inport = new WButtonIcon(92, 25, 20, 20, BTN_IMPORT, "search.import") - .setListener(i -> JecaGui.displayGui(new GuiImport())); + .setListener(i -> JecaGui.displayGui(new GuiImport())); 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); @@ -62,7 +67,9 @@ public class GuiSearch extends Gui { public GuiSearch() { text.setListener(i -> { String s = i.getText(); - yes.setDisabled(s.isEmpty() || Controller.getGroups().contains(s)); + yes.setDisabled( + s.isEmpty() || Controller.getGroups() + .contains(s)); }); add(new WHelp("search"), new WPanel()); add(labels, icon, search, inport, exportN, deleteN, rename); @@ -77,9 +84,11 @@ private void generate() { identifiers.add(id); }; - 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); + 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); } @Override @@ -134,6 +143,7 @@ private void setRename(boolean b) { } class Overlay extends WOverlay { + public Overlay(WLabel l) { Trio recipe = recipes.get(l.getLabel()); int x = l.xPos - 1; 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 71f8e3c87..a0787fd8e 100644 --- a/src/main/java/me/towdium/jecalculation/gui/guis/IGui.java +++ b/src/main/java/me/towdium/jecalculation/gui/guis/IGui.java @@ -12,6 +12,7 @@ */ @SideOnly(Side.CLIENT) public interface IGui extends IContainer { + default void onVisible(JecaGui gui) {} default boolean acceptsTransfer() { 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 148c212fa..245d2a616 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 @@ -1,9 +1,11 @@ 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 cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.gui.guis.Gui; import me.towdium.jecalculation.gui.guis.IGui; @@ -11,15 +13,17 @@ /** * Author: towdium - * Date: 17-9-28. + * Date: 17-9-28. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public interface IPicker extends IGui { + IPicker setCallback(Consumer callback); class Impl extends Gui implements IPicker { + protected Consumer callback; @Override 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 35ebe00d7..0be474262 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 @@ -2,9 +2,10 @@ import static me.towdium.jecalculation.gui.Resource.*; +import javax.annotation.ParametersAreNonnullByDefault; + 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; @@ -19,15 +20,16 @@ @ParametersAreNonnullByDefault @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())); + .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; @@ -66,7 +68,10 @@ private void setF(boolean b, WButton be, WButton bd, Runnable r) { r.run(); if (raw instanceof LItemStack) { LItemStack lis = (LItemStack) raw; - label.setLabel(lis.copy().setFMeta(fMeta).setFNbt(fNbt)); + label.setLabel( + lis.copy() + .setFMeta(fMeta) + .setFNbt(fNbt)); } } } 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 d37c54aaa..25fa34e3c 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 @@ -5,9 +5,10 @@ import static me.towdium.jecalculation.gui.Resource.BTN_YES; import static me.towdium.jecalculation.gui.Resource.ICN_TEXT; +import javax.annotation.ParametersAreNonnullByDefault; + 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.*; @@ -15,25 +16,33 @@ /** * Author: towdium - * Date: 17-9-29. + * Date: 17-9-29. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) 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)); + 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)); 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)); - })); + add( + new WButtonIcon(95, 7, 20, 20, BTN_YES, "common.confirm").setListener( + i -> { + 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 cb00d94d2..0fc82d611 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 @@ -2,12 +2,17 @@ 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 net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.oredict.OreDictionary; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.data.label.labels.LFluidStack; import me.towdium.jecalculation.data.label.labels.LOreDict; @@ -16,32 +21,37 @@ import me.towdium.jecalculation.gui.widgets.WLabelScroll; import me.towdium.jecalculation.gui.widgets.WSearch; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.oredict.OreDictionary; /** * Author: towdium - * Date: 17-9-28. + * Date: 17-9-28. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) 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) - .setLsnrLeftClick((i, v) -> notifyLsnr(i.get(v).getLabel())); + 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() + 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)) @@ -50,15 +60,18 @@ public FluidStack() { } public static class OreDict extends PickerSimple { + public OreDict() { super(generate()); } 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/IContainer.java b/src/main/java/me/towdium/jecalculation/gui/widgets/IContainer.java index 3fff4692a..02fd37c44 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/IContainer.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/IContainer.java @@ -5,6 +5,7 @@ * Date: 18-9-25 */ public interface IContainer extends IWidget { + void add(IWidget... w); void remove(IWidget... w); diff --git a/src/main/java/me/towdium/jecalculation/gui/widgets/ISearchable.java b/src/main/java/me/towdium/jecalculation/gui/widgets/ISearchable.java index 8d76c3895..b0ce01bc6 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/ISearchable.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/ISearchable.java @@ -5,5 +5,6 @@ * Date: 18-12-7 */ public interface ISearchable extends IWidget { + boolean setFilter(String s); } 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 a3be3ca33..5e481128c 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/IWidget.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/IWidget.java @@ -1,17 +1,20 @@ 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; /** * Author: towdium - * Date: 8/14/17. + * Date: 8/14/17. */ @ParametersAreNonnullByDefault public interface IWidget { + default boolean onDraw(JecaGui gui, int xMouse, int yMouse) { return false; } @@ -44,11 +47,13 @@ default boolean getLabelUnderMouse(int xMouse, int yMouse, Wrapper label @FunctionalInterface interface ListenerValue { + void invoke(W widget, V value); } @FunctionalInterface interface ListenerAction { + void invoke(W widget); } } 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 067a07ad1..1e53259d9 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WButton.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WButton.java @@ -2,26 +2,30 @@ 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 org.lwjgl.input.Keyboard; + +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.ClientUtils; -import org.lwjgl.input.Keyboard; /** * Author: towdium - * Date: 17-8-17. + * Date: 17-8-17. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public abstract class WButton extends WTooltip { + protected int xPos, yPos, xSize, ySize; protected ListenerAction listener; protected boolean disabled; @@ -76,13 +80,12 @@ private void trigger() { @Override public boolean onKeyPressed(JecaGui gui, char ch, int code) { - if (keys != null) - for (int i : keys) { - if (i == code) { - trigger(); - return true; - } + if (keys != null) for (int i : keys) { + if (i == code) { + trigger(); + 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 1242a3404..39a3a940f 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WButtonIcon.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WButtonIcon.java @@ -1,19 +1,21 @@ package me.towdium.jecalculation.gui.widgets; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.gui.Resource; /** * Author: towdium - * Date: 17-9-16. + * Date: 17-9-16. */ @ParametersAreNonnullByDefault @SideOnly(Side.CLIENT) public class WButtonIcon extends WButton { + protected Resource rNormal, rFocused, rDisabled; public WButtonIcon(int xPos, int yPos, int xSize, int ySize, Resource.ResourceGroup res, String name) { @@ -24,15 +26,8 @@ public WButtonIcon(int xPos, int yPos, int xSize, int ySize, Resource.ResourceGr 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 556a9cc6f..b6c39b28f 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WButtonText.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WButtonText.java @@ -1,18 +1,20 @@ package me.towdium.jecalculation.gui.widgets; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import me.towdium.jecalculation.gui.JecaGui; /** * Author: towdium - * Date: 17-9-16. + * Date: 17-9-16. */ @ParametersAreNonnullByDefault @SideOnly(Side.CLIENT) public class WButtonText extends WButton { + public static final JecaGui.Font focused_u = new JecaGui.Font(0xFFFFA0, true, false, false); public static final JecaGui.Font normal_u = new JecaGui.Font(0xFFFFFF, true, false, false); public static final JecaGui.Font focused_r = new JecaGui.Font(0xFFFFA0, true, false, true); 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 5c68c9f7b..1b0d72c87 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WContainer.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WContainer.java @@ -1,11 +1,13 @@ 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 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; @@ -14,12 +16,13 @@ /** * Author: towdium - * Date: 17-9-14. + * Date: 17-9-14. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WContainer implements IContainer { + protected List widgets = new ArrayList<>(); public void add(IWidget... w) { @@ -41,17 +44,15 @@ public boolean contains(IWidget w) { @Override 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; - }); + widgets.forEach(widget -> { if (widget.onDraw(gui, mouseX, mouseY)) w.value = widget; }); 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 @@ -61,30 +62,31 @@ public void onMouseFocused(JecaGui gui, int xMouse, int yMouse, int button) { @Override public boolean onKeyPressed(JecaGui gui, char ch, int code) { - return new Utilities.ReversedIterator<>(widgets).stream().anyMatch(i -> i.onKeyPressed(gui, ch, code)); + return new Utilities.ReversedIterator<>(widgets).stream() + .anyMatch(i -> i.onKeyPressed(gui, ch, code)); } @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 0264306b8..416ed0087 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WHelp.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WHelp.java @@ -6,11 +6,14 @@ import java.util.ArrayList; import java.util.List; + import javax.annotation.ParametersAreNonnullByDefault; + +import org.lwjgl.input.Keyboard; + 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 @@ -19,6 +22,7 @@ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class WHelp extends WContainer { + protected String key; public WHelp(String content) { @@ -29,6 +33,7 @@ public WHelp(String content) { } private class Impl extends WTooltip { + public Impl() { super("common.help"); } @@ -55,6 +60,7 @@ public boolean onMouseClicked(JecaGui gui, int xMouse, int yMouse, int button) { } private class Doc extends WContainer { + Text text = new Text(); WSwitcher switcher = new WSwitcher(7, 146, 162, text.amount()).setListener(i -> text.setPage(i.getIndex())); @@ -77,6 +83,7 @@ public boolean onMouseScroll(JecaGui gui, int xMouse, int yMouse, int diff) { } public class Text implements IWidget { + List> pages = new ArrayList<>(); int page; @@ -119,6 +126,7 @@ public void setPage(int i) { } public class Icon extends WTooltip { + public Icon() { super("common.close"); } 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 5dcb14fa9..50e6039e4 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WIcon.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WIcon.java @@ -2,22 +2,24 @@ 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 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; /** * Author: towdium - * Date: 17-8-18. + * Date: 17-8-18. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WIcon extends WTooltip { + public int xPos, yPos, xSize, ySize; public Resource normal, focused; @@ -51,11 +53,11 @@ public boolean onDraw(JecaGui gui, int xMouse, int yMouse) { @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); + 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 e057289ec..ae48c9be0 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WLabel.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WLabel.java @@ -3,13 +3,15 @@ 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 codechicken.lib.gui.GuiDraw; +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; @@ -18,12 +20,13 @@ /** * Author: towdium - * Date: 17-8-17. + * Date: 17-8-17. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WLabel implements IWidget { + public int xPos, yPos, xSize, ySize; ILabel label = ILabel.EMPTY; public boolean accept; @@ -62,10 +65,10 @@ public boolean onDraw(JecaGui gui, int xMouse, int yMouse) { 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); + 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; 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 094a57f6b..da92a7d12 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WLabelGroup.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WLabelGroup.java @@ -1,25 +1,28 @@ 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.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 cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; /** * Author: towdium - * Date: 17-8-17. + * Date: 17-8-17. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WLabelGroup extends WContainer { + ArrayList labels = new ArrayList<>(); ListenerValue lsnrUpdate; ListenerValue lsnrLeftClick, lsnrRightClick; @@ -31,20 +34,17 @@ public WLabelGroup(int xPos, int yPos, int column, int row, boolean accept) { public WLabelGroup(int xPos, int yPos, int column, int row, int xSize, int ySize, boolean accept) { 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); - }); - labels.add(l); - add(l); - }); + 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); }); + labels.add(l); + add(l); + }); } } @@ -53,11 +53,14 @@ public WLabel get(int index) { } public List getLabels() { - return labels.stream().map(WLabel::getLabel).collect(Collectors.toList()); + return labels.stream() + .map(WLabel::getLabel) + .collect(Collectors.toList()); } public void setLabel(ILabel label, int index) { - labels.get(index).setLabel(label); + labels.get(index) + .setLabel(label); } public void setLabel(List labels, int start) { 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 fa5821e87..0fbc0b192 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WLabelScroll.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WLabelScroll.java @@ -1,13 +1,15 @@ 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.List; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; + import javax.annotation.ParametersAreNonnullByDefault; + +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; @@ -15,12 +17,13 @@ /** * Author: towdium - * Date: 17-9-17. + * Date: 17-9-17. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WLabelScroll extends WContainer implements ISearchable { + protected List labels = new ArrayList<>(); protected List filtered = null; protected WLabelGroup labelGroup; @@ -37,14 +40,12 @@ public WLabelScroll(int xPos, int yPos, int column, int row, boolean accept) { 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)); @@ -60,8 +61,8 @@ public void update(float f) { labelGroup.setLabel(ls, current * column); float step = 1f / (amount - 1); scroll.setRatio(Math.min(row / (float) getAmountRows(), 1f)) - .setCurrent(f) - .setStep(step); + .setCurrent(f) + .setStep(step); } public WLabel get(int index) { @@ -83,8 +84,12 @@ public WLabelScroll setLabel(int idx, ILabel label) { public boolean setFilter(String str) { 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; } @@ -109,7 +114,8 @@ public List getLabels() { } protected void onUpdate(WLabelGroup w, int index) { - ILabel l = w.get(index).getLabel(); + ILabel l = w.get(index) + .getLabel(); int i = column * current + index; while (labels.size() <= i) labels.add(ILabel.EMPTY); labels.set(i, l); 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 d7f075756..f0fd32959 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WLcd.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WLcd.java @@ -7,7 +7,9 @@ import java.text.NumberFormat; import java.util.HashMap; import java.util.Objects; + import javax.annotation.ParametersAreNonnullByDefault; + import me.towdium.jecalculation.data.structure.RecordMath.Operator; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.gui.Resource; @@ -20,6 +22,7 @@ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class WLcd implements IWidget { + static HashMap PATTERN = new HashMap<>(); public int yPos; @@ -29,21 +32,21 @@ 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}); + 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); } @@ -117,10 +120,15 @@ protected void drawOperator(JecaGui gui, Operator operator) { } public void print(BigDecimal num) { - String s = num.stripTrailingZeros().toPlainString(); + String s = num.stripTrailingZeros() + .toPlainString(); double f = num.floatValue(); int len = f > 0 ? 7 : 6; - int sca = num.unscaledValue().abs().toString().length() - num.scale() - 1; + int sca = num.unscaledValue() + .abs() + .toString() + .length() - num.scale() + - 1; if (Math.abs(sca) > len) { String scale = String.valueOf(sca); len -= scale.length() + 2; 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 2315c2bc1..601327fff 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WLine.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WLine.java @@ -1,20 +1,22 @@ package me.towdium.jecalculation.gui.widgets; +import javax.annotation.ParametersAreNonnullByDefault; + 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; /** * Author: towdium - * Date: 17-8-18. + * Date: 17-8-18. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WLine implements IWidget { + int xPos, yPos, xSize, ySize; public WLine(int y) { @@ -40,6 +42,7 @@ public boolean onDraw(JecaGui gui, int xMouse, int yMouse) { } public static class Joint implements IWidget { + int xPos, yPos; boolean up, down, left, right; public static Resource u = Resource.WGT_SLOT.sub(9, 0, 2, 1); 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 a9d4d8e10..f56830cf7 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WOverlay.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WOverlay.java @@ -1,10 +1,12 @@ package me.towdium.jecalculation.gui.widgets; import javax.annotation.ParametersAreNonnullByDefault; + +import org.lwjgl.input.Keyboard; + 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; /** * Author: Towdium @@ -13,6 +15,7 @@ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class WOverlay extends WContainer { + @Override public boolean onKeyPressed(JecaGui gui, char ch, int code) { if (super.onKeyPressed(gui, ch, code)) return true; 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 09bf9dc51..0c4c6e885 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WPage.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WPage.java @@ -3,10 +3,12 @@ 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 cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import me.towdium.jecalculation.data.label.ILabel.RegistryEditor.Record; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.gui.Resource; @@ -14,12 +16,13 @@ /** * Author: towdium - * Date: 17-9-16. + * Date: 17-9-16. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WPage extends WTooltip { + protected int index; protected Record record; protected boolean focused; 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 0046e5ad9..4bb6ae1df 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WPanel.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WPanel.java @@ -1,9 +1,11 @@ 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 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.gui.Resource; @@ -12,13 +14,14 @@ /** * Author: towdium - * Date: 17-9-15. + * Date: 17-9-15. * Base panel of GUIs */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WPanel implements IWidget { + int xPos, yPos, xSize, ySize; public WPanel(int xPos, int yPos, int xSize, int ySize) { @@ -45,10 +48,11 @@ public boolean onTooltip(JecaGui gui, int xMouse, int yMouse, List toolt /** * Assuming Panel will be the first widget in the container's widgets. - * @param gui gui + * + * @param gui gui * @param xMouse mouse x * @param yMouse mouse y - * @param diff different + * @param diff different * @return true to stop the event */ @Override 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 365755453..f745d80ca 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WRectangle.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WRectangle.java @@ -1,19 +1,21 @@ package me.towdium.jecalculation.gui.widgets; +import javax.annotation.ParametersAreNonnullByDefault; + 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; /** * Author: towdium - * Date: 17-8-22. + * Date: 17-8-22. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WRectangle implements IWidget { + public int xPos, yPos, xSize, ySize, color; public WRectangle(int xPos, int yPos, int xSize, int ySize, int color) { 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 08468ff49..edfa9e03a 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WScroll.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WScroll.java @@ -2,24 +2,27 @@ 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 org.lwjgl.input.Mouse; + +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 org.lwjgl.input.Mouse; /** * Author: towdium - * Date: 17-8-19. + * Date: 17-8-19. * Scroll bar */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WScroll implements IWidget { + public int xPos, yPos, ySize; public float current; boolean active = false; 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 52e127d50..3b0735980 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WSearch.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WSearch.java @@ -3,19 +3,21 @@ import static me.towdium.jecalculation.gui.JecaGui.COLOR_TEXT_RED; import static me.towdium.jecalculation.gui.JecaGui.COLOR_TEXT_WHITE; +import javax.annotation.ParametersAreNonnullByDefault; + 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. + * Date: 17-9-28. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WSearch extends WTextField { + ISearchable[] lss; public WSearch(int xPos, int yPos, int xSize, ISearchable... lss) { 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 a178d240d..467d9bd4e 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WSwitcher.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WSwitcher.java @@ -5,25 +5,28 @@ 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 cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.utils.Utilities.Circulator; /** * Author: towdium - * Date: 17-8-19. + * Date: 17-8-19. * Widget to select page with button for left and right */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WSwitcher extends WContainer { + public static final int SIZE = 13; public ListenerAction listener; protected int xPos, xSize, yPos; @@ -36,10 +39,12 @@ public class WSwitcher extends WContainer { 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())); + xPos, + yPos, + xSize, + IntStream.rangeClosed(1, total) + .mapToObj(i -> i + "/" + total) + .collect(Collectors.toList())); } public WSwitcher(int xPos, int yPos, int xSize, List keys) { 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 070d5c191..631227af1 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WText.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WText.java @@ -1,19 +1,21 @@ package me.towdium.jecalculation.gui.widgets; +import javax.annotation.ParametersAreNonnullByDefault; + 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; /** * Author: towdium - * Date: 17-8-21. + * Date: 17-8-21. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WText implements IWidget { + public static final int UNDEFINED = Integer.MAX_VALUE; public int xPos, yPos, xSize; 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 7df2f9ccc..da404c3bc 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WTextField.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WTextField.java @@ -1,21 +1,24 @@ package me.towdium.jecalculation.gui.widgets; +import javax.annotation.ParametersAreNonnullByDefault; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiTextField; + 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; /** * Author: towdium - * Date: 17-8-18. + * Date: 17-8-18. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public class WTextField implements IWidget { + public ListenerAction listener; protected int xPos, yPos, xSize; GuiTextField textField; 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 2b8c5ad6c..fd1709660 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WTick.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WTick.java @@ -4,8 +4,10 @@ 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; @@ -17,6 +19,7 @@ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class WTick extends WContainer { + WButton button; int xPos, yPos, xSize, ySize; String name; @@ -57,6 +60,7 @@ public WTick setSelected(boolean selected) { } private class Normal extends WButton { + public Normal(int xPos, int yPos, int xSize, int ySize, @Nullable String name) { super(xPos, yPos, xSize, ySize, name); listener = i -> { @@ -73,6 +77,7 @@ protected List getSuffix() { } private class Selected extends WButton { + public Selected(int xPos, int yPos, int xSize, int ySize, @Nullable String name) { super(xPos, yPos, xSize, ySize, name); listener = i -> { 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 f9232e298..b1b4045bd 100644 --- a/src/main/java/me/towdium/jecalculation/gui/widgets/WTooltip.java +++ b/src/main/java/me/towdium/jecalculation/gui/widgets/WTooltip.java @@ -2,13 +2,15 @@ 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 cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; import me.towdium.jecalculation.utils.Utilities; @@ -17,12 +19,13 @@ /** * Author: towdium - * Date: 17-9-16. + * Date: 17-9-16. */ @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @SideOnly(Side.CLIENT) public abstract class WTooltip implements IWidget { + public String name; protected Utilities.Timer timer = new Utilities.Timer(); @@ -40,13 +43,13 @@ public boolean onDraw(JecaGui gui, int xMouse, int yMouse) { 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); + .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 de1befa79..84886af03 100644 --- a/src/main/java/me/towdium/jecalculation/nei/Adapter.java +++ b/src/main/java/me/towdium/jecalculation/nei/Adapter.java @@ -1,16 +1,19 @@ package me.towdium.jecalculation.nei; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.item.ItemStack; + 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; public class Adapter { + public static List adapters = new ArrayList<>(); public static Object convertFluid(ItemStack itemStack) { @@ -37,18 +40,24 @@ public static void init() { JustEnoughCalculation.logger.info("ae2 detected"); adapters.add(new AE2()); } - if (Loader.isModLoaded("gregtech")) { - if (GregTech6.isGT6()) { - JustEnoughCalculation.logger.info("gregtech6 detected"); - adapters.add(new GregTech6()); - } else { - JustEnoughCalculation.logger.info("gregtech5 detected"); - adapters.add(new GregTech()); + boolean isNH = false; + if (Loader.isModLoaded("gregtech") && !Loader.isModLoaded("gregapi")) { + try { + Class.forName("gregtech.api.recipe.RecipeMap"); + isNH = true; + JustEnoughCalculation.logger.info("NH version of GregTech detected"); + } catch (ClassNotFoundException e) { + JustEnoughCalculation.logger.info("GregTech5 detected"); } + adapters.add(new GregTech(isNH)); + } + if (Loader.isModLoaded("gregapi") && Loader.isModLoaded("gregapi_post")) { + JustEnoughCalculation.logger.info("GregTech6 detected"); + adapters.add(new GregTech6()); } try { if (Loader.isModLoaded("miscutils")) { - adapters.add(new GTPP()); + adapters.add(new GTPP(isNH)); JustEnoughCalculation.logger.info("gt++ detected"); } } catch (Exception e) { @@ -67,14 +76,15 @@ public static void init() { adapters.add(new Thaum()); JustEnoughCalculation.logger.info("Thaumcraft detected"); } - JustEnoughCalculation.logger.info("=====Just Enough Calculation Init Finish====="); + JustEnoughCalculation.logger.info("=====Just Enough Calculation Init Finished====="); } 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); @@ -87,7 +97,8 @@ public static void handleRecipe(IRecipeHandler recipe, int index, List } catch (Exception e) { Utilities.addChatMessage(Utilities.ChatMessage.RECIPE_TRANSFER_ERROR); JustEnoughCalculation.logger.error( - "Exception when handling recipe: " + recipe.getClass().getName()); + "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 fb4912d47..9e36550fa 100644 --- a/src/main/java/me/towdium/jecalculation/nei/JecaOverlayHandler.java +++ b/src/main/java/me/towdium/jecalculation/nei/JecaOverlayHandler.java @@ -1,5 +1,13 @@ package me.towdium.jecalculation.nei; +import java.util.*; +import java.util.stream.Collectors; + +import javax.annotation.Nonnull; + +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.item.ItemStack; + import codechicken.nei.api.IOverlayHandler; import codechicken.nei.recipe.GuiRecipeTab; import codechicken.nei.recipe.HandlerInfo; @@ -7,20 +15,16 @@ 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; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.gui.guis.GuiRecipe; import me.towdium.jecalculation.utils.wrappers.Trio; -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.item.ItemStack; @SideOnly(Side.CLIENT) public class JecaOverlayHandler implements IOverlayHandler { + @Override public void overlayRecipe(GuiContainer firstGui, IRecipeHandler recipe, int recipeIndex, boolean shift) { if (firstGui instanceof JecaGui) { @@ -36,8 +40,8 @@ public void overlayRecipe(GuiContainer firstGui, IRecipeHandler recipe, int reci } } - private static EnumMap>> convertRecipe( - IRecipeHandler recipe, int recipeIndex, Class context) { + private static EnumMap>> convertRecipe(IRecipeHandler recipe, + int recipeIndex, Class context) { // item disamb raw EnumMap>> merged = new EnumMap<>(Recipe.IO.class); @@ -51,47 +55,52 @@ private static EnumMap>> conver // output recipeOutputs.forEach(o -> merge(merged, Arrays.asList(o), context, Recipe.IO.OUTPUT)); - JecaOverlayHandler.getCatalyst(recipe).ifPresent(catalyst -> { - List catalysts = Collections.singletonList(catalyst); - merge(merged, catalysts, context, Recipe.IO.CATALYST); - }); + JecaOverlayHandler.getCatalyst(recipe) + .ifPresent(catalyst -> { + List catalysts = Collections.singletonList(catalyst); + merge(merged, catalysts, context, Recipe.IO.CATALYST); + }); return merged; } - private static void merge( - EnumMap>> dst, - List objs, - Class context, - Recipe.IO type) { - List list = objs.stream().map(ILabel.Converter::from).collect(Collectors.toList()); + 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; - ILabel rep = list.get(0).copy(); + ILabel rep = list.get(0) + .copy(); 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 = 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; - }); + 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) { if (!NEIPlugin.isCatalystEnabled()) { return Optional.empty(); } - final String handlerName = handler.toString().split("@")[0]; + final String handlerName = handler.toString() + .split("@")[0]; final String handlerID; if (handler instanceof TemplateRecipeHandler) { handlerID = (((TemplateRecipeHandler) handler).getOverlayIdentifier()); diff --git a/src/main/java/me/towdium/jecalculation/nei/JecaTooltipHandler.java b/src/main/java/me/towdium/jecalculation/nei/JecaTooltipHandler.java index ce6622d08..efef47eee 100644 --- a/src/main/java/me/towdium/jecalculation/nei/JecaTooltipHandler.java +++ b/src/main/java/me/towdium/jecalculation/nei/JecaTooltipHandler.java @@ -1,12 +1,15 @@ 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 codechicken.nei.guihook.IContainerTooltipHandler; +import me.towdium.jecalculation.gui.JecaGui; + public class JecaTooltipHandler implements IContainerTooltipHandler { + @Override public List handleTooltip(GuiContainer gui, int mousex, int mousey, List currenttip) { return currenttip; @@ -18,8 +21,8 @@ public List handleItemDisplayName(GuiContainer gui, ItemStack itemstack, } @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 b565f9dfb..16b39b0db 100644 --- a/src/main/java/me/towdium/jecalculation/nei/NEICalculatorConfig.java +++ b/src/main/java/me/towdium/jecalculation/nei/NEICalculatorConfig.java @@ -1,13 +1,14 @@ package me.towdium.jecalculation.nei; -import codechicken.nei.api.API; -import codechicken.nei.api.IConfigureNEI; 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 codechicken.nei.api.API; +import codechicken.nei.api.IConfigureNEI; import me.towdium.jecalculation.Tags; import me.towdium.jecalculation.gui.JecaGui; import me.towdium.jecalculation.nei.adapter.IAdapter; @@ -17,19 +18,22 @@ public class NEICalculatorConfig implements IConfigureNEI { @Override 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)); + /* + * 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 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); - }); + .forEach(ident -> { + API.registerGuiOverlay(JecaGui.class, ident); + API.registerGuiOverlayHandler(JecaGui.class, new JecaOverlayHandler(), ident); + }); } @Override diff --git a/src/main/java/me/towdium/jecalculation/nei/NEIPlugin.java b/src/main/java/me/towdium/jecalculation/nei/NEIPlugin.java index 6ff9d1462..9102cac59 100644 --- a/src/main/java/me/towdium/jecalculation/nei/NEIPlugin.java +++ b/src/main/java/me/towdium/jecalculation/nei/NEIPlugin.java @@ -1,5 +1,8 @@ package me.towdium.jecalculation.nei; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.FluidStack; + import codechicken.nei.guihook.GuiContainerManager; import codechicken.nei.recipe.GuiCraftingRecipe; import codechicken.nei.recipe.GuiUsageRecipe; @@ -7,8 +10,6 @@ import me.towdium.jecalculation.JustEnoughCalculation; import me.towdium.jecalculation.data.label.ILabel; import me.towdium.jecalculation.utils.Version; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; public class NEIPlugin { @@ -19,8 +20,10 @@ 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) { 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 1b85fa5ea..b145bde41 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/AE2.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/AE2.java @@ -1,14 +1,17 @@ package me.towdium.jecalculation.nei.adapter; -import codechicken.nei.recipe.IRecipeHandler; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; + import javax.annotation.ParametersAreNonnullByDefault; +import codechicken.nei.recipe.IRecipeHandler; + @ParametersAreNonnullByDefault public class AE2 implements IAdapter { + @Override public Set getAllOverlayIdentifier() { return new HashSet<>(Arrays.asList("inscriber", "grindstone")); 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 637e3a4c1..2ea4d5419 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/AdapterUtil.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/AdapterUtil.java @@ -1,6 +1,7 @@ package me.towdium.jecalculation.nei.adapter; import java.util.Optional; + import javax.annotation.ParametersAreNonnullByDefault; @SuppressWarnings("rawtypes") 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 002844e1d..98ffe66da 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,14 @@ package me.towdium.jecalculation.nei.adapter; -import codechicken.nei.recipe.IRecipeHandler; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; + import javax.annotation.ParametersAreNonnullByDefault; +import codechicken.nei.recipe.IRecipeHandler; + @ParametersAreNonnullByDefault public class Avaritia implements IAdapter { 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 9208b5fd2..d89f9a811 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/EnderIO.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/EnderIO.java @@ -1,21 +1,25 @@ package me.towdium.jecalculation.nei.adapter; -import codechicken.nei.recipe.IRecipeHandler; -import codechicken.nei.recipe.TemplateRecipeHandler; 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; +import codechicken.nei.recipe.IRecipeHandler; +import codechicken.nei.recipe.TemplateRecipeHandler; + @ParametersAreNonnullByDefault public class EnderIO implements IAdapter { @Override public Set getAllOverlayIdentifier() { - return new HashSet<>(Arrays.asList( + return new HashSet<>( + Arrays.asList( "EnderIOAlloySmelter", "EIOEnchanter", "EnderIOSagMill", @@ -29,8 +33,8 @@ public Set getAllOverlayIdentifier() { 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 { @@ -50,10 +54,12 @@ public Set getAllOverlayIdentifier() { @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()); + if (defaultHandlers.stream() + .anyMatch(aClass -> aClass.isInstance(recipe))) { + List otherStacks = recipe.getOtherStacks(index) + .stream() + .map(positionedStack -> positionedStack.items) + .collect(Collectors.toList()); outputs.addAll(otherStacks); } else { try { @@ -62,8 +68,8 @@ public void handleRecipe(IRecipeHandler recipe, int index, List inputs 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"); @@ -72,8 +78,8 @@ public void handleRecipe(IRecipeHandler recipe, int index, List inputs 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 eb3a55d10..54aa50617 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/Forestry.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/Forestry.java @@ -1,20 +1,24 @@ package me.towdium.jecalculation.nei.adapter; -import codechicken.nei.PositionedStack; -import codechicken.nei.recipe.IRecipeHandler; -import forestry.core.recipes.nei.PositionedFluidTank; -import forestry.core.recipes.nei.RecipeHandlerBase; -import forestry.factory.recipes.nei.*; 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; +import codechicken.nei.PositionedStack; +import codechicken.nei.recipe.IRecipeHandler; +import forestry.core.recipes.nei.PositionedFluidTank; +import forestry.core.recipes.nei.RecipeHandlerBase; +import forestry.factory.recipes.nei.*; + @ParametersAreNonnullByDefault public class Forestry implements IAdapter { + @Override public void handleRecipe(IRecipeHandler recipe, int index, List inputs, List outputs) { if (recipe instanceof RecipeHandlerBase) { @@ -33,28 +37,36 @@ public void handleRecipe(IRecipeHandler recipe, int index, List inputs 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()); } } private void centrifuge(RecipeHandlerBase recipe, int recipeIndex, List outputs) { if (recipe instanceof NEIHandlerCentrifuge) { List otherStacks = recipe.getOtherStacks(recipeIndex); - otherStacks.stream().map(positionedStack -> positionedStack.items).forEach(outputs::add); + otherStacks.stream() + .map(positionedStack -> positionedStack.items) + .forEach(outputs::add); } } 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()); } } @@ -62,8 +74,9 @@ private void fermenter(RecipeHandlerBase recipe, int recipeIndex, List 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); @@ -78,7 +91,9 @@ private void fermenter(RecipeHandlerBase recipe, int recipeIndex, List 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; @@ -96,15 +111,18 @@ private void moistener(RecipeHandlerBase recipe, int recipeIndex, List 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); @@ -124,12 +142,13 @@ private void still(RecipeHandlerBase recipe, int recipeIndex, List inp * @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) { 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 b31344b2f..376665682 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/GTPP.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/GTPP.java @@ -1,47 +1,56 @@ package me.towdium.jecalculation.nei.adapter; -import codechicken.nei.recipe.IRecipeHandler; 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; +import codechicken.nei.recipe.IRecipeHandler; + /** * don't work, why? */ @ParametersAreNonnullByDefault public class GTPP extends GregTech { + private final boolean isNH; + + public GTPP(boolean isNH) { + super(isNH); + this.isNH = isNH; + } + 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) { try { defaultHandlers.add(Class.forName(handler)); } catch (ClassNotFoundException e) { - // e.printStackTrace(); + // e.printStackTrace(); } } } @@ -49,25 +58,31 @@ public class GTPP extends GregTech { @Override public Set getAllOverlayIdentifier() { Set recipeNames = new HashSet<>(); + recipeNames.add("GTPP_Decayables"); + if (isNH) { + return recipeNames; + } + 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", "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(); } - // which one? - recipeNames.add("GTPP_Decayables"); - recipeNames.add("Decayables"); + return recipeNames; } @Override public void handleRecipe(IRecipeHandler recipe, int index, List inputs, List outputs) { - if (defaultHandlers.stream().anyMatch(aClass -> aClass.isInstance(recipe))) { + if (defaultHandlers.stream() + .anyMatch(aClass -> aClass.isInstance(recipe))) { 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 b3ad97166..970fdd489 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/GregTech.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/GregTech.java @@ -1,27 +1,61 @@ package me.towdium.jecalculation.nei.adapter; -import codechicken.nei.PositionedStack; -import codechicken.nei.recipe.IRecipeHandler; 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; +import codechicken.nei.PositionedStack; +import codechicken.nei.recipe.IRecipeHandler; +import gregtech.api.recipe.RecipeCategory; + @ParametersAreNonnullByDefault public class GregTech implements IAdapter { + + private static final Class gtDefault, gtAssLine; + + private final boolean isNH; + + static { + Class gtDf = null; + Class gtAL = null; + try { + gtDf = Class.forName("gregtech.nei.GT_NEI_DefaultHandler"); + gtAL = Class.forName("gregtech.nei.GT_NEI_AssLineHandler"); + } catch (ClassNotFoundException ignored) {} + gtDefault = gtDf; + gtAssLine = gtAL; + } + + public GregTech(boolean isNH) { + this.isNH = isNH; + } + @Override public Set getAllOverlayIdentifier() { + if (isNH) { + return RecipeCategory.ALL_RECIPE_CATEGORIES.values() + .stream() + .filter( + category -> category.recipeMap.getFrontend() + .getNEIProperties().registerNEI) + .map(category -> category.unlocalizedName) + .collect(Collectors.toSet()); + } + return reflectGetRecipeMapNEIName("gregtech.api.util.GT_Recipe$GT_Recipe_Map", "sMappings"); } - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) protected Set reflectGetRecipeMapNEIName(String clz, String staticField) { try { Class gtRecipeMapClz = Class.forName(clz); @@ -30,39 +64,24 @@ protected Set reflectGetRecipeMapNEIName(String clz, String staticField) 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()); + .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<>(); } } - private static final Class gtDefault, gtAssLine; - - static { - Class gtDf = null; - Class gtAL = null; - try { - gtDf = Class.forName("gregtech.nei.GT_NEI_DefaultHandler"); - gtAL = Class.forName("gregtech.nei.GT_NEI_AssLineHandler"); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - gtDefault = gtDf; - gtAssLine = gtAL; - } - @Override public void handleRecipe(IRecipeHandler recipe, int index, List inputs, List outputs) { - if (gtDefault.isInstance(recipe) || gtAssLine.isInstance(recipe)) { + if (gtDefault.isInstance(recipe) || (gtAssLine != null && gtAssLine.isInstance(recipe))) { handleDefault(recipe, index, inputs, outputs); } } @@ -71,9 +90,10 @@ protected void handleDefault(IRecipeHandler recipe, int index, List in 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) + 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); @@ -81,7 +101,7 @@ protected void handleDefault( return o; } else { throw new IllegalArgumentException( - "Shall get ItemStack or FluidStack, but get: " + o.getClass()); + "Shall get ItemStack or FluidStack, but get: " + o.getClass()); } }) .toArray()); @@ -89,10 +109,13 @@ protected void handleDefault( outputs.clear(); } List otherStacks = recipe.getOtherStacks(index); - outputs.addAll(otherStacks.stream() + outputs.addAll( + otherStacks.stream() .map(positionedStack -> positionedStack.items) - .map(itemStacks -> - Arrays.stream(itemStacks).map(GregTech::convertFluid).toArray()) + .map( + itemStacks -> Arrays.stream(itemStacks) + .map(GregTech::convertFluid) + .toArray()) .collect(Collectors.toList())); } @@ -105,30 +128,29 @@ public static Object convertFluid(ItemStack itemStack) { * For resolving version compatibility issues. * Copied from GTNewHorizons/GT5-Unofficial. */ - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) private static FluidStack getFluidFromDisplayStack(ItemStack aDisplayStack) { try { Class itemListClz = Class.forName("gregtech.api.enums.ItemList"); 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) { + return new FluidStack( + tFluid, + (int) aDisplayStack.getTagCompound() + .getLong("mFluidDisplayAmount")); + } 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 d08ced5b3..0a86180ce 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/GregTech6.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/GregTech6.java @@ -1,19 +1,23 @@ package me.towdium.jecalculation.nei.adapter; -import codechicken.nei.recipe.IRecipeHandler; -import codechicken.nei.recipe.TemplateRecipeHandler; 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; +import codechicken.nei.recipe.IRecipeHandler; +import codechicken.nei.recipe.TemplateRecipeHandler; + @ParametersAreNonnullByDefault public class GregTech6 implements IAdapter { + public static boolean isGT6() { try { Class buildInfoclz = Class.forName("gregtech.BuildInfo"); @@ -37,8 +41,7 @@ public Set getAllOverlayIdentifier() { for (Object value : maps.values()) { try { recipeNames.add((String) mNameNEIField.get(value)); - } catch (IllegalAccessException ignored) { - } + } catch (IllegalAccessException ignored) {} } } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); @@ -83,27 +86,29 @@ public void handleRecipe(IRecipeHandler recipe, int index, List inputs 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}) + 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}) + 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 -> + // 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())); + // 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())); } } @@ -117,10 +122,8 @@ private static FluidStack getFluidFromDisplayStack(ItemStack aDisplayStack) { 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 dee6b49ec..fe75de5f3 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,19 @@ package me.towdium.jecalculation.nei.adapter; -import codechicken.nei.recipe.IRecipeHandler; import java.util.Collections; import java.util.List; import java.util.Set; + import javax.annotation.ParametersAreNonnullByDefault; +import codechicken.nei.recipe.IRecipeHandler; + @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 97d63942c..964cd6272 100644 --- a/src/main/java/me/towdium/jecalculation/nei/adapter/Thaum.java +++ b/src/main/java/me/towdium/jecalculation/nei/adapter/Thaum.java @@ -1,18 +1,23 @@ package me.towdium.jecalculation.nei.adapter; -import codechicken.nei.recipe.IRecipeHandler; -import cpw.mods.fml.common.registry.GameData; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; + import javax.annotation.ParametersAreNonnullByDefault; + import net.minecraft.item.ItemStack; +import codechicken.nei.recipe.IRecipeHandler; +import cpw.mods.fml.common.registry.GameData; + @ParametersAreNonnullByDefault public class Thaum implements IAdapter { + @Override public Set getAllOverlayIdentifier() { - return new HashSet<>(Arrays.asList( + return new HashSet<>( + Arrays.asList( "arcaneshapedrecipes", "arcaneshapelessrecipes", "aspectsRecipe", @@ -23,14 +28,15 @@ public Set getAllOverlayIdentifier() { 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 { @@ -43,14 +49,16 @@ public Set getAllOverlayIdentifier() { @Override public void handleRecipe(IRecipeHandler recipe, int index, List inputs, List outputs) { - if (defaultHandlers.stream().anyMatch(handler -> handler.isInstance(recipe))) { + if (defaultHandlers.stream() + .anyMatch(handler -> handler.isInstance(recipe))) { // remove all aspects Iterator it = inputs.iterator(); while (it.hasNext()) { Object[] items = it.next(); for (Object item : items) { if (item instanceof ItemStack) { - String name = GameData.getItemRegistry().getNameForObject(((ItemStack) item).getItem()); + String name = GameData.getItemRegistry() + .getNameForObject(((ItemStack) item).getItem()); if ("thaumcraftneiplugin:Aspect".equals(name)) { it.remove(); break; diff --git a/src/main/java/me/towdium/jecalculation/network/ClientProxy.java b/src/main/java/me/towdium/jecalculation/network/ClientProxy.java index 4e170629e..cfa1d9b16 100644 --- a/src/main/java/me/towdium/jecalculation/network/ClientProxy.java +++ b/src/main/java/me/towdium/jecalculation/network/ClientProxy.java @@ -3,6 +3,8 @@ import static me.towdium.jecalculation.gui.JecaGui.keyOpenGuiCraft; import static me.towdium.jecalculation.gui.JecaGui.keyOpenGuiMath; +import net.minecraftforge.client.ClientCommandHandler; + import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.event.*; import me.towdium.jecalculation.JecaConfig; @@ -11,7 +13,6 @@ 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 { diff --git a/src/main/java/me/towdium/jecalculation/polyfill/MethodsReturnNonnullByDefault.java b/src/main/java/me/towdium/jecalculation/polyfill/MethodsReturnNonnullByDefault.java index bd8e39152..e62070e43 100644 --- a/src/main/java/me/towdium/jecalculation/polyfill/MethodsReturnNonnullByDefault.java +++ b/src/main/java/me/towdium/jecalculation/polyfill/MethodsReturnNonnullByDefault.java @@ -4,6 +4,7 @@ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; + import javax.annotation.Nonnull; import javax.annotation.meta.TypeQualifierDefault; @@ -14,7 +15,7 @@ *
  • An explicit nullness annotation *
  • The method overrides a method in a superclass (in which case the * annotation of the corresponding method in the superclass applies) - *
  • there is a default parameter annotation applied to a more tightly nested + *
  • there is a default parameter annotation applied to a more tightly nested * element. * */ diff --git a/src/main/java/me/towdium/jecalculation/polyfill/NBTHelper.java b/src/main/java/me/towdium/jecalculation/polyfill/NBTHelper.java index 6812fe4af..2b47558cc 100644 --- a/src/main/java/me/towdium/jecalculation/polyfill/NBTHelper.java +++ b/src/main/java/me/towdium/jecalculation/polyfill/NBTHelper.java @@ -3,7 +3,9 @@ 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; @@ -11,6 +13,7 @@ @ParametersAreNonnullByDefault public class NBTHelper { + /** * Get an NBTTagCompound from this stack's NBT data. * diff --git a/src/main/java/me/towdium/jecalculation/polyfill/SoundEvents.java b/src/main/java/me/towdium/jecalculation/polyfill/SoundEvents.java index 7b0fc3dfc..1dd614b92 100644 --- a/src/main/java/me/towdium/jecalculation/polyfill/SoundEvents.java +++ b/src/main/java/me/towdium/jecalculation/polyfill/SoundEvents.java @@ -1,5 +1,6 @@ package me.towdium.jecalculation.polyfill; public class SoundEvents { + public static final String UI_BUTTON_CLICK = "gui.button.press"; } 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 24c3fbbaf..6cb668f3b 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 @@ -8,10 +8,13 @@ import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; + import javax.annotation.Nullable; public class Streams { + public interface FunctionWithIndex { + /** Applies this function to the given argument and its index within a stream. */ R apply(T from, long index); } @@ -20,22 +23,27 @@ public interface FunctionWithIndex { * Returns a stream consisting of the results of applying the given function to the elements of * {@code stream} and their indices in the stream. For example, * - *
    {@code
    +     * 
    +     * {@code
          * mapWithIndex(
          *     Stream.of("a", "b", "c"),
          *     (str, index) -> str + ":" + index)
    -     * }
    + * } + *
    * - *

    would return {@code Stream.of("a:0", "b:1", "c:2")}. + *

    + * would return {@code Stream.of("a:0", "b:1", "c:2")}. * - *

    The resulting stream is + * The resulting stream is efficiently splittable * if and only if {@code stream} was efficiently splittable and its underlying spliterator * reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream * comes from a data structure supporting efficient indexed random access, typically an array or * list. * - *

    The order of the resulting stream is defined if and only if the order of the original stream + *

    + * 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) { @@ -47,23 +55,25 @@ public static Stream mapWithIndex(Stream stream, FunctionWithIndex< if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) { Iterator fromIterator = Spliterators.iterator(fromSpliterator); return StreamSupport.stream( - new Spliterators.AbstractSpliterator( - fromSpliterator.estimateSize(), - fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) { - long index = 0; - - @Override - public boolean tryAdvance(Consumer action) { - if (fromIterator.hasNext()) { - action.accept(function.apply(fromIterator.next(), index++)); - return true; - } - return false; + new Spliterators.AbstractSpliterator( + fromSpliterator.estimateSize(), + fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) { + + long index = 0; + + @Override + public boolean tryAdvance(Consumer action) { + if (fromIterator.hasNext()) { + action.accept(function.apply(fromIterator.next(), index++)); + return true; } - }, - isParallel); + return false; + } + }, + isParallel); } class Splitr extends MapWithIndexSpliterator, R, Splitr> implements Consumer { + T holder; Splitr(Spliterator splitr, long index) { @@ -96,9 +106,9 @@ Splitr createSplit(Spliterator from, long i) { return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel); } - private abstract static class MapWithIndexSpliterator< - F extends Spliterator, R, S extends MapWithIndexSpliterator> - implements Spliterator { + private abstract static class MapWithIndexSpliterator, R, S extends MapWithIndexSpliterator> + implements Spliterator { + final F fromSpliterator; long index; 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 62566e233..1139b3d13 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,15 +1,16 @@ 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 net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderHelper; + import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -19,9 +20,13 @@ import org.lwjgl.opengl.GLContext; import org.lwjgl.util.vector.Quaternion; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + @SuppressWarnings("ALL") @SideOnly(Side.CLIENT) 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(); @@ -155,19 +160,15 @@ public static void blendFunc(int srcFactor, int 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) { + if (srcFactor != blendState.srcFactor || dstFactor != blendState.dstFactor + || srcFactorAlpha != blendState.srcFactorAlpha + || dstFactorAlpha != blendState.dstFactorAlpha) { blendState.srcFactor = srcFactor; blendState.dstFactor = dstFactor; blendState.srcFactorAlpha = srcFactorAlpha; @@ -408,34 +409,18 @@ public static void bindTexture(int 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); } @@ -471,10 +456,9 @@ public static void viewport(int x, int y, int width, int 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) { + if (red != colorMaskState.red || green != colorMaskState.green + || blue != colorMaskState.blue + || alpha != colorMaskState.alpha) { colorMaskState.red = red; colorMaskState.green = green; colorMaskState.blue = blue; @@ -491,10 +475,9 @@ public static void clearDepth(double 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) { + 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; @@ -591,10 +574,9 @@ public static FloatBuffer quatToGlMatrix(FloatBuffer buffer, Quaternion quaterni } 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) { + if (colorRed != colorState.red || colorGreen != colorState.green + || colorBlue != colorState.blue + || colorAlpha != colorState.alpha) { colorState.red = colorRed; colorState.green = colorGreen; colorState.blue = colorBlue; @@ -756,6 +738,7 @@ public static void disableBlendProfile(GlStateManager.Profile p_187440_0_) { @SideOnly(Side.CLIENT) static class AlphaState { + public GlStateManager.BooleanState alphaTest; public int func; public float ref; @@ -769,6 +752,7 @@ private AlphaState() { @SideOnly(Side.CLIENT) static class BlendState { + public GlStateManager.BooleanState blend; public int srcFactor; public int dstFactor; @@ -786,6 +770,7 @@ private BlendState() { @SideOnly(Side.CLIENT) static class BooleanState { + private final int capability; private boolean currentState; @@ -816,6 +801,7 @@ public void setState(boolean state) { @SideOnly(Side.CLIENT) static class ClearState { + public double depth; public GlStateManager.Color color; @@ -827,6 +813,7 @@ private ClearState() { @SideOnly(Side.CLIENT) static class Color { + public float red; public float green; public float blue; @@ -850,6 +837,7 @@ public Color(float redIn, float greenIn, float blueIn, float alphaIn) { @SideOnly(Side.CLIENT) static class ColorLogicState { + public GlStateManager.BooleanState colorLogicOp; public int opcode; @@ -861,6 +849,7 @@ private ColorLogicState() { @SideOnly(Side.CLIENT) static class ColorMask { + public boolean red; public boolean green; public boolean blue; @@ -876,6 +865,7 @@ private ColorMask() { @SideOnly(Side.CLIENT) static class ColorMaterialState { + public GlStateManager.BooleanState colorMaterial; public int face; public int mode; @@ -889,6 +879,7 @@ private ColorMaterialState() { @SideOnly(Side.CLIENT) public static enum CullFace { + FRONT(1028), BACK(1029), FRONT_AND_BACK(1032); @@ -902,6 +893,7 @@ private CullFace(int modeIn) { @SideOnly(Side.CLIENT) static class CullState { + public GlStateManager.BooleanState cullFace; public int mode; @@ -913,6 +905,7 @@ private CullState() { @SideOnly(Side.CLIENT) static class DepthState { + public GlStateManager.BooleanState depthTest; public boolean maskEnabled; public int depthFunc; @@ -926,6 +919,7 @@ private DepthState() { @SideOnly(Side.CLIENT) public static enum DestFactor { + CONSTANT_ALPHA(32771), CONSTANT_COLOR(32769), DST_ALPHA(772), @@ -950,6 +944,7 @@ private DestFactor(int factorIn) { @SideOnly(Side.CLIENT) public static enum FogMode { + LINEAR(9729), EXP(2048), EXP2(2049); @@ -963,6 +958,7 @@ private FogMode(int capabilityIn) { @SideOnly(Side.CLIENT) static class FogState { + public GlStateManager.BooleanState fog; public int mode; public float density; @@ -979,6 +975,7 @@ private FogState() { @SideOnly(Side.CLIENT) public static enum LogicOp { + AND(5377), AND_INVERTED(5380), AND_REVERSE(5378), @@ -1005,6 +1002,7 @@ private LogicOp(int opcodeIn) { @SideOnly(Side.CLIENT) static class PolygonOffsetState { + public GlStateManager.BooleanState polygonOffsetFill; public GlStateManager.BooleanState polygonOffsetLine; public float factor; @@ -1018,7 +1016,9 @@ private PolygonOffsetState() { @SideOnly(Side.CLIENT) public static enum Profile { + DEFAULT { + public void apply() { GlStateManager.disableAlpha(); GlStateManager.alphaFunc(519, 0.0F); @@ -1032,14 +1032,22 @@ public void apply() { if (i == 0) { GL11.glLight( - GL11.GL_LIGHT0 + i, GL11.GL_DIFFUSE, reflectSetColorBuffer(1.0F, 1.0F, 1.0F, 1.0F)); + 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)); + 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.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)); + GL11.GL_LIGHT0 + i, + GL11.GL_SPECULAR, + reflectSetColorBuffer(0.0F, 0.0F, 0.0F, 1.0F)); } } @@ -1051,10 +1059,10 @@ public void apply() { 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.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); @@ -1097,7 +1105,9 @@ public void apply() { 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.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); @@ -1128,6 +1138,7 @@ public void apply() { public void clean() {} }, PLAYER_SKIN { + public void apply() { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); @@ -1138,12 +1149,13 @@ public void clean() { } }, TRANSPARENT_MODEL { + 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); } @@ -1163,6 +1175,7 @@ private Profile() {} @SideOnly(Side.CLIENT) public static enum SourceFactor { + CONSTANT_ALPHA(32771), CONSTANT_COLOR(32769), DST_ALPHA(772), @@ -1188,6 +1201,7 @@ private SourceFactor(int factorIn) { @SideOnly(Side.CLIENT) static class StencilFunc { + public int func; public int mask; @@ -1199,6 +1213,7 @@ private StencilFunc() { @SideOnly(Side.CLIENT) static class StencilState { + public GlStateManager.StencilFunc func; public int mask; public int fail; @@ -1224,6 +1239,7 @@ public static enum TexGen { @SideOnly(Side.CLIENT) static class TexGenCoord { + public GlStateManager.BooleanState textureGen; public int coord; public int param = -1; @@ -1236,6 +1252,7 @@ public TexGenCoord(int coordIn, int capabilityIn) { @SideOnly(Side.CLIENT) static class TexGenState { + public GlStateManager.TexGenCoord s; public GlStateManager.TexGenCoord t; public GlStateManager.TexGenCoord r; @@ -1251,6 +1268,7 @@ private TexGenState() { @SideOnly(Side.CLIENT) static class TextureState { + public GlStateManager.BooleanState texture2DState; public int textureName; @@ -1259,12 +1277,12 @@ private TextureState() { } } - 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 4f245908e..8a868c860 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 @@ -4,11 +4,14 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; + import javax.annotation.Nonnull; import javax.annotation.Nullable; + import org.apache.commons.lang3.Validate; public class NonNullList extends AbstractList { + private final List delegate; private final E 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 80c3bf93a..6653f969a 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,11 +1,13 @@ 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; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + 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(); @@ -430,8 +432,12 @@ public static int hsvToRGB(float hue, float saturation, float value) { 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); @@ -454,10 +460,8 @@ public static int hash(int p_188208_0_) { 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]; 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 25978345a..1b75fc505 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,10 +1,12 @@ package me.towdium.jecalculation.polyfill.mc.util.math; -import com.google.common.base.Objects; import javax.annotation.concurrent.Immutable; +import com.google.common.base.Objects; + @Immutable public class Vec3i implements Comparable { + public static final Vec3i NULL_VECTOR = new Vec3i(0, 0, 0); private final int x; private final int y; @@ -44,9 +46,8 @@ public int hashCode() { 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(); + 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(); } @@ -66,9 +67,9 @@ public int getZ() { 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()); + 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) { @@ -98,9 +99,9 @@ public double distanceSq(Vec3i to) { public String toString() { return Objects.toStringHelper(this) - .add("x", this.getX()) - .add("y", this.getY()) - .add("z", this.getZ()) - .toString(); + .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 17857c331..1faf61730 100644 --- a/src/main/java/me/towdium/jecalculation/utils/ClientUtils.java +++ b/src/main/java/me/towdium/jecalculation/utils/ClientUtils.java @@ -5,6 +5,7 @@ import net.minecraft.util.ResourceLocation; public class ClientUtils { + public static Minecraft mc() { return Minecraft.getMinecraft(); } @@ -12,7 +13,7 @@ public static Minecraft mc() { public static void playClickSound(float pitchIn) { try { mc().getSoundHandler() - .playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), pitchIn)); + .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 3bfbb1646..9b8945b90 100644 --- a/src/main/java/me/towdium/jecalculation/utils/ItemStackHelper.java +++ b/src/main/java/me/towdium/jecalculation/utils/ItemStackHelper.java @@ -4,6 +4,7 @@ import net.minecraft.item.ItemStack; public class ItemStackHelper { + public static final Item EMPTY_ITEM = null; public static final ItemStack EMPTY_ITEM_STACK = new ItemStack((Item) null); diff --git a/src/main/java/me/towdium/jecalculation/utils/NBTJson.java b/src/main/java/me/towdium/jecalculation/utils/NBTJson.java index 6b5d9550c..82b5d943a 100644 --- a/src/main/java/me/towdium/jecalculation/utils/NBTJson.java +++ b/src/main/java/me/towdium/jecalculation/utils/NBTJson.java @@ -1,6 +1,5 @@ package me.towdium.jecalculation.utils; -import com.google.gson.*; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; @@ -8,9 +7,13 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.IntStream; + import net.minecraft.nbt.*; +import com.google.gson.*; + public class NBTJson { + private static final Pattern numberPattern = Pattern.compile("^([-+]?[\\d]+\\.?[0-9]*)([bBsSlLfFdD]?)$"); private static final JsonParser parser = new JsonParser(); private static final Gson gson = new GsonBuilder().create(); @@ -71,8 +74,10 @@ public static NBTBase toNbt(JsonElement jsonElement) { 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); + if (m.groupCount() == 2 && m.group(2) + .length() > 0) { + final char numberType = m.group(2) + .charAt(0); switch (numberType) { case 'b': case 'B': @@ -107,19 +112,24 @@ public static NBTBase toNbt(JsonElement jsonElement) { nbtList.add(toNbt(element)); } - if (nbtList.stream().allMatch(n -> n instanceof NBTTagInt)) { - return new NBTTagIntArray(nbtList.stream() + if (nbtList.stream() + .allMatch(n -> n instanceof NBTTagInt)) { + 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()))); - } else { - NBTTagList nbtTagList = new NBTTagList(); - nbtList.forEach(nbtTagList::appendTag); + } else if (nbtList.stream() + .allMatch(n -> n instanceof NBTTagByte)) { + return new NBTTagByteArray( + toByteArray( + nbtList.stream() + .mapToInt(i -> ((NBTTagInt) i).func_150287_d()))); + } else { + NBTTagList nbtTagList = new NBTTagList(); + nbtList.forEach(nbtTagList::appendTag); - return nbtTagList; - } + return nbtTagList; + } } else if (jsonElement instanceof JsonObject) { // NBTTagCompound final JsonObject jsonObject = (JsonObject) jsonElement; @@ -134,10 +144,11 @@ public static NBTBase toNbt(JsonElement 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 78cf7b941..205c71dc6 100644 --- a/src/main/java/me/towdium/jecalculation/utils/ReflectionHelper.java +++ b/src/main/java/me/towdium/jecalculation/utils/ReflectionHelper.java @@ -4,16 +4,18 @@ /** * Author: Towdium - * Date: 2016/6/25. + * Date: 2016/6/25. */ public class ReflectionHelper { + @SuppressWarnings("unchecked") public static T getField(C o, String... names) { Field field = null; boolean flag = false; for (String name : names) { try { - field = o.getClass().getDeclaredField(name); + field = o.getClass() + .getDeclaredField(name); } catch (NoSuchFieldException e) { continue; } @@ -21,8 +23,9 @@ public static T getField(C o, String... names) { break; } if (!flag) { - StringBuilder buffer = - new StringBuilder("Field not found in class " + o.getClass().getCanonicalName() + ":"); + StringBuilder buffer = new StringBuilder( + "Field not found in class " + o.getClass() + .getCanonicalName() + ":"); for (String s : names) { buffer.append(" "); buffer.append(s); @@ -42,7 +45,8 @@ public static T getField(C o, String... names) { public static T get(C o, String name) { T res; try { - Field field = o.getClass().getDeclaredField(name); + Field field = o.getClass() + .getDeclaredField(name); field.setAccessible(true); res = (T) field.get(o); } catch (NoSuchFieldException | IllegalAccessException e) { @@ -54,7 +58,8 @@ public static T get(C o, String name) { public static void set(C o, String name, T value) { try { - Field field = o.getClass().getDeclaredField(name); + Field field = o.getClass() + .getDeclaredField(name); field.setAccessible(true); field.set(o, value); } catch (NoSuchFieldException | IllegalAccessException e) { diff --git a/src/main/java/me/towdium/jecalculation/utils/Utilities.java b/src/main/java/me/towdium/jecalculation/utils/Utilities.java index 923d00887..15cabbc8e 100644 --- a/src/main/java/me/towdium/jecalculation/utils/Utilities.java +++ b/src/main/java/me/towdium/jecalculation/utils/Utilities.java @@ -2,14 +2,6 @@ import static net.minecraft.client.resources.I18n.format; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; -import cpw.mods.fml.common.Loader; -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 java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -23,12 +15,10 @@ import java.util.function.Supplier; import java.util.stream.Stream; import java.util.stream.StreamSupport; + 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; @@ -37,26 +27,37 @@ 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; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; + +import cpw.mods.fml.common.Loader; +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.Tags; +import me.towdium.jecalculation.polyfill.NBTHelper; +import me.towdium.jecalculation.utils.wrappers.Pair; + /** * Author: Towdium - * Date: 2016/6/25. + * Date: 2016/6/25. */ -@SuppressWarnings({"unused", "UnusedReturnValue"}) +@SuppressWarnings({ "unused", "UnusedReturnValue" }) @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); @@ -67,7 +68,8 @@ public static String cutNumber(float f, int size) { @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public static Stream stream(Optional o) { - return o.map(Stream::of).orElse(Stream.empty()); + return o.map(Stream::of) + .orElse(Stream.empty()); } public static Supplier fake(Runnable r) { @@ -88,13 +90,16 @@ public static String repeat(String s, int n) { 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) { - return GameData.getItemRegistry().getNameForObject(item); + return GameData.getItemRegistry() + .getNameForObject(item); } public static String getName(ItemStack itemStack) { @@ -122,7 +127,8 @@ public static String getModName(Fluid fluid) { String iconName = icon.getIconName(); String modId = iconName.split(":")[0]; - Map indexedModList = Loader.instance().getIndexedModList(); + Map indexedModList = Loader.instance() + .getIndexedModList(); ModContainer modContainer = indexedModList.get(modId); if (modContainer == null) { String capitalizedModId = WordUtils.capitalize(modId); @@ -157,6 +163,7 @@ public static void addChatMessage(ChatMessage cm) { } public enum ChatMessage { + MAX_LOOP, RECIPE_TRANSFER_ERROR; @@ -173,6 +180,7 @@ private String get() { } public static class Relation { + public HashMap, V> data = new HashMap<>(); public void put(K a, K b, V v) { @@ -190,6 +198,7 @@ public V get(K a, K b) { } public static class Timer { + long time = System.currentTimeMillis(); boolean running = false; @@ -208,6 +217,7 @@ public long getTime() { @SuppressWarnings("UnusedReturnValue") public static class Circulator { + int total, current; public Circulator(int total) { @@ -250,6 +260,7 @@ public Circulator copy() { } public static class ReversedIterator implements Iterator { + ListIterator i; public ReversedIterator(List l) { @@ -278,6 +289,7 @@ public Stream stream() { @SideOnly(Side.CLIENT) public static class I18n { + public static boolean contains(String s1, String s2) { return s1.contains(s2); } @@ -297,18 +309,18 @@ public static String get(String translateKey, Object... parameters) { } 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 { + static FontRenderer renderer = ClientUtils.mc().fontRenderer; String str; @@ -367,6 +379,7 @@ else if (section > space) { } public static class Recent { + LinkedList data = new LinkedList<>(); BiPredicate tester; int limit; @@ -402,6 +415,7 @@ public int size() { } public static class Json { + @Nullable public static NBTTagCompound read(File f) { try { @@ -458,6 +472,8 @@ else if (parts.length == 2 || (parts.length == 3 && parts[2].startsWith("#"))) } public static String[] mergeStringArrays(String[]... arrays) { - return Stream.of(arrays).flatMap(Stream::of).toArray(String[]::new); + return Stream.of(arrays) + .flatMap(Stream::of) + .toArray(String[]::new); } } diff --git a/src/main/java/me/towdium/jecalculation/utils/Version.java b/src/main/java/me/towdium/jecalculation/utils/Version.java index d3342cc40..d7315b8d5 100644 --- a/src/main/java/me/towdium/jecalculation/utils/Version.java +++ b/src/main/java/me/towdium/jecalculation/utils/Version.java @@ -1,11 +1,13 @@ package me.towdium.jecalculation.utils; import javax.annotation.ParametersAreNonnullByDefault; + import me.towdium.jecalculation.polyfill.MethodsReturnNonnullByDefault; @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class Version implements Comparable { + private int major = 0, minor = 0, patch = 0; private String preRelease = ""; private final boolean success; diff --git a/src/main/java/me/towdium/jecalculation/utils/wrappers/Pair.java b/src/main/java/me/towdium/jecalculation/utils/wrappers/Pair.java index 4fad0b6bd..3fb67efff 100644 --- a/src/main/java/me/towdium/jecalculation/utils/wrappers/Pair.java +++ b/src/main/java/me/towdium/jecalculation/utils/wrappers/Pair.java @@ -2,9 +2,10 @@ /** * Author: Towdium - * Date: 2016/7/1. + * Date: 2016/7/1. */ public class Pair { + public K one; public V two; diff --git a/src/main/java/me/towdium/jecalculation/utils/wrappers/Quad.java b/src/main/java/me/towdium/jecalculation/utils/wrappers/Quad.java index 62daaed9c..92c198dc3 100644 --- a/src/main/java/me/towdium/jecalculation/utils/wrappers/Quad.java +++ b/src/main/java/me/towdium/jecalculation/utils/wrappers/Quad.java @@ -5,6 +5,7 @@ * Date: 18-12-7 */ public class Quad { + public T one; public U two; public V three; diff --git a/src/main/java/me/towdium/jecalculation/utils/wrappers/Trio.java b/src/main/java/me/towdium/jecalculation/utils/wrappers/Trio.java index 5a759000a..994aa679b 100644 --- a/src/main/java/me/towdium/jecalculation/utils/wrappers/Trio.java +++ b/src/main/java/me/towdium/jecalculation/utils/wrappers/Trio.java @@ -2,9 +2,10 @@ /** * Author: Towdium - * Date: 2016/7/1. + * Date: 2016/7/1. */ public class Trio { + public T one; public U two; public V three; 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 f4f4f411c..9f4b28ee4 100644 --- a/src/main/java/me/towdium/jecalculation/utils/wrappers/Wrapper.java +++ b/src/main/java/me/towdium/jecalculation/utils/wrappers/Wrapper.java @@ -4,13 +4,15 @@ import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; + import javax.annotation.Nullable; /** * Author: Towdium - * Date: 2016/7/1. + * Date: 2016/7/1. */ public class Wrapper { + public T value; public Predicate predicate = t -> true;