diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..4ffbd90 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,22 @@ +# This is the universal Text Editor Configuration +# for all GTNewHorizons projects +# See: https://editorconfig.org/ + +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{bat,ini}] +end_of_line = crlf + +[*.{dtd,json,info,mcmeta,md,sh,svg,xml,xsd,xsl,yaml,yml}] +indent_size = 2 + +[*.lang] +trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..fd2792b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,44 @@ +* text eol=lf + +*.[jJ][aA][rR] binary + +*.[pP][nN][gG] binary +*.[jJ][pP][gG] binary +*.[jJ][pP][eE][gG] binary +*.[gG][iI][fF] binary +*.[tT][iI][fF] binary +*.[tT][iI][fF][fF] binary +*.[iI][cC][oO] binary +*.[sS][vV][gG] text +*.[eE][pP][sS] binary +*.[xX][cC][fF] binary + +*.[kK][aA][rR] binary +*.[mM]4[aA] binary +*.[mM][iI][dD] binary +*.[mM][iI][dD][iI] binary +*.[mM][pP]3 binary +*.[oO][gG][gG] binary +*.[rR][aA] binary + +*.7[zZ] binary +*.[gG][zZ] binary +*.[tT][aA][rR] binary +*.[tT][gG][zZ] binary +*.[zZ][iI][pP] binary + +*.[tT][cC][nN] binary +*.[sS][oO] binary +*.[dD][lL][lL] binary +*.[dD][yY][lL][iI][bB] binary +*.[pP][sS][dD] binary +*.[tT][tT][fF] binary +*.[oO][tT][fF] binary + +*.[pP][aA][tT][cC][hH] -text + +*.[bB][aA][tT] text eol=crlf +*.[cC][mM][dD] text eol=crlf +*.[pP][sS]1 text eol=crlf + +*[aA][uU][tT][oO][gG][eE][nN][eE][rR][aA][tT][eE][dD]* binary diff --git a/.github/scripts/update_version b/.github/scripts/update_version new file mode 100644 index 0000000..3e5f752 --- /dev/null +++ b/.github/scripts/update_version @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +if ! git diff --name-only HEAD HEAD~1 | grep -qF 'build.gradle'; then + new_version="$(date +%s)" + sed --in-place "s!^//version:.*!//version: $new_version!g" build.gradle + git add build.gradle + git commit -m "[ci skip] update build script version to $new_version" + git push + printf 'Updated buildscript version to %s\n' "$new_version" +else + printf 'Ignored buildscript version update: no changes detected\n' +fi diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml new file mode 100644 index 0000000..3ee2f68 --- /dev/null +++ b/.github/workflows/build-and-test.yml @@ -0,0 +1,13 @@ + +name: Build and test + +on: + pull_request: + branches: [ master, main ] + push: + branches: [ master, main ] + +jobs: + build-and-test: + uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/build-and-test.yml@master + secrets: inherit diff --git a/.github/workflows/release-tags.yml b/.github/workflows/release-tags.yml new file mode 100644 index 0000000..e4c0be6 --- /dev/null +++ b/.github/workflows/release-tags.yml @@ -0,0 +1,14 @@ + +name: Release tagged build + +on: + push: + tags: [ '*' ] + +permissions: + contents: write + +jobs: + release-tags: + uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/release-tags.yml@master + secrets: inherit diff --git a/.gitignore b/.gitignore index 73f9454..48c525b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,32 @@ -.gradle/ -build/ -out/ -run/ -server/ -eclipse/ -src/META-INF/ -/*.iws -/*.ipr -/*.iml -bin/ +.gradle +.settings +/.idea/ +/.vscode/ +/run/ +/build/ +/eclipse/ .classpath .project -.settings/ \ No newline at end of file +/bin/ +/config/ +/crash-reports/ +/logs/ +options.txt +/saves/ +usernamecache.json +banned-ips.json +banned-players.json +eula.txt +ops.json +server.properties +servers.dat +usercache.json +whitelist.json +/out/ +*.iml +*.ipr +*.iws +src/main/resources/mixins.*.json +*.bat +*.DS_Store +!gradlew.bat diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..a6b5f68 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,3 @@ +# Any Github changes require admin approval +/.github/** @GTNewHorizons/admin + diff --git a/build.gradle b/build.gradle index 5a82c0d..bc7fcfd 100644 --- a/build.gradle +++ b/build.gradle @@ -1,54 +1,1103 @@ +//version: 1666118075 +/* + DO NOT CHANGE THIS FILE! + Also, you may replace this file at any time if there is an update available. + Please check https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/main/build.gradle for updates. + */ + + +import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar +import com.matthewprenger.cursegradle.CurseArtifact +import com.matthewprenger.cursegradle.CurseRelation +import com.modrinth.minotaur.dependencies.ModDependency +import com.modrinth.minotaur.dependencies.VersionDependency +import org.gradle.internal.logging.text.StyledTextOutput.Style +import org.gradle.internal.logging.text.StyledTextOutputFactory + +import java.nio.file.Files +import java.nio.file.Paths +import java.util.concurrent.TimeUnit +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream +import java.util.zip.ZipOutputStream + buildscript { repositories { mavenCentral() + maven { - name = "forge" - url = "http://files.minecraftforge.net/maven" + name 'forge' + url 'https://maven.minecraftforge.net' } maven { - name = "sonatype" - url = "https://oss.sonatype.org/content/repositories/snapshots/" + // GTNH ForgeGradle Fork + name = "GTNH Maven" + url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" + } + maven { + name 'sonatype' + url 'https://oss.sonatype.org/content/repositories/snapshots/' + } + maven { + name 'Scala CI dependencies' + url 'https://repo1.maven.org/maven2/' } } dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' + classpath 'net.minecraftforge.gradle:ForgeGradle:1.2.9' } } +plugins { + id 'java-library' + id 'idea' + id 'eclipse' + id 'scala' + id 'maven-publish' + id 'org.jetbrains.kotlin.jvm' version '1.5.30' apply false + id 'org.jetbrains.kotlin.kapt' version '1.5.30' apply false + id 'com.google.devtools.ksp' version '1.5.30-1.0.0' apply false + id 'org.ajoberstar.grgit' version '4.1.1' + id 'com.github.johnrengelman.shadow' version '4.0.4' + id 'com.palantir.git-version' version '0.13.0' apply false + id 'de.undercouch.download' version '5.0.1' + id 'com.github.gmazzo.buildconfig' version '3.0.3' apply false + id 'com.diffplug.spotless' version '6.7.2' apply false + id 'com.modrinth.minotaur' version '2.+' apply false + id 'com.matthewprenger.cursegradle' version '1.4.0' apply false +} +boolean settingsupdated = verifySettingsGradle() +settingsupdated = verifyGitAttributes() || settingsupdated +if (settingsupdated) + throw new GradleException("Settings has been updated, please re-run task.") + +dependencies { + implementation 'com.diffplug:blowdryer:1.6.0' +} + +apply plugin: 'com.diffplug.blowdryer' + +if (project.file('.git/HEAD').isFile()) { + apply plugin: 'com.palantir.git-version' +} + +def out = services.get(StyledTextOutputFactory).create('an-output') apply plugin: 'forge' -version = "1.7.10-1.0.4b" -group= "singulariteam.eternalsingularity" // http://maven.apache.org/guides/mini/guide-naming-conventions.html -archivesBaseName = "EternalSingularity" +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()) +} + +checkPropertyExists("modName") +checkPropertyExists("modId") +checkPropertyExists("modGroup") +checkPropertyExists("autoUpdateBuildScript") +checkPropertyExists("minecraftVersion") +checkPropertyExists("forgeVersion") +checkPropertyExists("replaceGradleTokenInFile") +checkPropertyExists("gradleTokenModId") +checkPropertyExists("gradleTokenModName") +checkPropertyExists("gradleTokenVersion") +checkPropertyExists("gradleTokenGroupName") +checkPropertyExists("apiPackage") +checkPropertyExists("accessTransformersFile") +checkPropertyExists("usesMixins") +checkPropertyExists("mixinPlugin") +checkPropertyExists("mixinsPackage") +checkPropertyExists("coreModClass") +checkPropertyExists("containsMixinsAndOrCoreModOnly") +checkPropertyExists("usesShadowedDependencies") +checkPropertyExists("developmentEnvironmentUserName") + +propertyDefaultIfUnset("noPublishedSources", false) +propertyDefaultIfUnset("usesMixinDebug", project.usesMixins) +propertyDefaultIfUnset("forceEnableMixins", false) +propertyDefaultIfUnset("channel", "stable") +propertyDefaultIfUnset("mappingsVersion", "12") +propertyDefaultIfUnset("modrinthProjectId", "") +propertyDefaultIfUnset("modrinthRelations", "") +propertyDefaultIfUnset("curseForgeProjectId", "") +propertyDefaultIfUnset("curseForgeRelations", "") + +String javaSourceDir = "src/main/java/" +String scalaSourceDir = "src/main/scala/" +String kotlinSourceDir = "src/main/kotlin/" + + +final String modGroupPath = modGroup.toString().replaceAll("\\.", "/") +final String apiPackagePath = apiPackage.toString().replaceAll("\\.", "/") + +String targetPackageJava = javaSourceDir + modGroupPath +String targetPackageScala = scalaSourceDir + modGroupPath +String targetPackageKotlin = kotlinSourceDir + modGroupPath +if (!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { + throw new GradleException("Could not resolve \"modGroup\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) +} + +if (apiPackage) { + targetPackageJava = javaSourceDir + modGroupPath + "/" + apiPackagePath + targetPackageScala = scalaSourceDir + modGroupPath + "/" + apiPackagePath + targetPackageKotlin = kotlinSourceDir + modGroupPath + "/" + apiPackagePath + if (!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { + throw new GradleException("Could not resolve \"apiPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) + } +} + +if (accessTransformersFile) { + String targetFile = "src/main/resources/META-INF/" + accessTransformersFile + if (!getFile(targetFile).exists()) { + throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile) + } +} + +if (usesMixins.toBoolean()) { + if (mixinsPackage.isEmpty()) { + throw new GradleException("\"usesMixins\" requires \"mixinsPackage\" to be set!") + } + final String mixinPackagePath = mixinsPackage.toString().replaceAll("\\.", "/") + final String mixinPluginPath = mixinPlugin.toString().replaceAll("\\.", "/") + + targetPackageJava = javaSourceDir + modGroupPath + "/" + mixinPackagePath + targetPackageScala = scalaSourceDir + modGroupPath + "/" + mixinPackagePath + targetPackageKotlin = kotlinSourceDir + modGroupPath + "/" + mixinPackagePath + if (!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { + throw new GradleException("Could not resolve \"mixinsPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) + } + + if (!mixinPlugin.isEmpty()) { + String targetFileJava = javaSourceDir + modGroupPath + "/" + mixinPluginPath + ".java" + String targetFileScala = scalaSourceDir + modGroupPath + "/" + mixinPluginPath + ".scala" + String targetFileScalaJava = scalaSourceDir + modGroupPath + "/" + mixinPluginPath + ".java" + String targetFileKotlin = kotlinSourceDir + modGroupPath + "/" + mixinPluginPath + ".kt" + if (!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { + throw new GradleException("Could not resolve \"mixinPlugin\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava + " or " + targetFileKotlin) + } + } +} + +if (coreModClass) { + final String coreModPath = coreModClass.toString().replaceAll("\\.", "/") + String targetFileJava = javaSourceDir + modGroupPath + "/" + coreModPath + ".java" + String targetFileScala = scalaSourceDir + modGroupPath + "/" + coreModPath + ".scala" + String targetFileScalaJava = scalaSourceDir + modGroupPath + "/" + coreModPath + ".java" + String targetFileKotlin = kotlinSourceDir + modGroupPath + "/" + coreModPath + ".kt" + if (!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { + throw new GradleException("Could not resolve \"coreModClass\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava + " or " + targetFileKotlin) + } +} + +configurations.all { + resolutionStrategy.cacheChangingModulesFor(0, TimeUnit.SECONDS) + + // Make sure GregTech build won't time out + System.setProperty("org.gradle.internal.http.connectionTimeout", 120000 as String) + System.setProperty("org.gradle.internal.http.socketTimeout", 120000 as String) +} + +// Fix Jenkins' Git: chmod a file should not be detected as a change and append a '.dirty' to the version +try { + 'git config core.fileMode false'.execute() +} +catch (Exception ignored) { + out.style(Style.Failure).println("git isn't installed at all") +} + +// Pulls version first from the VERSION env and then git tag +String identifiedVersion +String versionOverride = System.getenv("VERSION") ?: null +try { + identifiedVersion = versionOverride == null ? gitVersion() : versionOverride +} +catch (Exception ignored) { + out.style(Style.Failure).text( + 'This mod must be version controlled by Git AND the repository must provide at least one tag,\n' + + 'or the VERSION override must be set! ').style(Style.SuccessHeader).text('(Do NOT download from GitHub using the ZIP option, instead\n' + + 'clone the repository, see ').style(Style.Info).text('https://gtnh.miraheze.org/wiki/Development').style(Style.SuccessHeader).println(' for details.)' + ) + versionOverride = 'NO-GIT-TAG-SET' + identifiedVersion = versionOverride +} +version = minecraftVersion + '-' + identifiedVersion +ext { + modVersion = identifiedVersion +} + +if (identifiedVersion == versionOverride) { + out.style(Style.Failure).text('Override version to ').style(Style.Identifier).text(modVersion).style(Style.Failure).println('!\7') +} + +group = modGroup +if (project.hasProperty("customArchiveBaseName") && customArchiveBaseName) { + archivesBaseName = customArchiveBaseName +} else { + archivesBaseName = modId +} + +def arguments = [] +def jvmArguments = [] + +if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { + arguments += [ + "--tweakClass org.spongepowered.asm.launch.MixinTweaker" + ] + if (usesMixinDebug.toBoolean()) { + jvmArguments += [ + "-Dmixin.debug.countInjections=true", + "-Dmixin.debug.verbose=true", + "-Dmixin.debug.export=true" + ] + } +} minecraft { - version = "1.7.10-10.13.4.1614-1.7.10" - runDir = "run" + version = minecraftVersion + '-' + forgeVersion + '-' + minecraftVersion + runDir = 'run' + + if (replaceGradleTokenInFile) { + replaceIn replaceGradleTokenInFile + if (gradleTokenModId) { + replace gradleTokenModId, modId + } + if (gradleTokenModName) { + replace gradleTokenModName, modName + } + if (gradleTokenVersion) { + replace gradleTokenVersion, modVersion + } + if (gradleTokenGroupName) { + replace gradleTokenGroupName, modGroup + } + } + + clientIntellijRun { + args(arguments) + jvmArgs(jvmArguments) + + if (developmentEnvironmentUserName) { + args("--username", developmentEnvironmentUserName) + } + } + + serverIntellijRun { + args(arguments) + jvmArgs(jvmArguments) + } } -sourceCompatibility = 1.8 -targetCompatibility = 1.8 +if (file('addon.gradle').exists()) { + apply from: 'addon.gradle' +} + +apply from: 'repositories.gradle' + +configurations { + implementation.extendsFrom(shadowImplementation) // TODO: remove after all uses are refactored + implementation.extendsFrom(shadowCompile) + implementation.extendsFrom(shadeCompile) +} + +repositories { + maven { + 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/" + } + } +} dependencies { - compile fileTree(dir: 'libs', include: '*.jar') + if (usesMixins.toBoolean()) { + annotationProcessor('org.ow2.asm:asm-debug-all:5.0.3') + annotationProcessor('com.google.guava:guava:24.1.1-jre') + annotationProcessor('com.google.code.gson:gson:2.8.6') + annotationProcessor('org.spongepowered:mixin:0.8.5-GTNH:processor') + } + if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { + compile('com.gtnewhorizon:gtnhmixins:2.0.1') + } } -processResources -{ +apply from: 'dependencies.gradle' + +def mixingConfigRefMap = 'mixins.' + modId + '.refmap.json' +def refMap = "${tasks.compileJava.temporaryDir}" + File.separator + mixingConfigRefMap +def mixinSrg = "${tasks.reobf.temporaryDir}" + File.separator + "mixins.srg" + +task generateAssets { + if (usesMixins.toBoolean()) { + def mixinConfigFile = getFile("/src/main/resources/mixins." + modId + ".json") + if (!mixinConfigFile.exists()) { + def mixinPluginLine = "" + if(!mixinPlugin.isEmpty()) { + // We might not have a mixin plugin if we're using early/late mixins + mixinPluginLine += """\n "plugin": "${modGroup}.${mixinPlugin}", """ + } + + mixinConfigFile.text = """{ + "required": true, + "minVersion": "0.8.5-GTNH", + "package": "${modGroup}.${mixinsPackage}",${mixinPluginLine} + "refmap": "${mixingConfigRefMap}", + "target": "@env(DEFAULT)", + "compatibilityLevel": "JAVA_8", + "mixins": [], + "client": [], + "server": [] +} +""" + } + } +} + +task relocateShadowJar(type: ConfigureShadowRelocation) { + target = tasks.shadowJar + prefix = modGroup + ".shadow" +} + +shadowJar { + project.configurations.shadeCompile.each { dep -> + from(project.zipTree(dep)) { + exclude 'META-INF', 'META-INF/**' + } + } + + manifest { + attributes(getManifestAttributes()) + } + + minimize() // This will only allow shading for actually used classes + configurations = [ + project.configurations.shadowImplementation, + project.configurations.shadowCompile + ] + dependsOn(relocateShadowJar) +} + +jar { + project.configurations.shadeCompile.each { dep -> + from(project.zipTree(dep)) { + exclude 'META-INF', 'META-INF/**' + } + } + + manifest { + attributes(getManifestAttributes()) + } + + if (usesShadowedDependencies.toBoolean()) { + dependsOn(shadowJar) + enabled = false + } +} + +reobf { + if (usesMixins.toBoolean()) { + addExtraSrgFile mixinSrg + } +} + +afterEvaluate { + if (usesMixins.toBoolean()) { + tasks.compileJava { + options.compilerArgs += [ + "-AreobfSrgFile=${tasks.reobf.srg}", + "-AoutSrgFile=${mixinSrg}", + "-AoutRefMapFile=${refMap}", + // Elan: from what I understand they are just some linter configs so you get some warning on how to properly code + "-XDenableSunApiLintControl", + "-XDignore.symbol.file" + ] + } + } +} + +runClient { + if (developmentEnvironmentUserName) { + arguments += [ + "--username", + developmentEnvironmentUserName + ] + } + + args(arguments) + jvmArgs(jvmArguments) +} + +runServer { + args(arguments) + jvmArgs(jvmArguments) +} + +tasks.withType(JavaExec).configureEach { + javaLauncher.set( + javaToolchains.launcherFor { + languageVersion = projectJavaVersion + } + ) +} + +processResources { // this will ensure that this task is redone when the versions change. inputs.property "version", project.version inputs.property "mcversion", project.minecraft.version + exclude("spotless.gradle") // replace stuff in mcmod.info, nothing else from(sourceSets.main.resources.srcDirs) { include 'mcmod.info' - - // replace version and mcversion - expand 'version':project.version, 'mcversion':project.minecraft.version + + // replace modVersion and minecraftVersion + expand "minecraftVersion": project.minecraft.version, + "modVersion": modVersion, + "modId": modId, + "modName": modName } - - // copy everything else, thats not the mcmod.info + + if (usesMixins.toBoolean()) { + from refMap + } + + // copy everything else that's not the mcmod.info from(sourceSets.main.resources.srcDirs) { exclude 'mcmod.info' + exclude 'spotless.gradle' } } + +def getManifestAttributes() { + def manifestAttributes = [:] + if (!containsMixinsAndOrCoreModOnly.toBoolean() && (usesMixins.toBoolean() || coreModClass)) { + manifestAttributes += ["FMLCorePluginContainsFMLMod": true] + } + + if (accessTransformersFile) { + manifestAttributes += ["FMLAT": accessTransformersFile.toString()] + } + + if (coreModClass) { + manifestAttributes += ["FMLCorePlugin": modGroup + "." + coreModClass] + } + + if (usesMixins.toBoolean()) { + manifestAttributes += [ + "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", + "MixinConfigs" : "mixins." + modId + ".json", + "ForceLoadAsMod": !containsMixinsAndOrCoreModOnly.toBoolean() + ] + } + return manifestAttributes +} + +task sourcesJar(type: Jar) { + from(sourceSets.main.allSource) + from(file("$projectDir/LICENSE")) + getArchiveClassifier().set('sources') +} + +task shadowDevJar(type: ShadowJar) { + project.configurations.shadeCompile.each { dep -> + from(project.zipTree(dep)) { + exclude 'META-INF', 'META-INF/**' + } + } + + from sourceSets.main.output + getArchiveClassifier().set("dev") + + manifest { + attributes(getManifestAttributes()) + } + + minimize() // This will only allow shading for actually used classes + configurations = [ + project.configurations.shadowImplementation, + project.configurations.shadowCompile + ] +} + +task relocateShadowDevJar(type: ConfigureShadowRelocation) { + target = tasks.shadowDevJar + prefix = modGroup + ".shadow" +} + +task circularResolverJar(type: Jar) { + dependsOn(relocateShadowDevJar) + dependsOn(shadowDevJar) + enabled = false +} + +task devJar(type: Jar) { + project.configurations.shadeCompile.each { dep -> + from(project.zipTree(dep)) { + exclude 'META-INF', 'META-INF/**' + } + } + + from sourceSets.main.output + getArchiveClassifier().set("dev") + + manifest { + attributes(getManifestAttributes()) + } + + if (usesShadowedDependencies.toBoolean()) { + dependsOn(circularResolverJar) + enabled = false + } +} + +task apiJar(type: Jar) { + from(sourceSets.main.allSource) { + include modGroupPath + "/" + apiPackagePath + '/**' + } + + from(sourceSets.main.output) { + include modGroupPath + "/" + apiPackagePath + '/**' + } + + from(sourceSets.main.resources.srcDirs) { + include("LICENSE") + } + + getArchiveClassifier().set('api') +} + +artifacts { + if (!noPublishedSources) { + archives sourcesJar + } + archives devJar + if (apiPackage) { + archives apiJar + } +} + +// The gradle metadata includes all of the additional deps that we disabled from POM generation (including forgeBin with no groupID), +// and isn't strictly needed with the POM so just disable it. +tasks.withType(GenerateModuleMetadata) { + enabled = false +} + +// workaround variable hiding in pom processing +def projectConfigs = project.configurations + +publishing { + publications { + maven(MavenPublication) { + from components.java + if (usesShadowedDependencies.toBoolean()) { + artifact source: shadowJar, classifier: "" + } + if (!noPublishedSources) { + artifact source: sourcesJar, classifier: "sources" + } + artifact source: usesShadowedDependencies.toBoolean() ? shadowDevJar : devJar, classifier: "dev" + if (apiPackage) { + artifact source: apiJar, classifier: "api" + } + + groupId = System.getenv("ARTIFACT_GROUP_ID") ?: "com.github.GTNewHorizons" + artifactId = System.getenv("ARTIFACT_ID") ?: project.name + // Using the identified version, not project.version as it has the prepended 1.7.10 + version = System.getenv("RELEASE_VERSION") ?: identifiedVersion + + // remove extra garbage from minecraft and minecraftDeps configuration + pom.withXml { + def badArtifacts = [:].withDefault { [] as Set } + for (configuration in [ + projectConfigs.minecraft, + projectConfigs.minecraftDeps + ]) { + for (dependency in configuration.allDependencies) { + badArtifacts[dependency.group == null ? "" : dependency.group] += dependency.name + } + } + // example for specifying extra stuff to ignore + // badArtifacts["org.example.group"] += "artifactName" + + Node pomNode = asNode() + pomNode.dependencies.'*'.findAll() { + badArtifacts[it.groupId.text()].contains(it.artifactId.text()) + }.each() { + it.parent().remove(it) + } + } + } + } + + repositories { + maven { + url = "http://jenkins.usrv.eu:8081/nexus/content/repositories/releases" + credentials { + username = System.getenv("MAVEN_USER") ?: "NONE" + password = System.getenv("MAVEN_PASSWORD") ?: "NONE" + } + } + } +} + +if (modrinthProjectId.size() != 0 && System.getenv("MODRINTH_TOKEN") != null) { + apply plugin: 'com.modrinth.minotaur' + + File changelogFile = new File(System.getenv("CHANGELOG_FILE") ?: "CHANGELOG.md") + + modrinth { + token = System.getenv("MODRINTH_TOKEN") + projectId = modrinthProjectId + versionNumber = identifiedVersion + versionType = identifiedVersion.endsWith("-pre") ? "beta" : "release" + changelog = changelogFile.exists() ? changelogFile.getText("UTF-8") : "" + uploadFile = jar + additionalFiles = getSecondaryArtifacts() + gameVersions = [minecraftVersion] + loaders = ["forge"] + debugMode = false + } + + if (modrinthRelations.size() != 0) { + String[] deps = modrinthRelations.split(";") + deps.each { dep -> + if (dep.size() == 0) { + return + } + String[] parts = dep.split(":") + String[] qual = parts[0].split("-") + addModrinthDep(qual[0], qual[1], parts[1]) + } + } + if (usesMixins.toBoolean()) { + addModrinthDep("required", "version", "gtnhmixins") + } + tasks.modrinth.dependsOn(build) + tasks.publish.dependsOn(tasks.modrinth) +} + +if (curseForgeProjectId.size() != 0 && System.getenv("CURSEFORGE_TOKEN") != null) { + apply plugin: 'com.matthewprenger.cursegradle' + + File changelogFile = new File(System.getenv("CHANGELOG_FILE") ?: "CHANGELOG.md") + + curseforge { + apiKey = System.getenv("CURSEFORGE_TOKEN") + project { + id = curseForgeProjectId + if (changelogFile.exists()) { + changelogType = "markdown" + changelog = changelogFile + } + releaseType = identifiedVersion.endsWith("-pre") ? "beta" : "release" + addGameVersion minecraftVersion + addGameVersion "Forge" + mainArtifact jar + for (artifact in getSecondaryArtifacts()) addArtifact artifact + } + + options { + javaIntegration = false + forgeGradleIntegration = false + debug = false + } + } + + if (curseForgeRelations.size() != 0) { + String[] deps = curseForgeRelations.split(";") + deps.each { dep -> + if (dep.size() == 0) { + return + } + String[] parts = dep.split(":") + addCurseForgeRelation(parts[0], parts[1]) + } + } + if (usesMixins.toBoolean()) { + addCurseForgeRelation("requiredDependency", "gtnhmixins") + } + tasks.curseforge.dependsOn(build) + tasks.publish.dependsOn(tasks.curseforge) +} + +def addModrinthDep(scope, type, name) { + com.modrinth.minotaur.dependencies.Dependency dep; + if (!(scope in ["required", "optional", "incompatible", "embedded"])) { + throw new Exception("Invalid modrinth dependency scope: " + scope) + } + switch (type) { + case "project": + dep = new ModDependency(name, scope) + break + case "version": + dep = new VersionDependency(name, scope) + break + default: + throw new Exception("Invalid modrinth dependency type: " + type) + } + project.modrinth.dependencies.add(dep) +} + +def addCurseForgeRelation(type, name) { + if (!(type in ["requiredDependency", "embeddedLibrary", "optionalDependency", "tool", "incompatible"])) { + throw new Exception("Invalid CurseForge relation type: " + type) + } + CurseArtifact artifact = project.curseforge.curseProjects[0].mainArtifact + CurseRelation rel = (artifact.curseRelations ?: (artifact.curseRelations = new CurseRelation())) + rel."$type"(name) +} + +// Updating +task updateBuildScript { + doLast { + if (performBuildScriptUpdate(projectDir.toString())) return + + print("Build script already up-to-date!") + } +} + +if (!project.getGradle().startParameter.isOffline() && isNewBuildScriptVersionAvailable(projectDir.toString())) { + if (autoUpdateBuildScript.toBoolean()) { + performBuildScriptUpdate(projectDir.toString()) + } else { + out.style(Style.SuccessHeader).println("Build script update available! Run 'gradle updateBuildScript'") + } +} + +static URL availableBuildScriptUrl() { + new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/master/build.gradle") +} + +static URL exampleSettingsGradleUrl() { + new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/master/settings.gradle.example") +} + +static URL exampleGitAttributesUrl() { + new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/master/.gitattributes") +} + + +boolean verifyGitAttributes() { + def gitattributesFile = getFile(".gitattributes") + if (!gitattributesFile.exists()) { + println("Downloading default .gitattributes") + exampleGitAttributesUrl().withInputStream { i -> gitattributesFile.withOutputStream { it << i } } + exec { + workingDir '.' + commandLine 'git', 'add', '--renormalize', '.' + } + return true + } + return false +} + +boolean verifySettingsGradle() { + def settingsFile = getFile("settings.gradle") + if (!settingsFile.exists()) { + println("Downloading default settings.gradle") + exampleSettingsGradleUrl().withInputStream { i -> settingsFile.withOutputStream { it << i } } + return true + } + return false +} + +boolean performBuildScriptUpdate(String projectDir) { + if (isNewBuildScriptVersionAvailable(projectDir)) { + def buildscriptFile = getFile("build.gradle") + availableBuildScriptUrl().withInputStream { i -> buildscriptFile.withOutputStream { it << i } } + out.style(Style.Success).print("Build script updated. Please REIMPORT the project or RESTART your IDE!") + boolean settingsupdated = verifySettingsGradle() + settingsupdated = verifyGitAttributes() || settingsupdated + if (settingsupdated) + throw new GradleException("Settings has been updated, please re-run task.") + return true + } + return false +} + +boolean isNewBuildScriptVersionAvailable(String projectDir) { + Map parameters = ["connectTimeout": 2000, "readTimeout": 2000] + + String currentBuildScript = getFile("build.gradle").getText() + String currentBuildScriptHash = getVersionHash(currentBuildScript) + String availableBuildScript = availableBuildScriptUrl().newInputStream(parameters).getText() + String availableBuildScriptHash = getVersionHash(availableBuildScript) + + boolean isUpToDate = currentBuildScriptHash.empty || availableBuildScriptHash.empty || currentBuildScriptHash == availableBuildScriptHash + return !isUpToDate +} + +static String getVersionHash(String buildScriptContent) { + String versionLine = buildScriptContent.find("^//version: [a-z0-9]*") + if (versionLine != null) { + return versionLine.split(": ").last() + } + return "" +} + +configure(updateBuildScript) { + group = 'forgegradle' + description = 'Updates the build script to the latest version' +} + +// Parameter Deobfuscation + +task deobfParams { + doLast { + + String mcpDir = "$project.gradle.gradleUserHomeDir/caches/minecraft/de/oceanlabs/mcp/mcp_$channel/$mappingsVersion" + String mcpZIP = "$mcpDir/mcp_$channel-$mappingsVersion-${minecraftVersion}.zip" + String paramsCSV = "$mcpDir/params.csv" + + download.run { + src "https://maven.minecraftforge.net/de/oceanlabs/mcp/mcp_$channel/$mappingsVersion-$minecraftVersion/mcp_$channel-$mappingsVersion-${minecraftVersion}.zip" + dest mcpZIP + overwrite false + } + + if (!file(paramsCSV).exists()) { + println("Extracting MCP archive ...") + unzip(mcpZIP, mcpDir) + } + + println("Parsing params.csv ...") + Map params = new HashMap<>() + Files.lines(Paths.get(paramsCSV)).forEach { line -> + String[] cells = line.split(",") + if (cells.length > 2 && cells[0].matches("p_i?\\d+_\\d+_")) { + params.put(cells[0], cells[1]) + } + } + + out.style(Style.Success).println("Modified ${replaceParams(file("$projectDir/src/main/java"), params)} files!") + out.style(Style.Failure).println("Don't forget to verify that the code still works as before!\n It could be broken due to duplicate variables existing now\n or parameters taking priority over other variables.") + } +} + +static int replaceParams(File file, Map params) { + int fileCount = 0 + + if (file.isDirectory()) { + for (File f : file.listFiles()) { + fileCount += replaceParams(f, params) + } + return fileCount + } + println("Visiting ${file.getName()} ...") + try { + String content = new String(Files.readAllBytes(file.toPath())) + int hash = content.hashCode() + params.forEach { key, value -> + content = content.replaceAll(key, value) + } + if (hash != content.hashCode()) { + Files.write(file.toPath(), content.getBytes("UTF-8")) + return 1 + } + } catch (Exception e) { + e.printStackTrace() + } + return 0 +} + +// Credit: bitsnaps (https://gist.github.com/bitsnaps/00947f2dce66f4bbdabc67d7e7b33681) +static unzip(String zipFileName, String outputDir) { + byte[] buffer = new byte[16384] + ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName)) + ZipEntry zipEntry = zis.getNextEntry() + while (zipEntry != null) { + File newFile = new File(outputDir + File.separator, zipEntry.name) + if (zipEntry.isDirectory()) { + if (!newFile.isDirectory() && !newFile.mkdirs()) { + throw new IOException("Failed to create directory $newFile") + } + } else { + // fix for Windows-created archives + File parent = newFile.parentFile + if (!parent.isDirectory() && !parent.mkdirs()) { + throw new IOException("Failed to create directory $parent") + } + // write file content + FileOutputStream fos = new FileOutputStream(newFile) + int len = 0 + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len) + } + fos.close() + } + zipEntry = zis.getNextEntry() + } + zis.closeEntry() + zis.close() +} + +configure(deobfParams) { + group = 'forgegradle' + description = 'Rename all obfuscated parameter names inherited from Minecraft classes' +} + +// Dependency Deobfuscation + +def deobf(String sourceURL) { + try { + URL url = new URL(sourceURL) + String fileName = url.getFile() + + //get rid of directories: + int lastSlash = fileName.lastIndexOf("/") + if (lastSlash > 0) { + fileName = fileName.substring(lastSlash + 1) + } + //get rid of extension: + if (fileName.endsWith(".jar") || fileName.endsWith(".litemod")) { + fileName = fileName.substring(0, fileName.lastIndexOf(".")) + } + + String hostName = url.getHost() + if (hostName.startsWith("www.")) { + hostName = hostName.substring(4) + } + List parts = Arrays.asList(hostName.split("\\.")) + Collections.reverse(parts) + hostName = String.join(".", parts) + + return deobf(sourceURL, "$hostName/$fileName") + } catch (Exception e) { + return deobf(sourceURL, "deobf/${sourceURL.hashCode()}") + } +} + +// The method above is to be preferred. Use this method if the filename is not at the end of the URL. +def deobf(String sourceURL, String rawFileName) { + String bon2Version = "2.5.1" + String fileName = URLDecoder.decode(rawFileName, "UTF-8") + String cacheDir = "$project.gradle.gradleUserHomeDir/caches" + String bon2Dir = "$cacheDir/forge_gradle/deobf" + String bon2File = "$bon2Dir/BON2-${bon2Version}.jar" + String obfFile = "$cacheDir/modules-2/files-2.1/${fileName}.jar" + String deobfFile = "$cacheDir/modules-2/files-2.1/${fileName}-deobf.jar" + + if (file(deobfFile).exists()) { + return files(deobfFile) + } + + String mappingsVer + String remoteMappings = project.hasProperty('remoteMappings') ? project.remoteMappings : 'https://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/conf/' + if (remoteMappings) { + String id = "${forgeVersion.split("\\.")[3]}-$minecraftVersion" + String mappingsZIP = "$cacheDir/forge_gradle/maven_downloader/de/oceanlabs/mcp/mcp_snapshot_nodoc/$id/mcp_snapshot_nodoc-${id}.zip" + + zipMappings(mappingsZIP, remoteMappings, bon2Dir) + + mappingsVer = "snapshot_$id" + } else { + mappingsVer = "${channel}_$mappingsVersion" + } + + download.run { + src "http://jenkins.usrv.eu:8081/nexus/content/repositories/releases/com/github/parker8283/BON2/$bon2Version-CUSTOM/BON2-$bon2Version-CUSTOM-all.jar" + dest bon2File + quiet true + overwrite false + } + + download.run { + src sourceURL + dest obfFile + quiet true + overwrite false + } + + exec { + commandLine 'java', '-jar', bon2File, '--inputJar', obfFile, '--outputJar', deobfFile, '--mcVer', minecraftVersion, '--mappingsVer', mappingsVer, '--notch' + workingDir bon2Dir + standardOutput = new FileOutputStream("${deobfFile}.log") + } + + return files(deobfFile) +} + +def zipMappings(String zipPath, String url, String bon2Dir) { + File zipFile = new File(zipPath) + if (zipFile.exists()) { + return + } + + String fieldsCache = "$bon2Dir/data/fields.csv" + String methodsCache = "$bon2Dir/data/methods.csv" + + download.run { + src "${url}fields.csv" + dest fieldsCache + quiet true + } + download.run { + src "${url}methods.csv" + dest methodsCache + quiet true + } + + zipFile.getParentFile().mkdirs() + ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)) + + zos.putNextEntry(new ZipEntry("fields.csv")) + Files.copy(Paths.get(fieldsCache), zos) + zos.closeEntry() + + zos.putNextEntry(new ZipEntry("methods.csv")) + Files.copy(Paths.get(methodsCache), zos) + zos.closeEntry() + + zos.close() +} + +// Helper methods + +def checkPropertyExists(String propertyName) { + if (!project.hasProperty(propertyName)) { + throw new GradleException("This project requires a property \"" + propertyName + "\"! Please add it your \"gradle.properties\". You can find all properties and their description here: https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/main/gradle.properties") + } +} + +def propertyDefaultIfUnset(String propertyName, defaultValue) { + if (!project.hasProperty(propertyName) || project.property(propertyName) == "") { + project.ext.setProperty(propertyName, defaultValue) + } +} + +def getFile(String relativePath) { + return new File(projectDir, relativePath) +} + +def getSecondaryArtifacts() { + // Because noPublishedSources from the beginning of the script is somehow not visible here... + boolean noPublishedSources = project.hasProperty("noPublishedSources") ? project.noPublishedSources.toBoolean() : false + def secondaryArtifacts = [devJar] + if (!noPublishedSources) secondaryArtifacts += [sourcesJar] + if (apiPackage) secondaryArtifacts += [apiJar] + return secondaryArtifacts +} diff --git a/dependencies.gradle b/dependencies.gradle new file mode 100644 index 0000000..b6456d0 --- /dev/null +++ b/dependencies.gradle @@ -0,0 +1,5 @@ +// Add your dependencies here + +dependencies { + +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..a0ae88d --- /dev/null +++ b/gradle.properties @@ -0,0 +1,116 @@ +modName = Eternal Singularity + +# This is a case-sensitive string to identify your mod. Convention is to use lower case. +modId = eternalsingularity + +modGroup = singulariteam.eternalsingularity + +# WHY is there no version field? +# The build script relies on git to provide a version via tags. It is super easy and will enable you to always know the +# code base or your binary. Check out this tutorial: https://blog.mattclemente.com/2017/10/13/versioning-with-git-tags/ + +# Will update your build.gradle automatically whenever an update is available +autoUpdateBuildScript = false + +minecraftVersion = 1.7.10 +forgeVersion = 10.13.4.1614 + +# Specify a MCP channel and mappings version for dependency deobfuscation and the deobfParams task. +channel = stable +mappingsVersion = 12 + +# Define other MCP mappings for dependency deobfuscation +remoteMappings = https://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/conf/ + +# Select a username for testing your mod with breakpoints. You may leave this empty for a random username each time you +# restart Minecraft in development. Choose this dependent on your mod: +# Do you need consistent player progressing (for example Thaumcraft)? -> Select a name +# Do you need to test how your custom blocks interacts with a player that is not the owner? -> leave name empty +developmentEnvironmentUserName = Developer + +# Define a source file of your project with: +# public static final String VERSION = "GRADLETOKEN_VERSION"; +# The string's content will be replaced with your mod's version when compiled. You should use this to specify your mod's +# version in @Mod([...], version = VERSION, [...]) +# Leave these properties empty to skip individual token replacements +replaceGradleTokenInFile = Tags.java +gradleTokenModId = GRADLETOKEN_MODID +gradleTokenModName = GRADLETOKEN_MODNAME +gradleTokenVersion = GRADLETOKEN_VERSION +gradleTokenGroupName = GRADLETOKEN_GROUPNAME + +# In case your mod provides an API for other mods to implement you may declare its package here. Otherwise, you can +# leave this property empty. +# Example value: apiPackage = api + modGroup = com.myname.mymodid -> com.myname.mymodid.api +apiPackage = + +# Specify the configuration file for Forge's access transformers here. It must be placed into /src/main/resources/META-INF/ +# Example value: mymodid_at.cfg +accessTransformersFile = + +# Provides setup for Mixins if enabled. If you don't know what mixins are: Keep it disabled! +usesMixins = false +# Adds some debug arguments like verbose output and export +usesMixinDebug = false +# Specify the location of your implementation of IMixinConfigPlugin. Leave it empty otherwise. +mixinPlugin = +# Specify the package that contains all of your Mixins. You may only place Mixins in this package or the build will fail! +mixinsPackage = +# Specify the core mod entry class if you use a core mod. This class must implement IFMLLoadingPlugin! +# This parameter is for legacy compatibility only +# Example value: coreModClass = asm.FMLPlugin + modGroup = com.myname.mymodid -> com.myname.mymodid.asm.FMLPlugin +coreModClass = +# If your project is only a consolidation of mixins or a core mod and does NOT contain a 'normal' mod ( = some class +# that is annotated with @Mod) you want this to be true. When in doubt: leave it on false! +containsMixinsAndOrCoreModOnly = false + +# Enables Mixins even if this mod doesn't use them, useful if one of the dependencies uses mixins. +forceEnableMixins = false + +# If enabled, you may use 'shadowCompile' for dependencies. They will be integrated in your jar. It is your +# responsibility check the licence and request permission for distribution, if required. +usesShadowedDependencies = false + + +# 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 = + +# The project's relations on CurseForge. You can use this to refer to other projects on CurseForge. +# Syntax: type1:name1;type2:name2;... +# Where type can be one of [requiredDependency, embeddedLibrary, optionalDependency, tool, incompatible], +# and the name is the CurseForge project slug of the other mod. +# Example: requiredDependency:railcraft;embeddedLibrary:cofhlib;incompatible:buildcraft +# Note: GTNH Mixins is automatically set as a required dependency if usesMixins = true +curseForgeRelations = + + +# 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 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index b761216..5c2d1cf 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 678d9d8..3ab0b72 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Wed Jul 02 15:54:47 CDT 2014 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.9.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-bin.zip diff --git a/gradlew b/gradlew index 91a7e26..83f2acf 100755 --- a/gradlew +++ b/gradlew @@ -1,4 +1,20 @@ -#!/usr/bin/env bash +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ############################################################################## ## @@ -6,47 +22,6 @@ ## ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn ( ) { - echo "$*" -} - -die ( ) { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; -esac - -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" @@ -61,9 +36,49 @@ while [ -h "$PRG" ] ; do fi done SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >&- +cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" -cd "$SAVED" >&- +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"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# 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 + ;; +esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -90,7 +105,7 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then +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 @@ -110,10 +125,11 @@ if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then +# 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` @@ -154,11 +170,19 @@ if $cygwin ; then esac fi -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " } -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" +APP_ARGS=$(save "$@") -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +# 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" + +# 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")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 8a0b282..9618d8d 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,3 +1,19 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @@ -8,14 +24,14 @@ @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem 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" + @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome @@ -46,10 +62,9 @@ echo location of your Java installation. goto fail :init -@rem Get command-line arguments, handling Windowz variants +@rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. @@ -60,11 +75,6 @@ set _SKIP=2 if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ :execute @rem Setup the command line diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 0000000..09bbb51 --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,2 @@ +before_install: + - ./gradlew setupCIWorkspace \ No newline at end of file diff --git a/repositories.gradle b/repositories.gradle new file mode 100644 index 0000000..c884390 --- /dev/null +++ b/repositories.gradle @@ -0,0 +1,5 @@ +// Add any additional repositories for your dependencies here + +repositories { + +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..e013f5a --- /dev/null +++ b/settings.gradle @@ -0,0 +1,10 @@ +plugins { + id 'com.diffplug.blowdryerSetup' version '1.6.0' +} + +apply plugin: 'com.diffplug.blowdryerSetup' + +blowdryerSetup { + //github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.1.5') + devLocal '.' // Use this when testing config updates locally +} diff --git a/settings.gradle.example b/settings.gradle.example new file mode 100644 index 0000000..93c852a --- /dev/null +++ b/settings.gradle.example @@ -0,0 +1,10 @@ +plugins { + id 'com.diffplug.blowdryerSetup' version '1.6.0' +} + +apply plugin: 'com.diffplug.blowdryerSetup' + +blowdryerSetup { + github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.1.5') + //devLocal '.' // Use this when testing config updates locally +} diff --git a/src/main/java/singulariteam/eternalsingularity/EternalRecipeTweaker.java b/src/main/java/singulariteam/eternalsingularity/EternalRecipeTweaker.java index af4f0d2..c49d3c7 100644 --- a/src/main/java/singulariteam/eternalsingularity/EternalRecipeTweaker.java +++ b/src/main/java/singulariteam/eternalsingularity/EternalRecipeTweaker.java @@ -1,5 +1,7 @@ package singulariteam.eternalsingularity; +import java.util.Iterator; +import javax.annotation.Nonnull; import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IItemStack; @@ -9,130 +11,107 @@ import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import wanion.lib.common.MineTweakerHelper; -import javax.annotation.Nonnull; -import java.util.Iterator; - @ZenClass("mods.eternalsingularity") -public final class EternalRecipeTweaker -{ - private EternalRecipeTweaker() {} +public final class EternalRecipeTweaker { + private EternalRecipeTweaker() {} - public static void init() - { - MineTweakerAPI.registerClass(EternalRecipeTweaker.class); - } + public static void init() { + MineTweakerAPI.registerClass(EternalRecipeTweaker.class); + } - @ZenMethod - public static void add(@Nonnull final IItemStack input) - { - final ItemStack itemStack = MineTweakerHelper.toStack(input); - if (itemStack != null && itemStack.getItem() != null) - MineTweakerAPI.apply(new Add(itemStack)); - } + @ZenMethod + public static void add(@Nonnull final IItemStack input) { + final ItemStack itemStack = MineTweakerHelper.toStack(input); + if (itemStack != null && itemStack.getItem() != null) MineTweakerAPI.apply(new Add(itemStack)); + } - @ZenMethod - public static void remove(final IItemStack input) - { - final ItemStack itemStack = MineTweakerHelper.toStack(input); - if (itemStack != null && itemStack.getItem() != null) - MineTweakerAPI.apply(new Remove(itemStack)); - } + @ZenMethod + public static void remove(final IItemStack input) { + final ItemStack itemStack = MineTweakerHelper.toStack(input); + if (itemStack != null && itemStack.getItem() != null) MineTweakerAPI.apply(new Remove(itemStack)); + } - private static class Add implements IUndoableAction - { - private final ItemStack itemStack; + private static class Add implements IUndoableAction { + private final ItemStack itemStack; - public Add(@Nonnull final ItemStack itemStack) - { - this.itemStack = itemStack; - } + public Add(@Nonnull final ItemStack itemStack) { + this.itemStack = itemStack; + } - @Override - public void apply() - { - CommonProxy.getEternalSingularityRecipe().getInput().add(itemStack); - } + @Override + public void apply() { + CommonProxy.getEternalSingularityRecipe().getInput().add(itemStack); + } - @Override - public boolean canUndo() - { - return true; - } + @Override + public boolean canUndo() { + return true; + } - @Override - public void undo() - { - CommonProxy.getEternalSingularityRecipe().getInput().remove(itemStack); - } + @Override + public void undo() { + CommonProxy.getEternalSingularityRecipe().getInput().remove(itemStack); + } - @Override - public String describe() - { - return "Adding " + itemStack.getDisplayName() + " into Eternal Singularity Recipe."; - } + @Override + public String describe() { + return "Adding " + itemStack.getDisplayName() + " into Eternal Singularity Recipe."; + } - @Override - public String describeUndo() - { - return "Removing " + itemStack.getDisplayName() + " from Eternal Singularity Recipe."; - } + @Override + public String describeUndo() { + return "Removing " + itemStack.getDisplayName() + " from Eternal Singularity Recipe."; + } - @Override - public Object getOverrideKey() - { - return null; - } - } + @Override + public Object getOverrideKey() { + return null; + } + } - private static class Remove implements IUndoableAction - { - private final ItemStack itemStack; + private static class Remove implements IUndoableAction { + private final ItemStack itemStack; - private Remove(@Nonnull final ItemStack itemStackToRemove) - { - ItemStack itemStack = null; - for (final Iterator eternalSingularityRecipeIterator = CommonProxy.getEternalSingularityRecipe().getInput().iterator(); eternalSingularityRecipeIterator.hasNext() && itemStack == null; ) { - final Object input = eternalSingularityRecipeIterator.next(); - if (input instanceof ItemStack && ((ItemStack) input).isItemEqual(itemStackToRemove)) - itemStack = (ItemStack) input; - } - this.itemStack = itemStack; - } + private Remove(@Nonnull final ItemStack itemStackToRemove) { + ItemStack itemStack = null; + for (final Iterator eternalSingularityRecipeIterator = + CommonProxy.getEternalSingularityRecipe().getInput().iterator(); + eternalSingularityRecipeIterator.hasNext() && itemStack == null; ) { + final Object input = eternalSingularityRecipeIterator.next(); + if (input instanceof ItemStack && ((ItemStack) input).isItemEqual(itemStackToRemove)) + itemStack = (ItemStack) input; + } + this.itemStack = itemStack; + } - @Override - public void apply() - { - CommonProxy.getEternalSingularityRecipe().getInput().remove(itemStack); - } + @Override + public void apply() { + CommonProxy.getEternalSingularityRecipe().getInput().remove(itemStack); + } - @Override - public boolean canUndo() - { - return itemStack != null; - } + @Override + public boolean canUndo() { + return itemStack != null; + } - @Override - public void undo() - { - CommonProxy.getEternalSingularityRecipe().getInput().add(itemStack); - } + @Override + public void undo() { + CommonProxy.getEternalSingularityRecipe().getInput().add(itemStack); + } - @Override - public String describe() - { - return "Removing " + itemStack.getDisplayName() + " from Eternal Singularity Recipe."; - } + @Override + public String describe() { + return "Removing " + itemStack.getDisplayName() + " from Eternal Singularity Recipe."; + } - @Override - public String describeUndo() - { - return "Adding " + itemStack.getDisplayName() + " into Eternal Singularity Recipe."; - } + @Override + public String describeUndo() { + return "Adding " + itemStack.getDisplayName() + " into Eternal Singularity Recipe."; + } - @Override - public Object getOverrideKey() - { - return null; - } - } -} \ No newline at end of file + @Override + public Object getOverrideKey() { + return null; + } + } +} diff --git a/src/main/java/singulariteam/eternalsingularity/EternalSingularityMod.java b/src/main/java/singulariteam/eternalsingularity/EternalSingularityMod.java index 58374c6..4ebb3eb 100644 --- a/src/main/java/singulariteam/eternalsingularity/EternalSingularityMod.java +++ b/src/main/java/singulariteam/eternalsingularity/EternalSingularityMod.java @@ -1,5 +1,7 @@ package singulariteam.eternalsingularity; +import static singulariteam.eternalsingularity.Reference.*; + import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; @@ -13,45 +15,43 @@ import org.apache.logging.log4j.Logger; import singulariteam.eternalsingularity.item.EternalSingularityItem; import singulariteam.eternalsingularity.proxy.CommonProxy; -import static singulariteam.eternalsingularity.Reference.*; +@Mod( + modid = MOD_ID, + name = MOD_NAME, + version = MOD_VERSION, + acceptedMinecraftVersions = MC_VERSION, + dependencies = + "required-after:Avaritia;required-after:wanionlib@[1.7.10-1.3,);after:thermsingul;after:universalsingularities;after:aobdsingularities") +public class EternalSingularityMod { + @Mod.Instance(MOD_ID) + public static EternalSingularityMod instance; -@Mod(modid = MOD_ID, name = MOD_NAME, version = MOD_VERSION, acceptedMinecraftVersions = MC_VERSION, dependencies = "required-after:Avaritia;required-after:wanionlib@[1.7.10-1.3,);after:thermsingul;after:universalsingularities;after:aobdsingularities") -public class EternalSingularityMod -{ - @Mod.Instance(MOD_ID) - public static EternalSingularityMod instance; + public static Logger logger; - public static Logger logger; + @SidedProxy(serverSide = COMMON_PROXY, clientSide = CLIENT_PROXY) + public static CommonProxy proxy; - @SidedProxy(serverSide = COMMON_PROXY, clientSide = CLIENT_PROXY) - public static CommonProxy proxy; + public static final CreativeTabs creativeTabs = new CreativeTabs(MOD_ID) { + @SideOnly(Side.CLIENT) + @Override + public Item getTabIconItem() { + return EternalSingularityItem.instance; + } + }; - public static final CreativeTabs creativeTabs = new CreativeTabs(MOD_ID) - { - @SideOnly(Side.CLIENT) - @Override - public Item getTabIconItem() - { - return EternalSingularityItem.instance; - } - }; + @Mod.EventHandler + public void preInit(final FMLPreInitializationEvent event) { + logger = event.getModLog(); + proxy.preInit(event.getSuggestedConfigurationFile()); + } - @Mod.EventHandler - public void preInit(final FMLPreInitializationEvent event) - { - logger = event.getModLog(); - proxy.preInit(event.getSuggestedConfigurationFile()); - } + @Mod.EventHandler + public void init(final FMLInitializationEvent event) { + proxy.init(); + } - @Mod.EventHandler - public void init(final FMLInitializationEvent event) - { - proxy.init(); - } - - @Mod.EventHandler - public void postInit(final FMLPostInitializationEvent event) - { - proxy.postInit(); - } -} \ No newline at end of file + @Mod.EventHandler + public void postInit(final FMLPostInitializationEvent event) { + proxy.postInit(); + } +} diff --git a/src/main/java/singulariteam/eternalsingularity/Reference.java b/src/main/java/singulariteam/eternalsingularity/Reference.java index 71399c0..cbd8ef9 100644 --- a/src/main/java/singulariteam/eternalsingularity/Reference.java +++ b/src/main/java/singulariteam/eternalsingularity/Reference.java @@ -1,13 +1,12 @@ package singulariteam.eternalsingularity; -public final class Reference -{ - public static final String MOD_ID = "eternalsingularity"; - public static final String MOD_NAME = "Eternal Singularity"; - public static final String MOD_VERSION = "1.7.10-.1.0.4b"; - public static final String MC_VERSION = "[1.7.10]"; - static final String COMMON_PROXY = "singulariteam.eternalsingularity.proxy.CommonProxy"; - static final String CLIENT_PROXY = "singulariteam.eternalsingularity.proxy.ClientProxy"; +public final class Reference { + public static final String MOD_ID = "eternalsingularity"; + public static final String MOD_NAME = "Eternal Singularity"; + public static final String MOD_VERSION = "1.7.10-.1.0.4b"; + public static final String MC_VERSION = "[1.7.10]"; + static final String COMMON_PROXY = "singulariteam.eternalsingularity.proxy.CommonProxy"; + static final String CLIENT_PROXY = "singulariteam.eternalsingularity.proxy.ClientProxy"; - private Reference() {} -} \ No newline at end of file + private Reference() {} +} diff --git a/src/main/java/singulariteam/eternalsingularity/item/CompoundSingularityItem.java b/src/main/java/singulariteam/eternalsingularity/item/CompoundSingularityItem.java index 3ed15f2..855a804 100644 --- a/src/main/java/singulariteam/eternalsingularity/item/CompoundSingularityItem.java +++ b/src/main/java/singulariteam/eternalsingularity/item/CompoundSingularityItem.java @@ -1,14 +1,12 @@ package singulariteam.eternalsingularity.item; -import java.util.List; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import fox.spiteful.avaritia.Avaritia; import fox.spiteful.avaritia.items.ItemResource; import fox.spiteful.avaritia.items.LudicrousItems; import fox.spiteful.avaritia.render.ICosmicRenderItem; import fox.spiteful.avaritia.render.IHaloRenderItem; +import java.util.List; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; @@ -19,111 +17,98 @@ import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import singulariteam.eternalsingularity.EternalSingularityMod; -public class CompoundSingularityItem extends Item implements IHaloRenderItem, ICosmicRenderItem -{ - private final int max; +public class CompoundSingularityItem extends Item implements IHaloRenderItem, ICosmicRenderItem { + private final int max; - @SideOnly(Side.CLIENT) - private IIcon cosmicMask; - @SideOnly(Side.CLIENT) - private IIcon[] foregroundIcons, backgroundIcons; + @SideOnly(Side.CLIENT) + private IIcon cosmicMask; - public CompoundSingularityItem(final int max) - { - super(); - setHasSubtypes(true); - this.max = max; - setCreativeTab(EternalSingularityMod.creativeTabs); - } + @SideOnly(Side.CLIENT) + private IIcon[] foregroundIcons, backgroundIcons; - public EnumRarity getRarity(ItemStack stack) - { - return EnumRarity.uncommon; - } + public CompoundSingularityItem(final int max) { + super(); + setHasSubtypes(true); + this.max = max; + setCreativeTab(EternalSingularityMod.creativeTabs); + } - @Override - public String getUnlocalizedName(final ItemStack stack) - { - return "item.combined.singularity." + MathHelper.clamp_int(getDamage(stack), 0, max); - } + public EnumRarity getRarity(ItemStack stack) { + return EnumRarity.uncommon; + } - @SuppressWarnings("unchecked") - @SideOnly(Side.CLIENT) - public void getSubItems(Item item, CreativeTabs tab, List list) - { - for (int j = 0; j < max; j++) - list.add(new ItemStack(item, 1, j)); - } + @Override + public String getUnlocalizedName(final ItemStack stack) { + return "item.combined.singularity." + MathHelper.clamp_int(getDamage(stack), 0, max); + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getMaskTexture(ItemStack stack, EntityPlayer player) - { - return cosmicMask; - } + @SuppressWarnings("unchecked") + @SideOnly(Side.CLIENT) + public void getSubItems(Item item, CreativeTabs tab, List list) { + for (int j = 0; j < max; j++) list.add(new ItemStack(item, 1, j)); + } - @Override - @SideOnly(Side.CLIENT) - public float getMaskMultiplier(ItemStack stack, EntityPlayer player) - { - return 1.0f; - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getMaskTexture(ItemStack stack, EntityPlayer player) { + return cosmicMask; + } - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister ir) - { - super.registerIcons(ir); - foregroundIcons = new IIcon[max]; - backgroundIcons = new IIcon[max]; + @Override + @SideOnly(Side.CLIENT) + public float getMaskMultiplier(ItemStack stack, EntityPlayer player) { + return 1.0f; + } - for (int x = 0; x < max; x++) { - foregroundIcons[x] = ir.registerIcon("eternalsingularity:combined_singularity_" + x + "_overlay"); - backgroundIcons[x] = ir.registerIcon("eternalsingularity:combined_singularity_" + x); - } - this.cosmicMask = ir.registerIcon("eternalsingularity:combined_singularity_mask"); - } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister ir) { + super.registerIcons(ir); + foregroundIcons = new IIcon[max]; + backgroundIcons = new IIcon[max]; - @Override - public IIcon getIcon(ItemStack stack, int pass) - { - return pass == 1 ? this.foregroundIcons[stack.getItemDamage() % foregroundIcons.length] : this.backgroundIcons[stack.getItemDamage() % backgroundIcons.length]; - } + for (int x = 0; x < max; x++) { + foregroundIcons[x] = ir.registerIcon("eternalsingularity:combined_singularity_" + x + "_overlay"); + backgroundIcons[x] = ir.registerIcon("eternalsingularity:combined_singularity_" + x); + } + this.cosmicMask = ir.registerIcon("eternalsingularity:combined_singularity_mask"); + } - @SideOnly(Side.CLIENT) - @Override - public boolean requiresMultipleRenderPasses() - { - return true; - } + @Override + public IIcon getIcon(ItemStack stack, int pass) { + return pass == 1 + ? this.foregroundIcons[stack.getItemDamage() % foregroundIcons.length] + : this.backgroundIcons[stack.getItemDamage() % backgroundIcons.length]; + } - @SideOnly(Side.CLIENT) - public boolean drawHalo(ItemStack paramItemStack) - { - return true; - } + @SideOnly(Side.CLIENT) + @Override + public boolean requiresMultipleRenderPasses() { + return true; + } - @SideOnly(Side.CLIENT) - public IIcon getHaloTexture(ItemStack paramItemStack) - { - return ((ItemResource) LudicrousItems.resource).halo[0]; - } + @SideOnly(Side.CLIENT) + public boolean drawHalo(ItemStack paramItemStack) { + return true; + } - @SideOnly(Side.CLIENT) - public int getHaloSize(ItemStack paramItemStack) - { - return 4; - } + @SideOnly(Side.CLIENT) + public IIcon getHaloTexture(ItemStack paramItemStack) { + return ((ItemResource) LudicrousItems.resource).halo[0]; + } - @SideOnly(Side.CLIENT) - public boolean drawPulseEffect(ItemStack paramItemStack) - { - return false; - } + @SideOnly(Side.CLIENT) + public int getHaloSize(ItemStack paramItemStack) { + return 4; + } - @SideOnly(Side.CLIENT) - public int getHaloColour(ItemStack paramItemStack) - { - return -16777216; - } -} \ No newline at end of file + @SideOnly(Side.CLIENT) + public boolean drawPulseEffect(ItemStack paramItemStack) { + return false; + } + + @SideOnly(Side.CLIENT) + public int getHaloColour(ItemStack paramItemStack) { + return -16777216; + } +} diff --git a/src/main/java/singulariteam/eternalsingularity/item/EternalSingularityItem.java b/src/main/java/singulariteam/eternalsingularity/item/EternalSingularityItem.java index f7dead2..fa84e92 100644 --- a/src/main/java/singulariteam/eternalsingularity/item/EternalSingularityItem.java +++ b/src/main/java/singulariteam/eternalsingularity/item/EternalSingularityItem.java @@ -2,7 +2,6 @@ package singulariteam.eternalsingularity.item; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import fox.spiteful.avaritia.Avaritia; import fox.spiteful.avaritia.entity.EntityImmortalItem; import fox.spiteful.avaritia.items.ItemResource; import fox.spiteful.avaritia.items.LudicrousItems; @@ -18,106 +17,90 @@ import net.minecraft.util.IIcon; import net.minecraft.world.World; import singulariteam.eternalsingularity.EternalSingularityMod; -public class EternalSingularityItem extends Item implements IHaloRenderItem, ICosmicRenderItem -{ - public static final EternalSingularityItem instance = new EternalSingularityItem(); +public class EternalSingularityItem extends Item implements IHaloRenderItem, ICosmicRenderItem { + public static final EternalSingularityItem instance = new EternalSingularityItem(); - private IIcon cosmicMask; - private IIcon foregroundIcon; + private IIcon cosmicMask; + private IIcon foregroundIcon; - private EternalSingularityItem() - { - super(); - setCreativeTab(EternalSingularityMod.creativeTabs); - setTextureName("eternalsingularity:eternal_singularity2"); - } + private EternalSingularityItem() { + super(); + setCreativeTab(EternalSingularityMod.creativeTabs); + setTextureName("eternalsingularity:eternal_singularity2"); + } - public EnumRarity getRarity(ItemStack stack) - { - return LudicrousItems.cosmic; - } + public EnumRarity getRarity(ItemStack stack) { + return LudicrousItems.cosmic; + } - @Override - public String getUnlocalizedName(final ItemStack stack) - { - return "item.eternal.singularity"; - } + @Override + public String getUnlocalizedName(final ItemStack stack) { + return "item.eternal.singularity"; + } - @Override - public boolean hasCustomEntity(ItemStack stack) - { - return true; - } + @Override + public boolean hasCustomEntity(ItemStack stack) { + return true; + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getMaskTexture(ItemStack stack, EntityPlayer player) - { - return cosmicMask; - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getMaskTexture(ItemStack stack, EntityPlayer player) { + return cosmicMask; + } - @Override - @SideOnly(Side.CLIENT) - public float getMaskMultiplier(ItemStack stack, EntityPlayer player) - { - return 1.0f; - } + @Override + @SideOnly(Side.CLIENT) + public float getMaskMultiplier(ItemStack stack, EntityPlayer player) { + return 1.0f; + } - @SideOnly(Side.CLIENT) - @Override - public void registerIcons(IIconRegister ir) - { - super.registerIcons(ir); - this.cosmicMask = ir.registerIcon("eternalsingularity:eternal_singularity_mask"); - this.foregroundIcon = ir.registerIcon("eternalsingularity:eternal_singularity"); - } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister ir) { + super.registerIcons(ir); + this.cosmicMask = ir.registerIcon("eternalsingularity:eternal_singularity_mask"); + this.foregroundIcon = ir.registerIcon("eternalsingularity:eternal_singularity"); + } - @Override - public IIcon getIcon(ItemStack stack, int pass) - { - return pass == 1 ? foregroundIcon : super.getIcon(stack, pass); - } + @Override + public IIcon getIcon(ItemStack stack, int pass) { + return pass == 1 ? foregroundIcon : super.getIcon(stack, pass); + } - @SideOnly(Side.CLIENT) - @Override - public boolean requiresMultipleRenderPasses() - { - return true; - } + @SideOnly(Side.CLIENT) + @Override + public boolean requiresMultipleRenderPasses() { + return true; + } - @Override - public Entity createEntity(World world, Entity location, ItemStack itemstack) - { - return new EntityImmortalItem(world, location, itemstack); - } + @Override + public Entity createEntity(World world, Entity location, ItemStack itemstack) { + return new EntityImmortalItem(world, location, itemstack); + } - @SideOnly(Side.CLIENT) - public boolean drawHalo(ItemStack paramItemStack) - { - return true; - } + @SideOnly(Side.CLIENT) + public boolean drawHalo(ItemStack paramItemStack) { + return true; + } - @SideOnly(Side.CLIENT) - public IIcon getHaloTexture(ItemStack paramItemStack) - { - return ((ItemResource) LudicrousItems.resource).halo[0]; - } + @SideOnly(Side.CLIENT) + public IIcon getHaloTexture(ItemStack paramItemStack) { + return ((ItemResource) LudicrousItems.resource).halo[0]; + } - @SideOnly(Side.CLIENT) - public int getHaloSize(ItemStack paramItemStack) - { - return 4; - } + @SideOnly(Side.CLIENT) + public int getHaloSize(ItemStack paramItemStack) { + return 4; + } - @SideOnly(Side.CLIENT) - public boolean drawPulseEffect(ItemStack paramItemStack) - { - return false; - } + @SideOnly(Side.CLIENT) + public boolean drawPulseEffect(ItemStack paramItemStack) { + return false; + } - @SideOnly(Side.CLIENT) - public int getHaloColour(ItemStack paramItemStack) - { - return -16777216; - } -} \ No newline at end of file + @SideOnly(Side.CLIENT) + public int getHaloColour(ItemStack paramItemStack) { + return -16777216; + } +} diff --git a/src/main/java/singulariteam/eternalsingularity/proxy/ClientProxy.java b/src/main/java/singulariteam/eternalsingularity/proxy/ClientProxy.java index eb848d9..9a6ceb9 100644 --- a/src/main/java/singulariteam/eternalsingularity/proxy/ClientProxy.java +++ b/src/main/java/singulariteam/eternalsingularity/proxy/ClientProxy.java @@ -5,22 +5,19 @@ import singulariteam.eternalsingularity.item.EternalSingularityItem; import singulariteam.eternalsingularity.render.EternalItemRenderer; import singulariteam.eternalsingularity.render.ShaderHelper; -public final class ClientProxy extends CommonProxy -{ - EternalItemRenderer fancies = new EternalItemRenderer(); +public final class ClientProxy extends CommonProxy { + EternalItemRenderer fancies = new EternalItemRenderer(); - @Override - public void init() - { - MinecraftForgeClient.registerItemRenderer(EternalSingularityItem.instance, fancies); - ShaderHelper.initShaders(); - } + @Override + public void init() { + MinecraftForgeClient.registerItemRenderer(EternalSingularityItem.instance, fancies); + ShaderHelper.initShaders(); + } - @Override - public void postInit() - { - super.postInit(); - if (compoundSingularityItem != null) - MinecraftForgeClient.registerItemRenderer(compoundSingularityItem, fancies); - } + @Override + public void postInit() { + super.postInit(); + if (compoundSingularityItem != null) + MinecraftForgeClient.registerItemRenderer(compoundSingularityItem, fancies); + } } diff --git a/src/main/java/singulariteam/eternalsingularity/proxy/CommonProxy.java b/src/main/java/singulariteam/eternalsingularity/proxy/CommonProxy.java index d161241..dede1d5 100644 --- a/src/main/java/singulariteam/eternalsingularity/proxy/CommonProxy.java +++ b/src/main/java/singulariteam/eternalsingularity/proxy/CommonProxy.java @@ -1,9 +1,14 @@ package singulariteam.eternalsingularity.proxy; +import static fox.spiteful.avaritia.Config.craftingOnly; + import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.registry.GameRegistry; import fox.spiteful.avaritia.crafting.ExtremeCraftingManager; import fox.spiteful.avaritia.crafting.Grinder; +import java.io.File; +import java.util.*; +import javax.annotation.Nonnull; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; @@ -14,99 +19,101 @@ import singulariteam.eternalsingularity.EternalSingularityMod; import singulariteam.eternalsingularity.item.CompoundSingularityItem; import singulariteam.eternalsingularity.item.EternalSingularityItem; -import javax.annotation.Nonnull; -import java.io.File; -import java.util.*; +public class CommonProxy { + private static ShapelessOreRecipe eternalSingularityRecipe = null; + private static final Set classSet = new HashSet<>(); + protected CompoundSingularityItem compoundSingularityItem = null; + private File configFile; -import static fox.spiteful.avaritia.Config.craftingOnly; + public CommonProxy() {} -public class CommonProxy -{ - private static ShapelessOreRecipe eternalSingularityRecipe = null; - private static final Set classSet = new HashSet<>(); - protected CompoundSingularityItem compoundSingularityItem = null; - private File configFile; + public final void preInit(final File file) { + final Configuration config = new Configuration(configFile = file); + final String[] classNameList = config.getStringList( + "classNameList", + Configuration.CATEGORY_GENERAL, + new String[] { + "com.rcx.aobdsingularities.item.AOBDItemSingularity", + "fox.spiteful.avaritia.items.ItemSingularity", + "wanion.thermsingul.ThermalSingularityItem", + "wealthyturtle.uiesingularities.UniversalSingularityItem" + }, + "here is the absolute class name of the Item Classes that must be removed from Infinity Catalyst recipe and inserted into Eternal Singularity."); + if (config.hasChanged()) config.save(); + for (final String className : classNameList) { + try { + classSet.add(Class.forName(className)); + } catch (ClassNotFoundException e) { + EternalSingularityMod.logger.warn("Couldn't find " + className); + } + } + GameRegistry.registerItem(EternalSingularityItem.instance, "eternal_singularity"); + if (Loader.isModLoaded("MineTweaker3")) EternalRecipeTweaker.init(); + } - public CommonProxy() { } + public void init() {} - public final void preInit(final File file) - { - final Configuration config = new Configuration(configFile = file); - final String[] classNameList = config.getStringList("classNameList", Configuration.CATEGORY_GENERAL, new String[]{ - "com.rcx.aobdsingularities.item.AOBDItemSingularity", - "fox.spiteful.avaritia.items.ItemSingularity", - "wanion.thermsingul.ThermalSingularityItem", - "wealthyturtle.uiesingularities.UniversalSingularityItem" - }, "here is the absolute class name of the Item Classes that must be removed from Infinity Catalyst recipe and inserted into Eternal Singularity."); - if (config.hasChanged()) - config.save(); - for (final String className : classNameList) { - try { - classSet.add(Class.forName(className)); - } catch (ClassNotFoundException e) { - EternalSingularityMod.logger.warn("Couldn't find " + className); - } - } - GameRegistry.registerItem(EternalSingularityItem.instance, "eternal_singularity"); - if (Loader.isModLoaded("MineTweaker3")) - EternalRecipeTweaker.init(); - } + @Nonnull + public static ShapelessOreRecipe getEternalSingularityRecipe() { + return eternalSingularityRecipe; + } - public void init() {} - - @Nonnull - public static ShapelessOreRecipe getEternalSingularityRecipe() - { - return eternalSingularityRecipe; - } - - @SuppressWarnings("unchecked") - public void postInit() - { - if (classSet.isEmpty() || craftingOnly) - return; - final List singularities = new ArrayList<>(); - for (final Iterator catalystRecipeIterator = Grinder.catalyst.getInput().iterator(); catalystRecipeIterator.hasNext(); ) { - final Object input = catalystRecipeIterator.next(); - if (!(input instanceof ItemStack)) - continue; - final Item item = ((ItemStack) input).getItem(); - if (item != null && classSet.contains(item.getClass())) { - catalystRecipeIterator.remove(); - singularities.add(((ItemStack) input).copy()); - } - } - final Configuration config = new Configuration(configFile); - final int singularityCount = singularities.size(); - final boolean aboveTheLimit = singularityCount > 81; - final boolean useCompoundSingularities = config.getBoolean("useCompoundSingularities", Configuration.CATEGORY_GENERAL, aboveTheLimit, "When useCompoundSingularities is Enabled, Basic Singularities will Need to be Crafted into Compound Singularities First.\n[If there are > 81 Basic Singularities, this Config Option will be Set to True Automatically]") || aboveTheLimit; - final boolean easyMode = config.getBoolean("easyMode", Configuration.CATEGORY_GENERAL, false, "If this Config Option is Enabled, for Every 9 Singularities Used in the Eternal Singularity Recipe, You will Receive an Additional Eternal Singularity for the Recipe Output."); - if (config.hasChanged()) - config.save(); - final int compoundMax = (int) Math.ceil((float) singularityCount / 9); - (eternalSingularityRecipe = new ShapelessOreRecipe(new ItemStack(EternalSingularityItem.instance, easyMode ? MathHelper.clamp_int(compoundMax, 1, 64) : 1))).getInput().addAll(singularities); - if (useCompoundSingularities) { - GameRegistry.registerItem(compoundSingularityItem = new CompoundSingularityItem(compoundMax), "combined_singularity"); - final List eternalSingularityRecipeInputs = eternalSingularityRecipe.getInput(); - for (int i = 0; i < compoundMax; i++) { - final ShapelessOreRecipe compoundRecipe = new ShapelessOreRecipe(new ItemStack(compoundSingularityItem, 1, MathHelper.clamp_int(i, 0, 64))); - for (int s = 0; s < 9; s++) { - final int pos = 9 * i + s; - if (pos > singularityCount - 1) - break; - final Object input = eternalSingularityRecipeInputs.get(pos); - if (!(input instanceof ItemStack)) - continue; - compoundRecipe.getInput().add(((ItemStack) input).copy()); - } - if (compoundRecipe.getInput().size() > 0) - GameRegistry.addRecipe(compoundRecipe); - } - eternalSingularityRecipeInputs.clear(); - for (int i = 0; i < compoundMax; i++) - eternalSingularityRecipeInputs.add(new ItemStack(compoundSingularityItem, 1, i)); - } - ExtremeCraftingManager.getInstance().getRecipeList().add(eternalSingularityRecipe); - Grinder.catalyst.getInput().add(new ItemStack(EternalSingularityItem.instance)); - } -} \ No newline at end of file + @SuppressWarnings("unchecked") + public void postInit() { + if (classSet.isEmpty() || craftingOnly) return; + final List singularities = new ArrayList<>(); + for (final Iterator catalystRecipeIterator = + Grinder.catalyst.getInput().iterator(); + catalystRecipeIterator.hasNext(); ) { + final Object input = catalystRecipeIterator.next(); + if (!(input instanceof ItemStack)) continue; + final Item item = ((ItemStack) input).getItem(); + if (item != null && classSet.contains(item.getClass())) { + catalystRecipeIterator.remove(); + singularities.add(((ItemStack) input).copy()); + } + } + final Configuration config = new Configuration(configFile); + final int singularityCount = singularities.size(); + final boolean aboveTheLimit = singularityCount > 81; + final boolean useCompoundSingularities = config.getBoolean( + "useCompoundSingularities", + Configuration.CATEGORY_GENERAL, + aboveTheLimit, + "When useCompoundSingularities is Enabled, Basic Singularities will Need to be Crafted into Compound Singularities First.\n[If there are > 81 Basic Singularities, this Config Option will be Set to True Automatically]") + || aboveTheLimit; + final boolean easyMode = config.getBoolean( + "easyMode", + Configuration.CATEGORY_GENERAL, + false, + "If this Config Option is Enabled, for Every 9 Singularities Used in the Eternal Singularity Recipe, You will Receive an Additional Eternal Singularity for the Recipe Output."); + if (config.hasChanged()) config.save(); + final int compoundMax = (int) Math.ceil((float) singularityCount / 9); + (eternalSingularityRecipe = new ShapelessOreRecipe(new ItemStack( + EternalSingularityItem.instance, easyMode ? MathHelper.clamp_int(compoundMax, 1, 64) : 1))) + .getInput() + .addAll(singularities); + if (useCompoundSingularities) { + GameRegistry.registerItem( + compoundSingularityItem = new CompoundSingularityItem(compoundMax), "combined_singularity"); + final List eternalSingularityRecipeInputs = eternalSingularityRecipe.getInput(); + for (int i = 0; i < compoundMax; i++) { + final ShapelessOreRecipe compoundRecipe = new ShapelessOreRecipe( + new ItemStack(compoundSingularityItem, 1, MathHelper.clamp_int(i, 0, 64))); + for (int s = 0; s < 9; s++) { + final int pos = 9 * i + s; + if (pos > singularityCount - 1) break; + final Object input = eternalSingularityRecipeInputs.get(pos); + if (!(input instanceof ItemStack)) continue; + compoundRecipe.getInput().add(((ItemStack) input).copy()); + } + if (compoundRecipe.getInput().size() > 0) GameRegistry.addRecipe(compoundRecipe); + } + eternalSingularityRecipeInputs.clear(); + for (int i = 0; i < compoundMax; i++) + eternalSingularityRecipeInputs.add(new ItemStack(compoundSingularityItem, 1, i)); + } + ExtremeCraftingManager.getInstance().getRecipeList().add(eternalSingularityRecipe); + Grinder.catalyst.getInput().add(new ItemStack(EternalSingularityItem.instance)); + } +} diff --git a/src/main/java/singulariteam/eternalsingularity/render/CosmicRenderStuffs.java b/src/main/java/singulariteam/eternalsingularity/render/CosmicRenderStuffs.java index 43f99e4..369989f 100644 --- a/src/main/java/singulariteam/eternalsingularity/render/CosmicRenderStuffs.java +++ b/src/main/java/singulariteam/eternalsingularity/render/CosmicRenderStuffs.java @@ -1,116 +1,112 @@ package singulariteam.eternalsingularity.render; +import cpw.mods.fml.relauncher.ReflectionHelper; +import fox.spiteful.avaritia.render.LudicrousRenderEvents; import java.lang.reflect.Field; - import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.world.World; - -import org.apache.logging.log4j.Level; import org.lwjgl.opengl.ARBShaderObjects; -import cpw.mods.fml.relauncher.ReflectionHelper; -import fox.spiteful.avaritia.render.LudicrousRenderEvents; - public class CosmicRenderStuffs { - public static final ShaderCallback shaderCallback; - - public static float[] lightlevel = new float[3]; - - public static String[] lightmapobf = new String[] {"lightmapColors", "field_78504_Q", "U"}; - public static boolean inventoryRender = false; - public static float cosmicOpacity = 1.0f; - - static { - shaderCallback = new ShaderCallback() { - @Override - public void call(int shader) { - Minecraft mc = Minecraft.getMinecraft(); + public static final ShaderCallback shaderCallback; - float yaw = 0; - float pitch = 0; - float scale = 1.0f; - - if (!inventoryRender) { - yaw = (float)((mc.thePlayer.rotationYaw * 2 * Math.PI) / 360.0); - pitch = - (float)((mc.thePlayer.rotationPitch * 2 * Math.PI) / 360.0); - } else { - scale = 25.0f; - } - - int x = ARBShaderObjects.glGetUniformLocationARB(shader, "yaw"); - ARBShaderObjects.glUniform1fARB(x, yaw); - - int z = ARBShaderObjects.glGetUniformLocationARB(shader, "pitch"); - ARBShaderObjects.glUniform1fARB(z, pitch); - - int l = ARBShaderObjects.glGetUniformLocationARB(shader, "lightlevel"); - ARBShaderObjects.glUniform3fARB(l, lightlevel[0], lightlevel[1], lightlevel[2]); - - int lightmix = ARBShaderObjects.glGetUniformLocationARB(shader, "lightmix"); - ARBShaderObjects.glUniform1fARB(lightmix, 0.2f); - - int uvs = ARBShaderObjects.glGetUniformLocationARB(shader, "cosmicuvs"); - ARBShaderObjects.glUniformMatrix2ARB(uvs, false, LudicrousRenderEvents.cosmicUVs); - - int s = ARBShaderObjects.glGetUniformLocationARB(shader, "externalScale"); - ARBShaderObjects.glUniform1fARB(s, scale); - - int o = ARBShaderObjects.glGetUniformLocationARB(shader, "opacity"); - ARBShaderObjects.glUniform1fARB(o, cosmicOpacity); - } - }; - } - - public static void useShader() { - ShaderHelper.useShader(ShaderHelper.cosmicShader, shaderCallback); - } - public static void releaseShader() { - ShaderHelper.releaseShader(); - } - - private static Field mapfield = ReflectionHelper.findField(EntityRenderer.class, lightmapobf); - public static void setLightFromLocation(World world, int x, int y, int z) { - if(world == null){ + public static float[] lightlevel = new float[3]; + + public static String[] lightmapobf = new String[] {"lightmapColors", "field_78504_Q", "U"}; + public static boolean inventoryRender = false; + public static float cosmicOpacity = 1.0f; + + static { + shaderCallback = new ShaderCallback() { + @Override + public void call(int shader) { + Minecraft mc = Minecraft.getMinecraft(); + + float yaw = 0; + float pitch = 0; + float scale = 1.0f; + + if (!inventoryRender) { + yaw = (float) ((mc.thePlayer.rotationYaw * 2 * Math.PI) / 360.0); + pitch = -(float) ((mc.thePlayer.rotationPitch * 2 * Math.PI) / 360.0); + } else { + scale = 25.0f; + } + + int x = ARBShaderObjects.glGetUniformLocationARB(shader, "yaw"); + ARBShaderObjects.glUniform1fARB(x, yaw); + + int z = ARBShaderObjects.glGetUniformLocationARB(shader, "pitch"); + ARBShaderObjects.glUniform1fARB(z, pitch); + + int l = ARBShaderObjects.glGetUniformLocationARB(shader, "lightlevel"); + ARBShaderObjects.glUniform3fARB(l, lightlevel[0], lightlevel[1], lightlevel[2]); + + int lightmix = ARBShaderObjects.glGetUniformLocationARB(shader, "lightmix"); + ARBShaderObjects.glUniform1fARB(lightmix, 0.2f); + + int uvs = ARBShaderObjects.glGetUniformLocationARB(shader, "cosmicuvs"); + ARBShaderObjects.glUniformMatrix2ARB(uvs, false, LudicrousRenderEvents.cosmicUVs); + + int s = ARBShaderObjects.glGetUniformLocationARB(shader, "externalScale"); + ARBShaderObjects.glUniform1fARB(s, scale); + + int o = ARBShaderObjects.glGetUniformLocationARB(shader, "opacity"); + ARBShaderObjects.glUniform1fARB(o, cosmicOpacity); + } + }; + } + + public static void useShader() { + ShaderHelper.useShader(ShaderHelper.cosmicShader, shaderCallback); + } + + public static void releaseShader() { + ShaderHelper.releaseShader(); + } + + private static Field mapfield = ReflectionHelper.findField(EntityRenderer.class, lightmapobf); + + public static void setLightFromLocation(World world, int x, int y, int z) { + if (world == null) { setLightLevel(1.0f); return; } int coord = world.getLightBrightnessForSkyBlocks(x, y, z, 0); - - int[] map = null; - try { - map = (int[]) mapfield.get(Minecraft.getMinecraft().entityRenderer); - } catch (Exception e) {} - if (map == null) { - setLightLevel(1.0f); - return; - } - - int mx = (coord % 65536) / 16; + + int[] map = null; + try { + map = (int[]) mapfield.get(Minecraft.getMinecraft().entityRenderer); + } catch (Exception e) { + } + if (map == null) { + setLightLevel(1.0f); + return; + } + + int mx = (coord % 65536) / 16; int my = (coord / 65536) / 16; - - int lightcolour = map[my*16+mx]; - - setLightLevel( - 1.0F, - 1.0F, - 1.0F - ); - } - - public static void setLightLevel(float level) { - setLightLevel(level, level, level); - } - public static void setLightLevel(float r, float g, float b) { - lightlevel[0] = Math.max(0.0f, Math.min(1.0f, r)); - lightlevel[1] = Math.max(0.0f, Math.min(1.0f, g)); - lightlevel[2] = Math.max(0.0f, Math.min(1.0f, b)); - } - - public static void bindItemTexture() { - Minecraft mc = Minecraft.getMinecraft(); - mc.renderEngine.bindTexture(TextureMap.locationItemsTexture); - } -} \ No newline at end of file + + int lightcolour = map[my * 16 + mx]; + + setLightLevel(1.0F, 1.0F, 1.0F); + } + + public static void setLightLevel(float level) { + setLightLevel(level, level, level); + } + + public static void setLightLevel(float r, float g, float b) { + lightlevel[0] = Math.max(0.0f, Math.min(1.0f, r)); + lightlevel[1] = Math.max(0.0f, Math.min(1.0f, g)); + lightlevel[2] = Math.max(0.0f, Math.min(1.0f, b)); + } + + public static void bindItemTexture() { + Minecraft mc = Minecraft.getMinecraft(); + mc.renderEngine.bindTexture(TextureMap.locationItemsTexture); + } +} diff --git a/src/main/java/singulariteam/eternalsingularity/render/EternalItemRenderer.java b/src/main/java/singulariteam/eternalsingularity/render/EternalItemRenderer.java index c479fb2..da4c464 100644 --- a/src/main/java/singulariteam/eternalsingularity/render/EternalItemRenderer.java +++ b/src/main/java/singulariteam/eternalsingularity/render/EternalItemRenderer.java @@ -2,6 +2,7 @@ package singulariteam.eternalsingularity.render; import fox.spiteful.avaritia.render.ICosmicRenderItem; import fox.spiteful.avaritia.render.IHaloRenderItem; +import java.util.Random; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.client.renderer.RenderHelper; @@ -17,286 +18,304 @@ import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.util.Random; +public class EternalItemRenderer implements IItemRenderer { -public class EternalItemRenderer implements IItemRenderer { - - public Random rand = new Random(); - - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - //return type != ItemRenderType.INVENTORY; - return true; - } + public Random rand = new Random(); - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { - return helper == ItemRendererHelper.ENTITY_ROTATION || helper == ItemRendererHelper.ENTITY_BOBBING; - } + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + // return type != ItemRenderType.INVENTORY; + return true; + } - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { - boolean renderHalo = false; - boolean renderPulse = false; - - int spread = 0; - IIcon halo = null; - int haloColour = 0; - - net.minecraft.item.Item itype = item.getItem(); - if (itype instanceof IHaloRenderItem) { - IHaloRenderItem ihri = (IHaloRenderItem)itype; - - spread = ihri.getHaloSize(item); - halo = ihri.getHaloTexture(item); - haloColour = ihri.getHaloColour(item); - - renderHalo = ihri.drawHalo(item); - renderPulse = ihri.drawPulseEffect(item); - } - - RenderItem r = RenderItem.getInstance(); - Minecraft mc = Minecraft.getMinecraft(); - Tessellator t = Tessellator.instance; - this.processLightLevel(type, item, data); - //ShaderHelper.useShader(ShaderHelper.testShader, this.shaderCallback); - switch(type) { - case ENTITY : { - GL11.glPushMatrix(); - GL11.glTranslatef(-0.5F, 0F, 0F); - if(item.isOnItemFrame()) - GL11.glTranslatef(0F, -0.3F, 0.01F); - render(item, null); - GL11.glPopMatrix(); - - break; - } - case EQUIPPED : { - render(item, data[1] instanceof EntityPlayer ? (EntityPlayer) data[1] : null); - break; - } - case EQUIPPED_FIRST_PERSON : { - render(item, data[1] instanceof EntityPlayer ? (EntityPlayer) data[1] : null); - break; - } - case INVENTORY: { - GL11.glPushMatrix(); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - RenderHelper.enableGUIStandardItemLighting(); - - GL11.glDisable(GL11.GL_ALPHA_TEST); - GL11.glDisable(GL11.GL_DEPTH_TEST); - - if (renderHalo) { - float ca = (float)(haloColour >> 24 & 255) / 255.0F; - float cr = (float)(haloColour >> 16 & 255) / 255.0F; - float cg = (float)(haloColour >> 8 & 255) / 255.0F; - float cb = (float)(haloColour & 255) / 255.0F; - GL11.glColor4f(cr, cg, cb, ca); - - t.startDrawingQuads(); - t.addVertexWithUV(0-spread, 0-spread, 0, halo.getMinU(), halo.getMinV()); - t.addVertexWithUV(0-spread, 16+spread, 0, halo.getMinU(), halo.getMaxV()); - t.addVertexWithUV(16+spread, 16+spread, 0, halo.getMaxU(), halo.getMaxV()); - t.addVertexWithUV(16+spread, 0-spread, 0, halo.getMaxU(), halo.getMinV()); - t.draw(); - } - - if (renderPulse) { - GL11.glPushMatrix(); - double xs = (rand.nextGaussian() * 0.15) + 0.95; - double ox = (1-xs)/2.0; - GL11.glEnable(GL11.GL_BLEND); - GL11.glTranslated(ox*16.0, ox*16.0, 1.0); - GL11.glScaled(xs, xs, 1.0); - - IIcon icon = item.getItem().getIcon(item, 0); - - t.startDrawingQuads(); - t.setColorRGBA_F(1.0f, 1.0f, 1.0f, 0.6f); - t.addVertexWithUV(0-ox, 0-ox, 0, icon.getMinU(), icon.getMinV()); - t.addVertexWithUV(0-ox, 16+ox, 0, icon.getMinU(), icon.getMaxV()); - t.addVertexWithUV(16+ox, 16+ox, 0, icon.getMaxU(), icon.getMaxV()); - t.addVertexWithUV(16+ox, 0-ox, 0, icon.getMaxU(), icon.getMinV()); - t.draw(); - - GL11.glPopMatrix(); - } - - r.renderItemIntoGUI(mc.fontRenderer, mc.getTextureManager(), item, 0, 0, true); - - GL11.glEnable(GL11.GL_ALPHA_TEST); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - GL11.glEnable(GL11.GL_DEPTH_TEST); - - r.renderWithColor = true; - - GL11.glDisable(GL11.GL_BLEND); - GL11.glPopMatrix(); - - //middle? - - GL11.glPushMatrix(); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - RenderHelper.enableGUIStandardItemLighting(); - - GL11.glDisable(GL11.GL_ALPHA_TEST); - GL11.glDisable(GL11.GL_DEPTH_TEST); - - r.renderItemIntoGUI(mc.fontRenderer, mc.getTextureManager(), item, 0, 0, true); - - if (item.getItem() instanceof ICosmicRenderItem) { - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - RenderHelper.enableGUIStandardItemLighting(); - - GL11.glDisable(GL11.GL_ALPHA_TEST); - GL11.glDisable(GL11.GL_DEPTH_TEST); - - ICosmicRenderItem icri = (ICosmicRenderItem)(item.getItem()); - - CosmicRenderStuffs.cosmicOpacity = icri.getMaskMultiplier(item, null); - CosmicRenderStuffs.inventoryRender = true; - CosmicRenderStuffs.useShader(); - - IIcon cosmicicon = icri.getMaskTexture(item, null); - - GL11.glColor4d(1, 1, 1, 1); - - float minu = cosmicicon.getMinU(); - float maxu = cosmicicon.getMaxU(); - float minv = cosmicicon.getMinV(); - float maxv = cosmicicon.getMaxV(); - - t.startDrawingQuads(); - t.addVertexWithUV(0, 0, 0, minu, minv); - t.addVertexWithUV(0, 16, 0, minu, maxv); - t.addVertexWithUV(16, 16, 0, maxu, maxv); - t.addVertexWithUV(16, 0, 0, maxu, minv); - t.draw(); - - CosmicRenderStuffs.releaseShader(); - CosmicRenderStuffs.inventoryRender = false; - } - - GL11.glEnable(GL11.GL_ALPHA_TEST); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - GL11.glEnable(GL11.GL_DEPTH_TEST); - - r.renderWithColor = true; - - GL11.glDisable(GL11.GL_BLEND); - GL11.glPopMatrix(); - break; - } - default : break; - } - //ShaderHelper.releaseShader(); - - //Lumberjack.log(Level.INFO, light+""); - } - - public void render(ItemStack item, EntityPlayer player) { - int passes = 1; - if (item.getItem().requiresMultipleRenderPasses()) - { - passes = item.getItem().getRenderPasses(item.getItemDamage()); + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return helper == ItemRendererHelper.ENTITY_ROTATION || helper == ItemRendererHelper.ENTITY_BOBBING; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + boolean renderHalo = false; + boolean renderPulse = false; + + int spread = 0; + IIcon halo = null; + int haloColour = 0; + + net.minecraft.item.Item itype = item.getItem(); + if (itype instanceof IHaloRenderItem) { + IHaloRenderItem ihri = (IHaloRenderItem) itype; + + spread = ihri.getHaloSize(item); + halo = ihri.getHaloTexture(item); + haloColour = ihri.getHaloColour(item); + + renderHalo = ihri.drawHalo(item); + renderPulse = ihri.drawPulseEffect(item); } - - GL11.glPushMatrix(); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glColor4f(1F, 1F, 1F, 1F); - //ItemRenderer.renderItemIn2D(Tessellator.instance, f1, f2, f, f3, icon.getIconWidth(), icon.getIconHeight(), scale); - float r,g,b; - IIcon icon; - float f,f1,f2,f3; - float scale = 1F / 16F; + RenderItem r = RenderItem.getInstance(); + Minecraft mc = Minecraft.getMinecraft(); + Tessellator t = Tessellator.instance; + this.processLightLevel(type, item, data); + // ShaderHelper.useShader(ShaderHelper.testShader, this.shaderCallback); + switch (type) { + case ENTITY: { + GL11.glPushMatrix(); + GL11.glTranslatef(-0.5F, 0F, 0F); + if (item.isOnItemFrame()) GL11.glTranslatef(0F, -0.3F, 0.01F); + render(item, null); + GL11.glPopMatrix(); - //Lumberjack.log(Level.INFO, "passes: "+passes); - - for (int i = 0; i < passes; i++) - { - icon = this.getStackIcon(item, i, player); - - //Lumberjack.log(Level.INFO, "icon "+i+": "+icon); + break; + } + case EQUIPPED: { + render(item, data[1] instanceof EntityPlayer ? (EntityPlayer) data[1] : null); + break; + } + case EQUIPPED_FIRST_PERSON: { + render(item, data[1] instanceof EntityPlayer ? (EntityPlayer) data[1] : null); + break; + } + case INVENTORY: { + GL11.glPushMatrix(); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + RenderHelper.enableGUIStandardItemLighting(); + + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glDisable(GL11.GL_DEPTH_TEST); + + if (renderHalo) { + float ca = (float) (haloColour >> 24 & 255) / 255.0F; + float cr = (float) (haloColour >> 16 & 255) / 255.0F; + float cg = (float) (haloColour >> 8 & 255) / 255.0F; + float cb = (float) (haloColour & 255) / 255.0F; + GL11.glColor4f(cr, cg, cb, ca); + + t.startDrawingQuads(); + t.addVertexWithUV(0 - spread, 0 - spread, 0, halo.getMinU(), halo.getMinV()); + t.addVertexWithUV(0 - spread, 16 + spread, 0, halo.getMinU(), halo.getMaxV()); + t.addVertexWithUV(16 + spread, 16 + spread, 0, halo.getMaxU(), halo.getMaxV()); + t.addVertexWithUV(16 + spread, 0 - spread, 0, halo.getMaxU(), halo.getMinV()); + t.draw(); + } + + if (renderPulse) { + GL11.glPushMatrix(); + double xs = (rand.nextGaussian() * 0.15) + 0.95; + double ox = (1 - xs) / 2.0; + GL11.glEnable(GL11.GL_BLEND); + GL11.glTranslated(ox * 16.0, ox * 16.0, 1.0); + GL11.glScaled(xs, xs, 1.0); + + IIcon icon = item.getItem().getIcon(item, 0); + + t.startDrawingQuads(); + t.setColorRGBA_F(1.0f, 1.0f, 1.0f, 0.6f); + t.addVertexWithUV(0 - ox, 0 - ox, 0, icon.getMinU(), icon.getMinV()); + t.addVertexWithUV(0 - ox, 16 + ox, 0, icon.getMinU(), icon.getMaxV()); + t.addVertexWithUV(16 + ox, 16 + ox, 0, icon.getMaxU(), icon.getMaxV()); + t.addVertexWithUV(16 + ox, 0 - ox, 0, icon.getMaxU(), icon.getMinV()); + t.draw(); + + GL11.glPopMatrix(); + } + + r.renderItemIntoGUI(mc.fontRenderer, mc.getTextureManager(), item, 0, 0, true); + + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glEnable(GL11.GL_DEPTH_TEST); + + r.renderWithColor = true; + + GL11.glDisable(GL11.GL_BLEND); + GL11.glPopMatrix(); + + // middle? + + GL11.glPushMatrix(); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + RenderHelper.enableGUIStandardItemLighting(); + + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glDisable(GL11.GL_DEPTH_TEST); + + r.renderItemIntoGUI(mc.fontRenderer, mc.getTextureManager(), item, 0, 0, true); + + if (item.getItem() instanceof ICosmicRenderItem) { + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + RenderHelper.enableGUIStandardItemLighting(); + + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glDisable(GL11.GL_DEPTH_TEST); + + ICosmicRenderItem icri = (ICosmicRenderItem) (item.getItem()); + + CosmicRenderStuffs.cosmicOpacity = icri.getMaskMultiplier(item, null); + CosmicRenderStuffs.inventoryRender = true; + CosmicRenderStuffs.useShader(); + + IIcon cosmicicon = icri.getMaskTexture(item, null); + + GL11.glColor4d(1, 1, 1, 1); + + float minu = cosmicicon.getMinU(); + float maxu = cosmicicon.getMaxU(); + float minv = cosmicicon.getMinV(); + float maxv = cosmicicon.getMaxV(); + + t.startDrawingQuads(); + t.addVertexWithUV(0, 0, 0, minu, minv); + t.addVertexWithUV(0, 16, 0, minu, maxv); + t.addVertexWithUV(16, 16, 0, maxu, maxv); + t.addVertexWithUV(16, 0, 0, maxu, minv); + t.draw(); + + CosmicRenderStuffs.releaseShader(); + CosmicRenderStuffs.inventoryRender = false; + } + + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glEnable(GL11.GL_DEPTH_TEST); + + r.renderWithColor = true; + + GL11.glDisable(GL11.GL_BLEND); + GL11.glPopMatrix(); + break; + } + default: + break; + } + // ShaderHelper.releaseShader(); + + // Lumberjack.log(Level.INFO, light+""); + } + + public void render(ItemStack item, EntityPlayer player) { + int passes = 1; + if (item.getItem().requiresMultipleRenderPasses()) { + passes = item.getItem().getRenderPasses(item.getItemDamage()); + } + + GL11.glPushMatrix(); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1F, 1F, 1F, 1F); + // ItemRenderer.renderItemIn2D(Tessellator.instance, f1, f2, f, f3, icon.getIconWidth(), icon.getIconHeight(), + // scale); + + float r, g, b; + IIcon icon; + float f, f1, f2, f3; + float scale = 1F / 16F; + + // Lumberjack.log(Level.INFO, "passes: "+passes); + + for (int i = 0; i < passes; i++) { + icon = this.getStackIcon(item, i, player); + + // Lumberjack.log(Level.INFO, "icon "+i+": "+icon); + + f = icon.getMinU(); + f1 = icon.getMaxU(); + f2 = icon.getMinV(); + f3 = icon.getMaxV(); - f = icon.getMinU(); - f1 = icon.getMaxU(); - f2 = icon.getMinV(); - f3 = icon.getMaxV(); - int colour = item.getItem().getColorFromItemStack(item, i); - r = (float)(colour & 255) / 255.0F; - g = (float)(colour & 255) / 255.0F; - b = (float)(colour & 255) / 255.0F; + r = (float) (colour & 255) / 255.0F; + g = (float) (colour & 255) / 255.0F; + b = (float) (colour & 255) / 255.0F; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - ItemRenderer.renderItemIn2D(Tessellator.instance, f1, f2, f, f3, icon.getIconWidth(), icon.getIconHeight(), scale); + ItemRenderer.renderItemIn2D( + Tessellator.instance, f1, f2, f, f3, icon.getIconWidth(), icon.getIconHeight(), scale); } - - if (item.getItem() instanceof ICosmicRenderItem) { - GL11.glDisable(GL11.GL_ALPHA_TEST); - GL11.glDepthFunc(GL11.GL_EQUAL); - ICosmicRenderItem icri = (ICosmicRenderItem)(item.getItem()); - CosmicRenderStuffs.cosmicOpacity = icri.getMaskMultiplier(item, player); - CosmicRenderStuffs.useShader(); - - IIcon cosmicicon = icri.getMaskTexture(item, player); - - float minu = cosmicicon.getMinU(); - float maxu = cosmicicon.getMaxU(); - float minv = cosmicicon.getMinV(); - float maxv = cosmicicon.getMaxV(); - ItemRenderer.renderItemIn2D(Tessellator.instance, maxu, minv, minu, maxv, cosmicicon.getIconWidth(), cosmicicon.getIconHeight(), scale); - CosmicRenderStuffs.releaseShader(); - GL11.glDepthFunc(GL11.GL_LEQUAL); - GL11.glEnable(GL11.GL_ALPHA_TEST); - } - - GL11.glDisable(GL11.GL_BLEND); - GL11.glPopMatrix(); - GL11.glColor4f(1F, 1F, 1F, 1F); - } + if (item.getItem() instanceof ICosmicRenderItem) { + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glDepthFunc(GL11.GL_EQUAL); + ICosmicRenderItem icri = (ICosmicRenderItem) (item.getItem()); + CosmicRenderStuffs.cosmicOpacity = icri.getMaskMultiplier(item, player); + CosmicRenderStuffs.useShader(); - public void processLightLevel(ItemRenderType type, ItemStack item, Object... data) { - switch(type) { - case ENTITY : { - EntityItem ent = (EntityItem)(data[1]); - if (ent != null) { - CosmicRenderStuffs.setLightFromLocation(ent.worldObj, MathHelper.floor_double(ent.posX), MathHelper.floor_double(ent.posY), MathHelper.floor_double(ent.posZ)); - } - break; - } - case EQUIPPED : { - EntityLivingBase ent = (EntityLivingBase)(data[1]); - if (ent != null) { - CosmicRenderStuffs.setLightFromLocation(ent.worldObj, MathHelper.floor_double(ent.posX), MathHelper.floor_double(ent.posY), MathHelper.floor_double(ent.posZ)); - } - break; - } - case EQUIPPED_FIRST_PERSON : { - EntityLivingBase ent = (EntityLivingBase)(data[1]); - if (ent != null) { - CosmicRenderStuffs.setLightFromLocation(ent.worldObj, MathHelper.floor_double(ent.posX), MathHelper.floor_double(ent.posY), MathHelper.floor_double(ent.posZ)); - } - break; - } - case INVENTORY: { - CosmicRenderStuffs.setLightLevel(1.2f); - return; - } - default : { - CosmicRenderStuffs.setLightLevel(1.0f); - return; - } - } - } - - public IIcon getStackIcon(ItemStack stack, int pass, EntityPlayer player) { - return stack.getItem().getIcon(stack, pass); - } + IIcon cosmicicon = icri.getMaskTexture(item, player); + + float minu = cosmicicon.getMinU(); + float maxu = cosmicicon.getMaxU(); + float minv = cosmicicon.getMinV(); + float maxv = cosmicicon.getMaxV(); + ItemRenderer.renderItemIn2D( + Tessellator.instance, + maxu, + minv, + minu, + maxv, + cosmicicon.getIconWidth(), + cosmicicon.getIconHeight(), + scale); + CosmicRenderStuffs.releaseShader(); + GL11.glDepthFunc(GL11.GL_LEQUAL); + GL11.glEnable(GL11.GL_ALPHA_TEST); + } + + GL11.glDisable(GL11.GL_BLEND); + GL11.glPopMatrix(); + + GL11.glColor4f(1F, 1F, 1F, 1F); + } + + public void processLightLevel(ItemRenderType type, ItemStack item, Object... data) { + switch (type) { + case ENTITY: { + EntityItem ent = (EntityItem) (data[1]); + if (ent != null) { + CosmicRenderStuffs.setLightFromLocation( + ent.worldObj, + MathHelper.floor_double(ent.posX), + MathHelper.floor_double(ent.posY), + MathHelper.floor_double(ent.posZ)); + } + break; + } + case EQUIPPED: { + EntityLivingBase ent = (EntityLivingBase) (data[1]); + if (ent != null) { + CosmicRenderStuffs.setLightFromLocation( + ent.worldObj, + MathHelper.floor_double(ent.posX), + MathHelper.floor_double(ent.posY), + MathHelper.floor_double(ent.posZ)); + } + break; + } + case EQUIPPED_FIRST_PERSON: { + EntityLivingBase ent = (EntityLivingBase) (data[1]); + if (ent != null) { + CosmicRenderStuffs.setLightFromLocation( + ent.worldObj, + MathHelper.floor_double(ent.posX), + MathHelper.floor_double(ent.posY), + MathHelper.floor_double(ent.posZ)); + } + break; + } + case INVENTORY: { + CosmicRenderStuffs.setLightLevel(1.2f); + return; + } + default: { + CosmicRenderStuffs.setLightLevel(1.0f); + return; + } + } + } + + public IIcon getStackIcon(ItemStack stack, int pass, EntityPlayer player) { + return stack.getItem().getIcon(stack, pass); + } } diff --git a/src/main/java/singulariteam/eternalsingularity/render/ShaderCallback.java b/src/main/java/singulariteam/eternalsingularity/render/ShaderCallback.java index a775c39..824ad58 100644 --- a/src/main/java/singulariteam/eternalsingularity/render/ShaderCallback.java +++ b/src/main/java/singulariteam/eternalsingularity/render/ShaderCallback.java @@ -1,6 +1,5 @@ package singulariteam.eternalsingularity.render; -public abstract class ShaderCallback -{ - public abstract void call(int paramInt); +public abstract class ShaderCallback { + public abstract void call(int paramInt); } diff --git a/src/main/java/singulariteam/eternalsingularity/render/ShaderHelper.java b/src/main/java/singulariteam/eternalsingularity/render/ShaderHelper.java index 2eec7ee..aab4a4d 100644 --- a/src/main/java/singulariteam/eternalsingularity/render/ShaderHelper.java +++ b/src/main/java/singulariteam/eternalsingularity/render/ShaderHelper.java @@ -1,169 +1,156 @@ package singulariteam.eternalsingularity.render; -//import fox.spiteful.avaritia.Lumberjack; +// import fox.spiteful.avaritia.Lumberjack; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.OpenGlHelper; -import org.apache.logging.log4j.Level; import org.lwjgl.opengl.ARBFragmentShader; import org.lwjgl.opengl.ARBShaderObjects; import org.lwjgl.opengl.ARBVertexShader; import org.lwjgl.opengl.GL11; -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; - public final class ShaderHelper { - private static final int VERT = ARBVertexShader.GL_VERTEX_SHADER_ARB; - private static final int FRAG = ARBFragmentShader.GL_FRAGMENT_SHADER_ARB; - private static final String PREFIX = "/assets/eternalsingularity/shader/"; + private static final int VERT = ARBVertexShader.GL_VERTEX_SHADER_ARB; + private static final int FRAG = ARBFragmentShader.GL_FRAGMENT_SHADER_ARB; + private static final String PREFIX = "/assets/eternalsingularity/shader/"; - public static int cosmicShader = 0; + public static int cosmicShader = 0; - public static void initShaders() { - if(!useShaders()) - return; - - cosmicShader = createProgram("cosmic.vert", "cosmic.frag"); - } + public static void initShaders() { + if (!useShaders()) return; - public static void useShader(int shader, ShaderCallback callback) { - if(!useShaders()) - return; + cosmicShader = createProgram("cosmic.vert", "cosmic.frag"); + } - ARBShaderObjects.glUseProgramObjectARB(shader); + public static void useShader(int shader, ShaderCallback callback) { + if (!useShaders()) return; - if(shader != 0) { - int time = ARBShaderObjects.glGetUniformLocationARB(shader, "time"); - Minecraft mc = Minecraft.getMinecraft(); - if (mc.thePlayer != null && mc.thePlayer.worldObj != null) { - ARBShaderObjects.glUniform1iARB(time, (int)(mc.thePlayer.worldObj.getWorldTime() % Integer.MAX_VALUE)); - } + ARBShaderObjects.glUseProgramObjectARB(shader); - if(callback != null) - callback.call(shader); - } - } + if (shader != 0) { + int time = ARBShaderObjects.glGetUniformLocationARB(shader, "time"); + Minecraft mc = Minecraft.getMinecraft(); + if (mc.thePlayer != null && mc.thePlayer.worldObj != null) { + ARBShaderObjects.glUniform1iARB(time, (int) (mc.thePlayer.worldObj.getWorldTime() % Integer.MAX_VALUE)); + } - public static void useShader(int shader) { - useShader(shader, null); - } + if (callback != null) callback.call(shader); + } + } - public static void releaseShader() { - useShader(0); - } + public static void useShader(int shader) { + useShader(shader, null); + } - public static boolean useShaders() { - return OpenGlHelper.shadersSupported; - } + public static void releaseShader() { + useShader(0); + } - // Most of the code taken from the LWJGL wiki - // http://lwjgl.org/wiki/index.php?title=GLSL_Shaders_with_LWJGL + public static boolean useShaders() { + return OpenGlHelper.shadersSupported; + } - private static int createProgram(String vert, String frag) { - int vertId = 0, fragId = 0, program = 0; - if(vert != null) - vertId = createShader(PREFIX + vert, VERT); - if(frag != null) - fragId = createShader(PREFIX + frag, FRAG); + // Most of the code taken from the LWJGL wiki + // http://lwjgl.org/wiki/index.php?title=GLSL_Shaders_with_LWJGL - program = ARBShaderObjects.glCreateProgramObjectARB(); - if(program == 0) - return 0; + private static int createProgram(String vert, String frag) { + int vertId = 0, fragId = 0, program = 0; + if (vert != null) vertId = createShader(PREFIX + vert, VERT); + if (frag != null) fragId = createShader(PREFIX + frag, FRAG); - if(vert != null) - ARBShaderObjects.glAttachObjectARB(program, vertId); - if(frag != null) - ARBShaderObjects.glAttachObjectARB(program, fragId); + program = ARBShaderObjects.glCreateProgramObjectARB(); + if (program == 0) return 0; - ARBShaderObjects.glLinkProgramARB(program); - if(ARBShaderObjects.glGetObjectParameteriARB(program, ARBShaderObjects.GL_OBJECT_LINK_STATUS_ARB) == GL11.GL_FALSE) { - //Lumberjack.log(Level.ERROR, getLogInfo(program)); - return 0; - } + if (vert != null) ARBShaderObjects.glAttachObjectARB(program, vertId); + if (frag != null) ARBShaderObjects.glAttachObjectARB(program, fragId); - ARBShaderObjects.glValidateProgramARB(program); - if (ARBShaderObjects.glGetObjectParameteriARB(program, ARBShaderObjects.GL_OBJECT_VALIDATE_STATUS_ARB) == GL11.GL_FALSE) { - //Lumberjack.log(Level.ERROR, getLogInfo(program)); - return 0; - } + ARBShaderObjects.glLinkProgramARB(program); + if (ARBShaderObjects.glGetObjectParameteriARB(program, ARBShaderObjects.GL_OBJECT_LINK_STATUS_ARB) + == GL11.GL_FALSE) { + // Lumberjack.log(Level.ERROR, getLogInfo(program)); + return 0; + } - return program; - } + ARBShaderObjects.glValidateProgramARB(program); + if (ARBShaderObjects.glGetObjectParameteriARB(program, ARBShaderObjects.GL_OBJECT_VALIDATE_STATUS_ARB) + == GL11.GL_FALSE) { + // Lumberjack.log(Level.ERROR, getLogInfo(program)); + return 0; + } - private static int createShader(String filename, int shaderType){ - int shader = 0; - try { - shader = ARBShaderObjects.glCreateShaderObjectARB(shaderType); + return program; + } - if(shader == 0) - return 0; + private static int createShader(String filename, int shaderType) { + int shader = 0; + try { + shader = ARBShaderObjects.glCreateShaderObjectARB(shaderType); - ARBShaderObjects.glShaderSourceARB(shader, readFileAsString(filename)); - ARBShaderObjects.glCompileShaderARB(shader); + if (shader == 0) return 0; - if (ARBShaderObjects.glGetObjectParameteriARB(shader, ARBShaderObjects.GL_OBJECT_COMPILE_STATUS_ARB) == GL11.GL_FALSE) - throw new RuntimeException("Error creating shader \""+filename+"\": " + getLogInfo(shader)); + ARBShaderObjects.glShaderSourceARB(shader, readFileAsString(filename)); + ARBShaderObjects.glCompileShaderARB(shader); - return shader; - } - catch(Exception e) { - ARBShaderObjects.glDeleteObjectARB(shader); - e.printStackTrace(); - return -1; - } - } + if (ARBShaderObjects.glGetObjectParameteriARB(shader, ARBShaderObjects.GL_OBJECT_COMPILE_STATUS_ARB) + == GL11.GL_FALSE) + throw new RuntimeException("Error creating shader \"" + filename + "\": " + getLogInfo(shader)); - private static String getLogInfo(int obj) { - return ARBShaderObjects.glGetInfoLogARB(obj, ARBShaderObjects.glGetObjectParameteriARB(obj, ARBShaderObjects.GL_OBJECT_INFO_LOG_LENGTH_ARB)); - } + return shader; + } catch (Exception e) { + ARBShaderObjects.glDeleteObjectARB(shader); + e.printStackTrace(); + return -1; + } + } - private static String readFileAsString(String filename) throws Exception { - StringBuilder source = new StringBuilder(); - InputStream in = ShaderHelper.class.getResourceAsStream(filename); - Exception exception = null; - BufferedReader reader; + private static String getLogInfo(int obj) { + return ARBShaderObjects.glGetInfoLogARB( + obj, ARBShaderObjects.glGetObjectParameteriARB(obj, ARBShaderObjects.GL_OBJECT_INFO_LOG_LENGTH_ARB)); + } - if(in == null) - return ""; + private static String readFileAsString(String filename) throws Exception { + StringBuilder source = new StringBuilder(); + InputStream in = ShaderHelper.class.getResourceAsStream(filename); + Exception exception = null; + BufferedReader reader; - try { - reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); + if (in == null) return ""; - Exception innerExc= null; - try { - String line; - while((line = reader.readLine()) != null) - source.append(line).append('\n'); - } catch(Exception exc) { - exception = exc; - } finally { - try { - reader.close(); - } catch(Exception exc) { - if(innerExc == null) - innerExc = exc; - else exc.printStackTrace(); - } - } + try { + reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); - if(innerExc != null) - throw innerExc; - } catch(Exception exc) { - exception = exc; - } finally { - try { - in.close(); - } catch(Exception exc) { - if(exception == null) - exception = exc; - else exc.printStackTrace(); - } + Exception innerExc = null; + try { + String line; + while ((line = reader.readLine()) != null) source.append(line).append('\n'); + } catch (Exception exc) { + exception = exc; + } finally { + try { + reader.close(); + } catch (Exception exc) { + if (innerExc == null) innerExc = exc; + else exc.printStackTrace(); + } + } - if(exception != null) - throw exception; - } + if (innerExc != null) throw innerExc; + } catch (Exception exc) { + exception = exc; + } finally { + try { + in.close(); + } catch (Exception exc) { + if (exception == null) exception = exc; + else exc.printStackTrace(); + } - return source.toString(); - } -} \ No newline at end of file + if (exception != null) throw exception; + } + + return source.toString(); + } +} diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info index c8078e9..5c25adc 100644 --- a/src/main/resources/mcmod.info +++ b/src/main/resources/mcmod.info @@ -1,15 +1,21 @@ -[ { - "modid": "eternalsingularity", - "name": "Eternal Singularity", "description": "A Mod that Adds an Eternal Singularity! (That Works as a Singularity Binder)", - "version": "1.0.4b", - "mcversion": "1.7.10", - "url": "https://minecraft.curseforge.com/projects/eternal-singularity", - "updateUrl": "", - "authorList": ["RCXcrafter, WanionCane, Wealthyturtle"], - "logoFile": "EternalSingularityLogo.png", - "screenshots": [], - "dependencies": [] + "modListVersion": 2, + "modList": [{ + "modid": "${modId}", + "name": "${modName}", + "version": "${modVersion}", + "mcversion": "${minecraftVersion}", + "url": "https://github.com/SinTh0r4s/MyMod", + "updateUrl": "", + "authorList": ["SinTho0r4s"], + "credits": "", + "logoFile": "", + "screenshots": [], + "parent": "", + "requiredMods": [], + "dependencies": [], + "dependants": [], + "useDependencyInformation": true + }] } -] diff --git a/src/main/resources/spotless.gradle b/src/main/resources/spotless.gradle new file mode 100644 index 0000000..297067c --- /dev/null +++ b/src/main/resources/spotless.gradle @@ -0,0 +1,30 @@ +printf("Configuring spotless\n") + +// Spotless autoformatter +// See https://github.com/diffplug/spotless/tree/main/plugin-gradle +// Can be locally toggled via spotless:off/spotless:on comments +spotless { + encoding 'UTF-8' + + format 'misc', { + target '.gitignore' + + trimTrailingWhitespace() + indentWithSpaces(4) + endWithNewline() + } + java { + toggleOffOn() + importOrder() + removeUnusedImports() + palantirJavaFormat('1.1.0') // last version supporting jvm 8 + } + kotlin { + toggleOffOn() + ktfmt('0.39') + + trimTrailingWhitespace() + indentWithSpaces(4) + endWithNewline() + } +}